blob: cd27392bd560dcbff1cf60ba4a5f6488b0be1ef2 [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"
Greg Clayton8f343b02010-11-04 01:54:29 +000042#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000043#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000044#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000045#include "lldb/Target/JITLoaderList.h"
Alex Langford03e1a822019-05-29 18:08:22 +000046#include "lldb/Target/Language.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"
Sean Callanan579e70c2016-03-19 00:03:59 +000050#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000051#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000052#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000054#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000055#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000056#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057#include "lldb/Target/Target.h"
58#include "lldb/Target/TargetList.h"
59#include "lldb/Target/Thread.h"
60#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000061#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000062#include "lldb/Target/UnixSignals.h"
Pavel Labath181b8232018-12-14 15:59:49 +000063#include "lldb/Utility/Event.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000064#include "lldb/Utility/Log.h"
Zachary Turner50232572015-03-18 21:31:45 +000065#include "lldb/Utility/NameMatches.h"
Zachary Turner805e7102019-03-04 21:51:03 +000066#include "lldb/Utility/ProcessInfo.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000067#include "lldb/Utility/SelectHelper.h"
Pavel Labathd821c992018-08-07 11:07:21 +000068#include "lldb/Utility/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069
70using namespace lldb;
71using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000072using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073
Kate Stoneb9c1b512016-09-06 20:57:50 +000074// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000075// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000076#define ENABLE_MEMORY_CACHING
77
78#ifdef ENABLE_MEMORY_CACHING
79#define DISABLE_MEM_CACHE_DEFAULT false
80#else
81#define DISABLE_MEM_CACHE_DEFAULT true
82#endif
83
Kate Stoneb9c1b512016-09-06 20:57:50 +000084class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000085public:
Adrian Prantl0e4c4822019-03-06 21:22:25 +000086 ProcessOptionValueProperties(ConstString name)
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 : OptionValueProperties(name) {}
88
Adrian Prantl05097242018-04-30 16:49:04 +000089 // This constructor is used when creating ProcessOptionValueProperties when
90 // it is part of a new lldb_private::Process instance. It will copy all
91 // current global property values as needed
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 ProcessOptionValueProperties(ProcessProperties *global_properties)
93 : OptionValueProperties(*global_properties->GetValueProperties()) {}
94
95 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
96 bool will_modify,
97 uint32_t idx) const override {
Adrian Prantl05097242018-04-30 16:49:04 +000098 // When getting the value for a key from the process options, we will
99 // always try and grab the setting from the current process if there is
100 // one. Else we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 if (exe_ctx) {
102 Process *process = exe_ctx->GetProcessPtr();
103 if (process) {
104 ProcessOptionValueProperties *instance_properties =
105 static_cast<ProcessOptionValueProperties *>(
106 process->GetValueProperties().get());
107 if (this != instance_properties)
108 return instance_properties->ProtectedGetPropertyAtIndex(idx);
109 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000110 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 return ProtectedGetPropertyAtIndex(idx);
112 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000113};
114
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000115static constexpr PropertyDefinition g_properties[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000117 DISABLE_MEM_CACHE_DEFAULT, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 "Disable reading and caching of memory in fixed-size units."},
119 {"extra-startup-command", OptionValue::eTypeArray, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000120 OptionValue::eTypeString, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121 "A list containing extra commands understood by the particular process "
122 "plugin used. "
123 "For instance, to turn on debugserver logging set this to "
124 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
125 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000126 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127 "If true, breakpoints will be ignored during expression evaluation."},
128 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000129 nullptr, {}, "If true, errors in expression evaluation will unwind "
130 "the stack back to the state before the call."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000132 {}, "A path to a python OS plug-in module file that contains a "
133 "OperatingSystemPlugIn class."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000135 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136 "If true, stop when a shared library is loaded or unloaded."},
137 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000138 {}, "If true, detach will attempt to keep the process stopped."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000140 {}, "The memory cache line size"},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000142 {}, "If true, warn when stopped in code that is optimized where "
143 "stepping and variable availability may not behave as expected."},
Jim Inghamba205c12017-12-05 02:50:45 +0000144 {"stop-on-exec", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000145 nullptr, {},
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000146 "If true, stop when a shared library is loaded or unloaded."},
147 {"utility-expression-timeout", OptionValue::eTypeUInt64, false, 15,
148 nullptr, {},
149 "The time in seconds to wait for LLDB-internal utility expressions."}
150};
Greg Clayton67cc0632012-08-22 17:17:09 +0000151
152enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153 ePropertyDisableMemCache,
154 ePropertyExtraStartCommand,
155 ePropertyIgnoreBreakpointsInExpressions,
156 ePropertyUnwindOnErrorInExpressions,
157 ePropertyPythonOSPluginPath,
158 ePropertyStopOnSharedLibraryEvents,
159 ePropertyDetachKeepsStopped,
160 ePropertyMemCacheLineSize,
Jim Inghamba205c12017-12-05 02:50:45 +0000161 ePropertyWarningOptimization,
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000162 ePropertyStopOnExec,
163 ePropertyUtilityExpressionTimeout,
Greg Clayton67cc0632012-08-22 17:17:09 +0000164};
165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166ProcessProperties::ProcessProperties(lldb_private::Process *process)
167 : Properties(),
168 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000169{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170 if (process == nullptr) {
171 // Global process properties, set them up one time
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000172 m_collection_sp =
173 std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174 m_collection_sp->Initialize(g_properties);
175 m_collection_sp->AppendProperty(
176 ConstString("thread"), ConstString("Settings specific to threads."),
177 true, Thread::GetGlobalProperties()->GetValueProperties());
178 } else {
Jonas Devlieghere796ac802019-02-11 23:13:08 +0000179 m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
180 Process::GetGlobalProperties().get());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181 m_collection_sp->SetValueChangedCallback(
182 ePropertyPythonOSPluginPath,
183 ProcessProperties::OptionValueChangedCallback, this);
184 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000185}
186
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000187ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000188
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189void ProcessProperties::OptionValueChangedCallback(void *baton,
190 OptionValue *option_value) {
191 ProcessProperties *properties = (ProcessProperties *)baton;
192 if (properties->m_process)
193 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000194}
195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196bool ProcessProperties::GetDisableMemoryCache() const {
197 const uint32_t idx = ePropertyDisableMemCache;
198 return m_collection_sp->GetPropertyAtIndexAsBoolean(
199 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000200}
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
203 const uint32_t idx = ePropertyMemCacheLineSize;
204 return m_collection_sp->GetPropertyAtIndexAsUInt64(
205 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000206}
207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208Args ProcessProperties::GetExtraStartupCommands() const {
209 Args args;
210 const uint32_t idx = ePropertyExtraStartCommand;
211 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
212 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000213}
214
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215void ProcessProperties::SetExtraStartupCommands(const Args &args) {
216 const uint32_t idx = ePropertyExtraStartCommand;
217 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000218}
219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220FileSpec ProcessProperties::GetPythonOSPluginPath() const {
221 const uint32_t idx = ePropertyPythonOSPluginPath;
222 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000223}
224
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
226 const uint32_t idx = ePropertyPythonOSPluginPath;
227 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000228}
229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
231 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
232 return m_collection_sp->GetPropertyAtIndexAsBoolean(
233 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000234}
235
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
237 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
238 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000239}
240
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
242 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
243 return m_collection_sp->GetPropertyAtIndexAsBoolean(
244 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000245}
246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
248 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
249 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000250}
251
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
253 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
254 return m_collection_sp->GetPropertyAtIndexAsBoolean(
255 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000256}
257
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
259 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
260 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
261}
262
263bool ProcessProperties::GetDetachKeepsStopped() const {
264 const uint32_t idx = ePropertyDetachKeepsStopped;
265 return m_collection_sp->GetPropertyAtIndexAsBoolean(
266 nullptr, idx, g_properties[idx].default_uint_value != 0);
267}
268
269void ProcessProperties::SetDetachKeepsStopped(bool stop) {
270 const uint32_t idx = ePropertyDetachKeepsStopped;
271 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
272}
273
274bool ProcessProperties::GetWarningsOptimization() const {
275 const uint32_t idx = ePropertyWarningOptimization;
276 return m_collection_sp->GetPropertyAtIndexAsBoolean(
277 nullptr, idx, g_properties[idx].default_uint_value != 0);
278}
279
Jim Inghamba205c12017-12-05 02:50:45 +0000280bool ProcessProperties::GetStopOnExec() const {
281 const uint32_t idx = ePropertyStopOnExec;
282 return m_collection_sp->GetPropertyAtIndexAsBoolean(
283 nullptr, idx, g_properties[idx].default_uint_value != 0);
284}
285
Adrian Prantl4c03ea12019-04-05 22:43:42 +0000286std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
287 const uint32_t idx = ePropertyUtilityExpressionTimeout;
288 uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
289 nullptr, idx, g_properties[idx].default_uint_value);
290 return std::chrono::seconds(value);
291}
292
Zachary Turner97206d52017-05-12 04:51:55 +0000293Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000294 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000296 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 const int short_option = m_getopt_table[option_idx].val;
298
299 switch (short_option) {
300 case 's': // Stop at program entry point
301 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
302 break;
303
304 case 'i': // STDIN for read only
305 {
306 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000307 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 launch_info.AppendFileAction(action);
309 break;
310 }
311
312 case 'o': // Open STDOUT for write only
313 {
314 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000315 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316 launch_info.AppendFileAction(action);
317 break;
318 }
319
320 case 'e': // STDERR for write only
321 {
322 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000323 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324 launch_info.AppendFileAction(action);
325 break;
326 }
327
328 case 'p': // Process plug-in name
329 launch_info.SetProcessPluginName(option_arg);
330 break;
331
332 case 'n': // Disable STDIO
333 {
334 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000335 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 if (action.Open(STDIN_FILENO, dev_null, true, false))
337 launch_info.AppendFileAction(action);
338 if (action.Open(STDOUT_FILENO, dev_null, false, true))
339 launch_info.AppendFileAction(action);
340 if (action.Open(STDERR_FILENO, dev_null, false, true))
341 launch_info.AppendFileAction(action);
342 break;
343 }
344
345 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000346 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 break;
348
349 case 't': // Open process in new terminal window
350 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
351 break;
352
353 case 'a': {
354 TargetSP target_sp =
355 execution_context ? execution_context->GetTargetSP() : TargetSP();
356 PlatformSP platform_sp =
357 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000358 launch_info.GetArchitecture() =
359 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 } break;
361
362 case 'A': // Disable ASLR.
363 {
364 bool success;
365 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000366 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 if (success)
368 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000369 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 error.SetErrorStringWithFormat(
371 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000372 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 break;
374 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000375
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376 case 'X': // shell expand args.
377 {
378 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000379 const bool expand_args =
380 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 if (success)
382 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000383 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 error.SetErrorStringWithFormat(
385 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000386 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 break;
388 }
389
390 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000391 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000392 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 else
394 launch_info.SetShell(HostInfo::GetDefaultShell());
395 break;
396
397 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000398 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399 break;
400
401 default:
402 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
403 short_option);
404 break;
405 }
406 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000407}
408
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000409static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000411 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 "Stop at the entry point of the program when launching a process."},
413 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000414 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 "Set whether to disable address space layout randomization when launching "
416 "a process."},
417 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000418 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 "Name of the process plugin you want to use."},
420 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000421 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422 eArgTypeDirectoryName,
423 "Set the current working directory to <path> when running the inferior."},
424 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000425 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 "Set the architecture for the process to launch when ambiguous."},
427 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000428 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 "Specify an environment variable name/value string (--environment "
430 "NAME=VALUE). Can be specified multiple times for subsequent environment "
431 "entries."},
432 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000433 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000434 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000435
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000437 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 "Redirect stdin for the process to <filename>."},
439 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000440 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 "Redirect stdout for the process to <filename>."},
442 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000443 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000444 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000445
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000447 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000449
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000451 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 "Do not set up for terminal I/O to go to running process."},
453 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000454 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000456};
457
458llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000459 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000460}
Greg Clayton32e0a752011-03-30 18:16:51 +0000461
Zachary Turner31659452016-11-17 21:15:14 +0000462ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
463 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464 ListenerSP listener_sp,
465 const FileSpec *crash_file_path) {
466 static uint32_t g_process_unique_id = 0;
467
468 ProcessSP process_sp;
469 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000470 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471 ConstString const_plugin_name(plugin_name);
472 create_callback =
473 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
474 if (create_callback) {
475 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
476 if (process_sp) {
477 if (process_sp->CanDebug(target_sp, true)) {
478 process_sp->m_process_unique_id = ++g_process_unique_id;
479 } else
480 process_sp.reset();
481 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000482 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000483 } else {
484 for (uint32_t idx = 0;
485 (create_callback =
486 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
487 ++idx) {
488 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
489 if (process_sp) {
490 if (process_sp->CanDebug(target_sp, false)) {
491 process_sp->m_process_unique_id = ++g_process_unique_id;
492 break;
493 } else
494 process_sp.reset();
495 }
496 }
497 }
498 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000499}
500
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501ConstString &Process::GetStaticBroadcasterClass() {
502 static ConstString class_name("lldb.process");
503 return class_name;
504}
505
506Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
507 : Process(target_sp, listener_sp,
508 UnixSignals::Create(HostInfo::GetArchitecture())) {
509 // This constructor just delegates to the full Process constructor,
510 // defaulting to using the Host's UnixSignals.
511}
512
513Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
514 const UnixSignalsSP &unix_signals_sp)
515 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
516 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
517 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000518 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 m_private_state(eStateUnloaded),
520 m_private_state_broadcaster(nullptr,
521 "lldb.process.internal_state_broadcaster"),
522 m_private_state_control_broadcaster(
523 nullptr, "lldb.process.internal_state_control_broadcaster"),
524 m_private_state_listener_sp(
525 Listener::MakeListener("lldb.process.internal_state_listener")),
526 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
527 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
528 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
529 m_thread_list(this), m_extended_thread_list(this),
530 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
531 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000532 m_breakpoint_site_list(), m_dynamic_checkers_up(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
534 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
535 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
536 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
537 m_memory_cache(*this), m_allocated_memory_cache(*this),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000538 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000539 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
541 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
542 m_can_interpret_function_calls(false), m_warnings_issued(),
543 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
544 CheckInWithManager();
545
546 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
547 if (log)
548 log->Printf("%p Process::Process()", static_cast<void *>(this));
549
550 if (!m_unix_signals_sp)
551 m_unix_signals_sp = std::make_shared<UnixSignals>();
552
553 SetEventName(eBroadcastBitStateChanged, "state-changed");
554 SetEventName(eBroadcastBitInterrupt, "interrupt");
555 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
556 SetEventName(eBroadcastBitSTDERR, "stderr-available");
557 SetEventName(eBroadcastBitProfileData, "profile-data-available");
558 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
559
560 m_private_state_control_broadcaster.SetEventName(
561 eBroadcastInternalStateControlStop, "control-stop");
562 m_private_state_control_broadcaster.SetEventName(
563 eBroadcastInternalStateControlPause, "control-pause");
564 m_private_state_control_broadcaster.SetEventName(
565 eBroadcastInternalStateControlResume, "control-resume");
566
567 m_listener_sp->StartListeningForEvents(
568 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
569 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
570 eBroadcastBitProfileData | eBroadcastBitStructuredData);
571
572 m_private_state_listener_sp->StartListeningForEvents(
573 &m_private_state_broadcaster,
574 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
575
576 m_private_state_listener_sp->StartListeningForEvents(
577 &m_private_state_control_broadcaster,
578 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
579 eBroadcastInternalStateControlResume);
580 // We need something valid here, even if just the default UnixSignalsSP.
581 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
582
583 // Allow the platform to override the default cache line size
584 OptionValueSP value_sp =
585 m_collection_sp
586 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
587 ->GetValue();
588 uint32_t platform_cache_line_size =
589 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
590 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
591 value_sp->SetUInt64Value(platform_cache_line_size);
592}
593
594Process::~Process() {
595 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
596 if (log)
597 log->Printf("%p Process::~Process()", static_cast<void *>(this));
598 StopPrivateStateThread();
599
600 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000601 // explicitly clear the thread list here to ensure that the mutex is not
602 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603 m_thread_list.Clear();
604}
605
606const ProcessPropertiesSP &Process::GetGlobalProperties() {
607 // NOTE: intentional leak so we don't crash if global destructor chain gets
608 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000609 static ProcessPropertiesSP *g_settings_sp_ptr =
610 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611 return *g_settings_sp_ptr;
612}
613
614void Process::Finalize() {
615 m_finalizing = true;
616
617 // Destroy this process if needed
618 switch (GetPrivateState()) {
619 case eStateConnected:
620 case eStateAttaching:
621 case eStateLaunching:
622 case eStateStopped:
623 case eStateRunning:
624 case eStateStepping:
625 case eStateCrashed:
626 case eStateSuspended:
627 Destroy(false);
628 break;
629
630 case eStateInvalid:
631 case eStateUnloaded:
632 case eStateDetached:
633 case eStateExited:
634 break;
635 }
636
637 // Clear our broadcaster before we proceed with destroying
638 Broadcaster::Clear();
639
Adrian Prantl05097242018-04-30 16:49:04 +0000640 // Do any cleanup needed prior to being destructed... Subclasses that
641 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000642
643 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000644 // destroyed since it is very likely that undoing the loader will require
645 // access to the real process.
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000646 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000648 m_os_up.reset();
649 m_system_runtime_up.reset();
650 m_dyld_up.reset();
651 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652 m_thread_list_real.Destroy();
653 m_thread_list.Destroy();
654 m_extended_thread_list.Destroy();
655 m_queue_list.Clear();
656 m_queue_list_stop_id = 0;
657 std::vector<Notifications> empty_notifications;
658 m_notifications.swap(empty_notifications);
659 m_image_tokens.clear();
660 m_memory_cache.Clear();
661 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +0000662 {
663 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
664 m_language_runtimes.clear();
665 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666 m_instrumentation_runtimes.clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000667 m_next_event_action_up.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000668 // Clear the last natural stop ID since it has a strong reference to this
669 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
671 //#ifdef LLDB_CONFIGURATION_DEBUG
672 // StreamFile s(stdout, false);
673 // EventSP event_sp;
674 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
675 // {
676 // event_sp->Dump (&s);
677 // s.EOL();
678 // }
679 //#endif
680 // We have to be very careful here as the m_private_state_listener might
681 // contain events that have ProcessSP values in them which can keep this
682 // process around forever. These events need to be cleared out.
683 m_private_state_listener_sp->Clear();
684 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
685 m_public_run_lock.SetStopped();
686 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
687 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000688 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 m_finalize_called = true;
690}
691
692void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
693 m_notifications.push_back(callbacks);
694 if (callbacks.initialize != nullptr)
695 callbacks.initialize(callbacks.baton, this);
696}
697
698bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
699 std::vector<Notifications>::iterator pos, end = m_notifications.end();
700 for (pos = m_notifications.begin(); pos != end; ++pos) {
701 if (pos->baton == callbacks.baton &&
702 pos->initialize == callbacks.initialize &&
703 pos->process_state_changed == callbacks.process_state_changed) {
704 m_notifications.erase(pos);
705 return true;
706 }
707 }
708 return false;
709}
710
711void Process::SynchronouslyNotifyStateChanged(StateType state) {
712 std::vector<Notifications>::iterator notification_pos,
713 notification_end = m_notifications.end();
714 for (notification_pos = m_notifications.begin();
715 notification_pos != notification_end; ++notification_pos) {
716 if (notification_pos->process_state_changed)
717 notification_pos->process_state_changed(notification_pos->baton, this,
718 state);
719 }
720}
721
722// FIXME: We need to do some work on events before the general Listener sees
723// them.
724// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000725// we do the little "insert real insn, step & stop" trick. But we can't do
726// that when the event is delivered by the broadcaster - since that is done on
727// the thread that is waiting for new events, so if we needed more than one
728// event for our handling, we would stall. So instead we do it when we fetch
729// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730//
731
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732StateType Process::GetNextEvent(EventSP &event_sp) {
733 StateType state = eStateInvalid;
734
Pavel Labathd35031e12016-11-30 10:41:42 +0000735 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
736 std::chrono::seconds(0)) &&
737 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
739
740 return state;
741}
742
Pavel Labath3879fe02018-05-09 14:29:30 +0000743void Process::SyncIOHandler(uint32_t iohandler_id,
744 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745 // don't sync (potentially context switch) in case where there is no process
746 // IO
747 if (!m_process_input_reader)
748 return;
749
Pavel Labath3879fe02018-05-09 14:29:30 +0000750 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751
752 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000753 if (Result) {
754 LLDB_LOG(
755 log,
756 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
757 iohandler_id, *Result);
758 } else {
759 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
760 iohandler_id);
761 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762}
763
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000764StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
765 EventSP *event_sp_ptr, bool wait_always,
766 ListenerSP hijack_listener_sp,
767 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000769 // have restarted the target. We have to actually check each event, and in
770 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 if (event_sp_ptr)
772 event_sp_ptr->reset();
773 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000774 // If we are exited or detached, we won't ever get back to any other valid
775 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000777 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000780 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000781
Kate Stoneb9c1b512016-09-06 20:57:50 +0000782 if (!wait_always && StateIsStoppedState(state, true) &&
783 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000784 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000785 log->Printf("Process::%s returning without waiting for events; process "
786 "private and public states are already 'stopped'.",
787 __FUNCTION__);
788 // We need to toggle the run lock as this won't get done in
789 // SetPublicState() if the process is hijacked.
790 if (hijack_listener_sp && use_run_lock)
791 m_public_run_lock.SetStopped();
792 return state;
793 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795 while (state != eStateInvalid) {
796 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000797 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000798 if (event_sp_ptr && event_sp)
799 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +0000800
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
802 Process::HandleProcessStateChangedEvent(event_sp, stream,
803 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +0000804
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805 switch (state) {
806 case eStateCrashed:
807 case eStateDetached:
808 case eStateExited:
809 case eStateUnloaded:
810 // We need to toggle the run lock as this won't get done in
811 // SetPublicState() if the process is hijacked.
812 if (hijack_listener_sp && use_run_lock)
813 m_public_run_lock.SetStopped();
814 return state;
815 case eStateStopped:
816 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
817 continue;
818 else {
Pavel Labath78521ef2015-03-06 10:52:47 +0000819 // We need to toggle the run lock as this won't get done in
820 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +0000821 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 m_public_run_lock.SetStopped();
823 return state;
824 }
825 default:
826 continue;
827 }
828 }
829 return state;
830}
831
832bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
833 Stream *stream,
834 bool &pop_process_io_handler) {
835 const bool handle_pop = pop_process_io_handler;
836
837 pop_process_io_handler = false;
838 ProcessSP process_sp =
839 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
840
841 if (!process_sp)
842 return false;
843
844 StateType event_state =
845 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
846 if (event_state == eStateInvalid)
847 return false;
848
849 switch (event_state) {
850 case eStateInvalid:
851 case eStateUnloaded:
852 case eStateAttaching:
853 case eStateLaunching:
854 case eStateStepping:
855 case eStateDetached:
856 if (stream)
857 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
858 StateAsCString(event_state));
859 if (event_state == eStateDetached)
860 pop_process_io_handler = true;
861 break;
862
863 case eStateConnected:
864 case eStateRunning:
865 // Don't be chatty when we run...
866 break;
867
868 case eStateExited:
869 if (stream)
870 process_sp->GetStatus(*stream);
871 pop_process_io_handler = true;
872 break;
873
874 case eStateStopped:
875 case eStateCrashed:
876 case eStateSuspended:
877 // Make sure the program hasn't been auto-restarted:
878 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
879 if (stream) {
880 size_t num_reasons =
881 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
882 if (num_reasons > 0) {
883 // FIXME: Do we want to report this, or would that just be annoyingly
884 // chatty?
885 if (num_reasons == 1) {
886 const char *reason =
887 Process::ProcessEventData::GetRestartedReasonAtIndex(
888 event_sp.get(), 0);
889 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
890 process_sp->GetID(),
891 reason ? reason : "<UNKNOWN REASON>");
892 } else {
893 stream->Printf("Process %" PRIu64
894 " stopped and restarted, reasons:\n",
895 process_sp->GetID());
896
897 for (size_t i = 0; i < num_reasons; i++) {
898 const char *reason =
899 Process::ProcessEventData::GetRestartedReasonAtIndex(
900 event_sp.get(), i);
901 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
902 }
903 }
904 }
905 }
906 } else {
907 StopInfoSP curr_thread_stop_info_sp;
908 // Lock the thread list so it doesn't change on us, this is the scope for
909 // the locker:
910 {
911 ThreadList &thread_list = process_sp->GetThreadList();
912 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
913
914 ThreadSP curr_thread(thread_list.GetSelectedThread());
915 ThreadSP thread;
916 StopReason curr_thread_stop_reason = eStopReasonInvalid;
917 if (curr_thread) {
918 curr_thread_stop_reason = curr_thread->GetStopReason();
919 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
920 }
921 if (!curr_thread || !curr_thread->IsValid() ||
922 curr_thread_stop_reason == eStopReasonInvalid ||
923 curr_thread_stop_reason == eStopReasonNone) {
924 // Prefer a thread that has just completed its plan over another
925 // thread as current thread.
926 ThreadSP plan_thread;
927 ThreadSP other_thread;
928
929 const size_t num_threads = thread_list.GetSize();
930 size_t i;
931 for (i = 0; i < num_threads; ++i) {
932 thread = thread_list.GetThreadAtIndex(i);
933 StopReason thread_stop_reason = thread->GetStopReason();
934 switch (thread_stop_reason) {
935 case eStopReasonInvalid:
936 case eStopReasonNone:
937 break;
938
939 case eStopReasonSignal: {
940 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +0000941 // that signal. We have to have had another reason for stopping
942 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943 uint64_t signo = thread->GetStopInfo()->GetValue();
944 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
945 if (!other_thread)
946 other_thread = thread;
947 }
948 break;
949 }
950 case eStopReasonTrace:
951 case eStopReasonBreakpoint:
952 case eStopReasonWatchpoint:
953 case eStopReasonException:
954 case eStopReasonExec:
955 case eStopReasonThreadExiting:
956 case eStopReasonInstrumentation:
957 if (!other_thread)
958 other_thread = thread;
959 break;
960 case eStopReasonPlanComplete:
961 if (!plan_thread)
962 plan_thread = thread;
963 break;
964 }
965 }
966 if (plan_thread)
967 thread_list.SetSelectedThreadByID(plan_thread->GetID());
968 else if (other_thread)
969 thread_list.SetSelectedThreadByID(other_thread->GetID());
970 else {
971 if (curr_thread && curr_thread->IsValid())
972 thread = curr_thread;
973 else
974 thread = thread_list.GetThreadAtIndex(0);
975
976 if (thread)
977 thread_list.SetSelectedThreadByID(thread->GetID());
978 }
979 }
980 }
981 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +0000982 // have to run code, e.g. for Data formatters, and if we hold the
983 // ThreadList mutex, then the process is going to have a hard time
984 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 if (stream) {
986 Debugger &debugger = process_sp->GetTarget().GetDebugger();
987 if (debugger.GetTargetList().GetSelectedTarget().get() ==
988 &process_sp->GetTarget()) {
989 const bool only_threads_with_stop_reason = true;
990 const uint32_t start_frame = 0;
991 const uint32_t num_frames = 1;
992 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +0000993 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994 process_sp->GetStatus(*stream);
995 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
996 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +0000997 num_frames_with_source,
998 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 if (curr_thread_stop_info_sp) {
1000 lldb::addr_t crashing_address;
1001 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1002 curr_thread_stop_info_sp, &crashing_address);
1003 if (valobj_sp) {
1004 const bool qualify_cxx_base_classes = false;
1005
1006 const ValueObject::GetExpressionPathFormat format =
1007 ValueObject::GetExpressionPathFormat::
1008 eGetExpressionPathFormatHonorPointers;
1009 stream->PutCString("Likely cause: ");
1010 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1011 format);
1012 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1013 }
1014 }
1015 } else {
1016 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1017 process_sp->GetTarget().shared_from_this());
1018 if (target_idx != UINT32_MAX)
1019 stream->Printf("Target %d: (", target_idx);
1020 else
1021 stream->Printf("Target <unknown index>: (");
1022 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1023 stream->Printf(") stopped.\n");
1024 }
1025 }
1026
1027 // Pop the process IO handler
1028 pop_process_io_handler = true;
1029 }
1030 break;
1031 }
1032
1033 if (handle_pop && pop_process_io_handler)
1034 process_sp->PopProcessIOHandler();
1035
1036 return true;
1037}
1038
Kate Stoneb9c1b512016-09-06 20:57:50 +00001039bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1040 if (listener_sp) {
1041 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1042 eBroadcastBitInterrupt);
1043 } else
1044 return false;
1045}
Greg Claytondc6224e2014-10-21 01:00:42 +00001046
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001048
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001049StateType Process::GetStateChangedEvents(EventSP &event_sp,
1050 const Timeout<std::micro> &timeout,
1051 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001052 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001053 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001054
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055 ListenerSP listener_sp = hijack_listener_sp;
1056 if (!listener_sp)
1057 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001058
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001060 if (listener_sp->GetEventForBroadcasterWithType(
1061 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001062 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1064 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001065 else
1066 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001068
Pavel Labathd02b1c82017-02-10 11:49:33 +00001069 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070 return state;
1071}
Greg Claytondc6224e2014-10-21 01:00:42 +00001072
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073Event *Process::PeekAtStateChangedEvents() {
1074 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001075
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 if (log)
1077 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001078
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 Event *event_ptr;
1080 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1081 this, eBroadcastBitStateChanged);
1082 if (log) {
1083 if (event_ptr) {
1084 log->Printf(
1085 "Process::%s (event_ptr) => %s", __FUNCTION__,
1086 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1087 } else {
1088 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001089 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090 }
1091 return event_ptr;
1092}
Greg Claytondc6224e2014-10-21 01:00:42 +00001093
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001094StateType
1095Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1096 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001098 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001099
1100 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001101 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1102 &m_private_state_broadcaster,
1103 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001104 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001105 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1106 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1107
Pavel Labathd02b1c82017-02-10 11:49:33 +00001108 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1109 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110 return state;
1111}
1112
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001113bool Process::GetEventsPrivate(EventSP &event_sp,
1114 const Timeout<std::micro> &timeout,
1115 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001117 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118
1119 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001120 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001121 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001123 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124}
1125
1126bool Process::IsRunning() const {
1127 return StateIsRunningState(m_public_state.GetValue());
1128}
1129
1130int Process::GetExitStatus() {
1131 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1132
1133 if (m_public_state.GetValue() == eStateExited)
1134 return m_exit_status;
1135 return -1;
1136}
1137
1138const char *Process::GetExitDescription() {
1139 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1140
1141 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1142 return m_exit_string.c_str();
1143 return nullptr;
1144}
1145
1146bool Process::SetExitStatus(int status, const char *cstr) {
1147 // Use a mutex to protect setting the exit status.
1148 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1149
1150 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1151 LIBLLDB_LOG_PROCESS));
1152 if (log)
1153 log->Printf(
1154 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1155 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1156 cstr ? "\"" : "");
1157
1158 // We were already in the exited state
1159 if (m_private_state.GetValue() == eStateExited) {
1160 if (log)
1161 log->Printf("Process::SetExitStatus () ignoring exit status because "
1162 "state was already set to eStateExited");
1163 return false;
1164 }
1165
1166 m_exit_status = status;
1167 if (cstr)
1168 m_exit_string = cstr;
1169 else
1170 m_exit_string.clear();
1171
Adrian Prantl05097242018-04-30 16:49:04 +00001172 // Clear the last natural stop ID since it has a strong reference to this
1173 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1175
1176 SetPrivateState(eStateExited);
1177
1178 // Allow subclasses to do some cleanup
1179 DidExit();
1180
1181 return true;
1182}
1183
1184bool Process::IsAlive() {
1185 switch (m_private_state.GetValue()) {
1186 case eStateConnected:
1187 case eStateAttaching:
1188 case eStateLaunching:
1189 case eStateStopped:
1190 case eStateRunning:
1191 case eStateStepping:
1192 case eStateCrashed:
1193 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001194 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195 default:
1196 return false;
1197 }
Jason Molendaa814f702015-11-05 23:03:44 +00001198}
1199
Adrian Prantl05097242018-04-30 16:49:04 +00001200// This static callback can be used to watch for local child processes on the
1201// current host. The child process exits, the process will be found in the
1202// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001203// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204bool Process::SetProcessExitStatus(
1205 lldb::pid_t pid, bool exited,
1206 int signo, // Zero for no signal
1207 int exit_status // Exit value of process if signal is zero
1208 ) {
1209 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1210 if (log)
1211 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1212 ", exited=%i, signal=%i, exit_status=%i)\n",
1213 pid, exited, signo, exit_status);
1214
1215 if (exited) {
1216 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1217 if (target_sp) {
1218 ProcessSP process_sp(target_sp->GetProcessSP());
1219 if (process_sp) {
1220 const char *signal_cstr = nullptr;
1221 if (signo)
1222 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1223
1224 process_sp->SetExitStatus(exit_status, signal_cstr);
1225 }
1226 }
1227 return true;
1228 }
1229 return false;
1230}
1231
1232void Process::UpdateThreadListIfNeeded() {
1233 const uint32_t stop_id = GetStopID();
1234 if (m_thread_list.GetSize(false) == 0 ||
1235 stop_id != m_thread_list.GetStopID()) {
1236 const StateType state = GetPrivateState();
1237 if (StateIsStoppedState(state, true)) {
1238 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Adrian Prantl05097242018-04-30 16:49:04 +00001239 // m_thread_list does have its own mutex, but we need to hold onto the
1240 // mutex between the call to UpdateThreadList(...) and the
1241 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242 ThreadList &old_thread_list = m_thread_list;
1243 ThreadList real_thread_list(this);
1244 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001245 // Always update the thread list with the protocol specific thread list,
1246 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1248 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001249 // are shutting down, since that may call back into the SBAPI's,
1250 // requiring the API lock which is already held by whoever is shutting
1251 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 OperatingSystem *os = GetOperatingSystem();
1253 if (os && !m_destroy_in_process) {
1254 // Clear any old backing threads where memory threads might have been
1255 // backed by actual threads from the lldb_private::Process subclass
1256 size_t num_old_threads = old_thread_list.GetSize(false);
1257 for (size_t i = 0; i < num_old_threads; ++i)
1258 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1259
1260 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001261 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001262 // dynamic type or not and we need to avoid this. OperatingSystem
1263 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264
1265 Target &target = GetTarget();
1266 const lldb::DynamicValueType saved_prefer_dynamic =
1267 target.GetPreferDynamicValue();
1268 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1269 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1270
1271 // Now let the OperatingSystem plug-in update the thread list
1272
1273 os->UpdateThreadList(
1274 old_thread_list, // Old list full of threads created by OS plug-in
1275 real_thread_list, // The actual thread list full of threads
1276 // created by each lldb_private::Process
1277 // subclass
1278 new_thread_list); // The new thread list that we will show to the
1279 // user that gets filled in
1280
1281 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1282 target.SetPreferDynamicValue(saved_prefer_dynamic);
1283 } else {
1284 // No OS plug-in, the new thread list is the same as the real thread
1285 // list
1286 new_thread_list = real_thread_list;
1287 }
1288
1289 m_thread_list_real.Update(real_thread_list);
1290 m_thread_list.Update(new_thread_list);
1291 m_thread_list.SetStopID(stop_id);
1292
1293 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1294 // Clear any extended threads that we may have accumulated previously
1295 m_extended_thread_list.Clear();
1296 m_extended_thread_stop_id = GetLastNaturalStopID();
1297
1298 m_queue_list.Clear();
1299 m_queue_list_stop_id = GetLastNaturalStopID();
1300 }
1301 }
1302 }
1303 }
1304}
1305
1306void Process::UpdateQueueListIfNeeded() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001307 if (m_system_runtime_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001308 if (m_queue_list.GetSize() == 0 ||
1309 m_queue_list_stop_id != GetLastNaturalStopID()) {
1310 const StateType state = GetPrivateState();
1311 if (StateIsStoppedState(state, true)) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001312 m_system_runtime_up->PopulateQueueList(m_queue_list);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 m_queue_list_stop_id = GetLastNaturalStopID();
1314 }
1315 }
1316 }
1317}
1318
1319ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1320 OperatingSystem *os = GetOperatingSystem();
1321 if (os)
1322 return os->CreateThread(tid, context);
1323 return ThreadSP();
1324}
1325
1326uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1327 return AssignIndexIDToThread(thread_id);
1328}
1329
1330bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1331 return (m_thread_id_to_index_id_map.find(thread_id) !=
1332 m_thread_id_to_index_id_map.end());
1333}
1334
1335uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1336 uint32_t result = 0;
1337 std::map<uint64_t, uint32_t>::iterator iterator =
1338 m_thread_id_to_index_id_map.find(thread_id);
1339 if (iterator == m_thread_id_to_index_id_map.end()) {
1340 result = ++m_thread_index_id;
1341 m_thread_id_to_index_id_map[thread_id] = result;
1342 } else {
1343 result = iterator->second;
1344 }
1345
1346 return result;
1347}
1348
1349StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350 return m_public_state.GetValue();
1351}
1352
Kate Stoneb9c1b512016-09-06 20:57:50 +00001353void Process::SetPublicState(StateType new_state, bool restarted) {
1354 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1355 LIBLLDB_LOG_PROCESS));
1356 if (log)
1357 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1358 StateAsCString(new_state), restarted);
1359 const StateType old_state = m_public_state.GetValue();
1360 m_public_state.SetValue(new_state);
1361
Adrian Prantl05097242018-04-30 16:49:04 +00001362 // On the transition from Run to Stopped, we unlock the writer end of the run
1363 // lock. The lock gets locked in Resume, which is the public API to tell the
1364 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365 if (!StateChangedIsExternallyHijacked()) {
1366 if (new_state == eStateDetached) {
1367 if (log)
1368 log->Printf(
1369 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1370 StateAsCString(new_state));
1371 m_public_run_lock.SetStopped();
1372 } else {
1373 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1374 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1375 if ((old_state_is_stopped != new_state_is_stopped)) {
1376 if (new_state_is_stopped && !restarted) {
1377 if (log)
1378 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1379 StateAsCString(new_state));
1380 m_public_run_lock.SetStopped();
1381 }
1382 }
1383 }
1384 }
1385}
1386
Zachary Turner97206d52017-05-12 04:51:55 +00001387Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001388 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1389 LIBLLDB_LOG_PROCESS));
1390 if (log)
1391 log->Printf("Process::Resume -- locking run lock");
1392 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001393 Status error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001394 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001395 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001396 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001398 Status error = PrivateResume();
1399 if (!error.Success()) {
1400 // Undo running state change
1401 m_public_run_lock.SetStopped();
1402 }
1403 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001404}
1405
Jim Ingham3139fc92019-03-01 18:13:38 +00001406static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1407
Zachary Turner97206d52017-05-12 04:51:55 +00001408Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001409 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1410 LIBLLDB_LOG_PROCESS));
1411 if (log)
1412 log->Printf("Process::ResumeSynchronous -- locking run lock");
1413 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001414 Status error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001415 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001416 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1417 return error;
1418 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001419
Kate Stoneb9c1b512016-09-06 20:57:50 +00001420 ListenerSP listener_sp(
Jim Ingham3139fc92019-03-01 18:13:38 +00001421 Listener::MakeListener(g_resume_sync_name));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423
Zachary Turner97206d52017-05-12 04:51:55 +00001424 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001425 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001426 StateType state =
Konrad Kleine248a1302019-05-23 11:14:47 +00001427 WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001428 const bool must_be_alive =
1429 false; // eStateExited is ok, so this must be false
1430 if (!StateIsStoppedState(state, must_be_alive))
1431 error.SetErrorStringWithFormat(
1432 "process not in stopped state after synchronous resume: %s",
1433 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001434 } else {
1435 // Undo running state change
1436 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001437 }
Ed Mastec29693f2013-07-02 16:35:47 +00001438
Kate Stoneb9c1b512016-09-06 20:57:50 +00001439 // Undo the hijacking of process events...
1440 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001441
Kate Stoneb9c1b512016-09-06 20:57:50 +00001442 return error;
1443}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001444
Jim Ingham3139fc92019-03-01 18:13:38 +00001445bool Process::StateChangedIsExternallyHijacked() {
1446 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1447 const char *hijacking_name = GetHijackingListenerName();
1448 if (hijacking_name &&
1449 strcmp(hijacking_name, g_resume_sync_name))
1450 return true;
1451 }
1452 return false;
1453}
1454
1455bool Process::StateChangedIsHijackedForSynchronousResume() {
1456 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1457 const char *hijacking_name = GetHijackingListenerName();
1458 if (hijacking_name &&
1459 strcmp(hijacking_name, g_resume_sync_name) == 0)
1460 return true;
1461 }
1462 return false;
1463}
1464
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001466
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467void Process::SetPrivateState(StateType new_state) {
1468 if (m_finalize_called)
1469 return;
1470
1471 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1472 LIBLLDB_LOG_PROCESS));
1473 bool state_changed = false;
1474
1475 if (log)
1476 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1477
1478 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1479 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1480
1481 const StateType old_state = m_private_state.GetValueNoLock();
1482 state_changed = old_state != new_state;
1483
1484 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1485 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1486 if (old_state_is_stopped != new_state_is_stopped) {
1487 if (new_state_is_stopped)
1488 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001489 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001490 m_private_run_lock.SetRunning();
1491 }
1492
1493 if (state_changed) {
1494 m_private_state.SetValueNoLock(new_state);
1495 EventSP event_sp(
1496 new Event(eBroadcastBitStateChanged,
1497 new ProcessEventData(shared_from_this(), new_state)));
1498 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001499 // Note, this currently assumes that all threads in the list stop when
1500 // the process stops. In the future we will want to support a debugging
1501 // model where some threads continue to run while others are stopped.
1502 // When that happens we will either need a way for the thread list to
1503 // identify which threads are stopping or create a special thread list
1504 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001505 //
Adrian Prantl05097242018-04-30 16:49:04 +00001506 // The process plugin is responsible for managing the actual behavior of
1507 // the threads and should have stopped any threads that are going to stop
1508 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001509 m_thread_list.DidStop();
1510
1511 m_mod_id.BumpStopID();
1512 if (!m_mod_id.IsLastResumeForUserExpression())
1513 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1514 m_memory_cache.Clear();
1515 if (log)
1516 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1517 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001518 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001519
Kate Stoneb9c1b512016-09-06 20:57:50 +00001520 // Use our target to get a shared pointer to ourselves...
1521 if (m_finalize_called && !PrivateStateThreadIsValid())
1522 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001523 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001524 m_private_state_broadcaster.BroadcastEvent(event_sp);
1525 } else {
1526 if (log)
1527 log->Printf(
1528 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1529 StateAsCString(new_state));
1530 }
Jim Ingham22777012010-09-23 02:01:19 +00001531}
1532
Kate Stoneb9c1b512016-09-06 20:57:50 +00001533void Process::SetRunningUserExpression(bool on) {
1534 m_mod_id.SetRunningUserExpression(on);
1535}
1536
Raphael Isemannc01783a2018-08-29 22:50:54 +00001537void Process::SetRunningUtilityFunction(bool on) {
1538 m_mod_id.SetRunningUtilityFunction(on);
1539}
1540
Kate Stoneb9c1b512016-09-06 20:57:50 +00001541addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1542
1543const lldb::ABISP &Process::GetABI() {
1544 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001545 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546 return m_abi_sp;
1547}
1548
Alex Langford03e1a822019-05-29 18:08:22 +00001549std::vector<LanguageRuntime *>
1550Process::GetLanguageRuntimes(bool retry_if_null) {
1551 std::vector<LanguageRuntime *> language_runtimes;
1552
1553 if (m_finalizing)
1554 return language_runtimes;
1555
1556 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1557 // Before we pass off a copy of the language runtimes, we must make sure that
1558 // our collection is properly populated. It's possible that some of the
1559 // language runtimes were not loaded yet, either because nobody requested it
1560 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1561 // hadn't been loaded).
1562 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
1563 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type, retry_if_null))
1564 language_runtimes.emplace_back(runtime);
1565 }
1566
1567 return language_runtimes;
1568}
1569
Kate Stoneb9c1b512016-09-06 20:57:50 +00001570LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1571 bool retry_if_null) {
1572 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001573 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001574
Alex Langford7d3e97f2019-05-29 21:07:53 +00001575 LanguageRuntime *runtime = nullptr;
1576
Alex Langford74eb76f2019-05-22 23:01:18 +00001577 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001578 LanguageRuntimeCollection::iterator pos;
1579 pos = m_language_runtimes.find(language);
Alex Langford7d3e97f2019-05-29 21:07:53 +00001580 if (pos == m_language_runtimes.end() || (retry_if_null && !pos->second)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001581 lldb::LanguageRuntimeSP runtime_sp(
1582 LanguageRuntime::FindPlugin(this, language));
1583
1584 m_language_runtimes[language] = runtime_sp;
Alex Langford7d3e97f2019-05-29 21:07:53 +00001585 runtime = runtime_sp.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001586 } else
Alex Langford7d3e97f2019-05-29 21:07:53 +00001587 runtime = pos->second.get();
1588
1589 if (runtime)
1590 // It's possible that a language runtime can support multiple LanguageTypes,
1591 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1592 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1593 // primary language type and make sure that our runtime supports it.
1594 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1595
1596 return runtime;
Jim Ingham22777012010-09-23 02:01:19 +00001597}
1598
Kate Stoneb9c1b512016-09-06 20:57:50 +00001599bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1600 if (m_finalizing)
1601 return false;
1602
1603 if (in_value.IsDynamic())
1604 return false;
1605 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1606
1607 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1608 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1609 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1610 }
1611
Alex Langford41dc5522019-05-30 21:03:53 +00001612 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1613 if (runtime->CouldHaveDynamicValue(in_value))
1614 return true;
1615 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001616
Alex Langford41dc5522019-05-30 21:03:53 +00001617 return false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001618}
1619
Kate Stoneb9c1b512016-09-06 20:57:50 +00001620void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001621 m_dynamic_checkers_up.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001622}
1623
Kate Stoneb9c1b512016-09-06 20:57:50 +00001624BreakpointSiteList &Process::GetBreakpointSiteList() {
1625 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001626}
1627
Kate Stoneb9c1b512016-09-06 20:57:50 +00001628const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1629 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001630}
1631
Kate Stoneb9c1b512016-09-06 20:57:50 +00001632void Process::DisableAllBreakpointSites() {
1633 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1634 // bp_site->SetEnabled(true);
1635 DisableBreakpointSite(bp_site);
1636 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001637}
1638
Zachary Turner97206d52017-05-12 04:51:55 +00001639Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1640 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001641
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642 if (error.Success())
1643 m_breakpoint_site_list.Remove(break_id);
1644
1645 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001646}
1647
Zachary Turner97206d52017-05-12 04:51:55 +00001648Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1649 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001650 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1651 if (bp_site_sp) {
1652 if (bp_site_sp->IsEnabled())
1653 error = DisableBreakpointSite(bp_site_sp.get());
1654 } else {
1655 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1656 break_id);
1657 }
1658
1659 return error;
1660}
1661
Zachary Turner97206d52017-05-12 04:51:55 +00001662Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1663 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001664 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1665 if (bp_site_sp) {
1666 if (!bp_site_sp->IsEnabled())
1667 error = EnableBreakpointSite(bp_site_sp.get());
1668 } else {
1669 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1670 break_id);
1671 }
1672 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001673}
1674
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001675lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1677 bool use_hardware) {
1678 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001679
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680 bool show_error = true;
1681 switch (GetState()) {
1682 case eStateInvalid:
1683 case eStateUnloaded:
1684 case eStateConnected:
1685 case eStateAttaching:
1686 case eStateLaunching:
1687 case eStateDetached:
1688 case eStateExited:
1689 show_error = false;
1690 break;
1691
1692 case eStateStopped:
1693 case eStateRunning:
1694 case eStateStepping:
1695 case eStateCrashed:
1696 case eStateSuspended:
1697 show_error = IsAlive();
1698 break;
1699 }
1700
Adrian Prantl05097242018-04-30 16:49:04 +00001701 // Reset the IsIndirect flag here, in case the location changes from pointing
1702 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 owner->SetIsIndirect(false);
1704
1705 if (owner->ShouldResolveIndirectFunctions()) {
1706 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1707 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001708 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001709 Address symbol_address = symbol->GetAddress();
1710 load_addr = ResolveIndirectFunction(&symbol_address, error);
1711 if (!error.Success() && show_error) {
1712 GetTarget().GetDebugger().GetErrorFile()->Printf(
1713 "warning: failed to resolve indirect function at 0x%" PRIx64
1714 " for breakpoint %i.%i: %s\n",
1715 symbol->GetLoadAddress(&GetTarget()),
1716 owner->GetBreakpoint().GetID(), owner->GetID(),
1717 error.AsCString() ? error.AsCString() : "unknown error");
1718 return LLDB_INVALID_BREAK_ID;
1719 }
1720 Address resolved_address(load_addr);
1721 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1722 owner->SetIsIndirect(true);
1723 } else
1724 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1725 } else
1726 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1727
1728 if (load_addr != LLDB_INVALID_ADDRESS) {
1729 BreakpointSiteSP bp_site_sp;
1730
1731 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001732 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001733
1734 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1735
1736 if (bp_site_sp) {
1737 bp_site_sp->AddOwner(owner);
1738 owner->SetBreakpointSite(bp_site_sp);
1739 return bp_site_sp->GetID();
1740 } else {
1741 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1742 load_addr, use_hardware));
1743 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001744 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001745 if (error.Success()) {
1746 owner->SetBreakpointSite(bp_site_sp);
1747 return m_breakpoint_site_list.Add(bp_site_sp);
1748 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001749 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750 // Report error for setting breakpoint...
1751 GetTarget().GetDebugger().GetErrorFile()->Printf(
1752 "warning: failed to set breakpoint site at 0x%" PRIx64
1753 " for breakpoint %i.%i: %s\n",
1754 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1755 error.AsCString() ? error.AsCString() : "unknown error");
1756 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001757 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001758 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001759 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760 }
1761 // We failed to enable the breakpoint
1762 return LLDB_INVALID_BREAK_ID;
1763}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001764
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1766 lldb::user_id_t owner_loc_id,
1767 BreakpointSiteSP &bp_site_sp) {
1768 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1769 if (num_owners == 0) {
1770 // Don't try to disable the site if we don't have a live process anymore.
1771 if (IsAlive())
1772 DisableBreakpointSite(bp_site_sp.get());
1773 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1774 }
1775}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001776
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1778 uint8_t *buf) const {
1779 size_t bytes_removed = 0;
1780 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001781
Kate Stoneb9c1b512016-09-06 20:57:50 +00001782 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1783 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001784 bp_sites_in_range.ForEach([bp_addr, size,
1785 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001786 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1787 addr_t intersect_addr;
1788 size_t intersect_size;
1789 size_t opcode_offset;
1790 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1791 &intersect_size, &opcode_offset)) {
1792 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1793 assert(bp_addr < intersect_addr + intersect_size &&
1794 intersect_addr + intersect_size <= bp_addr + size);
1795 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1796 size_t buf_offset = intersect_addr - bp_addr;
1797 ::memcpy(buf + buf_offset,
1798 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1799 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001800 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001801 }
1802 });
1803 }
1804 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001805}
1806
Kate Stoneb9c1b512016-09-06 20:57:50 +00001807size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1808 PlatformSP platform_sp(GetTarget().GetPlatform());
1809 if (platform_sp)
1810 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1811 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812}
1813
Zachary Turner97206d52017-05-12 04:51:55 +00001814Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1815 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816 assert(bp_site != nullptr);
1817 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1818 const addr_t bp_addr = bp_site->GetLoadAddress();
1819 if (log)
1820 log->Printf(
1821 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1822 bp_site->GetID(), (uint64_t)bp_addr);
1823 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001825 log->Printf(
1826 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1827 " -- already enabled",
1828 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001829 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001830 }
1831
1832 if (bp_addr == LLDB_INVALID_ADDRESS) {
1833 error.SetErrorString("BreakpointSite contains an invalid load address.");
1834 return error;
1835 }
1836 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1837 // trap for the breakpoint site
1838 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1839
1840 if (bp_opcode_size == 0) {
1841 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1842 "returned zero, unable to get breakpoint "
1843 "trap for address 0x%" PRIx64,
1844 bp_addr);
1845 } else {
1846 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1847
1848 if (bp_opcode_bytes == nullptr) {
1849 error.SetErrorString(
1850 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1851 return error;
1852 }
1853
1854 // Save the original opcode by reading it
1855 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1856 error) == bp_opcode_size) {
1857 // Write a software breakpoint in place of the original opcode
1858 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1859 bp_opcode_size) {
1860 uint8_t verify_bp_opcode_bytes[64];
1861 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1862 error) == bp_opcode_size) {
1863 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1864 bp_opcode_size) == 0) {
1865 bp_site->SetEnabled(true);
1866 bp_site->SetType(BreakpointSite::eSoftware);
1867 if (log)
1868 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
1869 "addr = 0x%" PRIx64 " -- SUCCESS",
1870 bp_site->GetID(), (uint64_t)bp_addr);
1871 } else
1872 error.SetErrorString(
1873 "failed to verify the breakpoint trap in memory.");
1874 } else
1875 error.SetErrorString(
1876 "Unable to read memory to verify breakpoint trap.");
1877 } else
1878 error.SetErrorString("Unable to write breakpoint trap to memory.");
1879 } else
1880 error.SetErrorString("Unable to read memory at breakpoint address.");
1881 }
1882 if (log && error.Fail())
1883 log->Printf(
1884 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1885 " -- FAILED: %s",
1886 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1887 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001888}
1889
Zachary Turner97206d52017-05-12 04:51:55 +00001890Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1891 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001892 assert(bp_site != nullptr);
1893 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1894 addr_t bp_addr = bp_site->GetLoadAddress();
1895 lldb::user_id_t breakID = bp_site->GetID();
1896 if (log)
1897 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1898 ") addr = 0x%" PRIx64,
1899 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001900
Kate Stoneb9c1b512016-09-06 20:57:50 +00001901 if (bp_site->IsHardware()) {
1902 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1903 } else if (bp_site->IsEnabled()) {
1904 const size_t break_op_size = bp_site->GetByteSize();
1905 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1906 if (break_op_size > 0) {
1907 // Clear a software breakpoint instruction
1908 uint8_t curr_break_op[8];
1909 assert(break_op_size <= sizeof(curr_break_op));
1910 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001911
Kate Stoneb9c1b512016-09-06 20:57:50 +00001912 // Read the breakpoint opcode
1913 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1914 break_op_size) {
1915 bool verify = false;
1916 // Make sure the breakpoint opcode exists at this address
1917 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1918 break_op_found = true;
1919 // We found a valid breakpoint opcode at this address, now restore
1920 // the saved opcode.
1921 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1922 break_op_size, error) == break_op_size) {
1923 verify = true;
1924 } else
1925 error.SetErrorString(
1926 "Memory write failed when restoring original opcode.");
1927 } else {
1928 error.SetErrorString(
1929 "Original breakpoint trap is no longer in memory.");
1930 // Set verify to true and so we can check if the original opcode has
1931 // already been restored
1932 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001933 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001934
Kate Stoneb9c1b512016-09-06 20:57:50 +00001935 if (verify) {
1936 uint8_t verify_opcode[8];
1937 assert(break_op_size < sizeof(verify_opcode));
1938 // Verify that our original opcode made it back to the inferior
1939 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1940 break_op_size) {
1941 // compare the memory we just read with the original opcode
1942 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1943 break_op_size) == 0) {
1944 // SUCCESS
1945 bp_site->SetEnabled(false);
1946 if (log)
1947 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
1948 "addr = 0x%" PRIx64 " -- SUCCESS",
1949 bp_site->GetID(), (uint64_t)bp_addr);
1950 return error;
1951 } else {
1952 if (break_op_found)
1953 error.SetErrorString("Failed to restore original opcode.");
1954 }
1955 } else
1956 error.SetErrorString("Failed to read memory to verify that "
1957 "breakpoint trap was restored.");
1958 }
1959 } else
1960 error.SetErrorString(
1961 "Unable to read memory that should contain the breakpoint trap.");
1962 }
1963 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001964 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001965 log->Printf(
1966 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1967 " -- already disabled",
1968 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001969 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001970 }
1971
1972 if (log)
1973 log->Printf(
1974 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1975 " -- FAILED: %s",
1976 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1977 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001978}
1979
Adrian Prantl05097242018-04-30 16:49:04 +00001980// Uncomment to verify memory caching works after making changes to caching
1981// code
Greg Clayton58be07b2011-01-07 06:08:19 +00001982//#define VERIFY_MEMORY_READS
1983
Zachary Turner97206d52017-05-12 04:51:55 +00001984size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001985 error.Clear();
1986 if (!GetDisableMemoryCache()) {
1987#if defined(VERIFY_MEMORY_READS)
1988 // Memory caching is enabled, with debug verification
1989
1990 if (buf && size) {
1991 // Uncomment the line below to make sure memory caching is working.
1992 // I ran this through the test suite and got no assertions, so I am
1993 // pretty confident this is working well. If any changes are made to
1994 // memory caching, uncomment the line below and test your changes!
1995
1996 // Verify all memory reads by using the cache first, then redundantly
1997 // reading the same memory from the inferior and comparing to make sure
1998 // everything is exactly the same.
1999 std::string verify_buf(size, '\0');
2000 assert(verify_buf.size() == size);
2001 const size_t cache_bytes_read =
2002 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00002003 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002004 const size_t verify_bytes_read =
2005 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2006 verify_buf.size(), verify_error);
2007 assert(cache_bytes_read == verify_bytes_read);
2008 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2009 assert(verify_error.Success() == error.Success());
2010 return cache_bytes_read;
2011 }
2012 return 0;
2013#else // !defined(VERIFY_MEMORY_READS)
2014 // Memory caching is enabled, without debug verification
2015
2016 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002017#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002018 } else {
2019 // Memory caching is disabled
2020
2021 return ReadMemoryFromInferior(addr, buf, size, error);
2022 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002023}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002024
2025size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00002026 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002027 char buf[256];
2028 out_str.clear();
2029 addr_t curr_addr = addr;
2030 while (true) {
2031 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2032 if (length == 0)
2033 break;
2034 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00002035 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2036 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00002037 if (length == sizeof(buf) - 1)
2038 curr_addr += length;
2039 else
2040 break;
2041 }
2042 return out_str.size();
2043}
2044
2045size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00002046 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002047 size_t total_bytes_read = 0;
2048 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00002049 // Ensure a null terminator independent of the number of bytes that is
2050 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002051 memset(dst, 0, max_bytes);
2052 size_t bytes_left = max_bytes - type_width;
2053
2054 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2055 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2056 "string with more than 4 bytes "
2057 "per character!");
2058
Greg Clayton4c82d422012-05-18 23:20:01 +00002059 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002060 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2061 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002062
Kate Stoneb9c1b512016-09-06 20:57:50 +00002063 error.Clear();
2064 while (bytes_left > 0 && error.Success()) {
2065 addr_t cache_line_bytes_left =
2066 cache_line_size - (curr_addr % cache_line_size);
2067 addr_t bytes_to_read =
2068 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2069 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002070
Kate Stoneb9c1b512016-09-06 20:57:50 +00002071 if (bytes_read == 0)
2072 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002073
Kate Stoneb9c1b512016-09-06 20:57:50 +00002074 // Search for a null terminator of correct size and alignment in
2075 // bytes_read
2076 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2077 for (size_t i = aligned_start;
2078 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2079 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2080 error.Clear();
2081 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002082 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002083
2084 total_bytes_read += bytes_read;
2085 curr_dst += bytes_read;
2086 curr_addr += bytes_read;
2087 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002088 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002089 } else {
2090 if (max_bytes)
2091 error.SetErrorString("invalid arguments");
2092 }
2093 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002094}
2095
Kate Stoneb9c1b512016-09-06 20:57:50 +00002096// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002097// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002098size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002099 size_t dst_max_len,
2100 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002101 size_t total_cstr_len = 0;
2102 if (dst && dst_max_len) {
2103 result_error.Clear();
2104 // NULL out everything just to be safe
2105 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002106 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002107 addr_t curr_addr = addr;
2108 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2109 size_t bytes_left = dst_max_len - 1;
2110 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002111
Kate Stoneb9c1b512016-09-06 20:57:50 +00002112 while (bytes_left > 0) {
2113 addr_t cache_line_bytes_left =
2114 cache_line_size - (curr_addr % cache_line_size);
2115 addr_t bytes_to_read =
2116 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2117 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002118
Kate Stoneb9c1b512016-09-06 20:57:50 +00002119 if (bytes_read == 0) {
2120 result_error = error;
2121 dst[total_cstr_len] = '\0';
2122 break;
2123 }
2124 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002125
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126 total_cstr_len += len;
2127
2128 if (len < bytes_to_read)
2129 break;
2130
2131 curr_dst += bytes_read;
2132 curr_addr += bytes_read;
2133 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002134 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002135 } else {
2136 if (dst == nullptr)
2137 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002138 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139 result_error.Clear();
2140 }
2141 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002142}
2143
Kate Stoneb9c1b512016-09-06 20:57:50 +00002144size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002145 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002146 if (buf == nullptr || size == 0)
2147 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002148
Kate Stoneb9c1b512016-09-06 20:57:50 +00002149 size_t bytes_read = 0;
2150 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002151
Kate Stoneb9c1b512016-09-06 20:57:50 +00002152 while (bytes_read < size) {
2153 const size_t curr_size = size - bytes_read;
2154 const size_t curr_bytes_read =
2155 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2156 bytes_read += curr_bytes_read;
2157 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2158 break;
2159 }
2160
2161 // Replace any software breakpoint opcodes that fall into this range back
2162 // into "buf" before we return
2163 if (bytes_read > 0)
2164 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2165 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002166}
2167
Kate Stoneb9c1b512016-09-06 20:57:50 +00002168uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2169 size_t integer_byte_size,
2170 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002171 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002172 Scalar scalar;
2173 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2174 error))
2175 return scalar.ULongLong(fail_value);
2176 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002177}
2178
Kate Stoneb9c1b512016-09-06 20:57:50 +00002179int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2180 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002181 int64_t fail_value,
2182 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002183 Scalar scalar;
2184 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2185 error))
2186 return scalar.SLongLong(fail_value);
2187 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002188}
2189
Zachary Turner97206d52017-05-12 04:51:55 +00002190addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002191 Scalar scalar;
2192 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2193 error))
2194 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2195 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002196}
2197
Kate Stoneb9c1b512016-09-06 20:57:50 +00002198bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002199 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002200 Scalar scalar;
2201 const uint32_t addr_byte_size = GetAddressByteSize();
2202 if (addr_byte_size <= 4)
2203 scalar = (uint32_t)ptr_value;
2204 else
2205 scalar = ptr_value;
2206 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2207 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002208}
2209
Kate Stoneb9c1b512016-09-06 20:57:50 +00002210size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002211 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002212 size_t bytes_written = 0;
2213 const uint8_t *bytes = (const uint8_t *)buf;
2214
2215 while (bytes_written < size) {
2216 const size_t curr_size = size - bytes_written;
2217 const size_t curr_bytes_written = DoWriteMemory(
2218 addr + bytes_written, bytes + bytes_written, curr_size, error);
2219 bytes_written += curr_bytes_written;
2220 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2221 break;
2222 }
2223 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002224}
2225
Kate Stoneb9c1b512016-09-06 20:57:50 +00002226size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002227 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002228#if defined(ENABLE_MEMORY_CACHING)
2229 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002230#endif
2231
Kate Stoneb9c1b512016-09-06 20:57:50 +00002232 if (buf == nullptr || size == 0)
2233 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002234
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002236
Kate Stoneb9c1b512016-09-06 20:57:50 +00002237 // We need to write any data that would go where any current software traps
2238 // (enabled software breakpoints) any software traps (breakpoints) that we
2239 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002240
Kate Stoneb9c1b512016-09-06 20:57:50 +00002241 BreakpointSiteList bp_sites_in_range;
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002242 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002243 return WriteMemoryPrivate(addr, buf, size, error);
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002244
2245 // No breakpoint sites overlap
2246 if (bp_sites_in_range.IsEmpty())
2247 return WriteMemoryPrivate(addr, buf, size, error);
2248
2249 const uint8_t *ubuf = (const uint8_t *)buf;
2250 uint64_t bytes_written = 0;
2251
2252 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2253 &error](BreakpointSite *bp) -> void {
2254 if (error.Fail())
2255 return;
2256
2257 addr_t intersect_addr;
2258 size_t intersect_size;
2259 size_t opcode_offset;
2260 const bool intersects = bp->IntersectsRange(
2261 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2262 UNUSED_IF_ASSERT_DISABLED(intersects);
2263 assert(intersects);
2264 assert(addr <= intersect_addr && intersect_addr < addr + size);
2265 assert(addr < intersect_addr + intersect_size &&
2266 intersect_addr + intersect_size <= addr + size);
2267 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2268
2269 // Check for bytes before this breakpoint
2270 const addr_t curr_addr = addr + bytes_written;
2271 if (intersect_addr > curr_addr) {
2272 // There are some bytes before this breakpoint that we need to just
2273 // write to memory
2274 size_t curr_size = intersect_addr - curr_addr;
2275 size_t curr_bytes_written =
2276 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2277 bytes_written += curr_bytes_written;
2278 if (curr_bytes_written != curr_size) {
2279 // We weren't able to write all of the requested bytes, we are
2280 // done looping and will return the number of bytes that we have
2281 // written so far.
2282 if (error.Success())
2283 error.SetErrorToGenericError();
2284 }
2285 }
2286 // Now write any bytes that would cover up any software breakpoints
2287 // directly into the breakpoint opcode buffer
2288 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2289 intersect_size);
2290 bytes_written += intersect_size;
2291 });
Kate Stoneb9c1b512016-09-06 20:57:50 +00002292
2293 // Write any remaining bytes after the last breakpoint if we have any left
Jonas Devlieghere533fe612019-04-01 20:39:03 +00002294 if (bytes_written < size)
2295 bytes_written +=
2296 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2297 size - bytes_written, error);
2298
2299 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002300}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002301
Kate Stoneb9c1b512016-09-06 20:57:50 +00002302size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002303 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002304 if (byte_size == UINT32_MAX)
2305 byte_size = scalar.GetByteSize();
2306 if (byte_size > 0) {
2307 uint8_t buf[32];
2308 const size_t mem_size =
2309 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2310 if (mem_size > 0)
2311 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002312 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002313 error.SetErrorString("failed to get scalar as memory data");
2314 } else {
2315 error.SetErrorString("invalid scalar value");
2316 }
2317 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002318}
2319
Kate Stoneb9c1b512016-09-06 20:57:50 +00002320size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2321 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002322 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002323 uint64_t uval = 0;
2324 if (byte_size == 0) {
2325 error.SetErrorString("byte size is zero");
2326 } else if (byte_size & (byte_size - 1)) {
2327 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2328 byte_size);
2329 } else if (byte_size <= sizeof(uval)) {
2330 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2331 if (bytes_read == byte_size) {
2332 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2333 GetAddressByteSize());
2334 lldb::offset_t offset = 0;
2335 if (byte_size <= 4)
2336 scalar = data.GetMaxU32(&offset, byte_size);
2337 else
2338 scalar = data.GetMaxU64(&offset, byte_size);
2339 if (is_signed)
2340 scalar.SignExtend(byte_size * 8);
2341 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002342 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002343 } else {
2344 error.SetErrorStringWithFormat(
2345 "byte size of %u is too large for integer scalar type", byte_size);
2346 }
2347 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002348}
2349
Pavel Labath16064d32018-03-20 11:56:24 +00002350Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2351 Status error;
2352 for (const auto &Entry : entries) {
2353 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2354 error);
2355 if (!error.Success())
2356 break;
2357 }
2358 return error;
2359}
2360
Greg Claytond495c532011-05-17 03:37:42 +00002361#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002362addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002363 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002364 if (GetPrivateState() != eStateStopped) {
2365 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002366 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002367 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002368
2369#if defined(USE_ALLOCATE_MEMORY_CACHE)
2370 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002371#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002372 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2373 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2374 if (log)
2375 log->Printf("Process::AllocateMemory(size=%" PRIu64
2376 ", permissions=%s) => 0x%16.16" PRIx64
2377 " (m_stop_id = %u m_memory_id = %u)",
2378 (uint64_t)size, GetPermissionsAsCString(permissions),
2379 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2380 m_mod_id.GetMemoryID());
2381 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002382#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383}
2384
Kate Stoneb9c1b512016-09-06 20:57:50 +00002385addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002386 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002387 addr_t return_addr = AllocateMemory(size, permissions, error);
2388 if (error.Success()) {
2389 std::string buffer(size, 0);
2390 WriteMemory(return_addr, buffer.c_str(), size, error);
2391 }
2392 return return_addr;
2393}
2394
2395bool Process::CanJIT() {
2396 if (m_can_jit == eCanJITDontKnow) {
2397 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002398 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002399
2400 uint64_t allocated_memory = AllocateMemory(
2401 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2402 err);
2403
2404 if (err.Success()) {
2405 m_can_jit = eCanJITYes;
2406 if (log)
2407 log->Printf("Process::%s pid %" PRIu64
2408 " allocation test passed, CanJIT () is true",
2409 __FUNCTION__, GetID());
2410 } else {
2411 m_can_jit = eCanJITNo;
2412 if (log)
2413 log->Printf("Process::%s pid %" PRIu64
2414 " allocation test failed, CanJIT () is false: %s",
2415 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002416 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002417
2418 DeallocateMemory(allocated_memory);
2419 }
2420
2421 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002422}
2423
Kate Stoneb9c1b512016-09-06 20:57:50 +00002424void Process::SetCanJIT(bool can_jit) {
2425 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002426}
2427
Kate Stoneb9c1b512016-09-06 20:57:50 +00002428void Process::SetCanRunCode(bool can_run_code) {
2429 SetCanJIT(can_run_code);
2430 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002431}
2432
Zachary Turner97206d52017-05-12 04:51:55 +00002433Status Process::DeallocateMemory(addr_t ptr) {
2434 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002435#if defined(USE_ALLOCATE_MEMORY_CACHE)
2436 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2437 error.SetErrorStringWithFormat(
2438 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2439 }
Greg Claytond495c532011-05-17 03:37:42 +00002440#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002441 error = DoDeallocateMemory(ptr);
2442
2443 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2444 if (log)
2445 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2446 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2447 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2448 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002449#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002450 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002451}
2452
Kate Stoneb9c1b512016-09-06 20:57:50 +00002453ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2454 lldb::addr_t header_addr,
2455 size_t size_to_read) {
2456 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2457 if (log) {
2458 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2459 file_spec.GetPath().c_str());
2460 }
2461 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2462 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002463 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002464 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2465 shared_from_this(), header_addr, error, size_to_read);
2466 if (objfile)
2467 return module_sp;
2468 }
2469 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002470}
2471
Kate Stoneb9c1b512016-09-06 20:57:50 +00002472bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2473 uint32_t &permissions) {
2474 MemoryRegionInfo range_info;
2475 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002476 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002477 if (!error.Success())
2478 return false;
2479 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2480 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2481 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2482 return false;
2483 }
2484
2485 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2486 permissions |= lldb::ePermissionsReadable;
2487
2488 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2489 permissions |= lldb::ePermissionsWritable;
2490
2491 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2492 permissions |= lldb::ePermissionsExecutable;
2493
2494 return true;
2495}
2496
Zachary Turner97206d52017-05-12 04:51:55 +00002497Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2498 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002499 error.SetErrorString("watchpoints are not supported");
2500 return error;
2501}
2502
Zachary Turner97206d52017-05-12 04:51:55 +00002503Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2504 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002505 error.SetErrorString("watchpoints are not supported");
2506 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002507}
2508
2509StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002510Process::WaitForProcessStopPrivate(EventSP &event_sp,
2511 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002512 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002513
Kate Stoneb9c1b512016-09-06 20:57:50 +00002514 while (true) {
2515 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002516 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002517
Kate Stoneb9c1b512016-09-06 20:57:50 +00002518 if (StateIsStoppedState(state, false))
2519 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002520
Kate Stoneb9c1b512016-09-06 20:57:50 +00002521 // If state is invalid, then we timed out
2522 if (state == eStateInvalid)
2523 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002524
Kate Stoneb9c1b512016-09-06 20:57:50 +00002525 if (event_sp)
2526 HandlePrivateEvent(event_sp);
2527 }
2528 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002529}
2530
Kate Stoneb9c1b512016-09-06 20:57:50 +00002531void Process::LoadOperatingSystemPlugin(bool flush) {
2532 if (flush)
2533 m_thread_list.Clear();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002534 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002535 if (flush)
2536 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002537}
2538
Zachary Turner97206d52017-05-12 04:51:55 +00002539Status Process::Launch(ProcessLaunchInfo &launch_info) {
2540 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002541 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002542 m_dyld_up.reset();
2543 m_jit_loaders_up.reset();
2544 m_system_runtime_up.reset();
2545 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002546 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002547
Kate Stoneb9c1b512016-09-06 20:57:50 +00002548 Module *exe_module = GetTarget().GetExecutableModulePointer();
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002549 if (!exe_module) {
2550 error.SetErrorString("executable module does not exist");
2551 return error;
2552 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002553
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002554 char local_exec_file_path[PATH_MAX];
2555 char platform_exec_file_path[PATH_MAX];
2556 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2557 sizeof(local_exec_file_path));
2558 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2559 sizeof(platform_exec_file_path));
2560 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2561 // Install anything that might need to be installed prior to launching.
2562 // For host systems, this will do nothing, but if we are connected to a
2563 // remote platform it will install any needed binaries
2564 error = GetTarget().Install(&launch_info);
2565 if (error.Fail())
2566 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002567
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002568 if (PrivateStateThreadIsValid())
2569 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002570
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002571 error = WillLaunch(exe_module);
2572 if (error.Success()) {
2573 const bool restarted = false;
2574 SetPublicState(eStateLaunching, restarted);
2575 m_should_detach = false;
2576
2577 if (m_public_run_lock.TrySetRunning()) {
2578 // Now launch using these arguments.
2579 error = DoLaunch(exe_module, launch_info);
2580 } else {
2581 // This shouldn't happen
2582 error.SetErrorString("failed to acquire process run lock");
2583 }
2584
2585 if (error.Fail()) {
2586 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2587 SetID(LLDB_INVALID_PROCESS_ID);
2588 const char *error_string = error.AsCString();
2589 if (error_string == nullptr)
2590 error_string = "launch failed";
2591 SetExitStatus(-1, error_string);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002592 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002593 } else {
2594 EventSP event_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002595
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002596 // Now wait for the process to launch and return control to us, and then
2597 // call DidLaunch:
2598 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Stella Stamenova36d457c2018-06-01 19:14:53 +00002599
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002600 if (state == eStateInvalid || !event_sp) {
2601 // We were able to launch the process, but we failed to catch the
2602 // initial stop.
2603 error.SetErrorString("failed to catch stop after launch");
2604 SetExitStatus(0, "failed to catch stop after launch");
2605 Destroy(false);
2606 } else if (state == eStateStopped || state == eStateCrashed) {
2607 DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002608
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002609 DynamicLoader *dyld = GetDynamicLoader();
2610 if (dyld)
2611 dyld->DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002612
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002613 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002614
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002615 SystemRuntime *system_runtime = GetSystemRuntime();
2616 if (system_runtime)
2617 system_runtime->DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002618
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002619 if (!m_os_up)
2620 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002621
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002622 // We successfully launched the process and stopped, now it the
2623 // right time to set up signal filters before resuming.
2624 UpdateAutomaticSignalFiltering();
Greg Clayton35824e32015-02-20 20:59:47 +00002625
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002626 // Note, the stop event was consumed above, but not handled. This
2627 // was done to give DidLaunch a chance to run. The target is either
2628 // stopped or crashed. Directly set the state. This is done to
2629 // prevent a stop message with a bunch of spurious output on thread
2630 // status, as well as not pop a ProcessIOHandler.
2631 SetPublicState(state, false);
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002632
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002633 if (PrivateStateThreadIsValid())
2634 ResumePrivateStateThread();
2635 else
2636 StartPrivateStateThread();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002637
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002638 // Target was stopped at entry as was intended. Need to notify the
2639 // listeners about it.
2640 if (state == eStateStopped &&
2641 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002642 HandlePrivateEvent(event_sp);
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002643 } else if (state == eStateExited) {
2644 // We exited while trying to launch somehow. Don't call DidLaunch
2645 // as that's not likely to work, and return an invalid pid.
2646 HandlePrivateEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002647 }
2648 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002649 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002650 } else {
2651 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2652 local_exec_file_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002653 }
Zachary Turner7e89b3c2019-03-08 00:11:27 +00002654
Kate Stoneb9c1b512016-09-06 20:57:50 +00002655 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002656}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002657
Zachary Turner97206d52017-05-12 04:51:55 +00002658Status Process::LoadCore() {
2659 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002660 if (error.Success()) {
2661 ListenerSP listener_sp(
2662 Listener::MakeListener("lldb.process.load_core_listener"));
2663 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002664
Kate Stoneb9c1b512016-09-06 20:57:50 +00002665 if (PrivateStateThreadIsValid())
2666 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002667 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002668 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002669
Kate Stoneb9c1b512016-09-06 20:57:50 +00002670 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002671 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002672 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002673
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002674 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002675
Kate Stoneb9c1b512016-09-06 20:57:50 +00002676 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002677 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002679
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002680 if (!m_os_up)
Greg Clayton29eeea02017-02-09 18:55:41 +00002681 LoadOperatingSystemPlugin(false);
2682
Kate Stoneb9c1b512016-09-06 20:57:50 +00002683 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002684 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002685 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002686
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002687 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002688 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002689 StateType state =
Pavel Labath7ada1c52019-06-25 07:14:29 +00002690 WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002691
2692 if (!StateIsStoppedState(state, false)) {
2693 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2694 if (log)
2695 log->Printf("Process::Halt() failed to stop, state is: %s",
2696 StateAsCString(state));
2697 error.SetErrorString(
2698 "Did not get stopped event after loading the core file.");
2699 }
2700 RestoreProcessEvents();
2701 }
2702 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002703}
2704
Kate Stoneb9c1b512016-09-06 20:57:50 +00002705DynamicLoader *Process::GetDynamicLoader() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002706 if (!m_dyld_up)
2707 m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2708 return m_dyld_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002709}
2710
Antonio Afonso943faef2019-06-11 20:16:13 +00002711DataExtractor Process::GetAuxvData() { return DataExtractor(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712
2713JITLoaderList &Process::GetJITLoaders() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002714 if (!m_jit_loaders_up) {
2715 m_jit_loaders_up.reset(new JITLoaderList());
2716 JITLoader::LoadPlugins(this, *m_jit_loaders_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002717 }
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002718 return *m_jit_loaders_up;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002719}
2720
2721SystemRuntime *Process::GetSystemRuntime() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002722 if (!m_system_runtime_up)
2723 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2724 return m_system_runtime_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725}
2726
2727Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2728 uint32_t exec_count)
2729 : NextEventAction(process), m_exec_count(exec_count) {
2730 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2731 if (log)
2732 log->Printf(
2733 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2734 __FUNCTION__, static_cast<void *>(process), exec_count);
2735}
2736
2737Process::NextEventAction::EventActionResult
2738Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2739 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2740
2741 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2742 if (log)
2743 log->Printf(
2744 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2745 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2746
2747 switch (state) {
2748 case eStateAttaching:
2749 return eEventActionSuccess;
2750
2751 case eStateRunning:
2752 case eStateConnected:
2753 return eEventActionRetry;
2754
2755 case eStateStopped:
2756 case eStateCrashed:
2757 // During attach, prior to sending the eStateStopped event,
2758 // lldb_private::Process subclasses must set the new process ID.
2759 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002760 // We don't want these events to be reported, so go set the
2761 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2763
2764 if (m_exec_count > 0) {
2765 --m_exec_count;
2766
2767 if (log)
2768 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2769 "remaining exec count to %" PRIu32 ", requesting resume",
2770 __FUNCTION__, StateAsCString(state), m_exec_count);
2771
2772 RequestResume();
2773 return eEventActionRetry;
2774 } else {
2775 if (log)
2776 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2777 "execs expected to start, continuing with attach",
2778 __FUNCTION__, StateAsCString(state));
2779
2780 m_process->CompleteAttach();
2781 return eEventActionSuccess;
2782 }
2783 break;
2784
2785 default:
2786 case eStateExited:
2787 case eStateInvalid:
2788 break;
2789 }
2790
2791 m_exit_string.assign("No valid Process");
2792 return eEventActionExit;
2793}
2794
2795Process::NextEventAction::EventActionResult
2796Process::AttachCompletionHandler::HandleBeingInterrupted() {
2797 return eEventActionSuccess;
2798}
2799
2800const char *Process::AttachCompletionHandler::GetExitString() {
2801 return m_exit_string.c_str();
2802}
2803
2804ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2805 if (m_listener_sp)
2806 return m_listener_sp;
2807 else
2808 return debugger.GetListener();
2809}
2810
Zachary Turner97206d52017-05-12 04:51:55 +00002811Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002812 m_abi_sp.reset();
2813 m_process_input_reader.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002814 m_dyld_up.reset();
2815 m_jit_loaders_up.reset();
2816 m_system_runtime_up.reset();
2817 m_os_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002818
2819 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002820 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2822 char process_name[PATH_MAX];
2823
2824 if (attach_info.GetExecutableFile().GetPath(process_name,
2825 sizeof(process_name))) {
2826 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2827
2828 if (wait_for_launch) {
2829 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2830 if (error.Success()) {
2831 if (m_public_run_lock.TrySetRunning()) {
2832 m_should_detach = true;
2833 const bool restarted = false;
2834 SetPublicState(eStateAttaching, restarted);
2835 // Now attach using these arguments.
2836 error = DoAttachToProcessWithName(process_name, attach_info);
2837 } else {
2838 // This shouldn't happen
2839 error.SetErrorString("failed to acquire process run lock");
2840 }
2841
2842 if (error.Fail()) {
2843 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2844 SetID(LLDB_INVALID_PROCESS_ID);
2845 if (error.AsCString() == nullptr)
2846 error.SetErrorString("attach failed");
2847
2848 SetExitStatus(-1, error.AsCString());
2849 }
2850 } else {
2851 SetNextEventAction(new Process::AttachCompletionHandler(
2852 this, attach_info.GetResumeCount()));
2853 StartPrivateStateThread();
2854 }
2855 return error;
2856 }
2857 } else {
2858 ProcessInstanceInfoList process_infos;
2859 PlatformSP platform_sp(GetTarget().GetPlatform());
2860
2861 if (platform_sp) {
2862 ProcessInstanceInfoMatch match_info;
2863 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00002864 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002865 platform_sp->FindProcesses(match_info, process_infos);
2866 const uint32_t num_matches = process_infos.GetSize();
2867 if (num_matches == 1) {
2868 attach_pid = process_infos.GetProcessIDAtIndex(0);
2869 // Fall through and attach using the above process ID
2870 } else {
2871 match_info.GetProcessInfo().GetExecutableFile().GetPath(
2872 process_name, sizeof(process_name));
2873 if (num_matches > 1) {
2874 StreamString s;
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002875 ProcessInstanceInfo::DumpTableHeader(s, true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876 for (size_t i = 0; i < num_matches; i++) {
2877 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
Pavel Labathaa51e6a2019-03-04 18:48:00 +00002878 s, platform_sp->GetUserIDResolver(), true, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002879 }
2880 error.SetErrorStringWithFormat(
2881 "more than one process named %s:\n%s", process_name,
2882 s.GetData());
2883 } else
2884 error.SetErrorStringWithFormat(
2885 "could not find a process named %s", process_name);
2886 }
2887 } else {
2888 error.SetErrorString(
2889 "invalid platform, can't find processes by name");
2890 return error;
2891 }
2892 }
2893 } else {
2894 error.SetErrorString("invalid process name");
2895 }
2896 }
2897
2898 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2899 error = WillAttachToProcessWithID(attach_pid);
2900 if (error.Success()) {
2901
2902 if (m_public_run_lock.TrySetRunning()) {
2903 // Now attach using these arguments.
2904 m_should_detach = true;
2905 const bool restarted = false;
2906 SetPublicState(eStateAttaching, restarted);
2907 error = DoAttachToProcessWithID(attach_pid, attach_info);
2908 } else {
2909 // This shouldn't happen
2910 error.SetErrorString("failed to acquire process run lock");
2911 }
2912
2913 if (error.Success()) {
2914 SetNextEventAction(new Process::AttachCompletionHandler(
2915 this, attach_info.GetResumeCount()));
2916 StartPrivateStateThread();
2917 } else {
Greg Clayton71337622011-02-24 22:24:29 +00002918 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002919 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002920
Kate Stoneb9c1b512016-09-06 20:57:50 +00002921 const char *error_string = error.AsCString();
2922 if (error_string == nullptr)
2923 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00002924
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 SetExitStatus(-1, error_string);
2926 }
Greg Claytonb766a732011-02-04 01:58:07 +00002927 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002928 }
2929 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00002930}
2931
Kate Stoneb9c1b512016-09-06 20:57:50 +00002932void Process::CompleteAttach() {
2933 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2934 LIBLLDB_LOG_TARGET));
2935 if (log)
2936 log->Printf("Process::%s()", __FUNCTION__);
2937
2938 // Let the process subclass figure out at much as it can about the process
2939 // before we go looking for a dynamic loader plug-in.
2940 ArchSpec process_arch;
2941 DidAttach(process_arch);
2942
2943 if (process_arch.IsValid()) {
2944 GetTarget().SetArchitecture(process_arch);
2945 if (log) {
2946 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
2947 log->Printf("Process::%s replacing process architecture with DidAttach() "
2948 "architecture: %s",
2949 __FUNCTION__, triple_str ? triple_str : "<null>");
2950 }
2951 }
2952
2953 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00002954 // architecture, and if it isn't the same as the one we've already set,
2955 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002956 PlatformSP platform_sp(GetTarget().GetPlatform());
2957 assert(platform_sp);
2958 if (platform_sp) {
2959 const ArchSpec &target_arch = GetTarget().GetArchitecture();
2960 if (target_arch.IsValid() &&
2961 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2962 ArchSpec platform_arch;
2963 platform_sp =
2964 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2965 if (platform_sp) {
2966 GetTarget().SetPlatform(platform_sp);
2967 GetTarget().SetArchitecture(platform_arch);
2968 if (log)
2969 log->Printf("Process::%s switching platform to %s and architecture "
2970 "to %s based on info from attach",
2971 __FUNCTION__, platform_sp->GetName().AsCString(""),
2972 platform_arch.GetTriple().getTriple().c_str());
2973 }
2974 } else if (!process_arch.IsValid()) {
2975 ProcessInstanceInfo process_info;
2976 GetProcessInfo(process_info);
2977 const ArchSpec &process_arch = process_info.GetArchitecture();
2978 if (process_arch.IsValid() &&
2979 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
2980 GetTarget().SetArchitecture(process_arch);
2981 if (log)
2982 log->Printf("Process::%s switching architecture to %s based on info "
2983 "the platform retrieved for pid %" PRIu64,
2984 __FUNCTION__,
2985 process_arch.GetTriple().getTriple().c_str(), GetID());
2986 }
2987 }
2988 }
2989
2990 // We have completed the attach, now it is time to find the dynamic loader
2991 // plug-in
2992 DynamicLoader *dyld = GetDynamicLoader();
2993 if (dyld) {
2994 dyld->DidAttach();
2995 if (log) {
2996 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2997 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
2998 "executable is %s (using %s plugin)",
2999 __FUNCTION__,
3000 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3001 : "<none>",
3002 dyld->GetPluginName().AsCString("<unnamed>"));
3003 }
3004 }
3005
3006 GetJITLoaders().DidAttach();
3007
3008 SystemRuntime *system_runtime = GetSystemRuntime();
3009 if (system_runtime) {
3010 system_runtime->DidAttach();
3011 if (log) {
3012 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3013 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3014 "executable is %s (using %s plugin)",
3015 __FUNCTION__,
3016 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3017 : "<none>",
3018 system_runtime->GetPluginName().AsCString("<unnamed>"));
3019 }
3020 }
3021
Jim Ingham8864b432019-06-28 17:57:19 +00003022 if (!m_os_up) {
Greg Clayton29eeea02017-02-09 18:55:41 +00003023 LoadOperatingSystemPlugin(false);
Jim Ingham8864b432019-06-28 17:57:19 +00003024 if (m_os_up) {
3025 // Somebody might have gotten threads before now, but we need to force the
3026 // update after we've loaded the OperatingSystem plugin or it won't get a
3027 // chance to process the threads.
3028 m_thread_list.Clear();
3029 UpdateThreadListIfNeeded();
3030 }
3031 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003032 // Figure out which one is the executable, and set that in our target:
3033 const ModuleList &target_modules = GetTarget().GetImages();
3034 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3035 size_t num_modules = target_modules.GetSize();
3036 ModuleSP new_executable_module_sp;
3037
3038 for (size_t i = 0; i < num_modules; i++) {
3039 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3040 if (module_sp && module_sp->IsExecutable()) {
3041 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3042 new_executable_module_sp = module_sp;
3043 break;
3044 }
3045 }
3046 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00003047 GetTarget().SetExecutableModule(new_executable_module_sp,
3048 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003049 if (log) {
3050 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3051 log->Printf(
3052 "Process::%s after looping through modules, target executable is %s",
3053 __FUNCTION__,
3054 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3055 : "<none>");
3056 }
3057 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003058}
3059
Zachary Turner97206d52017-05-12 04:51:55 +00003060Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003061 m_abi_sp.reset();
3062 m_process_input_reader.reset();
3063
3064 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003065 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003066
Zachary Turner97206d52017-05-12 04:51:55 +00003067 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003068 if (error.Success()) {
3069 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3070 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003071 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003072
3073 if (state == eStateStopped || state == eStateCrashed) {
3074 // If we attached and actually have a process on the other end, then
3075 // this ended up being the equivalent of an attach.
3076 CompleteAttach();
3077
3078 // This delays passing the stopped event to listeners till
3079 // CompleteAttach gets a chance to complete...
3080 HandlePrivateEvent(event_sp);
3081 }
3082 }
3083
3084 if (PrivateStateThreadIsValid())
3085 ResumePrivateStateThread();
3086 else
3087 StartPrivateStateThread();
3088 }
3089 return error;
3090}
3091
Zachary Turner97206d52017-05-12 04:51:55 +00003092Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3094 LIBLLDB_LOG_STEP));
3095 if (log)
3096 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3097 "private state: %s",
3098 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3099 StateAsCString(m_private_state.GetValue()));
3100
Adrian Prantl05097242018-04-30 16:49:04 +00003101 // If signals handing status changed we might want to update our signal
3102 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003103 UpdateAutomaticSignalFiltering();
3104
Zachary Turner97206d52017-05-12 04:51:55 +00003105 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003106 // Tell the process it is about to resume before the thread list
3107 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003108 // Now let the thread list know we are about to resume so it can let all of
3109 // our threads know that they are about to be resumed. Threads will each be
3110 // called with Thread::WillResume(StateType) where StateType contains the
3111 // state that they are supposed to have when the process is resumed
3112 // (suspended/running/stepping). Threads should also check their resume
3113 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3114 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003115 if (m_thread_list.WillResume()) {
3116 // Last thing, do the PreResumeActions.
3117 if (!RunPreResumeActions()) {
3118 error.SetErrorStringWithFormat(
3119 "Process::PrivateResume PreResumeActions failed, not resuming.");
3120 } else {
3121 m_mod_id.BumpResumeID();
3122 error = DoResume();
3123 if (error.Success()) {
3124 DidResume();
3125 m_thread_list.DidResume();
3126 if (log)
3127 log->Printf("Process thinks the process has resumed.");
Jason Molendaf47c7342018-12-17 23:33:40 +00003128 } else {
3129 if (log)
3130 log->Printf(
3131 "Process::PrivateResume() DoResume failed.");
3132 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003133 }
3134 }
3135 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003136 // Somebody wanted to run without running (e.g. we were faking a step
3137 // from one frame of a set of inlined frames that share the same PC to
3138 // another.) So generate a continue & a stopped event, and let the world
3139 // handle them.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140 if (log)
3141 log->Printf(
3142 "Process::PrivateResume() asked to simulate a start & stop.");
3143
3144 SetPrivateState(eStateRunning);
3145 SetPrivateState(eStateStopped);
3146 }
3147 } else if (log)
3148 log->Printf("Process::PrivateResume() got an error \"%s\".",
3149 error.AsCString("<unknown error>"));
3150 return error;
3151}
3152
Zachary Turner97206d52017-05-12 04:51:55 +00003153Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003154 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003155 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003156
Adrian Prantl05097242018-04-30 16:49:04 +00003157 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3158 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003159 m_clear_thread_plans_on_stop |= clear_thread_plans;
3160
3161 ListenerSP halt_listener_sp(
3162 Listener::MakeListener("lldb.process.halt_listener"));
3163 HijackProcessEvents(halt_listener_sp);
3164
3165 EventSP event_sp;
3166
3167 SendAsyncInterrupt();
3168
3169 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003170 // Don't hijack and eat the eStateExited as the code that was doing the
3171 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003172 RestoreProcessEvents();
3173 SetExitStatus(SIGKILL, "Cancelled async attach.");
3174 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003175 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003176 }
3177
3178 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003179 StateType state = WaitForProcessToStop(
3180 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003181 RestoreProcessEvents();
3182
3183 if (state == eStateInvalid || !event_sp) {
3184 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003185 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003186 }
3187
3188 BroadcastEvent(event_sp);
3189
Zachary Turner97206d52017-05-12 04:51:55 +00003190 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003191}
3192
Zachary Turner97206d52017-05-12 04:51:55 +00003193Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3194 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003195
3196 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003197 // expression, for instance, then the public state will be stopped, but we
3198 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003199 if (m_public_state.GetValue() == eStateRunning ||
3200 m_private_state.GetValue() == eStateRunning) {
3201 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003202 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003203 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003204
Kate Stoneb9c1b512016-09-06 20:57:50 +00003205 ListenerSP listener_sp(
3206 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3207 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003208
Pavel Labath19da1f12015-12-07 12:36:52 +00003209 SendAsyncInterrupt();
3210
Kate Stoneb9c1b512016-09-06 20:57:50 +00003211 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003212 StateType state =
3213 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003214
Pavel Labath19da1f12015-12-07 12:36:52 +00003215 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003216
Kate Stoneb9c1b512016-09-06 20:57:50 +00003217 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003218 // exited event into the shared pointer passed in and return. Our caller
3219 // doesn't need to do anything else, since they don't have a process
3220 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003221
3222 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3223 if (log)
3224 log->Printf("Process::%s() Process exited while waiting to stop.",
3225 __FUNCTION__);
3226 return error;
3227 } else
3228 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3229
3230 if (state != eStateStopped) {
3231 if (log)
3232 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3233 StateAsCString(state));
3234 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003235 // here, but if the lower levels just bobbled sending the event and we
3236 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003237 StateType private_state = m_private_state.GetValue();
3238 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003239 return Status(
3240 "Attempt to stop the target in order to detach timed out. "
3241 "State = %s",
3242 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003243 }
3244 }
3245 }
3246 return error;
3247}
3248
Zachary Turner97206d52017-05-12 04:51:55 +00003249Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003250 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003251 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003252 m_destroy_in_process = true;
3253
3254 error = WillDetach();
3255
3256 if (error.Success()) {
3257 if (DetachRequiresHalt()) {
3258 error = StopForDestroyOrDetach(exit_event_sp);
3259 if (!error.Success()) {
3260 m_destroy_in_process = false;
3261 return error;
3262 } else if (exit_event_sp) {
3263 // We shouldn't need to do anything else here. There's no process left
3264 // to detach from...
3265 StopPrivateStateThread();
3266 m_destroy_in_process = false;
3267 return error;
3268 }
3269 }
3270
3271 m_thread_list.DiscardThreadPlans();
3272 DisableAllBreakpointSites();
3273
3274 error = DoDetach(keep_stopped);
3275 if (error.Success()) {
3276 DidDetach();
3277 StopPrivateStateThread();
3278 } else {
3279 return error;
3280 }
3281 }
3282 m_destroy_in_process = false;
3283
Adrian Prantl05097242018-04-30 16:49:04 +00003284 // If we exited when we were waiting for a process to stop, then forward the
3285 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003286 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003287 // Directly broadcast our exited event because we shut down our private
3288 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003289 BroadcastEvent(exit_event_sp);
3290 }
3291
3292 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003293 // not end up propagating the last events through the event system, in which
3294 // case we might strand the write lock. Unlock it here so when we do to tear
3295 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003296
3297 m_public_run_lock.SetStopped();
3298 return error;
3299}
3300
Zachary Turner97206d52017-05-12 04:51:55 +00003301Status Process::Destroy(bool force_kill) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003302
3303 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003304 // don't do any unnecessary work that might hinder the destruction. Remember
3305 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003306 // failed and the process stays around for some reason it won't be in a
3307 // confused state.
3308
3309 if (force_kill)
3310 m_should_detach = false;
3311
3312 if (GetShouldDetach()) {
3313 // FIXME: This will have to be a process setting:
3314 bool keep_stopped = false;
3315 Detach(keep_stopped);
3316 }
3317
3318 m_destroy_in_process = true;
3319
Zachary Turner97206d52017-05-12 04:51:55 +00003320 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003321 if (error.Success()) {
3322 EventSP exit_event_sp;
3323 if (DestroyRequiresHalt()) {
3324 error = StopForDestroyOrDetach(exit_event_sp);
3325 }
3326
3327 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003328 // Ditch all thread plans, and remove all our breakpoints: in case we
3329 // have to restart the target to kill it, we don't want it hitting a
3330 // breakpoint... Only do this if we've stopped, however, since if we
3331 // didn't manage to halt it above, then we're not going to have much luck
3332 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003333 m_thread_list.DiscardThreadPlans();
3334 DisableAllBreakpointSites();
3335 }
3336
3337 error = DoDestroy();
3338 if (error.Success()) {
3339 DidDestroy();
3340 StopPrivateStateThread();
3341 }
3342 m_stdio_communication.Disconnect();
3343 m_stdio_communication.StopReadThread();
3344 m_stdin_forward = false;
3345
3346 if (m_process_input_reader) {
3347 m_process_input_reader->SetIsDone(true);
3348 m_process_input_reader->Cancel();
3349 m_process_input_reader.reset();
3350 }
3351
Adrian Prantl05097242018-04-30 16:49:04 +00003352 // If we exited when we were waiting for a process to stop, then forward
3353 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003354 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003355 // Directly broadcast our exited event because we shut down our private
3356 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003357 BroadcastEvent(exit_event_sp);
3358 }
3359
Adrian Prantl05097242018-04-30 16:49:04 +00003360 // If we have been interrupted (to kill us) in the middle of running, we
3361 // may not end up propagating the last events through the event system, in
3362 // which case we might strand the write lock. Unlock it here so when we do
3363 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003364 m_public_run_lock.SetStopped();
3365 }
3366
3367 m_destroy_in_process = false;
3368
3369 return error;
3370}
3371
Zachary Turner97206d52017-05-12 04:51:55 +00003372Status Process::Signal(int signal) {
3373 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003374 if (error.Success()) {
3375 error = DoSignal(signal);
3376 if (error.Success())
3377 DidSignal();
3378 }
3379 return error;
3380}
3381
3382void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3383 assert(signals_sp && "null signals_sp");
3384 m_unix_signals_sp = signals_sp;
3385}
3386
3387const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3388 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3389 return m_unix_signals_sp;
3390}
3391
3392lldb::ByteOrder Process::GetByteOrder() const {
3393 return GetTarget().GetArchitecture().GetByteOrder();
3394}
3395
3396uint32_t Process::GetAddressByteSize() const {
3397 return GetTarget().GetArchitecture().GetAddressByteSize();
3398}
3399
3400bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3401 const StateType state =
3402 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3403 bool return_value = true;
3404 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3405 LIBLLDB_LOG_PROCESS));
3406
3407 switch (state) {
3408 case eStateDetached:
3409 case eStateExited:
3410 case eStateUnloaded:
3411 m_stdio_communication.SynchronizeWithReadThread();
3412 m_stdio_communication.Disconnect();
3413 m_stdio_communication.StopReadThread();
3414 m_stdin_forward = false;
3415
3416 LLVM_FALLTHROUGH;
3417 case eStateConnected:
3418 case eStateAttaching:
3419 case eStateLaunching:
3420 // These events indicate changes in the state of the debugging session,
3421 // always report them.
3422 return_value = true;
3423 break;
3424 case eStateInvalid:
3425 // We stopped for no apparent reason, don't report it.
3426 return_value = false;
3427 break;
3428 case eStateRunning:
3429 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003430 // If we've started the target running, we handle the cases where we are
3431 // already running and where there is a transition from stopped to running
3432 // differently. running -> running: Automatically suppress extra running
3433 // events stopped -> running: Report except when there is one or more no
3434 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003435 // and no yes votes.
3436 SynchronouslyNotifyStateChanged(state);
3437 if (m_force_next_event_delivery)
3438 return_value = true;
3439 else {
3440 switch (m_last_broadcast_state) {
3441 case eStateRunning:
3442 case eStateStepping:
3443 // We always suppress multiple runnings with no PUBLIC stop in between.
3444 return_value = false;
3445 break;
3446 default:
3447 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003448 // run if we aren't running so we don't miss any running events. If I
3449 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3450 // and hit the breakpoints on multiple threads, then somehow during the
3451 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003452
3453 // This is a transition from stop to run.
3454 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3455 case eVoteYes:
3456 case eVoteNoOpinion:
3457 return_value = true;
3458 break;
3459 case eVoteNo:
3460 return_value = false;
3461 break;
3462 }
3463 break;
3464 }
3465 }
3466 break;
3467 case eStateStopped:
3468 case eStateCrashed:
3469 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003470 // We've stopped. First see if we're going to restart the target. If we
3471 // are going to stop, then we always broadcast the event. If we aren't
3472 // going to stop, let the thread plans decide if we're going to report this
3473 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003474
3475 m_stdio_communication.SynchronizeWithReadThread();
3476 RefreshStateAfterStop();
3477 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3478 if (log)
3479 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3480 "interrupt, state: %s",
3481 static_cast<void *>(event_ptr), StateAsCString(state));
3482 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003483 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003484 m_thread_list.ShouldStop(event_ptr);
3485 return_value = true;
3486 } else {
3487 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3488 bool should_resume = false;
3489
3490 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003491 // restarted... Asking the thread list is also not likely to go well,
3492 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003493
3494 if (!was_restarted)
3495 should_resume = !m_thread_list.ShouldStop(event_ptr);
3496
3497 if (was_restarted || should_resume || m_resume_requested) {
3498 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3499 if (log)
3500 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3501 "%s was_restarted: %i stop_vote: %d.",
3502 should_resume, StateAsCString(state), was_restarted,
3503 stop_vote);
3504
3505 switch (stop_vote) {
3506 case eVoteYes:
3507 return_value = true;
3508 break;
3509 case eVoteNoOpinion:
3510 case eVoteNo:
3511 return_value = false;
3512 break;
3513 }
3514
3515 if (!was_restarted) {
3516 if (log)
3517 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3518 "from state: %s",
3519 static_cast<void *>(event_ptr), StateAsCString(state));
3520 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3521 PrivateResume();
3522 }
3523 } else {
3524 return_value = true;
3525 SynchronouslyNotifyStateChanged(state);
3526 }
3527 }
3528 break;
3529 }
3530
3531 // Forcing the next event delivery is a one shot deal. So reset it here.
3532 m_force_next_event_delivery = false;
3533
3534 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003535 // events get coalesced.) But we only coalesce against events we actually
3536 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3537 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3538 // done, because the PublicState reflects the last event pulled off the
3539 // queue, and there may be several events stacked up on the queue unserviced.
3540 // So the PublicState may not reflect the last broadcasted event yet.
3541 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003542
3543 if (return_value)
3544 m_last_broadcast_state = state;
3545
3546 if (log)
3547 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3548 "broadcast state: %s - %s",
3549 static_cast<void *>(event_ptr), StateAsCString(state),
3550 StateAsCString(m_last_broadcast_state),
3551 return_value ? "YES" : "NO");
3552 return return_value;
3553}
3554
3555bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3556 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3557
3558 bool already_running = PrivateStateThreadIsValid();
3559 if (log)
3560 log->Printf("Process::%s()%s ", __FUNCTION__,
3561 already_running ? " already running"
3562 : " starting private state thread");
3563
3564 if (!is_secondary_thread && already_running)
3565 return true;
3566
Adrian Prantl05097242018-04-30 16:49:04 +00003567 // Create a thread that watches our internal state and controls which events
3568 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003569 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003570 uint32_t max_len = llvm::get_max_thread_name_length();
3571 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003572 // On platforms with abbreviated thread name lengths, choose thread names
3573 // that fit within the limit.
3574 if (already_running)
3575 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3576 else
3577 snprintf(thread_name, sizeof(thread_name), "intern-state");
3578 } else {
3579 if (already_running)
3580 snprintf(thread_name, sizeof(thread_name),
3581 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3582 GetID());
3583 else
3584 snprintf(thread_name, sizeof(thread_name),
3585 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3586 }
3587
3588 // Create the private state thread, and start it running.
3589 PrivateStateThreadArgs *args_ptr =
3590 new PrivateStateThreadArgs(this, is_secondary_thread);
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003591 llvm::Expected<HostThread> private_state_thread =
Kate Stoneb9c1b512016-09-06 20:57:50 +00003592 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003593 (void *)args_ptr, 8 * 1024 * 1024);
3594 if (!private_state_thread) {
3595 LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3596 "failed to launch host thread: {}",
3597 llvm::toString(private_state_thread.takeError()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003598 return false;
Jonas Devliegheref39c2e12019-07-05 17:42:08 +00003599 }
3600
3601 assert(private_state_thread->IsJoinable());
3602 m_private_state_thread = *private_state_thread;
3603 ResumePrivateStateThread();
3604 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003605}
3606
3607void Process::PausePrivateStateThread() {
3608 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3609}
3610
3611void Process::ResumePrivateStateThread() {
3612 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3613}
3614
3615void Process::StopPrivateStateThread() {
3616 if (m_private_state_thread.IsJoinable())
3617 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3618 else {
3619 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3620 if (log)
3621 log->Printf(
3622 "Went to stop the private state thread, but it was already invalid.");
3623 }
3624}
3625
3626void Process::ControlPrivateStateThread(uint32_t signal) {
3627 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3628
3629 assert(signal == eBroadcastInternalStateControlStop ||
3630 signal == eBroadcastInternalStateControlPause ||
3631 signal == eBroadcastInternalStateControlResume);
3632
3633 if (log)
3634 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3635
3636 // Signal the private state thread
3637 if (m_private_state_thread.IsJoinable()) {
3638 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003639 // It is important to do this outside of the if below, because it's
3640 // possible that the thread state is invalid but that the thread is waiting
3641 // on a control event instead of simply being on its way out (this should
3642 // not happen, but it apparently can).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003643 if (log)
3644 log->Printf("Sending control event of type: %d.", signal);
3645 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3646 m_private_state_control_broadcaster.BroadcastEvent(signal,
3647 event_receipt_sp);
3648
3649 // Wait for the event receipt or for the private state thread to exit
3650 bool receipt_received = false;
3651 if (PrivateStateThreadIsValid()) {
3652 while (!receipt_received) {
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003653 // Check for a receipt for n seconds and then check if the private
Adrian Prantl05097242018-04-30 16:49:04 +00003654 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003655 receipt_received =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00003656 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003657 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003658 // Check if the private state thread is still around. If it isn't
3659 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003660 if (!PrivateStateThreadIsValid())
3661 break; // Private state thread exited or is exiting, we are done
3662 }
3663 }
3664 }
3665
3666 if (signal == eBroadcastInternalStateControlStop) {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003667 thread_result_t result = {};
Kate Stoneb9c1b512016-09-06 20:57:50 +00003668 m_private_state_thread.Join(&result);
3669 m_private_state_thread.Reset();
3670 }
3671 } else {
3672 if (log)
3673 log->Printf(
3674 "Private state thread already dead, no need to signal it to stop.");
3675 }
3676}
3677
3678void Process::SendAsyncInterrupt() {
3679 if (PrivateStateThreadIsValid())
3680 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3681 nullptr);
3682 else
3683 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3684}
3685
3686void Process::HandlePrivateEvent(EventSP &event_sp) {
3687 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3688 m_resume_requested = false;
3689
3690 const StateType new_state =
3691 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3692
3693 // First check to see if anybody wants a shot at this event:
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003694 if (m_next_event_action_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003695 NextEventAction::EventActionResult action_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003696 m_next_event_action_up->PerformAction(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003697 if (log)
3698 log->Printf("Ran next event action, result was %d.", action_result);
3699
3700 switch (action_result) {
3701 case NextEventAction::eEventActionSuccess:
3702 SetNextEventAction(nullptr);
3703 break;
3704
3705 case NextEventAction::eEventActionRetry:
3706 break;
3707
3708 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003709 // Handle Exiting Here. If we already got an exited event, we should
3710 // just propagate it. Otherwise, swallow this event, and set our state
3711 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003712 if (new_state != eStateExited) {
3713 // FIXME: should cons up an exited event, and discard this one.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003714 SetExitStatus(0, m_next_event_action_up->GetExitString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003715 SetNextEventAction(nullptr);
3716 return;
3717 }
3718 SetNextEventAction(nullptr);
3719 break;
3720 }
3721 }
3722
3723 // See if we should broadcast this state to external clients?
3724 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3725
3726 if (should_broadcast) {
3727 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3728 if (log) {
3729 log->Printf("Process::%s (pid = %" PRIu64
3730 ") broadcasting new state %s (old state %s) to %s",
3731 __FUNCTION__, GetID(), StateAsCString(new_state),
3732 StateAsCString(GetState()),
3733 is_hijacked ? "hijacked" : "public");
3734 }
3735 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3736 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003737 // Only push the input handler if we aren't fowarding events, as this
3738 // means the curses GUI is in use... Or don't push it if we are launching
3739 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003740 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3741 new_state != eStateLaunching && new_state != eStateAttaching) {
3742 PushProcessIOHandler();
3743 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3744 eBroadcastAlways);
3745 if (log)
3746 log->Printf("Process::%s updated m_iohandler_sync to %d",
3747 __FUNCTION__, m_iohandler_sync.GetValue());
3748 }
3749 } else if (StateIsStoppedState(new_state, false)) {
3750 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003751 // If the lldb_private::Debugger is handling the events, we don't want
3752 // to pop the process IOHandler here, we want to do it when we receive
3753 // the stopped event so we can carefully control when the process
3754 // IOHandler is popped because when we stop we want to display some
3755 // text stating how and why we stopped, then maybe some
3756 // process/thread/frame info, and then we want the "(lldb) " prompt to
3757 // show up. If we pop the process IOHandler here, then we will cause
3758 // the command interpreter to become the top IOHandler after the
3759 // process pops off and it will update its prompt right away... See the
3760 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003761 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3762 // Otherwise we end up getting overlapping "(lldb) " prompts and
3763 // garbled output.
3764 //
3765 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003766 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3767 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003768 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003769 // thread plans, or when commands want to run in synchronous mode and
3770 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003771 // that will hijack the events is a simple expression:
3772 //
3773 // (lldb) expr (int)puts("hello")
3774 //
3775 // This will cause the internal process state thread to resume and halt
3776 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3777 // events) and we do need the IO handler to be pushed and popped
3778 // correctly.
3779
3780 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3781 PopProcessIOHandler();
3782 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003783 }
3784
3785 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003786 } else {
3787 if (log) {
3788 log->Printf(
3789 "Process::%s (pid = %" PRIu64
3790 ") suppressing state %s (old state %s): should_broadcast == false",
3791 __FUNCTION__, GetID(), StateAsCString(new_state),
3792 StateAsCString(GetState()));
3793 }
3794 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003795}
3796
Zachary Turner97206d52017-05-12 04:51:55 +00003797Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003798 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003799 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003800 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003801 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003802
3803 // Ask the process subclass to actually halt our process
3804 bool caused_stop;
3805 error = DoHalt(caused_stop);
3806
3807 DidHalt();
3808 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003809}
3810
Kate Stoneb9c1b512016-09-06 20:57:50 +00003811thread_result_t Process::PrivateStateThread(void *arg) {
3812 std::unique_ptr<PrivateStateThreadArgs> args_up(
3813 static_cast<PrivateStateThreadArgs *>(arg));
3814 thread_result_t result =
3815 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3816 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003817}
3818
Kate Stoneb9c1b512016-09-06 20:57:50 +00003819thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3820 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003821
Kate Stoneb9c1b512016-09-06 20:57:50 +00003822 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3823 if (log)
3824 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3825 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003826
Kate Stoneb9c1b512016-09-06 20:57:50 +00003827 bool exit_now = false;
3828 bool interrupt_requested = false;
3829 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003830 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003831 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003832 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3833 if (log)
3834 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3835 ") got a control event: %d",
3836 __FUNCTION__, static_cast<void *>(this), GetID(),
3837 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003838
Kate Stoneb9c1b512016-09-06 20:57:50 +00003839 switch (event_sp->GetType()) {
3840 case eBroadcastInternalStateControlStop:
3841 exit_now = true;
3842 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003843
Kate Stoneb9c1b512016-09-06 20:57:50 +00003844 case eBroadcastInternalStateControlPause:
3845 control_only = true;
3846 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003847
Kate Stoneb9c1b512016-09-06 20:57:50 +00003848 case eBroadcastInternalStateControlResume:
3849 control_only = false;
3850 break;
3851 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003852
Kate Stoneb9c1b512016-09-06 20:57:50 +00003853 continue;
3854 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3855 if (m_public_state.GetValue() == eStateAttaching) {
3856 if (log)
3857 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3858 ") woke up with an interrupt while attaching - "
3859 "forwarding interrupt.",
3860 __FUNCTION__, static_cast<void *>(this), GetID());
3861 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3862 } else if (StateIsRunningState(m_last_broadcast_state)) {
3863 if (log)
3864 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3865 ") woke up with an interrupt - Halting.",
3866 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00003867 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003868 if (error.Fail() && log)
3869 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3870 ") failed to halt the process: %s",
3871 __FUNCTION__, static_cast<void *>(this), GetID(),
3872 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00003873 // Halt should generate a stopped event. Make a note of the fact that
3874 // we were doing the interrupt, so we can set the interrupted flag
3875 // after we receive the event. We deliberately set this to true even if
3876 // HaltPrivate failed, so that we can interrupt on the next natural
3877 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003878 interrupt_requested = true;
3879 } else {
3880 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00003881 // running and sends an interrupt request, but the process actually
3882 // stops before we receive it. In that case, we can just ignore the
3883 // request. We use m_last_broadcast_state, because the Stopped event
3884 // may not have been popped of the event queue yet, which is when the
3885 // public state gets updated.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003886 if (log)
3887 log->Printf(
3888 "Process::%s ignoring interrupt as we have already stopped.",
3889 __FUNCTION__);
3890 }
3891 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003892 }
3893
Kate Stoneb9c1b512016-09-06 20:57:50 +00003894 const StateType internal_state =
3895 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003896
Kate Stoneb9c1b512016-09-06 20:57:50 +00003897 if (internal_state != eStateInvalid) {
3898 if (m_clear_thread_plans_on_stop &&
3899 StateIsStoppedState(internal_state, true)) {
3900 m_clear_thread_plans_on_stop = false;
3901 m_thread_list.DiscardThreadPlans();
3902 }
3903
3904 if (interrupt_requested) {
3905 if (StateIsStoppedState(internal_state, true)) {
3906 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00003907 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00003908 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3909 interrupt_requested = false;
3910 } else if (log) {
3911 log->Printf("Process::%s interrupt_requested, but a non-stopped "
3912 "state '%s' received.",
3913 __FUNCTION__, StateAsCString(internal_state));
3914 }
3915 }
3916
3917 HandlePrivateEvent(event_sp);
3918 }
3919
3920 if (internal_state == eStateInvalid || internal_state == eStateExited ||
3921 internal_state == eStateDetached) {
3922 if (log)
3923 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3924 ") about to exit with internal state %s...",
3925 __FUNCTION__, static_cast<void *>(this), GetID(),
3926 StateAsCString(internal_state));
3927
3928 break;
3929 }
3930 }
3931
3932 // Verify log is still enabled before attempting to write to it...
3933 if (log)
3934 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3935 __FUNCTION__, static_cast<void *>(this), GetID());
3936
3937 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00003938 // will have already acquired the public_run_lock, and isn't done with what
3939 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003940 if (!is_secondary_thread)
3941 m_public_run_lock.SetStopped();
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00003942 return {};
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003943}
3944
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003945// Process Event Data
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003946
Kate Stoneb9c1b512016-09-06 20:57:50 +00003947Process::ProcessEventData::ProcessEventData()
3948 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3949 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003950
Kate Stoneb9c1b512016-09-06 20:57:50 +00003951Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3952 StateType state)
3953 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3954 m_update_state(0), m_interrupted(false) {
3955 if (process_sp)
3956 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003957}
3958
Eugene Zelenko8f30a652015-10-23 18:39:37 +00003959Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003960
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003961ConstString Process::ProcessEventData::GetFlavorString() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003962 static ConstString g_flavor("Process::ProcessEventData");
3963 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003964}
3965
Adrian Prantl0e4c4822019-03-06 21:22:25 +00003966ConstString Process::ProcessEventData::GetFlavor() const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003967 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003968}
3969
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3971 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00003972
Kate Stoneb9c1b512016-09-06 20:57:50 +00003973 if (!process_sp)
3974 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003975
Kate Stoneb9c1b512016-09-06 20:57:50 +00003976 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00003977 // pulled off of the private process event queue, and then any number of
3978 // times, first when it gets pulled off of the public event queue, then other
3979 // times when we're pretending that this is where we stopped at the end of
3980 // expression evaluation. m_update_state is used to distinguish these three
3981 // cases; it is 0 when we're just pulling it off for private handling, and >
3982 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00003983 // command handling then.
3984 if (m_update_state != 1)
3985 return;
3986
3987 process_sp->SetPublicState(
3988 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
3989
Jason Molendab3a3cd12016-12-08 06:27:29 +00003990 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00003991 // Let process subclasses know we are about to do a public stop and do
3992 // anything they might need to in order to speed up register and memory
3993 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00003994 process_sp->WillPublicStop();
3995 }
3996
Kate Stoneb9c1b512016-09-06 20:57:50 +00003997 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00003998 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
3999 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00004000 // end up restarting the process.
4001 if (m_interrupted)
4002 return;
4003
4004 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4005 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004006 ThreadList &curr_thread_list = process_sp->GetThreadList();
4007 uint32_t num_threads = curr_thread_list.GetSize();
4008 uint32_t idx;
4009
4010 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00004011 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004012
4013 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00004014 // target has run (except for expressions) and immediately exit, but if we
4015 // get that wrong (which is possible) then the thread list might have
4016 // changed, and that would cause our iteration here to crash. We could
4017 // make a copy of the thread list, but we'd really like to also know if it
4018 // has changed at all, so we make up a vector of the thread ID's and check
4019 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004020 std::vector<uint32_t> thread_index_array(num_threads);
4021 for (idx = 0; idx < num_threads; ++idx)
4022 thread_index_array[idx] =
4023 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4024
4025 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00004026 // continue the target running if no thread says we should stop. Of course
4027 // if some thread's PerformAction actually sets the target running, then it
4028 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004029
4030 bool still_should_stop = false;
4031
4032 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00004033 // we stop but no thread has a valid stop reason. In that case we should
4034 // just stop, because we have no way of telling what the right thing to do
4035 // is, and it's better to let the user decide than continue behind their
4036 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004037
4038 bool does_anybody_have_an_opinion = false;
4039
4040 for (idx = 0; idx < num_threads; ++idx) {
4041 curr_thread_list = process_sp->GetThreadList();
4042 if (curr_thread_list.GetSize() != num_threads) {
4043 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4044 LIBLLDB_LOG_PROCESS));
4045 if (log)
4046 log->Printf(
4047 "Number of threads changed from %u to %u while processing event.",
4048 num_threads, curr_thread_list.GetSize());
4049 break;
4050 }
4051
4052 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4053
4054 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4055 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4056 LIBLLDB_LOG_PROCESS));
4057 if (log)
4058 log->Printf("The thread at position %u changed from %u to %u while "
4059 "processing event.",
4060 idx, thread_index_array[idx], thread_sp->GetIndexID());
4061 break;
4062 }
4063
4064 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4065 if (stop_info_sp && stop_info_sp->IsValid()) {
4066 does_anybody_have_an_opinion = true;
4067 bool this_thread_wants_to_stop;
4068 if (stop_info_sp->GetOverrideShouldStop()) {
4069 this_thread_wants_to_stop =
4070 stop_info_sp->GetOverriddenShouldStopValue();
4071 } else {
4072 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00004073 // The stop action might restart the target. If it does, then we
4074 // want to mark that in the event so that whoever is receiving it
4075 // will know to wait for the running event and reflect that state
4076 // appropriately. We also need to stop processing actions, since they
4077 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004078
4079 // FIXME: we might have run.
4080 if (stop_info_sp->HasTargetRunSinceMe()) {
4081 SetRestarted(true);
4082 break;
4083 }
4084
4085 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004086 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004087
4088 if (!still_should_stop)
4089 still_should_stop = this_thread_wants_to_stop;
4090 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004091 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004092
4093 if (!GetRestarted()) {
4094 if (!still_should_stop && does_anybody_have_an_opinion) {
4095 // We've been asked to continue, so do that here.
4096 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004097 // Use the public resume method here, since this is just extending a
4098 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004099 process_sp->PrivateResume();
4100 } else {
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004101 bool hijacked =
4102 process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4103 !process_sp->StateChangedIsHijackedForSynchronousResume();
Jim Ingham3139fc92019-03-01 18:13:38 +00004104
4105 if (!hijacked) {
4106 // If we didn't restart, run the Stop Hooks here.
4107 // Don't do that if state changed events aren't hooked up to the
Jonas Devlieghereedb52e22019-05-23 20:25:49 +00004108 // public (or SyncResume) broadcasters. StopHooks are just for
4109 // real public stops. They might also restart the target,
Jim Ingham3139fc92019-03-01 18:13:38 +00004110 // so watch for that.
4111 process_sp->GetTarget().RunStopHooks();
4112 if (process_sp->GetPrivateState() == eStateRunning)
4113 SetRestarted(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004114 }
4115 }
4116 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004117}
Zachary Turner805e7102019-03-04 21:51:03 +00004118}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004119
Kate Stoneb9c1b512016-09-06 20:57:50 +00004120void Process::ProcessEventData::Dump(Stream *s) const {
4121 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004122
Kate Stoneb9c1b512016-09-06 20:57:50 +00004123 if (process_sp)
4124 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4125 static_cast<void *>(process_sp.get()), process_sp->GetID());
4126 else
4127 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004128
Kate Stoneb9c1b512016-09-06 20:57:50 +00004129 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004130}
4131
4132const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004133Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4134 if (event_ptr) {
4135 const EventData *event_data = event_ptr->GetData();
4136 if (event_data &&
4137 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4138 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4139 }
4140 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004141}
4142
4143ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004144Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4145 ProcessSP process_sp;
4146 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4147 if (data)
4148 process_sp = data->GetProcessSP();
4149 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004150}
4151
Kate Stoneb9c1b512016-09-06 20:57:50 +00004152StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4153 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4154 if (data == nullptr)
4155 return eStateInvalid;
4156 else
4157 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004158}
4159
Kate Stoneb9c1b512016-09-06 20:57:50 +00004160bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4161 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4162 if (data == nullptr)
4163 return false;
4164 else
4165 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004166}
4167
Kate Stoneb9c1b512016-09-06 20:57:50 +00004168void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4169 bool new_value) {
4170 ProcessEventData *data =
4171 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4172 if (data != nullptr)
4173 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004174}
4175
Jim Ingham0161b492013-02-09 01:29:05 +00004176size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004177Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4178 ProcessEventData *data =
4179 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4180 if (data != nullptr)
4181 return data->GetNumRestartedReasons();
4182 else
4183 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004184}
4185
4186const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004187Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4188 size_t idx) {
4189 ProcessEventData *data =
4190 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4191 if (data != nullptr)
4192 return data->GetRestartedReasonAtIndex(idx);
4193 else
4194 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004195}
4196
Kate Stoneb9c1b512016-09-06 20:57:50 +00004197void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4198 const char *reason) {
4199 ProcessEventData *data =
4200 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4201 if (data != nullptr)
4202 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004203}
4204
Kate Stoneb9c1b512016-09-06 20:57:50 +00004205bool Process::ProcessEventData::GetInterruptedFromEvent(
4206 const Event *event_ptr) {
4207 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4208 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004209 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004210 else
4211 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004212}
4213
Kate Stoneb9c1b512016-09-06 20:57:50 +00004214void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4215 bool new_value) {
4216 ProcessEventData *data =
4217 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4218 if (data != nullptr)
4219 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004220}
4221
Kate Stoneb9c1b512016-09-06 20:57:50 +00004222bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4223 ProcessEventData *data =
4224 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4225 if (data) {
4226 data->SetUpdateStateOnRemoval();
4227 return true;
4228 }
4229 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004230}
4231
Jim Inghamb87b9e62018-06-26 23:38:58 +00004232lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004233
4234void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4235 exe_ctx.SetTargetPtr(&GetTarget());
4236 exe_ctx.SetProcessPtr(this);
4237 exe_ctx.SetThreadPtr(nullptr);
4238 exe_ctx.SetFramePtr(nullptr);
4239}
4240
4241// uint32_t
4242// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4243// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004244//{
4245// return 0;
4246//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004247//
4248// ArchSpec
4249// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004250//{
4251// return Host::GetArchSpecForExistingProcess (pid);
4252//}
4253//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004254// ArchSpec
4255// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004256//{
4257// return Host::GetArchSpecForExistingProcess (process_name);
4258//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004259
Kate Stoneb9c1b512016-09-06 20:57:50 +00004260void Process::AppendSTDOUT(const char *s, size_t len) {
4261 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4262 m_stdout_data.append(s, len);
4263 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4264 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004265}
4266
Kate Stoneb9c1b512016-09-06 20:57:50 +00004267void Process::AppendSTDERR(const char *s, size_t len) {
4268 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4269 m_stderr_data.append(s, len);
4270 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4271 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004272}
4273
Kate Stoneb9c1b512016-09-06 20:57:50 +00004274void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4275 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4276 m_profile_data.push_back(one_profile_data);
4277 BroadcastEventIfUnique(eBroadcastBitProfileData,
4278 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004279}
4280
Kate Stoneb9c1b512016-09-06 20:57:50 +00004281void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4282 const StructuredDataPluginSP &plugin_sp) {
4283 BroadcastEvent(
4284 eBroadcastBitStructuredData,
4285 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004286}
4287
4288StructuredDataPluginSP
Adrian Prantl0e4c4822019-03-06 21:22:25 +00004289Process::GetStructuredDataPlugin(ConstString type_name) const {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004290 auto find_it = m_structured_data_plugin_map.find(type_name);
4291 if (find_it != m_structured_data_plugin_map.end())
4292 return find_it->second;
4293 else
4294 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004295}
4296
Zachary Turner97206d52017-05-12 04:51:55 +00004297size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004298 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4299 if (m_profile_data.empty())
4300 return 0;
4301
4302 std::string &one_profile_data = m_profile_data.front();
4303 size_t bytes_available = one_profile_data.size();
4304 if (bytes_available > 0) {
4305 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4306 if (log)
4307 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4308 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4309 if (bytes_available > buf_size) {
4310 memcpy(buf, one_profile_data.c_str(), buf_size);
4311 one_profile_data.erase(0, buf_size);
4312 bytes_available = buf_size;
4313 } else {
4314 memcpy(buf, one_profile_data.c_str(), bytes_available);
4315 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004316 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004317 }
4318 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004319}
4320
Greg Clayton93e86192011-11-13 04:45:22 +00004321// Process STDIO
Greg Clayton93e86192011-11-13 04:45:22 +00004322
Zachary Turner97206d52017-05-12 04:51:55 +00004323size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004324 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4325 size_t bytes_available = m_stdout_data.size();
4326 if (bytes_available > 0) {
4327 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4328 if (log)
4329 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4330 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4331 if (bytes_available > buf_size) {
4332 memcpy(buf, m_stdout_data.c_str(), buf_size);
4333 m_stdout_data.erase(0, buf_size);
4334 bytes_available = buf_size;
4335 } else {
4336 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4337 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004338 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004339 }
4340 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004341}
4342
Zachary Turner97206d52017-05-12 04:51:55 +00004343size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004344 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4345 size_t bytes_available = m_stderr_data.size();
4346 if (bytes_available > 0) {
4347 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4348 if (log)
4349 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4350 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4351 if (bytes_available > buf_size) {
4352 memcpy(buf, m_stderr_data.c_str(), buf_size);
4353 m_stderr_data.erase(0, buf_size);
4354 bytes_available = buf_size;
4355 } else {
4356 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4357 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004358 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004359 }
4360 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004361}
4362
Kate Stoneb9c1b512016-09-06 20:57:50 +00004363void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4364 size_t src_len) {
4365 Process *process = (Process *)baton;
4366 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004367}
4368
Kate Stoneb9c1b512016-09-06 20:57:50 +00004369class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004370public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004371 IOHandlerProcessSTDIO(Process *process, int write_fd)
4372 : IOHandler(process->GetTarget().GetDebugger(),
4373 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004374 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004375 m_pipe.CreateNew(false);
4376 m_read_file.SetDescriptor(GetInputFD(), false);
4377 }
4378
4379 ~IOHandlerProcessSTDIO() override = default;
4380
Adrian Prantl05097242018-04-30 16:49:04 +00004381 // Each IOHandler gets to run until it is done. It should read data from the
4382 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004383 void Run() override {
4384 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4385 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4386 SetIsDone(true);
4387 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004388 }
4389
Kate Stoneb9c1b512016-09-06 20:57:50 +00004390 SetIsDone(false);
4391 const int read_fd = m_read_file.GetDescriptor();
4392 TerminalState terminal_state;
4393 terminal_state.Save(read_fd, false);
4394 Terminal terminal(read_fd);
4395 terminal.SetCanonical(false);
4396 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004397// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004398#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004399 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4400 m_is_running = true;
4401 while (!GetIsDone()) {
4402 SelectHelper select_helper;
4403 select_helper.FDSetRead(read_fd);
4404 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004405 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004406
Kate Stoneb9c1b512016-09-06 20:57:50 +00004407 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004408 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004409 } else {
4410 char ch = 0;
4411 size_t n;
4412 if (select_helper.FDIsSetRead(read_fd)) {
4413 n = 1;
4414 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4415 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4416 SetIsDone(true);
4417 } else
4418 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004419 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004420 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4421 size_t bytes_read;
4422 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004423 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004424 if (error.Success()) {
4425 switch (ch) {
4426 case 'q':
4427 SetIsDone(true);
4428 break;
4429 case 'i':
4430 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004431 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004432 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004433 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004434 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004435 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004436 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004437 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004438 m_is_running = false;
4439#endif
4440 terminal_state.Restore();
4441 }
4442
4443 void Cancel() override {
4444 SetIsDone(true);
4445 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004446 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4447 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004448 //
4449 // (lldb) step_process_thousands_of_times
4450 //
4451 // In this case the command interpreter will be in the middle of handling
4452 // the command and if the process pushes and pops the IOHandler thousands
4453 // of times, we can end up writing to m_pipe without ever consuming the
4454 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4455 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4456 if (m_is_running) {
4457 char ch = 'q'; // Send 'q' for quit
4458 size_t bytes_written = 0;
4459 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004460 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004461 }
4462
4463 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004464 // Do only things that are safe to do in an interrupt context (like in a
4465 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004466 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4467 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004468 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004469 if (m_active) {
4470 char ch = 'i'; // Send 'i' for interrupt
4471 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004472 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004473 return result.Success();
4474 } else {
4475 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004476 // currently so do the right thing if we aren't actively watching for
4477 // STDIN by sending the interrupt to the process. Otherwise the write to
4478 // the pipe above would do nothing. This can happen when the command
4479 // interpreter is running and gets a "expression ...". It will be on the
4480 // IOHandler thread and sending the input is complete to the delegate
4481 // which will cause the expression to run, which will push the process IO
4482 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004483
4484 if (StateIsRunningState(m_process->GetState())) {
4485 m_process->SendAsyncInterrupt();
4486 return true;
4487 }
4488 }
4489 return false;
4490 }
4491
4492 void GotEOF() override {}
4493
Greg Clayton44d93782014-01-27 23:43:24 +00004494protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004495 Process *m_process;
4496 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4497 File m_write_file; // Write to this file (usually the master pty for getting
4498 // io to debuggee)
4499 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004500 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004501};
4502
Kate Stoneb9c1b512016-09-06 20:57:50 +00004503void Process::SetSTDIOFileDescriptor(int fd) {
4504 // First set up the Read Thread for reading/handling process I/O
4505
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004506 std::unique_ptr<ConnectionFileDescriptor> conn_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004507 new ConnectionFileDescriptor(fd, true));
4508
Jonas Devlieghered5b44032019-02-13 06:25:41 +00004509 if (conn_up) {
4510 m_stdio_communication.SetConnection(conn_up.release());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004511 if (m_stdio_communication.IsConnected()) {
4512 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4513 STDIOReadThreadBytesReceived, this);
4514 m_stdio_communication.StartReadThread();
4515
4516 // Now read thread is set up, set up input reader.
4517
4518 if (!m_process_input_reader)
Jonas Devlieghere796ac802019-02-11 23:13:08 +00004519 m_process_input_reader =
4520 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004521 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004522 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004523}
4524
Kate Stoneb9c1b512016-09-06 20:57:50 +00004525bool Process::ProcessIOHandlerIsActive() {
4526 IOHandlerSP io_handler_sp(m_process_input_reader);
4527 if (io_handler_sp)
4528 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4529 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004530}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004531bool Process::PushProcessIOHandler() {
4532 IOHandlerSP io_handler_sp(m_process_input_reader);
4533 if (io_handler_sp) {
4534 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4535 if (log)
4536 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004537
Kate Stoneb9c1b512016-09-06 20:57:50 +00004538 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004539 // If we evaluate an utility function, then we don't cancel the current
4540 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4541 // existing IOHandler that potentially provides the user interface (e.g.
4542 // the IOHandler for Editline).
4543 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4544 GetTarget().GetDebugger().PushIOHandler(io_handler_sp, cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004545 return true;
4546 }
4547 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004548}
4549
Kate Stoneb9c1b512016-09-06 20:57:50 +00004550bool Process::PopProcessIOHandler() {
4551 IOHandlerSP io_handler_sp(m_process_input_reader);
4552 if (io_handler_sp)
4553 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4554 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004555}
4556
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004557// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004558void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004559
Kate Stoneb9c1b512016-09-06 20:57:50 +00004560void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004561
Kate Stoneb9c1b512016-09-06 20:57:50 +00004562namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004563// RestorePlanState is used to record the "is private", "is master" and "okay
4564// to discard" fields of the plan we are running, and reset it on Clean or on
4565// destruction. It will only reset the state once, so you can call Clean and
4566// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004567
Kate Stoneb9c1b512016-09-06 20:57:50 +00004568class RestorePlanState {
4569public:
4570 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4571 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4572 if (m_thread_plan_sp) {
4573 m_private = m_thread_plan_sp->GetPrivate();
4574 m_is_master = m_thread_plan_sp->IsMasterPlan();
4575 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4576 }
4577 }
4578
4579 ~RestorePlanState() { Clean(); }
4580
4581 void Clean() {
4582 if (!m_already_reset && m_thread_plan_sp) {
4583 m_already_reset = true;
4584 m_thread_plan_sp->SetPrivate(m_private);
4585 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4586 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4587 }
4588 }
4589
4590private:
4591 lldb::ThreadPlanSP m_thread_plan_sp;
4592 bool m_already_reset;
4593 bool m_private;
4594 bool m_is_master;
4595 bool m_okay_to_discard;
4596};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004597} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004598
Pavel Labath2ce22162016-12-01 10:57:30 +00004599static microseconds
4600GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4601 const milliseconds default_one_thread_timeout(250);
4602
4603 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004604 if (!options.GetTimeout()) {
4605 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4606 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004607 }
4608
4609 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004610 if (options.GetOneThreadTimeout())
4611 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004612
4613 // Otherwise use half the total timeout, bounded by the
4614 // default_one_thread_timeout.
4615 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004616 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004617}
4618
4619static Timeout<std::micro>
4620GetExpressionTimeout(const EvaluateExpressionOptions &options,
4621 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004622 // If we are going to run all threads the whole time, or if we are only going
4623 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004624 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004625 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004626
4627 if (before_first_timeout)
4628 return GetOneThreadExpressionTimeout(options);
4629
Pavel Labath43d35412016-12-06 11:24:51 +00004630 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004631 return llvm::None;
4632 else
Pavel Labath43d35412016-12-06 11:24:51 +00004633 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004634}
4635
Pavel Labath45dde232017-05-25 10:50:06 +00004636static llvm::Optional<ExpressionResults>
4637HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4638 RestorePlanState &restorer, const EventSP &event_sp,
4639 EventSP &event_to_broadcast_sp,
4640 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4641 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4642
4643 ThreadPlanSP plan = thread.GetCompletedPlan();
4644 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4645 LLDB_LOG(log, "execution completed successfully");
4646
4647 // Restore the plan state so it will get reported as intended when we are
4648 // done.
4649 restorer.Clean();
4650 return eExpressionCompleted;
4651 }
4652
4653 StopInfoSP stop_info_sp = thread.GetStopInfo();
4654 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4655 stop_info_sp->ShouldNotify(event_sp.get())) {
4656 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4657 if (!options.DoesIgnoreBreakpoints()) {
4658 // Restore the plan state and then force Private to false. We are going
4659 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004660 // it won't report correctly when we continue to its termination later
4661 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004662 restorer.Clean();
4663 thread_plan_sp->SetPrivate(false);
4664 event_to_broadcast_sp = event_sp;
4665 }
4666 return eExpressionHitBreakpoint;
4667 }
4668
4669 if (!handle_interrupts &&
4670 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4671 return llvm::None;
4672
4673 LLDB_LOG(log, "thread plan did not successfully complete");
4674 if (!options.DoesUnwindOnError())
4675 event_to_broadcast_sp = event_sp;
4676 return eExpressionInterrupted;
4677}
4678
Jim Ingham1624a2d2014-05-05 02:26:40 +00004679ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004680Process::RunThreadPlan(ExecutionContext &exe_ctx,
4681 lldb::ThreadPlanSP &thread_plan_sp,
4682 const EvaluateExpressionOptions &options,
4683 DiagnosticManager &diagnostic_manager) {
4684 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004685
Kate Stoneb9c1b512016-09-06 20:57:50 +00004686 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4687
4688 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004689 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004690 eDiagnosticSeverityError,
4691 "RunThreadPlan called with empty thread plan.");
4692 return eExpressionSetupError;
4693 }
4694
4695 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004696 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004697 eDiagnosticSeverityError,
4698 "RunThreadPlan called with an invalid thread plan.");
4699 return eExpressionSetupError;
4700 }
4701
4702 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004703 diagnostic_manager.PutString(eDiagnosticSeverityError,
4704 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004705 return eExpressionSetupError;
4706 }
4707
4708 Thread *thread = exe_ctx.GetThreadPtr();
4709 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004710 diagnostic_manager.PutString(eDiagnosticSeverityError,
4711 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004712 return eExpressionSetupError;
4713 }
4714
4715 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004716 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004717
4718 RestorePlanState thread_plan_restorer(thread_plan_sp);
4719
Adrian Prantl05097242018-04-30 16:49:04 +00004720 // We rely on the thread plan we are running returning "PlanCompleted" if
4721 // when it successfully completes. For that to be true the plan can't be
4722 // private - since private plans suppress themselves in the GetCompletedPlan
4723 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004724
4725 thread_plan_sp->SetPrivate(false);
4726
4727 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004728 // when they are done we will end up asking the plan above us whether we
4729 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004730
4731 thread_plan_sp->SetIsMasterPlan(true);
4732 thread_plan_sp->SetOkayToDiscard(false);
4733
Raphael Isemannc01783a2018-08-29 22:50:54 +00004734 // If we are running some utility expression for LLDB, we now have to mark
4735 // this in the ProcesModID of this process. This RAII takes care of marking
4736 // and reverting the mark it once we are done running the expression.
4737 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4738
Kate Stoneb9c1b512016-09-06 20:57:50 +00004739 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004740 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004741 eDiagnosticSeverityError,
4742 "RunThreadPlan called while the private state was not stopped.");
4743 return eExpressionSetupError;
4744 }
4745
4746 // Save the thread & frame from the exe_ctx for restoration after we run
4747 const uint32_t thread_idx_id = thread->GetIndexID();
4748 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4749 if (!selected_frame_sp) {
4750 thread->SetSelectedFrame(nullptr);
4751 selected_frame_sp = thread->GetSelectedFrame();
4752 if (!selected_frame_sp) {
4753 diagnostic_manager.Printf(
4754 eDiagnosticSeverityError,
4755 "RunThreadPlan called without a selected frame on thread %d",
4756 thread_idx_id);
4757 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004758 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004759 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004760
Adrian Prantl05097242018-04-30 16:49:04 +00004761 // Make sure the timeout values make sense. The one thread timeout needs to
4762 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004763 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4764 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004765 diagnostic_manager.PutString(eDiagnosticSeverityError,
4766 "RunThreadPlan called with one thread "
4767 "timeout greater than total timeout");
4768 return eExpressionSetupError;
4769 }
4770
Kate Stoneb9c1b512016-09-06 20:57:50 +00004771 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004772
Kate Stoneb9c1b512016-09-06 20:57:50 +00004773 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004774 // We don't want to do that either, so we should arrange to reset them as
4775 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004776
Kate Stoneb9c1b512016-09-06 20:57:50 +00004777 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004778
Kate Stoneb9c1b512016-09-06 20:57:50 +00004779 uint32_t selected_tid;
4780 StackID selected_stack_id;
4781 if (selected_thread_sp) {
4782 selected_tid = selected_thread_sp->GetIndexID();
4783 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4784 } else {
4785 selected_tid = LLDB_INVALID_THREAD_ID;
4786 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004787
Kate Stoneb9c1b512016-09-06 20:57:50 +00004788 HostThread backup_private_state_thread;
4789 lldb::StateType old_state = eStateInvalid;
4790 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004791
Kate Stoneb9c1b512016-09-06 20:57:50 +00004792 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4793 LIBLLDB_LOG_PROCESS));
4794 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4795 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004796 // public events on this thread, since we are the thread that is generating
4797 // public events. The simplest thing to do is to spin up a temporary thread
4798 // to handle private state thread events while we are fielding public
4799 // events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004800 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004801 log->Printf("Running thread plan on private state thread, spinning up "
4802 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004803
Kate Stoneb9c1b512016-09-06 20:57:50 +00004804 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004805
Kate Stoneb9c1b512016-09-06 20:57:50 +00004806 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004807 // anything it pushes, and then stop, returning control here. But in the
4808 // normal course of things, the plan above us on the stack would be given a
4809 // shot at the stop event before deciding to stop, and we don't want that.
4810 // So we insert a "stopper" base plan on the stack before the plan we want
4811 // to run. Since base plans always stop and return control to the user,
4812 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004813 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4814 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4815 // Have to make sure our public state is stopped, since otherwise the
4816 // reporting logic below doesn't work correctly.
4817 old_state = m_public_state.GetValue();
4818 m_public_state.SetValueNoLock(eStateStopped);
4819
4820 // Now spin up the private state thread:
4821 StartPrivateStateThread(true);
4822 }
4823
4824 thread->QueueThreadPlan(
4825 thread_plan_sp, false); // This used to pass "true" does that make sense?
4826
4827 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004828 // In this case, we aren't actually going to run, we just want to stop
4829 // right away. Flush this thread so we will refetch the stacks and show the
4830 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004831 // FIXME: To make this prettier we should invent some stop reason for this,
4832 // but that
4833 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004834 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004835 thread->Flush();
4836 return eExpressionStoppedForDebug;
4837 }
4838
4839 ListenerSP listener_sp(
4840 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4841
4842 lldb::EventSP event_to_broadcast_sp;
4843
4844 {
4845 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004846 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004847 //
4848 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004849 // exits during execution), then the event is put into
4850 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004851
4852 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4853
4854 if (log) {
4855 StreamString s;
4856 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4857 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4858 " to run thread plan \"%s\".",
4859 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00004860 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004861
4862 bool got_event;
4863 lldb::EventSP event_sp;
4864 lldb::StateType stop_state = lldb::eStateInvalid;
4865
4866 bool before_first_timeout = true; // This is set to false the first time
4867 // that we have to halt the target.
4868 bool do_resume = true;
4869 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004870
4871 // This is just for accounting:
4872 uint32_t num_resumes = 0;
4873
Kate Stoneb9c1b512016-09-06 20:57:50 +00004874 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00004875 // going to run one thread, then we don't need the first timeout. So we
4876 // pretend we are after the first timeout already.
4877 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00004878 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00004879
Kate Stoneb9c1b512016-09-06 20:57:50 +00004880 if (log)
Pavel Labath2ce22162016-12-01 10:57:30 +00004881 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
4882 options.GetStopOthers(), options.GetTryAllThreads(),
4883 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004884
Adrian Prantl05097242018-04-30 16:49:04 +00004885 // This isn't going to work if there are unfetched events on the queue. Are
4886 // there cases where we might want to run the remaining events here, and
4887 // then try to call the function? That's probably being too tricky for our
4888 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004889
4890 Event *other_events = listener_sp->PeekAtNextEvent();
4891 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004892 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004893 eDiagnosticSeverityError,
4894 "RunThreadPlan called with pending events on the queue.");
4895 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00004896 }
4897
Kate Stoneb9c1b512016-09-06 20:57:50 +00004898 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00004899 // calling a function as part of a thread plan, in which case the last
4900 // delivered event could be the running event, and we don't want event
4901 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004902 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00004903
Kate Stoneb9c1b512016-09-06 20:57:50 +00004904// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00004905// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00004906
Kate Stoneb9c1b512016-09-06 20:57:50 +00004907#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00004908 // It's pretty much impossible to write test cases for things like: One
4909 // thread timeout expires, I go to halt, but the process already stopped on
4910 // the function call stop breakpoint. Turning on this define will make us
4911 // not fetch the first event till after the halt. So if you run a quick
4912 // function, it will have completed, and the completion event will be
4913 // waiting, when you interrupt for halt. The expression evaluation should
4914 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004915 bool miss_first_event = true;
4916#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00004917 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00004918 // We usually want to resume the process if we get to the top of the
4919 // loop. The only exception is if we get two running events with no
4920 // intervening stop, which can happen, we will just wait for then next
4921 // stop event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004922 if (log)
4923 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
4924 "before_first_timeout: %i.",
4925 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00004926
Kate Stoneb9c1b512016-09-06 20:57:50 +00004927 if (do_resume || handle_running_event) {
4928 // Do the initial resume and wait for the running event before going
4929 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00004930
Kate Stoneb9c1b512016-09-06 20:57:50 +00004931 if (do_resume) {
4932 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00004933 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004934 if (!resume_error.Success()) {
4935 diagnostic_manager.Printf(
4936 eDiagnosticSeverityError,
4937 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4938 resume_error.AsCString());
4939 return_value = eExpressionSetupError;
4940 break;
4941 }
Jason Molendaef7d6412015-08-06 03:27:10 +00004942 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004943
Pavel Labathd35031e12016-11-30 10:41:42 +00004944 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00004945 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00004946 if (!got_event) {
4947 if (log)
4948 log->Printf("Process::RunThreadPlan(): didn't get any event after "
4949 "resume %" PRIu32 ", exiting.",
4950 num_resumes);
4951
4952 diagnostic_manager.Printf(eDiagnosticSeverityError,
4953 "didn't get any event after resume %" PRIu32
4954 ", exiting.",
4955 num_resumes);
4956 return_value = eExpressionSetupError;
4957 break;
4958 }
4959
4960 stop_state =
4961 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4962
4963 if (stop_state != eStateRunning) {
4964 bool restarted = false;
4965
4966 if (stop_state == eStateStopped) {
4967 restarted = Process::ProcessEventData::GetRestartedFromEvent(
4968 event_sp.get());
4969 if (log)
4970 log->Printf(
4971 "Process::RunThreadPlan(): didn't get running event after "
4972 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4973 "handle_running_event: %i).",
4974 num_resumes, StateAsCString(stop_state), restarted, do_resume,
4975 handle_running_event);
4976 }
4977
4978 if (restarted) {
4979 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00004980 // should ever get a stopped & restarted event here. But if I do,
4981 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004982 const bool clear_thread_plans = false;
4983 const bool use_run_lock = false;
4984 Halt(clear_thread_plans, use_run_lock);
4985 }
4986
4987 diagnostic_manager.Printf(
4988 eDiagnosticSeverityError,
4989 "didn't get running event after initial resume, got %s instead.",
4990 StateAsCString(stop_state));
4991 return_value = eExpressionSetupError;
4992 break;
4993 }
4994
4995 if (log)
4996 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00004997 // We need to call the function synchronously, so spin waiting for it
4998 // to return. If we get interrupted while executing, we're going to
4999 // lose our context, and won't be able to gather the result at this
5000 // point. We set the timeout AFTER the resume, since the resume takes
5001 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005002 } else {
5003 if (log)
5004 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5005 }
5006
Kate Stoneb9c1b512016-09-06 20:57:50 +00005007 do_resume = true;
5008 handle_running_event = true;
5009
5010 // Now wait for the process to stop again:
5011 event_sp.reset();
5012
Pavel Labath2ce22162016-12-01 10:57:30 +00005013 Timeout<std::micro> timeout =
5014 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005015 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005016 if (timeout) {
5017 auto now = system_clock::now();
5018 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5019 "endpoint is %s",
5020 llvm::to_string(now).c_str(),
5021 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005022 } else {
5023 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005024 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005025 }
5026
5027#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5028 // See comment above...
5029 if (miss_first_event) {
5030 usleep(1000);
5031 miss_first_event = false;
5032 got_event = false;
5033 } else
5034#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005035 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005036
5037 if (got_event) {
5038 if (event_sp) {
5039 bool keep_going = false;
5040 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5041 const bool clear_thread_plans = false;
5042 const bool use_run_lock = false;
5043 Halt(clear_thread_plans, use_run_lock);
5044 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005045 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5046 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005047 if (log)
5048 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5049 "eBroadcastBitInterrupted, exiting.");
5050 break;
5051 } else {
5052 stop_state =
5053 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5054 if (log)
5055 log->Printf(
5056 "Process::RunThreadPlan(): in while loop, got event: %s.",
5057 StateAsCString(stop_state));
5058
5059 switch (stop_state) {
5060 case lldb::eStateStopped: {
5061 // We stopped, figure out what we are going to do now.
5062 ThreadSP thread_sp =
5063 GetThreadList().FindThreadByIndexID(thread_idx_id);
5064 if (!thread_sp) {
5065 // Ooh, our thread has vanished. Unlikely that this was
5066 // successful execution...
5067 if (log)
5068 log->Printf("Process::RunThreadPlan(): execution completed "
5069 "but our thread (index-id=%u) has vanished.",
5070 thread_idx_id);
5071 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00005072 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5073 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005074 // If we were restarted, we just need to go back up to fetch
5075 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00005076 if (log) {
5077 log->Printf("Process::RunThreadPlan(): Got a stop and "
5078 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005079 }
Pavel Labath45dde232017-05-25 10:50:06 +00005080 keep_going = true;
5081 do_resume = false;
5082 handle_running_event = true;
5083 } else {
5084 const bool handle_interrupts = true;
5085 return_value = *HandleStoppedEvent(
5086 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5087 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005088 }
5089 } break;
5090
5091 case lldb::eStateRunning:
5092 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005093 // running events without an intervening stop, and in that case
5094 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005095 do_resume = false;
5096 keep_going = true;
5097 handle_running_event = false;
5098 break;
5099
5100 default:
5101 if (log)
5102 log->Printf("Process::RunThreadPlan(): execution stopped with "
5103 "unexpected state: %s.",
5104 StateAsCString(stop_state));
5105
5106 if (stop_state == eStateExited)
5107 event_to_broadcast_sp = event_sp;
5108
Zachary Turnere2411fa2016-11-12 19:12:56 +00005109 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005110 eDiagnosticSeverityError,
5111 "execution stopped with unexpected state.");
5112 return_value = eExpressionInterrupted;
5113 break;
5114 }
5115 }
5116
5117 if (keep_going)
5118 continue;
5119 else
5120 break;
5121 } else {
5122 if (log)
5123 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5124 "the event pointer was null. How odd...");
5125 return_value = eExpressionInterrupted;
5126 break;
5127 }
5128 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005129 // If we didn't get an event that means we've timed out... We will
5130 // interrupt the process here. Depending on what we were asked to do
5131 // we will either exit, or try with all threads running for the same
5132 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005133
5134 if (log) {
5135 if (options.GetTryAllThreads()) {
5136 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005137 LLDB_LOG(log,
5138 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005139 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005140 LLDB_LOG(log, "Restarting function with all threads enabled and "
5141 "timeout: {0} timed out, abandoning execution.",
5142 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005143 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005144 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5145 "abandoning execution.",
5146 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005147 }
5148
5149 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005150 // around to calling Halt the target could have stopped. That's fine,
5151 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005152 // BUT it is also possible that we stopped & restarted (e.g. hit a
5153 // signal with "stop" set to false.) In
5154 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005155 // back to waiting for the Halt's stopped event. That's what this
5156 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005157
5158 bool back_to_top = true;
5159 uint32_t try_halt_again = 0;
5160 bool do_halt = true;
5161 const uint32_t num_retries = 5;
5162 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005163 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005164 if (do_halt) {
5165 if (log)
5166 log->Printf("Process::RunThreadPlan(): Running Halt.");
5167 const bool clear_thread_plans = false;
5168 const bool use_run_lock = false;
5169 Halt(clear_thread_plans, use_run_lock);
5170 }
5171 if (halt_error.Success()) {
5172 if (log)
5173 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5174
Pavel Labathd35031e12016-11-30 10:41:42 +00005175 got_event =
Adrian Prantl4c03ea12019-04-05 22:43:42 +00005176 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005177
5178 if (got_event) {
5179 stop_state =
5180 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5181 if (log) {
5182 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5183 StateAsCString(stop_state));
5184 if (stop_state == lldb::eStateStopped &&
5185 Process::ProcessEventData::GetInterruptedFromEvent(
5186 event_sp.get()))
5187 log->PutCString(" Event was the Halt interruption event.");
5188 }
5189
5190 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005191 if (Process::ProcessEventData::GetRestartedFromEvent(
5192 event_sp.get())) {
5193 if (log)
5194 log->PutCString("Process::RunThreadPlan(): Went to halt "
5195 "but got a restarted event, there must be "
5196 "an un-restarted stopped event so try "
5197 "again... "
5198 "Exiting wait loop.");
5199 try_halt_again++;
5200 do_halt = false;
5201 continue;
5202 }
5203
Pavel Labath45dde232017-05-25 10:50:06 +00005204 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005205 // delivered it, the process could have already finished its
5206 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005207 const bool handle_interrupts = false;
5208 if (auto result = HandleStoppedEvent(
5209 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5210 event_to_broadcast_sp, options, handle_interrupts)) {
5211 return_value = *result;
5212 back_to_top = false;
5213 break;
5214 }
5215
Kate Stoneb9c1b512016-09-06 20:57:50 +00005216 if (!options.GetTryAllThreads()) {
5217 if (log)
5218 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5219 "was false, we stopped so now we're "
5220 "quitting.");
5221 return_value = eExpressionInterrupted;
5222 back_to_top = false;
5223 break;
5224 }
5225
5226 if (before_first_timeout) {
5227 // Set all the other threads to run, and return to the top of
5228 // the loop, which will continue;
5229 before_first_timeout = false;
5230 thread_plan_sp->SetStopOthers(false);
5231 if (log)
5232 log->PutCString(
5233 "Process::RunThreadPlan(): about to resume.");
5234
5235 back_to_top = true;
5236 break;
5237 } else {
5238 // Running all threads failed, so return Interrupted.
5239 if (log)
5240 log->PutCString("Process::RunThreadPlan(): running all "
5241 "threads timed out.");
5242 return_value = eExpressionInterrupted;
5243 back_to_top = false;
5244 break;
5245 }
5246 }
5247 } else {
5248 if (log)
5249 log->PutCString("Process::RunThreadPlan(): halt said it "
5250 "succeeded, but I got no event. "
5251 "I'm getting out of here passing Interrupted.");
5252 return_value = eExpressionInterrupted;
5253 back_to_top = false;
5254 break;
5255 }
5256 } else {
5257 try_halt_again++;
5258 continue;
5259 }
5260 }
5261
5262 if (!back_to_top || try_halt_again > num_retries)
5263 break;
5264 else
5265 continue;
5266 }
5267 } // END WAIT LOOP
5268
Adrian Prantl05097242018-04-30 16:49:04 +00005269 // If we had to start up a temporary private state thread to run this
5270 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005271 if (backup_private_state_thread.IsJoinable()) {
5272 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005273 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005274 m_private_state_thread = backup_private_state_thread;
5275 if (stopper_base_plan_sp) {
5276 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5277 }
5278 if (old_state != eStateInvalid)
5279 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005280 }
5281
Kate Stoneb9c1b512016-09-06 20:57:50 +00005282 if (return_value != eExpressionCompleted && log) {
5283 // Print a backtrace into the log so we can figure out where we are:
5284 StreamString s;
5285 s.PutCString("Thread state after unsuccessful completion: \n");
5286 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005287 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005288 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005289 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005290 // There are three cases where this could happen: 1) The execution
5291 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5292 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005293 bool should_unwind = (return_value == eExpressionInterrupted &&
5294 options.DoesUnwindOnError()) ||
5295 (return_value == eExpressionHitBreakpoint &&
5296 options.DoesIgnoreBreakpoints());
5297
5298 if (return_value == eExpressionCompleted || should_unwind) {
5299 thread_plan_sp->RestoreThreadState();
5300 }
5301
5302 // Now do some processing on the results of the run:
5303 if (return_value == eExpressionInterrupted ||
5304 return_value == eExpressionHitBreakpoint) {
5305 if (log) {
5306 StreamString s;
5307 if (event_sp)
5308 event_sp->Dump(&s);
5309 else {
5310 log->PutCString("Process::RunThreadPlan(): Stop event that "
5311 "interrupted us is NULL.");
5312 }
5313
5314 StreamString ts;
5315
5316 const char *event_explanation = nullptr;
5317
5318 do {
5319 if (!event_sp) {
5320 event_explanation = "<no event>";
5321 break;
5322 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5323 event_explanation = "<user interrupt>";
5324 break;
5325 } else {
5326 const Process::ProcessEventData *event_data =
5327 Process::ProcessEventData::GetEventDataFromEvent(
5328 event_sp.get());
5329
5330 if (!event_data) {
5331 event_explanation = "<no event data>";
5332 break;
5333 }
5334
5335 Process *process = event_data->GetProcessSP().get();
5336
5337 if (!process) {
5338 event_explanation = "<no process>";
5339 break;
5340 }
5341
5342 ThreadList &thread_list = process->GetThreadList();
5343
5344 uint32_t num_threads = thread_list.GetSize();
5345 uint32_t thread_index;
5346
5347 ts.Printf("<%u threads> ", num_threads);
5348
5349 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5350 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5351
5352 if (!thread) {
5353 ts.Printf("<?> ");
5354 continue;
5355 }
5356
5357 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5358 RegisterContext *register_context =
5359 thread->GetRegisterContext().get();
5360
5361 if (register_context)
5362 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5363 else
5364 ts.Printf("[ip unknown] ");
5365
5366 // Show the private stop info here, the public stop info will be
5367 // from the last natural stop.
5368 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5369 if (stop_info_sp) {
5370 const char *stop_desc = stop_info_sp->GetDescription();
5371 if (stop_desc)
5372 ts.PutCString(stop_desc);
5373 }
5374 ts.Printf(">");
5375 }
5376
5377 event_explanation = ts.GetData();
5378 }
Jonas Devlieghere09ad8c82019-05-24 00:44:33 +00005379 } while (false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005380
5381 if (event_explanation)
5382 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5383 s.GetData(), event_explanation);
5384 else
5385 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5386 s.GetData());
5387 }
5388
5389 if (should_unwind) {
5390 if (log)
5391 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5392 "discarding thread plans up to %p.",
5393 static_cast<void *>(thread_plan_sp.get()));
5394 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5395 } else {
5396 if (log)
5397 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5398 "plan: %p not discarding.",
5399 static_cast<void *>(thread_plan_sp.get()));
5400 }
5401 } else if (return_value == eExpressionSetupError) {
5402 if (log)
5403 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5404
5405 if (options.DoesUnwindOnError()) {
5406 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5407 }
5408 } else {
5409 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5410 if (log)
5411 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5412 return_value = eExpressionCompleted;
5413 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5414 if (log)
5415 log->PutCString(
5416 "Process::RunThreadPlan(): thread plan was discarded");
5417 return_value = eExpressionDiscarded;
5418 } else {
5419 if (log)
5420 log->PutCString(
5421 "Process::RunThreadPlan(): thread plan stopped in mid course");
5422 if (options.DoesUnwindOnError() && thread_plan_sp) {
5423 if (log)
5424 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5425 "'cause unwind_on_error is set.");
5426 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5427 }
5428 }
5429 }
5430
5431 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005432 // target Check that it's still there, and if it is put it back in the
5433 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005434 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5435 if (thread) {
5436 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5437 }
5438
5439 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005440 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005441
5442 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5443 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5444 selected_stack_id.IsValid()) {
5445 // We were able to restore the selected thread, now restore the frame:
5446 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5447 StackFrameSP old_frame_sp =
5448 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5449 selected_stack_id);
5450 if (old_frame_sp)
5451 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5452 old_frame_sp.get());
5453 }
5454 }
5455 }
5456
5457 // If the process exited during the run of the thread plan, notify everyone.
5458
5459 if (event_to_broadcast_sp) {
5460 if (log)
5461 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5462 BroadcastEvent(event_to_broadcast_sp);
5463 }
5464
5465 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005466}
5467
Kate Stoneb9c1b512016-09-06 20:57:50 +00005468const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5469 const char *result_name;
5470
5471 switch (result) {
5472 case eExpressionCompleted:
5473 result_name = "eExpressionCompleted";
5474 break;
5475 case eExpressionDiscarded:
5476 result_name = "eExpressionDiscarded";
5477 break;
5478 case eExpressionInterrupted:
5479 result_name = "eExpressionInterrupted";
5480 break;
5481 case eExpressionHitBreakpoint:
5482 result_name = "eExpressionHitBreakpoint";
5483 break;
5484 case eExpressionSetupError:
5485 result_name = "eExpressionSetupError";
5486 break;
5487 case eExpressionParseError:
5488 result_name = "eExpressionParseError";
5489 break;
5490 case eExpressionResultUnavailable:
5491 result_name = "eExpressionResultUnavailable";
5492 break;
5493 case eExpressionTimedOut:
5494 result_name = "eExpressionTimedOut";
5495 break;
5496 case eExpressionStoppedForDebug:
5497 result_name = "eExpressionStoppedForDebug";
5498 break;
5499 }
5500 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005501}
5502
Kate Stoneb9c1b512016-09-06 20:57:50 +00005503void Process::GetStatus(Stream &strm) {
5504 const StateType state = GetState();
5505 if (StateIsStoppedState(state, false)) {
5506 if (state == eStateExited) {
5507 int exit_status = GetExitStatus();
5508 const char *exit_description = GetExitDescription();
5509 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5510 GetID(), exit_status, exit_status,
5511 exit_description ? exit_description : "");
5512 } else {
5513 if (state == eStateConnected)
5514 strm.Printf("Connected to remote target.\n");
5515 else
5516 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5517 }
5518 } else {
5519 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5520 }
Pavel Labatha933d512016-04-05 13:07:16 +00005521}
5522
Kate Stoneb9c1b512016-09-06 20:57:50 +00005523size_t Process::GetThreadStatus(Stream &strm,
5524 bool only_threads_with_stop_reason,
5525 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005526 uint32_t num_frames_with_source,
5527 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005528 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005529
Kate Stoneb9c1b512016-09-06 20:57:50 +00005530 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005531 // very well might run code (e.g. if we need it to get return values or
5532 // arguments.) For that to work the process has to be able to acquire it.
5533 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005534
5535 uint32_t num_threads;
5536 std::vector<lldb::tid_t> thread_id_array;
5537 // Scope for thread list locker;
5538 {
5539 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5540 ThreadList &curr_thread_list = GetThreadList();
5541 num_threads = curr_thread_list.GetSize();
5542 uint32_t idx;
5543 thread_id_array.resize(num_threads);
5544 for (idx = 0; idx < num_threads; ++idx)
5545 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5546 }
5547
5548 for (uint32_t i = 0; i < num_threads; i++) {
5549 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5550 if (thread_sp) {
5551 if (only_threads_with_stop_reason) {
5552 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5553 if (!stop_info_sp || !stop_info_sp->IsValid())
5554 continue;
5555 }
5556 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005557 num_frames_with_source,
5558 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005559 ++num_thread_infos_dumped;
5560 } else {
5561 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5562 if (log)
5563 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5564 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005565 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005566 }
5567 return num_thread_infos_dumped;
5568}
5569
5570void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5571 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5572}
5573
5574bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5575 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5576 region.GetByteSize());
5577}
5578
5579void Process::AddPreResumeAction(PreResumeActionCallback callback,
5580 void *baton) {
5581 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5582}
5583
5584bool Process::RunPreResumeActions() {
5585 bool result = true;
5586 while (!m_pre_resume_actions.empty()) {
5587 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5588 m_pre_resume_actions.pop_back();
5589 bool this_result = action.callback(action.baton);
5590 if (result)
5591 result = this_result;
5592 }
5593 return result;
5594}
5595
5596void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5597
Jim Inghamffd91752016-10-20 22:50:00 +00005598void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5599{
5600 PreResumeCallbackAndBaton element(callback, baton);
5601 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5602 if (found_iter != m_pre_resume_actions.end())
5603 {
5604 m_pre_resume_actions.erase(found_iter);
5605 }
5606}
5607
Kate Stoneb9c1b512016-09-06 20:57:50 +00005608ProcessRunLock &Process::GetRunLock() {
5609 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5610 return m_private_run_lock;
5611 else
5612 return m_public_run_lock;
5613}
5614
5615void Process::Flush() {
5616 m_thread_list.Flush();
5617 m_extended_thread_list.Flush();
5618 m_extended_thread_stop_id = 0;
5619 m_queue_list.Clear();
5620 m_queue_list_stop_id = 0;
5621}
5622
5623void Process::DidExec() {
5624 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5625 if (log)
5626 log->Printf("Process::%s()", __FUNCTION__);
5627
5628 Target &target = GetTarget();
5629 target.CleanupProcess();
5630 target.ClearModules(false);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005631 m_dynamic_checkers_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005632 m_abi_sp.reset();
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005633 m_system_runtime_up.reset();
5634 m_os_up.reset();
5635 m_dyld_up.reset();
5636 m_jit_loaders_up.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005637 m_image_tokens.clear();
5638 m_allocated_memory_cache.Clear();
Alex Langford74eb76f2019-05-22 23:01:18 +00005639 {
5640 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5641 m_language_runtimes.clear();
5642 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005643 m_instrumentation_runtimes.clear();
5644 m_thread_list.DiscardThreadPlans();
5645 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005646 DoDidExec();
5647 CompleteAttach();
5648 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005649 // CompleteAttach() in case the dynamic loader loaded things in new
5650 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005651 Flush();
5652
Adrian Prantl05097242018-04-30 16:49:04 +00005653 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5654 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005655 target.DidExec();
5656}
5657
Zachary Turner97206d52017-05-12 04:51:55 +00005658addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005659 if (address == nullptr) {
5660 error.SetErrorString("Invalid address argument");
5661 return LLDB_INVALID_ADDRESS;
5662 }
5663
5664 addr_t function_addr = LLDB_INVALID_ADDRESS;
5665
5666 addr_t addr = address->GetLoadAddress(&GetTarget());
5667 std::map<addr_t, addr_t>::const_iterator iter =
5668 m_resolved_indirect_addresses.find(addr);
5669 if (iter != m_resolved_indirect_addresses.end()) {
5670 function_addr = (*iter).second;
5671 } else {
5672 if (!InferiorCall(this, address, function_addr)) {
5673 Symbol *symbol = address->CalculateSymbolContextSymbol();
5674 error.SetErrorStringWithFormat(
5675 "Unable to call resolver for indirect function %s",
5676 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5677 function_addr = LLDB_INVALID_ADDRESS;
5678 } else {
5679 m_resolved_indirect_addresses.insert(
5680 std::pair<addr_t, addr_t>(addr, function_addr));
5681 }
5682 }
5683 return function_addr;
5684}
5685
5686void Process::ModulesDidLoad(ModuleList &module_list) {
5687 SystemRuntime *sys_runtime = GetSystemRuntime();
5688 if (sys_runtime) {
5689 sys_runtime->ModulesDidLoad(module_list);
5690 }
5691
5692 GetJITLoaders().ModulesDidLoad(module_list);
5693
5694 // Give runtimes a chance to be created.
5695 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5696 m_instrumentation_runtimes);
5697
5698 // Tell runtimes about new modules.
5699 for (auto pos = m_instrumentation_runtimes.begin();
5700 pos != m_instrumentation_runtimes.end(); ++pos) {
5701 InstrumentationRuntimeSP runtime = pos->second;
5702 runtime->ModulesDidLoad(module_list);
5703 }
5704
Adrian Prantl05097242018-04-30 16:49:04 +00005705 // Let any language runtimes we have already created know about the modules
5706 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005707
Adrian Prantl05097242018-04-30 16:49:04 +00005708 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005709 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005710 // unloaded.
Alex Langford74eb76f2019-05-22 23:01:18 +00005711 {
5712 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5713 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5714 for (const auto &pair : language_runtimes) {
5715 // We must check language_runtime_sp to make sure it is not nullptr as we
5716 // might cache the fact that we didn't have a language runtime for a
5717 // language.
5718 LanguageRuntimeSP language_runtime_sp = pair.second;
5719 if (language_runtime_sp)
5720 language_runtime_sp->ModulesDidLoad(module_list);
5721 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005722 }
5723
5724 // If we don't have an operating system plug-in, try to load one since
5725 // loading shared libraries might cause a new one to try and load
Jonas Devlieghered5b44032019-02-13 06:25:41 +00005726 if (!m_os_up)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005727 LoadOperatingSystemPlugin(false);
5728
5729 // Give structured-data plugins a chance to see the modified modules.
5730 for (auto pair : m_structured_data_plugin_map) {
5731 if (pair.second)
5732 pair.second->ModulesDidLoad(*this, module_list);
5733 }
5734}
5735
5736void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5737 const char *fmt, ...) {
5738 bool print_warning = true;
5739
5740 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5741 if (!stream_sp)
5742 return;
5743 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5744 return;
5745 }
5746
5747 if (repeat_key != nullptr) {
5748 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5749 if (it == m_warnings_issued.end()) {
5750 m_warnings_issued[warning_type] = WarningsPointerSet();
5751 m_warnings_issued[warning_type].insert(repeat_key);
5752 } else {
5753 if (it->second.find(repeat_key) != it->second.end()) {
5754 print_warning = false;
5755 } else {
5756 it->second.insert(repeat_key);
5757 }
5758 }
5759 }
5760
5761 if (print_warning) {
5762 va_list args;
5763 va_start(args, fmt);
5764 stream_sp->PrintfVarArg(fmt, args);
5765 va_end(args);
5766 }
5767}
5768
5769void Process::PrintWarningOptimization(const SymbolContext &sc) {
5770 if (GetWarningsOptimization() && sc.module_sp &&
5771 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5772 sc.function->GetIsOptimized()) {
5773 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5774 "%s was compiled with optimization - stepping may behave "
5775 "oddly; variables may not be available.\n",
5776 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5777 }
5778}
5779
5780bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5781 info.Clear();
5782
5783 PlatformSP platform_sp = GetTarget().GetPlatform();
5784 if (!platform_sp)
5785 return false;
5786
5787 return platform_sp->GetProcessInfo(GetID(), info);
5788}
5789
5790ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5791 ThreadCollectionSP threads;
5792
5793 const MemoryHistorySP &memory_history =
5794 MemoryHistory::FindPlugin(shared_from_this());
5795
5796 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005797 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005798 }
5799
Jonas Devlieghere796ac802019-02-11 23:13:08 +00005800 threads = std::make_shared<ThreadCollection>(
5801 memory_history->GetHistoryThreads(addr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005802
5803 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005804}
Kuba Brecka63927542014-10-11 01:59:32 +00005805
5806InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005807Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5808 InstrumentationRuntimeCollection::iterator pos;
5809 pos = m_instrumentation_runtimes.find(type);
5810 if (pos == m_instrumentation_runtimes.end()) {
5811 return InstrumentationRuntimeSP();
5812 } else
5813 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005814}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005815
Kate Stoneb9c1b512016-09-06 20:57:50 +00005816bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5817 const ArchSpec &arch, ModuleSpec &module_spec) {
5818 module_spec.Clear();
5819 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005820}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005821
Kate Stoneb9c1b512016-09-06 20:57:50 +00005822size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5823 m_image_tokens.push_back(image_ptr);
5824 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005825}
5826
Kate Stoneb9c1b512016-09-06 20:57:50 +00005827lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5828 if (token < m_image_tokens.size())
5829 return m_image_tokens[token];
5830 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005831}
5832
Kate Stoneb9c1b512016-09-06 20:57:50 +00005833void Process::ResetImageToken(size_t token) {
5834 if (token < m_image_tokens.size())
5835 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005836}
Jason Molendafd4cea52016-01-08 21:40:11 +00005837
5838Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005839Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5840 AddressRange range_bounds) {
5841 Target &target = GetTarget();
5842 DisassemblerSP disassembler_sp;
5843 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005844
Kate Stoneb9c1b512016-09-06 20:57:50 +00005845 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005846
Kate Stoneb9c1b512016-09-06 20:57:50 +00005847 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005848 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005849 if (!default_stop_addr.IsValid())
5850 return retval;
5851
5852 ExecutionContext exe_ctx(this);
5853 const char *plugin_name = nullptr;
5854 const char *flavor = nullptr;
5855 const bool prefer_file_cache = true;
5856 disassembler_sp = Disassembler::DisassembleRange(
5857 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
5858 prefer_file_cache);
5859 if (disassembler_sp)
5860 insn_list = &disassembler_sp->GetInstructionList();
5861
5862 if (insn_list == nullptr) {
5863 return retval;
5864 }
5865
5866 size_t insn_offset =
5867 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5868 if (insn_offset == UINT32_MAX) {
5869 return retval;
5870 }
5871
5872 uint32_t branch_index =
Greg Claytondf225762019-05-09 20:39:34 +00005873 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target,
5874 false /* ignore_calls*/);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005875 if (branch_index == UINT32_MAX) {
5876 return retval;
5877 }
5878
5879 if (branch_index > insn_offset) {
5880 Address next_branch_insn_address =
5881 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5882 if (next_branch_insn_address.IsValid() &&
5883 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5884 retval = next_branch_insn_address;
5885 }
5886 }
5887
5888 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00005889}
Howard Hellyerad007562016-07-07 08:21:28 +00005890
Zachary Turner97206d52017-05-12 04:51:55 +00005891Status
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005892Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00005893
Zachary Turner97206d52017-05-12 04:51:55 +00005894 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00005895
Kate Stoneb9c1b512016-09-06 20:57:50 +00005896 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00005897
Kate Stoneb9c1b512016-09-06 20:57:50 +00005898 region_list.clear();
5899 do {
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005900 lldb_private::MemoryRegionInfo region_info;
5901 error = GetMemoryRegionInfo(range_end, region_info);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005902 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5903 if (error.Fail()) {
5904 region_list.clear();
5905 break;
Todd Fiala75930012016-08-19 04:21:48 +00005906 }
5907
Tatyana Krasnukha36788bb2018-12-20 15:02:58 +00005908 range_end = region_info.GetRange().GetRangeEnd();
5909 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5910 region_list.push_back(std::move(region_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005911 }
5912 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00005913
Kate Stoneb9c1b512016-09-06 20:57:50 +00005914 return error;
5915}
5916
Zachary Turner97206d52017-05-12 04:51:55 +00005917Status
Adrian Prantl0e4c4822019-03-06 21:22:25 +00005918Process::ConfigureStructuredData(ConstString type_name,
Zachary Turner97206d52017-05-12 04:51:55 +00005919 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005920 // If you get this, the Process-derived class needs to implement a method to
5921 // enable an already-reported asynchronous structured data feature. See
5922 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00005923 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005924}
5925
5926void Process::MapSupportedStructuredDataPlugins(
5927 const StructuredData::Array &supported_type_names) {
5928 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5929
5930 // Bail out early if there are no type names to map.
5931 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00005932 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00005933 log->Printf("Process::%s(): no structured data types supported",
5934 __FUNCTION__);
5935 return;
5936 }
Todd Fiala75930012016-08-19 04:21:48 +00005937
Kate Stoneb9c1b512016-09-06 20:57:50 +00005938 // Convert StructuredData type names to ConstString instances.
5939 std::set<ConstString> const_type_names;
5940
5941 if (log)
5942 log->Printf("Process::%s(): the process supports the following async "
5943 "structured data types:",
5944 __FUNCTION__);
5945
5946 supported_type_names.ForEach(
5947 [&const_type_names, &log](StructuredData::Object *object) {
5948 if (!object) {
5949 // Invalid - shouldn't be null objects in the array.
5950 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005951 }
5952
5953 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005954 if (!type_name) {
5955 // Invalid format - all type names should be strings.
5956 return false;
Todd Fiala75930012016-08-19 04:21:48 +00005957 }
5958
5959 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00005960 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00005961 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005962 });
Todd Fiala75930012016-08-19 04:21:48 +00005963
Adrian Prantl05097242018-04-30 16:49:04 +00005964 // For each StructuredDataPlugin, if the plugin handles any of the types in
5965 // the supported_type_names, map that type name to that plugin. Stop when
5966 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005967 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00005968 // supports?
5969 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5970 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00005971 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5972 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00005973 if (!create_instance)
5974 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005975
Kate Stoneb9c1b512016-09-06 20:57:50 +00005976 // Create the plugin.
5977 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5978 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00005979 // This plugin doesn't think it can work with the process. Move on to the
5980 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005981 continue;
Todd Fiala75930012016-08-19 04:21:48 +00005982 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005983
Adrian Prantl05097242018-04-30 16:49:04 +00005984 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005985 std::vector<ConstString> names_to_remove;
5986 for (auto &type_name : const_type_names) {
5987 if (plugin_sp->SupportsStructuredDataType(type_name)) {
5988 m_structured_data_plugin_map.insert(
5989 std::make_pair(type_name, plugin_sp));
5990 names_to_remove.push_back(type_name);
5991 if (log)
5992 log->Printf("Process::%s(): using plugin %s for type name "
5993 "%s",
5994 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
5995 type_name.GetCString());
5996 }
5997 }
5998
5999 // Remove the type names that were consumed by this plugin.
6000 for (auto &type_name : names_to_remove)
6001 const_type_names.erase(type_name);
6002 }
Todd Fiala75930012016-08-19 04:21:48 +00006003}
6004
Kate Stoneb9c1b512016-09-06 20:57:50 +00006005bool Process::RouteAsyncStructuredData(
6006 const StructuredData::ObjectSP object_sp) {
6007 // Nothing to do if there's no data.
6008 if (!object_sp)
6009 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006010
Adrian Prantl05097242018-04-30 16:49:04 +00006011 // The contract is this must be a dictionary, so we can look up the routing
6012 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006013 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6014 if (!dictionary)
6015 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006016
Kate Stoneb9c1b512016-09-06 20:57:50 +00006017 // Grab the async structured type name (i.e. the feature/plugin name).
6018 ConstString type_name;
6019 if (!dictionary->GetValueForKeyAsString("type", type_name))
6020 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006021
Kate Stoneb9c1b512016-09-06 20:57:50 +00006022 // Check if there's a plugin registered for this type name.
6023 auto find_it = m_structured_data_plugin_map.find(type_name);
6024 if (find_it == m_structured_data_plugin_map.end()) {
6025 // We don't have a mapping for this structured data type.
6026 return false;
6027 }
Todd Fiala75930012016-08-19 04:21:48 +00006028
Kate Stoneb9c1b512016-09-06 20:57:50 +00006029 // Route the structured data to the plugin.
6030 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6031 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006032}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006033
Zachary Turner97206d52017-05-12 04:51:55 +00006034Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006035 // Default implementation does nothign.
6036 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00006037 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006038}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006039
Frederic Rissd10d3792018-05-11 18:21:11 +00006040UtilityFunction *Process::GetLoadImageUtilityFunction(
6041 Platform *platform,
6042 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006043 if (platform != GetTarget().GetPlatform().get())
6044 return nullptr;
Frederic Rissd10d3792018-05-11 18:21:11 +00006045 std::call_once(m_dlopen_utility_func_flag_once,
6046 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006047 return m_dlopen_utility_func_up.get();
6048}