blob: 93b9e3f0b7350e2a347389c459c1cf7006d33b5e [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eugene Zelenko8f30a652015-10-23 18:39:37 +000010// C Includes
11// C++ Includes
Greg Clayton5cc45e02016-02-26 19:41:49 +000012#include <atomic>
Greg Clayton04df8ee2016-02-26 19:38:18 +000013#include <mutex>
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +000014
Eugene Zelenko8f30a652015-10-23 18:39:37 +000015// Other libraries and framework includes
Pavel Labath2ce22162016-12-01 10:57:30 +000016#include "llvm/Support/ScopedPrinter.h"
Zachary Turner777de772017-03-04 16:42:25 +000017#include "llvm/Support/Threading.h"
18
Eugene Zelenko8f30a652015-10-23 18:39:37 +000019// Project includes
Sean Callanan579e70c2016-03-19 00:03:59 +000020#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000022#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include "lldb/Core/Debugger.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000024#include "lldb/Core/Event.h"
Greg Clayton1f746072012-08-29 21:13:06 +000025#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000026#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000027#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000028#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000029#include "lldb/Expression/DiagnosticManager.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000030#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000031#include "lldb/Expression/UserExpression.h"
Jim Ingham1ecb34f2018-04-17 20:44:47 +000032#include "lldb/Expression/UtilityFunction.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000033#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000034#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000036#include "lldb/Host/HostInfo.h"
Zachary Turner3eb2b442017-03-22 23:33:16 +000037#include "lldb/Host/OptionParser.h"
Greg Clayton100eb932014-07-02 21:10:39 +000038#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000039#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000040#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000041#include "lldb/Interpreter/CommandInterpreter.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000042#include "lldb/Interpreter/OptionArgParser.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000043#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000044#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000045#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Target/ABI.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000047#include "lldb/Target/CPPLanguageRuntime.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000048#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000049#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000050#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000051#include "lldb/Target/JITLoaderList.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000052#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000053#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000054#include "lldb/Target/MemoryRegionInfo.h"
Jim Ingham22777012010-09-23 02:01:19 +000055#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000056#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000057#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000058#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000059#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000060#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000061#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000062#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000063#include "lldb/Target/Target.h"
64#include "lldb/Target/TargetList.h"
65#include "lldb/Target/Thread.h"
66#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000067#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000068#include "lldb/Target/UnixSignals.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000069#include "lldb/Utility/Log.h"
Zachary Turner50232572015-03-18 21:31:45 +000070#include "lldb/Utility/NameMatches.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000071#include "lldb/Utility/SelectHelper.h"
Pavel Labathd821c992018-08-07 11:07:21 +000072#include "lldb/Utility/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073
74using namespace lldb;
75using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000076using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000077
Kate Stoneb9c1b512016-09-06 20:57:50 +000078// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000079// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000080#define ENABLE_MEMORY_CACHING
81
82#ifdef ENABLE_MEMORY_CACHING
83#define DISABLE_MEM_CACHE_DEFAULT false
84#else
85#define DISABLE_MEM_CACHE_DEFAULT true
86#endif
87
Kate Stoneb9c1b512016-09-06 20:57:50 +000088class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000089public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 ProcessOptionValueProperties(const ConstString &name)
91 : OptionValueProperties(name) {}
92
Adrian Prantl05097242018-04-30 16:49:04 +000093 // This constructor is used when creating ProcessOptionValueProperties when
94 // it is part of a new lldb_private::Process instance. It will copy all
95 // current global property values as needed
Kate Stoneb9c1b512016-09-06 20:57:50 +000096 ProcessOptionValueProperties(ProcessProperties *global_properties)
97 : OptionValueProperties(*global_properties->GetValueProperties()) {}
98
99 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
100 bool will_modify,
101 uint32_t idx) const override {
Adrian Prantl05097242018-04-30 16:49:04 +0000102 // When getting the value for a key from the process options, we will
103 // always try and grab the setting from the current process if there is
104 // one. Else we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105 if (exe_ctx) {
106 Process *process = exe_ctx->GetProcessPtr();
107 if (process) {
108 ProcessOptionValueProperties *instance_properties =
109 static_cast<ProcessOptionValueProperties *>(
110 process->GetValueProperties().get());
111 if (this != instance_properties)
112 return instance_properties->ProtectedGetPropertyAtIndex(idx);
113 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000114 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000115 return ProtectedGetPropertyAtIndex(idx);
116 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000117};
118
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000119static constexpr PropertyDefinition g_properties[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000121 DISABLE_MEM_CACHE_DEFAULT, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122 "Disable reading and caching of memory in fixed-size units."},
123 {"extra-startup-command", OptionValue::eTypeArray, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000124 OptionValue::eTypeString, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 "A list containing extra commands understood by the particular process "
126 "plugin used. "
127 "For instance, to turn on debugserver logging set this to "
128 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
129 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000130 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 "If true, breakpoints will be ignored during expression evaluation."},
132 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000133 nullptr, {}, "If true, errors in expression evaluation will unwind "
134 "the stack back to the state before the call."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000136 {}, "A path to a python OS plug-in module file that contains a "
137 "OperatingSystemPlugIn class."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000139 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 "If true, stop when a shared library is loaded or unloaded."},
141 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000142 {}, "If true, detach will attempt to keep the process stopped."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000144 {}, "The memory cache line size"},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000146 {}, "If true, warn when stopped in code that is optimized where "
147 "stepping and variable availability may not behave as expected."},
Jim Inghamba205c12017-12-05 02:50:45 +0000148 {"stop-on-exec", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000149 nullptr, {},
Tatyana Krasnukhae40db052018-09-27 07:11:58 +0000150 "If true, stop when a shared library is loaded or unloaded."}};
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,
162 ePropertyStopOnExec
Greg Clayton67cc0632012-08-22 17:17:09 +0000163};
164
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165ProcessProperties::ProcessProperties(lldb_private::Process *process)
166 : Properties(),
167 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000168{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000169 if (process == nullptr) {
170 // Global process properties, set them up one time
171 m_collection_sp.reset(
172 new ProcessOptionValueProperties(ConstString("process")));
173 m_collection_sp->Initialize(g_properties);
174 m_collection_sp->AppendProperty(
175 ConstString("thread"), ConstString("Settings specific to threads."),
176 true, Thread::GetGlobalProperties()->GetValueProperties());
177 } else {
178 m_collection_sp.reset(
179 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
180 m_collection_sp->SetValueChangedCallback(
181 ePropertyPythonOSPluginPath,
182 ProcessProperties::OptionValueChangedCallback, this);
183 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000184}
185
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000186ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188void ProcessProperties::OptionValueChangedCallback(void *baton,
189 OptionValue *option_value) {
190 ProcessProperties *properties = (ProcessProperties *)baton;
191 if (properties->m_process)
192 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195bool ProcessProperties::GetDisableMemoryCache() const {
196 const uint32_t idx = ePropertyDisableMemCache;
197 return m_collection_sp->GetPropertyAtIndexAsBoolean(
198 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000199}
200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
202 const uint32_t idx = ePropertyMemCacheLineSize;
203 return m_collection_sp->GetPropertyAtIndexAsUInt64(
204 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000205}
206
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207Args ProcessProperties::GetExtraStartupCommands() const {
208 Args args;
209 const uint32_t idx = ePropertyExtraStartCommand;
210 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
211 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000212}
213
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214void ProcessProperties::SetExtraStartupCommands(const Args &args) {
215 const uint32_t idx = ePropertyExtraStartCommand;
216 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000217}
218
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219FileSpec ProcessProperties::GetPythonOSPluginPath() const {
220 const uint32_t idx = ePropertyPythonOSPluginPath;
221 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000222}
223
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
225 const uint32_t idx = ePropertyPythonOSPluginPath;
226 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000227}
228
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
230 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
231 return m_collection_sp->GetPropertyAtIndexAsBoolean(
232 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000233}
234
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
236 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
237 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000238}
239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
241 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
242 return m_collection_sp->GetPropertyAtIndexAsBoolean(
243 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000244}
245
Kate Stoneb9c1b512016-09-06 20:57:50 +0000246void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
247 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
248 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000249}
250
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
252 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
253 return m_collection_sp->GetPropertyAtIndexAsBoolean(
254 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000255}
256
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
258 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
259 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
260}
261
262bool ProcessProperties::GetDetachKeepsStopped() const {
263 const uint32_t idx = ePropertyDetachKeepsStopped;
264 return m_collection_sp->GetPropertyAtIndexAsBoolean(
265 nullptr, idx, g_properties[idx].default_uint_value != 0);
266}
267
268void ProcessProperties::SetDetachKeepsStopped(bool stop) {
269 const uint32_t idx = ePropertyDetachKeepsStopped;
270 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
271}
272
273bool ProcessProperties::GetWarningsOptimization() const {
274 const uint32_t idx = ePropertyWarningOptimization;
275 return m_collection_sp->GetPropertyAtIndexAsBoolean(
276 nullptr, idx, g_properties[idx].default_uint_value != 0);
277}
278
Jim Inghamba205c12017-12-05 02:50:45 +0000279bool ProcessProperties::GetStopOnExec() const {
280 const uint32_t idx = ePropertyStopOnExec;
281 return m_collection_sp->GetPropertyAtIndexAsBoolean(
282 nullptr, idx, g_properties[idx].default_uint_value != 0);
283}
284
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
286 const char *cstr;
287 if (m_pid != LLDB_INVALID_PROCESS_ID)
288 s.Printf(" pid = %" PRIu64 "\n", m_pid);
289
290 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
291 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
292
293 if (m_executable) {
294 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
295 s.PutCString(" file = ");
296 m_executable.Dump(&s);
297 s.EOL();
298 }
299 const uint32_t argc = m_arguments.GetArgumentCount();
300 if (argc > 0) {
301 for (uint32_t i = 0; i < argc; i++) {
302 const char *arg = m_arguments.GetArgumentAtIndex(i);
303 if (i < 10)
304 s.Printf(" arg[%u] = %s\n", i, arg);
305 else
306 s.Printf("arg[%u] = %s\n", i, arg);
307 }
308 }
309
Pavel Labath62930e52018-01-10 11:57:31 +0000310 s.Format("{0}", m_environment);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000311
312 if (m_arch.IsValid()) {
313 s.Printf(" arch = ");
314 m_arch.DumpTriple(s);
315 s.EOL();
316 }
317
318 if (m_uid != UINT32_MAX) {
319 cstr = platform->GetUserName(m_uid);
320 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
321 }
322 if (m_gid != UINT32_MAX) {
323 cstr = platform->GetGroupName(m_gid);
324 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
325 }
326 if (m_euid != UINT32_MAX) {
327 cstr = platform->GetUserName(m_euid);
328 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
329 }
330 if (m_egid != UINT32_MAX) {
331 cstr = platform->GetGroupName(m_egid);
332 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
333 }
334}
335
336void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
337 bool show_args, bool verbose) {
338 const char *label;
339 if (show_args || verbose)
340 label = "ARGUMENTS";
341 else
342 label = "NAME";
343
344 if (verbose) {
345 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
346 " %s\n",
347 label);
348 s.PutCString("====== ====== ========== ========== ========== ========== "
349 "======================== ============================\n");
350 } else {
351 s.Printf("PID PARENT USER TRIPLE %s\n", label);
352 s.PutCString("====== ====== ========== ======================== "
353 "============================\n");
354 }
355}
356
357void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
358 bool show_args, bool verbose) const {
359 if (m_pid != LLDB_INVALID_PROCESS_ID) {
Greg Clayton32e0a752011-03-30 18:16:51 +0000360 const char *cstr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000362
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 StreamString arch_strm;
Todd Fiala7df337f2015-10-13 23:41:19 +0000364 if (m_arch.IsValid())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 m_arch.DumpTriple(arch_strm);
366
367 if (verbose) {
368 cstr = platform->GetUserName(m_uid);
369 if (cstr &&
370 cstr[0]) // Watch for empty string that indicates lookup failed
371 s.Printf("%-10s ", cstr);
372 else
373 s.Printf("%-10u ", m_uid);
374
375 cstr = platform->GetGroupName(m_gid);
376 if (cstr &&
377 cstr[0]) // Watch for empty string that indicates lookup failed
378 s.Printf("%-10s ", cstr);
379 else
380 s.Printf("%-10u ", m_gid);
381
382 cstr = platform->GetUserName(m_euid);
383 if (cstr &&
384 cstr[0]) // Watch for empty string that indicates lookup failed
385 s.Printf("%-10s ", cstr);
386 else
387 s.Printf("%-10u ", m_euid);
388
389 cstr = platform->GetGroupName(m_egid);
390 if (cstr &&
391 cstr[0]) // Watch for empty string that indicates lookup failed
392 s.Printf("%-10s ", cstr);
393 else
394 s.Printf("%-10u ", m_egid);
395
Zachary Turnerc1564272016-11-16 21:15:24 +0000396 s.Printf("%-24s ", arch_strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 } else {
398 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
Zachary Turnerc1564272016-11-16 21:15:24 +0000399 arch_strm.GetData());
Todd Fiala7df337f2015-10-13 23:41:19 +0000400 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 if (verbose || show_args) {
403 const uint32_t argc = m_arguments.GetArgumentCount();
404 if (argc > 0) {
405 for (uint32_t i = 0; i < argc; i++) {
406 if (i > 0)
407 s.PutChar(' ');
408 s.PutCString(m_arguments.GetArgumentAtIndex(i));
409 }
410 }
411 } else {
412 s.PutCString(GetName());
Greg Clayton32e0a752011-03-30 18:16:51 +0000413 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414
415 s.EOL();
416 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000417}
418
Zachary Turner97206d52017-05-12 04:51:55 +0000419Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000420 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000422 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 const int short_option = m_getopt_table[option_idx].val;
424
425 switch (short_option) {
426 case 's': // Stop at program entry point
427 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
428 break;
429
430 case 'i': // STDIN for read only
431 {
432 FileAction action;
433 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
434 launch_info.AppendFileAction(action);
435 break;
436 }
437
438 case 'o': // Open STDOUT for write only
439 {
440 FileAction action;
441 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
442 launch_info.AppendFileAction(action);
443 break;
444 }
445
446 case 'e': // STDERR for write only
447 {
448 FileAction action;
449 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
450 launch_info.AppendFileAction(action);
451 break;
452 }
453
454 case 'p': // Process plug-in name
455 launch_info.SetProcessPluginName(option_arg);
456 break;
457
458 case 'n': // Disable STDIO
459 {
460 FileAction action;
461 const FileSpec dev_null{FileSystem::DEV_NULL, false};
462 if (action.Open(STDIN_FILENO, dev_null, true, false))
463 launch_info.AppendFileAction(action);
464 if (action.Open(STDOUT_FILENO, dev_null, false, true))
465 launch_info.AppendFileAction(action);
466 if (action.Open(STDERR_FILENO, dev_null, false, true))
467 launch_info.AppendFileAction(action);
468 break;
469 }
470
471 case 'w':
472 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
473 break;
474
475 case 't': // Open process in new terminal window
476 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
477 break;
478
479 case 'a': {
480 TargetSP target_sp =
481 execution_context ? execution_context->GetTargetSP() : TargetSP();
482 PlatformSP platform_sp =
483 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000484 launch_info.GetArchitecture() =
485 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 } break;
487
488 case 'A': // Disable ASLR.
489 {
490 bool success;
491 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000492 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 if (success)
494 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000495 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496 error.SetErrorStringWithFormat(
497 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000498 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 break;
500 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000501
Kate Stoneb9c1b512016-09-06 20:57:50 +0000502 case 'X': // shell expand args.
503 {
504 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000505 const bool expand_args =
506 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507 if (success)
508 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000509 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 error.SetErrorStringWithFormat(
511 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000512 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513 break;
514 }
515
516 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000517 if (!option_arg.empty())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518 launch_info.SetShell(FileSpec(option_arg, false));
519 else
520 launch_info.SetShell(HostInfo::GetDefaultShell());
521 break;
522
523 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000524 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 break;
526
527 default:
528 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
529 short_option);
530 break;
531 }
532 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000533}
534
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000535static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000537 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538 "Stop at the entry point of the program when launching a process."},
539 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000540 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 "Set whether to disable address space layout randomization when launching "
542 "a process."},
543 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000544 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 "Name of the process plugin you want to use."},
546 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000547 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 eArgTypeDirectoryName,
549 "Set the current working directory to <path> when running the inferior."},
550 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000551 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 "Set the architecture for the process to launch when ambiguous."},
553 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000554 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 "Specify an environment variable name/value string (--environment "
556 "NAME=VALUE). Can be specified multiple times for subsequent environment "
557 "entries."},
558 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000559 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000561
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000563 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 "Redirect stdin for the process to <filename>."},
565 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000566 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 "Redirect stdout for the process to <filename>."},
568 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000569 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000571
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000573 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000575
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000577 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578 "Do not set up for terminal I/O to go to running process."},
579 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000580 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000582};
583
584llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000585 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000586}
Greg Clayton32e0a752011-03-30 18:16:51 +0000587
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
Pavel Labathc4a33952017-02-20 11:35:33 +0000589 if (m_name_match_type == NameMatch::Ignore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000590 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591 const char *match_name = m_match_info.GetName();
592 if (!match_name)
Greg Clayton32e0a752011-03-30 18:16:51 +0000593 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594
595 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
Greg Clayton32e0a752011-03-30 18:16:51 +0000596}
597
Kate Stoneb9c1b512016-09-06 20:57:50 +0000598bool ProcessInstanceInfoMatch::Matches(
599 const ProcessInstanceInfo &proc_info) const {
600 if (!NameMatches(proc_info.GetName()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000601 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602
603 if (m_match_info.ProcessIDIsValid() &&
604 m_match_info.GetProcessID() != proc_info.GetProcessID())
605 return false;
606
607 if (m_match_info.ParentProcessIDIsValid() &&
608 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
609 return false;
610
611 if (m_match_info.UserIDIsValid() &&
612 m_match_info.GetUserID() != proc_info.GetUserID())
613 return false;
614
615 if (m_match_info.GroupIDIsValid() &&
616 m_match_info.GetGroupID() != proc_info.GetGroupID())
617 return false;
618
619 if (m_match_info.EffectiveUserIDIsValid() &&
620 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
621 return false;
622
623 if (m_match_info.EffectiveGroupIDIsValid() &&
624 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
625 return false;
626
627 if (m_match_info.GetArchitecture().IsValid() &&
628 !m_match_info.GetArchitecture().IsCompatibleMatch(
629 proc_info.GetArchitecture()))
630 return false;
631 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000632}
633
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
Pavel Labathc4a33952017-02-20 11:35:33 +0000635 if (m_name_match_type != NameMatch::Ignore)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636 return false;
637
638 if (m_match_info.ProcessIDIsValid())
639 return false;
640
641 if (m_match_info.ParentProcessIDIsValid())
642 return false;
643
644 if (m_match_info.UserIDIsValid())
645 return false;
646
647 if (m_match_info.GroupIDIsValid())
648 return false;
649
650 if (m_match_info.EffectiveUserIDIsValid())
651 return false;
652
653 if (m_match_info.EffectiveGroupIDIsValid())
654 return false;
655
656 if (m_match_info.GetArchitecture().IsValid())
657 return false;
658
659 if (m_match_all_users)
660 return false;
661
662 return true;
663}
664
665void ProcessInstanceInfoMatch::Clear() {
666 m_match_info.Clear();
Pavel Labathc4a33952017-02-20 11:35:33 +0000667 m_name_match_type = NameMatch::Ignore;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 m_match_all_users = false;
669}
670
Zachary Turner31659452016-11-17 21:15:14 +0000671ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
672 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000673 ListenerSP listener_sp,
674 const FileSpec *crash_file_path) {
675 static uint32_t g_process_unique_id = 0;
676
677 ProcessSP process_sp;
678 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000679 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680 ConstString const_plugin_name(plugin_name);
681 create_callback =
682 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
683 if (create_callback) {
684 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
685 if (process_sp) {
686 if (process_sp->CanDebug(target_sp, true)) {
687 process_sp->m_process_unique_id = ++g_process_unique_id;
688 } else
689 process_sp.reset();
690 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 } else {
693 for (uint32_t idx = 0;
694 (create_callback =
695 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
696 ++idx) {
697 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
698 if (process_sp) {
699 if (process_sp->CanDebug(target_sp, false)) {
700 process_sp->m_process_unique_id = ++g_process_unique_id;
701 break;
702 } else
703 process_sp.reset();
704 }
705 }
706 }
707 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708}
709
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710ConstString &Process::GetStaticBroadcasterClass() {
711 static ConstString class_name("lldb.process");
712 return class_name;
713}
714
715Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
716 : Process(target_sp, listener_sp,
717 UnixSignals::Create(HostInfo::GetArchitecture())) {
718 // This constructor just delegates to the full Process constructor,
719 // defaulting to using the Host's UnixSignals.
720}
721
722Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
723 const UnixSignalsSP &unix_signals_sp)
724 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
725 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
726 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000727 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728 m_private_state(eStateUnloaded),
729 m_private_state_broadcaster(nullptr,
730 "lldb.process.internal_state_broadcaster"),
731 m_private_state_control_broadcaster(
732 nullptr, "lldb.process.internal_state_control_broadcaster"),
733 m_private_state_listener_sp(
734 Listener::MakeListener("lldb.process.internal_state_listener")),
735 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
736 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
737 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
738 m_thread_list(this), m_extended_thread_list(this),
739 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
740 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
741 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
742 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
743 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
744 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
745 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
746 m_memory_cache(*this), m_allocated_memory_cache(*this),
747 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000748 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
750 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
751 m_can_interpret_function_calls(false), m_warnings_issued(),
752 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
753 CheckInWithManager();
754
755 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
756 if (log)
757 log->Printf("%p Process::Process()", static_cast<void *>(this));
758
759 if (!m_unix_signals_sp)
760 m_unix_signals_sp = std::make_shared<UnixSignals>();
761
762 SetEventName(eBroadcastBitStateChanged, "state-changed");
763 SetEventName(eBroadcastBitInterrupt, "interrupt");
764 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
765 SetEventName(eBroadcastBitSTDERR, "stderr-available");
766 SetEventName(eBroadcastBitProfileData, "profile-data-available");
767 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
768
769 m_private_state_control_broadcaster.SetEventName(
770 eBroadcastInternalStateControlStop, "control-stop");
771 m_private_state_control_broadcaster.SetEventName(
772 eBroadcastInternalStateControlPause, "control-pause");
773 m_private_state_control_broadcaster.SetEventName(
774 eBroadcastInternalStateControlResume, "control-resume");
775
776 m_listener_sp->StartListeningForEvents(
777 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
778 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
779 eBroadcastBitProfileData | eBroadcastBitStructuredData);
780
781 m_private_state_listener_sp->StartListeningForEvents(
782 &m_private_state_broadcaster,
783 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
784
785 m_private_state_listener_sp->StartListeningForEvents(
786 &m_private_state_control_broadcaster,
787 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
788 eBroadcastInternalStateControlResume);
789 // We need something valid here, even if just the default UnixSignalsSP.
790 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
791
792 // Allow the platform to override the default cache line size
793 OptionValueSP value_sp =
794 m_collection_sp
795 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
796 ->GetValue();
797 uint32_t platform_cache_line_size =
798 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
799 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
800 value_sp->SetUInt64Value(platform_cache_line_size);
801}
802
803Process::~Process() {
804 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
805 if (log)
806 log->Printf("%p Process::~Process()", static_cast<void *>(this));
807 StopPrivateStateThread();
808
809 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000810 // explicitly clear the thread list here to ensure that the mutex is not
811 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812 m_thread_list.Clear();
813}
814
815const ProcessPropertiesSP &Process::GetGlobalProperties() {
816 // NOTE: intentional leak so we don't crash if global destructor chain gets
817 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000818 static ProcessPropertiesSP *g_settings_sp_ptr =
819 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 return *g_settings_sp_ptr;
821}
822
823void Process::Finalize() {
824 m_finalizing = true;
825
826 // Destroy this process if needed
827 switch (GetPrivateState()) {
828 case eStateConnected:
829 case eStateAttaching:
830 case eStateLaunching:
831 case eStateStopped:
832 case eStateRunning:
833 case eStateStepping:
834 case eStateCrashed:
835 case eStateSuspended:
836 Destroy(false);
837 break;
838
839 case eStateInvalid:
840 case eStateUnloaded:
841 case eStateDetached:
842 case eStateExited:
843 break;
844 }
845
846 // Clear our broadcaster before we proceed with destroying
847 Broadcaster::Clear();
848
Adrian Prantl05097242018-04-30 16:49:04 +0000849 // Do any cleanup needed prior to being destructed... Subclasses that
850 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851
852 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000853 // destroyed since it is very likely that undoing the loader will require
854 // access to the real process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 m_dynamic_checkers_ap.reset();
856 m_abi_sp.reset();
857 m_os_ap.reset();
858 m_system_runtime_ap.reset();
859 m_dyld_ap.reset();
860 m_jit_loaders_ap.reset();
861 m_thread_list_real.Destroy();
862 m_thread_list.Destroy();
863 m_extended_thread_list.Destroy();
864 m_queue_list.Clear();
865 m_queue_list_stop_id = 0;
866 std::vector<Notifications> empty_notifications;
867 m_notifications.swap(empty_notifications);
868 m_image_tokens.clear();
869 m_memory_cache.Clear();
870 m_allocated_memory_cache.Clear();
871 m_language_runtimes.clear();
872 m_instrumentation_runtimes.clear();
873 m_next_event_action_ap.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000874 // Clear the last natural stop ID since it has a strong reference to this
875 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000876 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
877 //#ifdef LLDB_CONFIGURATION_DEBUG
878 // StreamFile s(stdout, false);
879 // EventSP event_sp;
880 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
881 // {
882 // event_sp->Dump (&s);
883 // s.EOL();
884 // }
885 //#endif
886 // We have to be very careful here as the m_private_state_listener might
887 // contain events that have ProcessSP values in them which can keep this
888 // process around forever. These events need to be cleared out.
889 m_private_state_listener_sp->Clear();
890 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
891 m_public_run_lock.SetStopped();
892 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
893 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000894 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895 m_finalize_called = true;
896}
897
898void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
899 m_notifications.push_back(callbacks);
900 if (callbacks.initialize != nullptr)
901 callbacks.initialize(callbacks.baton, this);
902}
903
904bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
905 std::vector<Notifications>::iterator pos, end = m_notifications.end();
906 for (pos = m_notifications.begin(); pos != end; ++pos) {
907 if (pos->baton == callbacks.baton &&
908 pos->initialize == callbacks.initialize &&
909 pos->process_state_changed == callbacks.process_state_changed) {
910 m_notifications.erase(pos);
911 return true;
912 }
913 }
914 return false;
915}
916
917void Process::SynchronouslyNotifyStateChanged(StateType state) {
918 std::vector<Notifications>::iterator notification_pos,
919 notification_end = m_notifications.end();
920 for (notification_pos = m_notifications.begin();
921 notification_pos != notification_end; ++notification_pos) {
922 if (notification_pos->process_state_changed)
923 notification_pos->process_state_changed(notification_pos->baton, this,
924 state);
925 }
926}
927
928// FIXME: We need to do some work on events before the general Listener sees
929// them.
930// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000931// we do the little "insert real insn, step & stop" trick. But we can't do
932// that when the event is delivered by the broadcaster - since that is done on
933// the thread that is waiting for new events, so if we needed more than one
934// event for our handling, we would stall. So instead we do it when we fetch
935// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936//
937
Kate Stoneb9c1b512016-09-06 20:57:50 +0000938StateType Process::GetNextEvent(EventSP &event_sp) {
939 StateType state = eStateInvalid;
940
Pavel Labathd35031e12016-11-30 10:41:42 +0000941 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
942 std::chrono::seconds(0)) &&
943 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000944 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
945
946 return state;
947}
948
Pavel Labath3879fe02018-05-09 14:29:30 +0000949void Process::SyncIOHandler(uint32_t iohandler_id,
950 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 // don't sync (potentially context switch) in case where there is no process
952 // IO
953 if (!m_process_input_reader)
954 return;
955
Pavel Labath3879fe02018-05-09 14:29:30 +0000956 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957
958 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000959 if (Result) {
960 LLDB_LOG(
961 log,
962 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
963 iohandler_id, *Result);
964 } else {
965 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
966 iohandler_id);
967 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968}
969
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000970StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
971 EventSP *event_sp_ptr, bool wait_always,
972 ListenerSP hijack_listener_sp,
973 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000975 // have restarted the target. We have to actually check each event, and in
976 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 if (event_sp_ptr)
978 event_sp_ptr->reset();
979 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000980 // If we are exited or detached, we won't ever get back to any other valid
981 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000983 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000986 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000987
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 if (!wait_always && StateIsStoppedState(state, true) &&
989 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000990 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 log->Printf("Process::%s returning without waiting for events; process "
992 "private and public states are already 'stopped'.",
993 __FUNCTION__);
994 // We need to toggle the run lock as this won't get done in
995 // SetPublicState() if the process is hijacked.
996 if (hijack_listener_sp && use_run_lock)
997 m_public_run_lock.SetStopped();
998 return state;
999 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 while (state != eStateInvalid) {
1002 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001003 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 if (event_sp_ptr && event_sp)
1005 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001006
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1008 Process::HandleProcessStateChangedEvent(event_sp, stream,
1009 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +00001010
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 switch (state) {
1012 case eStateCrashed:
1013 case eStateDetached:
1014 case eStateExited:
1015 case eStateUnloaded:
1016 // We need to toggle the run lock as this won't get done in
1017 // SetPublicState() if the process is hijacked.
1018 if (hijack_listener_sp && use_run_lock)
1019 m_public_run_lock.SetStopped();
1020 return state;
1021 case eStateStopped:
1022 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1023 continue;
1024 else {
Pavel Labath78521ef2015-03-06 10:52:47 +00001025 // We need to toggle the run lock as this won't get done in
1026 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001027 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028 m_public_run_lock.SetStopped();
1029 return state;
1030 }
1031 default:
1032 continue;
1033 }
1034 }
1035 return state;
1036}
1037
1038bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1039 Stream *stream,
1040 bool &pop_process_io_handler) {
1041 const bool handle_pop = pop_process_io_handler;
1042
1043 pop_process_io_handler = false;
1044 ProcessSP process_sp =
1045 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1046
1047 if (!process_sp)
1048 return false;
1049
1050 StateType event_state =
1051 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1052 if (event_state == eStateInvalid)
1053 return false;
1054
1055 switch (event_state) {
1056 case eStateInvalid:
1057 case eStateUnloaded:
1058 case eStateAttaching:
1059 case eStateLaunching:
1060 case eStateStepping:
1061 case eStateDetached:
1062 if (stream)
1063 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1064 StateAsCString(event_state));
1065 if (event_state == eStateDetached)
1066 pop_process_io_handler = true;
1067 break;
1068
1069 case eStateConnected:
1070 case eStateRunning:
1071 // Don't be chatty when we run...
1072 break;
1073
1074 case eStateExited:
1075 if (stream)
1076 process_sp->GetStatus(*stream);
1077 pop_process_io_handler = true;
1078 break;
1079
1080 case eStateStopped:
1081 case eStateCrashed:
1082 case eStateSuspended:
1083 // Make sure the program hasn't been auto-restarted:
1084 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1085 if (stream) {
1086 size_t num_reasons =
1087 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1088 if (num_reasons > 0) {
1089 // FIXME: Do we want to report this, or would that just be annoyingly
1090 // chatty?
1091 if (num_reasons == 1) {
1092 const char *reason =
1093 Process::ProcessEventData::GetRestartedReasonAtIndex(
1094 event_sp.get(), 0);
1095 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1096 process_sp->GetID(),
1097 reason ? reason : "<UNKNOWN REASON>");
1098 } else {
1099 stream->Printf("Process %" PRIu64
1100 " stopped and restarted, reasons:\n",
1101 process_sp->GetID());
1102
1103 for (size_t i = 0; i < num_reasons; i++) {
1104 const char *reason =
1105 Process::ProcessEventData::GetRestartedReasonAtIndex(
1106 event_sp.get(), i);
1107 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1108 }
1109 }
1110 }
1111 }
1112 } else {
1113 StopInfoSP curr_thread_stop_info_sp;
1114 // Lock the thread list so it doesn't change on us, this is the scope for
1115 // the locker:
1116 {
1117 ThreadList &thread_list = process_sp->GetThreadList();
1118 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1119
1120 ThreadSP curr_thread(thread_list.GetSelectedThread());
1121 ThreadSP thread;
1122 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1123 if (curr_thread) {
1124 curr_thread_stop_reason = curr_thread->GetStopReason();
1125 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1126 }
1127 if (!curr_thread || !curr_thread->IsValid() ||
1128 curr_thread_stop_reason == eStopReasonInvalid ||
1129 curr_thread_stop_reason == eStopReasonNone) {
1130 // Prefer a thread that has just completed its plan over another
1131 // thread as current thread.
1132 ThreadSP plan_thread;
1133 ThreadSP other_thread;
1134
1135 const size_t num_threads = thread_list.GetSize();
1136 size_t i;
1137 for (i = 0; i < num_threads; ++i) {
1138 thread = thread_list.GetThreadAtIndex(i);
1139 StopReason thread_stop_reason = thread->GetStopReason();
1140 switch (thread_stop_reason) {
1141 case eStopReasonInvalid:
1142 case eStopReasonNone:
1143 break;
1144
1145 case eStopReasonSignal: {
1146 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +00001147 // that signal. We have to have had another reason for stopping
1148 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149 uint64_t signo = thread->GetStopInfo()->GetValue();
1150 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1151 if (!other_thread)
1152 other_thread = thread;
1153 }
1154 break;
1155 }
1156 case eStopReasonTrace:
1157 case eStopReasonBreakpoint:
1158 case eStopReasonWatchpoint:
1159 case eStopReasonException:
1160 case eStopReasonExec:
1161 case eStopReasonThreadExiting:
1162 case eStopReasonInstrumentation:
1163 if (!other_thread)
1164 other_thread = thread;
1165 break;
1166 case eStopReasonPlanComplete:
1167 if (!plan_thread)
1168 plan_thread = thread;
1169 break;
1170 }
1171 }
1172 if (plan_thread)
1173 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1174 else if (other_thread)
1175 thread_list.SetSelectedThreadByID(other_thread->GetID());
1176 else {
1177 if (curr_thread && curr_thread->IsValid())
1178 thread = curr_thread;
1179 else
1180 thread = thread_list.GetThreadAtIndex(0);
1181
1182 if (thread)
1183 thread_list.SetSelectedThreadByID(thread->GetID());
1184 }
1185 }
1186 }
1187 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +00001188 // have to run code, e.g. for Data formatters, and if we hold the
1189 // ThreadList mutex, then the process is going to have a hard time
1190 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001191 if (stream) {
1192 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1193 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1194 &process_sp->GetTarget()) {
1195 const bool only_threads_with_stop_reason = true;
1196 const uint32_t start_frame = 0;
1197 const uint32_t num_frames = 1;
1198 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001199 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001200 process_sp->GetStatus(*stream);
1201 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1202 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001203 num_frames_with_source,
1204 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 if (curr_thread_stop_info_sp) {
1206 lldb::addr_t crashing_address;
1207 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1208 curr_thread_stop_info_sp, &crashing_address);
1209 if (valobj_sp) {
1210 const bool qualify_cxx_base_classes = false;
1211
1212 const ValueObject::GetExpressionPathFormat format =
1213 ValueObject::GetExpressionPathFormat::
1214 eGetExpressionPathFormatHonorPointers;
1215 stream->PutCString("Likely cause: ");
1216 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1217 format);
1218 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1219 }
1220 }
1221 } else {
1222 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1223 process_sp->GetTarget().shared_from_this());
1224 if (target_idx != UINT32_MAX)
1225 stream->Printf("Target %d: (", target_idx);
1226 else
1227 stream->Printf("Target <unknown index>: (");
1228 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1229 stream->Printf(") stopped.\n");
1230 }
1231 }
1232
1233 // Pop the process IO handler
1234 pop_process_io_handler = true;
1235 }
1236 break;
1237 }
1238
1239 if (handle_pop && pop_process_io_handler)
1240 process_sp->PopProcessIOHandler();
1241
1242 return true;
1243}
1244
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1246 if (listener_sp) {
1247 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1248 eBroadcastBitInterrupt);
1249 } else
1250 return false;
1251}
Greg Claytondc6224e2014-10-21 01:00:42 +00001252
Kate Stoneb9c1b512016-09-06 20:57:50 +00001253void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001254
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001255StateType Process::GetStateChangedEvents(EventSP &event_sp,
1256 const Timeout<std::micro> &timeout,
1257 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001259 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001260
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 ListenerSP listener_sp = hijack_listener_sp;
1262 if (!listener_sp)
1263 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001264
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001266 if (listener_sp->GetEventForBroadcasterWithType(
1267 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001268 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1270 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001271 else
1272 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001273 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001274
Pavel Labathd02b1c82017-02-10 11:49:33 +00001275 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276 return state;
1277}
Greg Claytondc6224e2014-10-21 01:00:42 +00001278
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279Event *Process::PeekAtStateChangedEvents() {
1280 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001281
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 if (log)
1283 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001284
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285 Event *event_ptr;
1286 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1287 this, eBroadcastBitStateChanged);
1288 if (log) {
1289 if (event_ptr) {
1290 log->Printf(
1291 "Process::%s (event_ptr) => %s", __FUNCTION__,
1292 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1293 } else {
1294 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001295 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 }
1297 return event_ptr;
1298}
Greg Claytondc6224e2014-10-21 01:00:42 +00001299
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001300StateType
1301Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1302 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001304 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001305
1306 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001307 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1308 &m_private_state_broadcaster,
1309 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001310 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001311 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1312 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1313
Pavel Labathd02b1c82017-02-10 11:49:33 +00001314 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1315 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316 return state;
1317}
1318
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001319bool Process::GetEventsPrivate(EventSP &event_sp,
1320 const Timeout<std::micro> &timeout,
1321 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001323 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324
1325 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001326 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001327 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001329 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330}
1331
1332bool Process::IsRunning() const {
1333 return StateIsRunningState(m_public_state.GetValue());
1334}
1335
1336int Process::GetExitStatus() {
1337 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1338
1339 if (m_public_state.GetValue() == eStateExited)
1340 return m_exit_status;
1341 return -1;
1342}
1343
1344const char *Process::GetExitDescription() {
1345 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1346
1347 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1348 return m_exit_string.c_str();
1349 return nullptr;
1350}
1351
1352bool Process::SetExitStatus(int status, const char *cstr) {
1353 // Use a mutex to protect setting the exit status.
1354 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1355
1356 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1357 LIBLLDB_LOG_PROCESS));
1358 if (log)
1359 log->Printf(
1360 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1361 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1362 cstr ? "\"" : "");
1363
1364 // We were already in the exited state
1365 if (m_private_state.GetValue() == eStateExited) {
1366 if (log)
1367 log->Printf("Process::SetExitStatus () ignoring exit status because "
1368 "state was already set to eStateExited");
1369 return false;
1370 }
1371
1372 m_exit_status = status;
1373 if (cstr)
1374 m_exit_string = cstr;
1375 else
1376 m_exit_string.clear();
1377
Adrian Prantl05097242018-04-30 16:49:04 +00001378 // Clear the last natural stop ID since it has a strong reference to this
1379 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001380 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1381
1382 SetPrivateState(eStateExited);
1383
1384 // Allow subclasses to do some cleanup
1385 DidExit();
1386
1387 return true;
1388}
1389
1390bool Process::IsAlive() {
1391 switch (m_private_state.GetValue()) {
1392 case eStateConnected:
1393 case eStateAttaching:
1394 case eStateLaunching:
1395 case eStateStopped:
1396 case eStateRunning:
1397 case eStateStepping:
1398 case eStateCrashed:
1399 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001400 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001401 default:
1402 return false;
1403 }
Jason Molendaa814f702015-11-05 23:03:44 +00001404}
1405
Adrian Prantl05097242018-04-30 16:49:04 +00001406// This static callback can be used to watch for local child processes on the
1407// current host. The child process exits, the process will be found in the
1408// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001409// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410bool Process::SetProcessExitStatus(
1411 lldb::pid_t pid, bool exited,
1412 int signo, // Zero for no signal
1413 int exit_status // Exit value of process if signal is zero
1414 ) {
1415 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1416 if (log)
1417 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1418 ", exited=%i, signal=%i, exit_status=%i)\n",
1419 pid, exited, signo, exit_status);
1420
1421 if (exited) {
1422 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1423 if (target_sp) {
1424 ProcessSP process_sp(target_sp->GetProcessSP());
1425 if (process_sp) {
1426 const char *signal_cstr = nullptr;
1427 if (signo)
1428 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1429
1430 process_sp->SetExitStatus(exit_status, signal_cstr);
1431 }
1432 }
1433 return true;
1434 }
1435 return false;
1436}
1437
1438void Process::UpdateThreadListIfNeeded() {
1439 const uint32_t stop_id = GetStopID();
1440 if (m_thread_list.GetSize(false) == 0 ||
1441 stop_id != m_thread_list.GetStopID()) {
1442 const StateType state = GetPrivateState();
1443 if (StateIsStoppedState(state, true)) {
1444 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Adrian Prantl05097242018-04-30 16:49:04 +00001445 // m_thread_list does have its own mutex, but we need to hold onto the
1446 // mutex between the call to UpdateThreadList(...) and the
1447 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001448 ThreadList &old_thread_list = m_thread_list;
1449 ThreadList real_thread_list(this);
1450 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001451 // Always update the thread list with the protocol specific thread list,
1452 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001453 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1454 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001455 // are shutting down, since that may call back into the SBAPI's,
1456 // requiring the API lock which is already held by whoever is shutting
1457 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001458 OperatingSystem *os = GetOperatingSystem();
1459 if (os && !m_destroy_in_process) {
1460 // Clear any old backing threads where memory threads might have been
1461 // backed by actual threads from the lldb_private::Process subclass
1462 size_t num_old_threads = old_thread_list.GetSize(false);
1463 for (size_t i = 0; i < num_old_threads; ++i)
1464 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1465
1466 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001467 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001468 // dynamic type or not and we need to avoid this. OperatingSystem
1469 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001470
1471 Target &target = GetTarget();
1472 const lldb::DynamicValueType saved_prefer_dynamic =
1473 target.GetPreferDynamicValue();
1474 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1475 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1476
1477 // Now let the OperatingSystem plug-in update the thread list
1478
1479 os->UpdateThreadList(
1480 old_thread_list, // Old list full of threads created by OS plug-in
1481 real_thread_list, // The actual thread list full of threads
1482 // created by each lldb_private::Process
1483 // subclass
1484 new_thread_list); // The new thread list that we will show to the
1485 // user that gets filled in
1486
1487 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1488 target.SetPreferDynamicValue(saved_prefer_dynamic);
1489 } else {
1490 // No OS plug-in, the new thread list is the same as the real thread
1491 // list
1492 new_thread_list = real_thread_list;
1493 }
1494
1495 m_thread_list_real.Update(real_thread_list);
1496 m_thread_list.Update(new_thread_list);
1497 m_thread_list.SetStopID(stop_id);
1498
1499 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1500 // Clear any extended threads that we may have accumulated previously
1501 m_extended_thread_list.Clear();
1502 m_extended_thread_stop_id = GetLastNaturalStopID();
1503
1504 m_queue_list.Clear();
1505 m_queue_list_stop_id = GetLastNaturalStopID();
1506 }
1507 }
1508 }
1509 }
1510}
1511
1512void Process::UpdateQueueListIfNeeded() {
1513 if (m_system_runtime_ap) {
1514 if (m_queue_list.GetSize() == 0 ||
1515 m_queue_list_stop_id != GetLastNaturalStopID()) {
1516 const StateType state = GetPrivateState();
1517 if (StateIsStoppedState(state, true)) {
1518 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1519 m_queue_list_stop_id = GetLastNaturalStopID();
1520 }
1521 }
1522 }
1523}
1524
1525ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1526 OperatingSystem *os = GetOperatingSystem();
1527 if (os)
1528 return os->CreateThread(tid, context);
1529 return ThreadSP();
1530}
1531
1532uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1533 return AssignIndexIDToThread(thread_id);
1534}
1535
1536bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1537 return (m_thread_id_to_index_id_map.find(thread_id) !=
1538 m_thread_id_to_index_id_map.end());
1539}
1540
1541uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1542 uint32_t result = 0;
1543 std::map<uint64_t, uint32_t>::iterator iterator =
1544 m_thread_id_to_index_id_map.find(thread_id);
1545 if (iterator == m_thread_id_to_index_id_map.end()) {
1546 result = ++m_thread_index_id;
1547 m_thread_id_to_index_id_map[thread_id] = result;
1548 } else {
1549 result = iterator->second;
1550 }
1551
1552 return result;
1553}
1554
1555StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001556 return m_public_state.GetValue();
1557}
1558
1559bool Process::StateChangedIsExternallyHijacked() {
1560 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1561 const char *hijacking_name = GetHijackingListenerName();
1562 if (hijacking_name &&
1563 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1564 return true;
1565 }
1566 return false;
1567}
1568
1569void Process::SetPublicState(StateType new_state, bool restarted) {
1570 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1571 LIBLLDB_LOG_PROCESS));
1572 if (log)
1573 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1574 StateAsCString(new_state), restarted);
1575 const StateType old_state = m_public_state.GetValue();
1576 m_public_state.SetValue(new_state);
1577
Adrian Prantl05097242018-04-30 16:49:04 +00001578 // On the transition from Run to Stopped, we unlock the writer end of the run
1579 // lock. The lock gets locked in Resume, which is the public API to tell the
1580 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001581 if (!StateChangedIsExternallyHijacked()) {
1582 if (new_state == eStateDetached) {
1583 if (log)
1584 log->Printf(
1585 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1586 StateAsCString(new_state));
1587 m_public_run_lock.SetStopped();
1588 } else {
1589 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1590 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1591 if ((old_state_is_stopped != new_state_is_stopped)) {
1592 if (new_state_is_stopped && !restarted) {
1593 if (log)
1594 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1595 StateAsCString(new_state));
1596 m_public_run_lock.SetStopped();
1597 }
1598 }
1599 }
1600 }
1601}
1602
Zachary Turner97206d52017-05-12 04:51:55 +00001603Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001604 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1605 LIBLLDB_LOG_PROCESS));
1606 if (log)
1607 log->Printf("Process::Resume -- locking run lock");
1608 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001609 Status error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001610 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001611 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001612 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001613 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001614 Status error = PrivateResume();
1615 if (!error.Success()) {
1616 // Undo running state change
1617 m_public_run_lock.SetStopped();
1618 }
1619 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001620}
1621
Zachary Turner97206d52017-05-12 04:51:55 +00001622Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001623 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1624 LIBLLDB_LOG_PROCESS));
1625 if (log)
1626 log->Printf("Process::ResumeSynchronous -- locking run lock");
1627 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001628 Status error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001629 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001630 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1631 return error;
1632 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001633
Kate Stoneb9c1b512016-09-06 20:57:50 +00001634 ListenerSP listener_sp(
1635 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1636 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001637
Zachary Turner97206d52017-05-12 04:51:55 +00001638 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001639 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001640 StateType state =
1641 WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001642 const bool must_be_alive =
1643 false; // eStateExited is ok, so this must be false
1644 if (!StateIsStoppedState(state, must_be_alive))
1645 error.SetErrorStringWithFormat(
1646 "process not in stopped state after synchronous resume: %s",
1647 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001648 } else {
1649 // Undo running state change
1650 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001651 }
Ed Mastec29693f2013-07-02 16:35:47 +00001652
Kate Stoneb9c1b512016-09-06 20:57:50 +00001653 // Undo the hijacking of process events...
1654 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001655
Kate Stoneb9c1b512016-09-06 20:57:50 +00001656 return error;
1657}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001658
Kate Stoneb9c1b512016-09-06 20:57:50 +00001659StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001660
Kate Stoneb9c1b512016-09-06 20:57:50 +00001661void Process::SetPrivateState(StateType new_state) {
1662 if (m_finalize_called)
1663 return;
1664
1665 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1666 LIBLLDB_LOG_PROCESS));
1667 bool state_changed = false;
1668
1669 if (log)
1670 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1671
1672 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1673 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1674
1675 const StateType old_state = m_private_state.GetValueNoLock();
1676 state_changed = old_state != new_state;
1677
1678 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1679 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1680 if (old_state_is_stopped != new_state_is_stopped) {
1681 if (new_state_is_stopped)
1682 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001683 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001684 m_private_run_lock.SetRunning();
1685 }
1686
1687 if (state_changed) {
1688 m_private_state.SetValueNoLock(new_state);
1689 EventSP event_sp(
1690 new Event(eBroadcastBitStateChanged,
1691 new ProcessEventData(shared_from_this(), new_state)));
1692 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001693 // Note, this currently assumes that all threads in the list stop when
1694 // the process stops. In the future we will want to support a debugging
1695 // model where some threads continue to run while others are stopped.
1696 // When that happens we will either need a way for the thread list to
1697 // identify which threads are stopping or create a special thread list
1698 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699 //
Adrian Prantl05097242018-04-30 16:49:04 +00001700 // The process plugin is responsible for managing the actual behavior of
1701 // the threads and should have stopped any threads that are going to stop
1702 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001703 m_thread_list.DidStop();
1704
1705 m_mod_id.BumpStopID();
1706 if (!m_mod_id.IsLastResumeForUserExpression())
1707 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1708 m_memory_cache.Clear();
1709 if (log)
1710 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1711 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001712 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001713
Kate Stoneb9c1b512016-09-06 20:57:50 +00001714 // Use our target to get a shared pointer to ourselves...
1715 if (m_finalize_called && !PrivateStateThreadIsValid())
1716 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001717 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001718 m_private_state_broadcaster.BroadcastEvent(event_sp);
1719 } else {
1720 if (log)
1721 log->Printf(
1722 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1723 StateAsCString(new_state));
1724 }
Jim Ingham22777012010-09-23 02:01:19 +00001725}
1726
Kate Stoneb9c1b512016-09-06 20:57:50 +00001727void Process::SetRunningUserExpression(bool on) {
1728 m_mod_id.SetRunningUserExpression(on);
1729}
1730
Raphael Isemannc01783a2018-08-29 22:50:54 +00001731void Process::SetRunningUtilityFunction(bool on) {
1732 m_mod_id.SetRunningUtilityFunction(on);
1733}
1734
Kate Stoneb9c1b512016-09-06 20:57:50 +00001735addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1736
1737const lldb::ABISP &Process::GetABI() {
1738 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001739 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001740 return m_abi_sp;
1741}
1742
1743LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1744 bool retry_if_null) {
1745 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001746 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747
1748 LanguageRuntimeCollection::iterator pos;
1749 pos = m_language_runtimes.find(language);
1750 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1751 lldb::LanguageRuntimeSP runtime_sp(
1752 LanguageRuntime::FindPlugin(this, language));
1753
1754 m_language_runtimes[language] = runtime_sp;
1755 return runtime_sp.get();
1756 } else
1757 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001758}
1759
Kate Stoneb9c1b512016-09-06 20:57:50 +00001760CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1761 LanguageRuntime *runtime =
1762 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1763 if (runtime != nullptr &&
1764 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1765 return static_cast<CPPLanguageRuntime *>(runtime);
1766 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001767}
1768
Kate Stoneb9c1b512016-09-06 20:57:50 +00001769ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1770 LanguageRuntime *runtime =
1771 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1772 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1773 return static_cast<ObjCLanguageRuntime *>(runtime);
1774 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001775}
1776
Kate Stoneb9c1b512016-09-06 20:57:50 +00001777bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1778 if (m_finalizing)
1779 return false;
1780
1781 if (in_value.IsDynamic())
1782 return false;
1783 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1784
1785 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1786 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1787 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1788 }
1789
1790 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1791 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1792 return true;
1793
1794 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1795 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001796}
1797
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1799 m_dynamic_checkers_ap.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001800}
1801
Kate Stoneb9c1b512016-09-06 20:57:50 +00001802BreakpointSiteList &Process::GetBreakpointSiteList() {
1803 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001804}
1805
Kate Stoneb9c1b512016-09-06 20:57:50 +00001806const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1807 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808}
1809
Kate Stoneb9c1b512016-09-06 20:57:50 +00001810void Process::DisableAllBreakpointSites() {
1811 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1812 // bp_site->SetEnabled(true);
1813 DisableBreakpointSite(bp_site);
1814 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001815}
1816
Zachary Turner97206d52017-05-12 04:51:55 +00001817Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1818 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001819
Kate Stoneb9c1b512016-09-06 20:57:50 +00001820 if (error.Success())
1821 m_breakpoint_site_list.Remove(break_id);
1822
1823 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824}
1825
Zachary Turner97206d52017-05-12 04:51:55 +00001826Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1827 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001828 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1829 if (bp_site_sp) {
1830 if (bp_site_sp->IsEnabled())
1831 error = DisableBreakpointSite(bp_site_sp.get());
1832 } else {
1833 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1834 break_id);
1835 }
1836
1837 return error;
1838}
1839
Zachary Turner97206d52017-05-12 04:51:55 +00001840Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1841 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001842 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1843 if (bp_site_sp) {
1844 if (!bp_site_sp->IsEnabled())
1845 error = EnableBreakpointSite(bp_site_sp.get());
1846 } else {
1847 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1848 break_id);
1849 }
1850 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001851}
1852
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001853lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001854Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1855 bool use_hardware) {
1856 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001857
Kate Stoneb9c1b512016-09-06 20:57:50 +00001858 bool show_error = true;
1859 switch (GetState()) {
1860 case eStateInvalid:
1861 case eStateUnloaded:
1862 case eStateConnected:
1863 case eStateAttaching:
1864 case eStateLaunching:
1865 case eStateDetached:
1866 case eStateExited:
1867 show_error = false;
1868 break;
1869
1870 case eStateStopped:
1871 case eStateRunning:
1872 case eStateStepping:
1873 case eStateCrashed:
1874 case eStateSuspended:
1875 show_error = IsAlive();
1876 break;
1877 }
1878
Adrian Prantl05097242018-04-30 16:49:04 +00001879 // Reset the IsIndirect flag here, in case the location changes from pointing
1880 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001881 owner->SetIsIndirect(false);
1882
1883 if (owner->ShouldResolveIndirectFunctions()) {
1884 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1885 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001886 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001887 Address symbol_address = symbol->GetAddress();
1888 load_addr = ResolveIndirectFunction(&symbol_address, error);
1889 if (!error.Success() && show_error) {
1890 GetTarget().GetDebugger().GetErrorFile()->Printf(
1891 "warning: failed to resolve indirect function at 0x%" PRIx64
1892 " for breakpoint %i.%i: %s\n",
1893 symbol->GetLoadAddress(&GetTarget()),
1894 owner->GetBreakpoint().GetID(), owner->GetID(),
1895 error.AsCString() ? error.AsCString() : "unknown error");
1896 return LLDB_INVALID_BREAK_ID;
1897 }
1898 Address resolved_address(load_addr);
1899 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1900 owner->SetIsIndirect(true);
1901 } else
1902 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1903 } else
1904 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1905
1906 if (load_addr != LLDB_INVALID_ADDRESS) {
1907 BreakpointSiteSP bp_site_sp;
1908
1909 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001910 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001911
1912 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1913
1914 if (bp_site_sp) {
1915 bp_site_sp->AddOwner(owner);
1916 owner->SetBreakpointSite(bp_site_sp);
1917 return bp_site_sp->GetID();
1918 } else {
1919 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1920 load_addr, use_hardware));
1921 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001922 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001923 if (error.Success()) {
1924 owner->SetBreakpointSite(bp_site_sp);
1925 return m_breakpoint_site_list.Add(bp_site_sp);
1926 } else {
1927 if (show_error) {
1928 // Report error for setting breakpoint...
1929 GetTarget().GetDebugger().GetErrorFile()->Printf(
1930 "warning: failed to set breakpoint site at 0x%" PRIx64
1931 " for breakpoint %i.%i: %s\n",
1932 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1933 error.AsCString() ? error.AsCString() : "unknown error");
1934 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001935 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001936 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001937 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001938 }
1939 // We failed to enable the breakpoint
1940 return LLDB_INVALID_BREAK_ID;
1941}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001942
Kate Stoneb9c1b512016-09-06 20:57:50 +00001943void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1944 lldb::user_id_t owner_loc_id,
1945 BreakpointSiteSP &bp_site_sp) {
1946 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1947 if (num_owners == 0) {
1948 // Don't try to disable the site if we don't have a live process anymore.
1949 if (IsAlive())
1950 DisableBreakpointSite(bp_site_sp.get());
1951 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1952 }
1953}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001954
Kate Stoneb9c1b512016-09-06 20:57:50 +00001955size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1956 uint8_t *buf) const {
1957 size_t bytes_removed = 0;
1958 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001959
Kate Stoneb9c1b512016-09-06 20:57:50 +00001960 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1961 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001962 bp_sites_in_range.ForEach([bp_addr, size,
1963 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001964 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1965 addr_t intersect_addr;
1966 size_t intersect_size;
1967 size_t opcode_offset;
1968 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1969 &intersect_size, &opcode_offset)) {
1970 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1971 assert(bp_addr < intersect_addr + intersect_size &&
1972 intersect_addr + intersect_size <= bp_addr + size);
1973 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1974 size_t buf_offset = intersect_addr - bp_addr;
1975 ::memcpy(buf + buf_offset,
1976 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1977 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001978 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001979 }
1980 });
1981 }
1982 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001983}
1984
Kate Stoneb9c1b512016-09-06 20:57:50 +00001985size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1986 PlatformSP platform_sp(GetTarget().GetPlatform());
1987 if (platform_sp)
1988 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1989 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001990}
1991
Zachary Turner97206d52017-05-12 04:51:55 +00001992Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1993 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001994 assert(bp_site != nullptr);
1995 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1996 const addr_t bp_addr = bp_site->GetLoadAddress();
1997 if (log)
1998 log->Printf(
1999 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
2000 bp_site->GetID(), (uint64_t)bp_addr);
2001 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002002 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002003 log->Printf(
2004 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2005 " -- already enabled",
2006 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002007 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002008 }
2009
2010 if (bp_addr == LLDB_INVALID_ADDRESS) {
2011 error.SetErrorString("BreakpointSite contains an invalid load address.");
2012 return error;
2013 }
2014 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2015 // trap for the breakpoint site
2016 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2017
2018 if (bp_opcode_size == 0) {
2019 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2020 "returned zero, unable to get breakpoint "
2021 "trap for address 0x%" PRIx64,
2022 bp_addr);
2023 } else {
2024 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2025
2026 if (bp_opcode_bytes == nullptr) {
2027 error.SetErrorString(
2028 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2029 return error;
2030 }
2031
2032 // Save the original opcode by reading it
2033 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2034 error) == bp_opcode_size) {
2035 // Write a software breakpoint in place of the original opcode
2036 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2037 bp_opcode_size) {
2038 uint8_t verify_bp_opcode_bytes[64];
2039 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2040 error) == bp_opcode_size) {
2041 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2042 bp_opcode_size) == 0) {
2043 bp_site->SetEnabled(true);
2044 bp_site->SetType(BreakpointSite::eSoftware);
2045 if (log)
2046 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2047 "addr = 0x%" PRIx64 " -- SUCCESS",
2048 bp_site->GetID(), (uint64_t)bp_addr);
2049 } else
2050 error.SetErrorString(
2051 "failed to verify the breakpoint trap in memory.");
2052 } else
2053 error.SetErrorString(
2054 "Unable to read memory to verify breakpoint trap.");
2055 } else
2056 error.SetErrorString("Unable to write breakpoint trap to memory.");
2057 } else
2058 error.SetErrorString("Unable to read memory at breakpoint address.");
2059 }
2060 if (log && error.Fail())
2061 log->Printf(
2062 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2063 " -- FAILED: %s",
2064 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2065 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066}
2067
Zachary Turner97206d52017-05-12 04:51:55 +00002068Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2069 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002070 assert(bp_site != nullptr);
2071 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2072 addr_t bp_addr = bp_site->GetLoadAddress();
2073 lldb::user_id_t breakID = bp_site->GetID();
2074 if (log)
2075 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2076 ") addr = 0x%" PRIx64,
2077 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002078
Kate Stoneb9c1b512016-09-06 20:57:50 +00002079 if (bp_site->IsHardware()) {
2080 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2081 } else if (bp_site->IsEnabled()) {
2082 const size_t break_op_size = bp_site->GetByteSize();
2083 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2084 if (break_op_size > 0) {
2085 // Clear a software breakpoint instruction
2086 uint8_t curr_break_op[8];
2087 assert(break_op_size <= sizeof(curr_break_op));
2088 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002089
Kate Stoneb9c1b512016-09-06 20:57:50 +00002090 // Read the breakpoint opcode
2091 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2092 break_op_size) {
2093 bool verify = false;
2094 // Make sure the breakpoint opcode exists at this address
2095 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2096 break_op_found = true;
2097 // We found a valid breakpoint opcode at this address, now restore
2098 // the saved opcode.
2099 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2100 break_op_size, error) == break_op_size) {
2101 verify = true;
2102 } else
2103 error.SetErrorString(
2104 "Memory write failed when restoring original opcode.");
2105 } else {
2106 error.SetErrorString(
2107 "Original breakpoint trap is no longer in memory.");
2108 // Set verify to true and so we can check if the original opcode has
2109 // already been restored
2110 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002112
Kate Stoneb9c1b512016-09-06 20:57:50 +00002113 if (verify) {
2114 uint8_t verify_opcode[8];
2115 assert(break_op_size < sizeof(verify_opcode));
2116 // Verify that our original opcode made it back to the inferior
2117 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2118 break_op_size) {
2119 // compare the memory we just read with the original opcode
2120 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2121 break_op_size) == 0) {
2122 // SUCCESS
2123 bp_site->SetEnabled(false);
2124 if (log)
2125 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2126 "addr = 0x%" PRIx64 " -- SUCCESS",
2127 bp_site->GetID(), (uint64_t)bp_addr);
2128 return error;
2129 } else {
2130 if (break_op_found)
2131 error.SetErrorString("Failed to restore original opcode.");
2132 }
2133 } else
2134 error.SetErrorString("Failed to read memory to verify that "
2135 "breakpoint trap was restored.");
2136 }
2137 } else
2138 error.SetErrorString(
2139 "Unable to read memory that should contain the breakpoint trap.");
2140 }
2141 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002143 log->Printf(
2144 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2145 " -- already disabled",
2146 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002147 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002148 }
2149
2150 if (log)
2151 log->Printf(
2152 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2153 " -- FAILED: %s",
2154 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2155 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002156}
2157
Adrian Prantl05097242018-04-30 16:49:04 +00002158// Uncomment to verify memory caching works after making changes to caching
2159// code
Greg Clayton58be07b2011-01-07 06:08:19 +00002160//#define VERIFY_MEMORY_READS
2161
Zachary Turner97206d52017-05-12 04:51:55 +00002162size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002163 error.Clear();
2164 if (!GetDisableMemoryCache()) {
2165#if defined(VERIFY_MEMORY_READS)
2166 // Memory caching is enabled, with debug verification
2167
2168 if (buf && size) {
2169 // Uncomment the line below to make sure memory caching is working.
2170 // I ran this through the test suite and got no assertions, so I am
2171 // pretty confident this is working well. If any changes are made to
2172 // memory caching, uncomment the line below and test your changes!
2173
2174 // Verify all memory reads by using the cache first, then redundantly
2175 // reading the same memory from the inferior and comparing to make sure
2176 // everything is exactly the same.
2177 std::string verify_buf(size, '\0');
2178 assert(verify_buf.size() == size);
2179 const size_t cache_bytes_read =
2180 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00002181 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002182 const size_t verify_bytes_read =
2183 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2184 verify_buf.size(), verify_error);
2185 assert(cache_bytes_read == verify_bytes_read);
2186 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2187 assert(verify_error.Success() == error.Success());
2188 return cache_bytes_read;
2189 }
2190 return 0;
2191#else // !defined(VERIFY_MEMORY_READS)
2192 // Memory caching is enabled, without debug verification
2193
2194 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002195#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002196 } else {
2197 // Memory caching is disabled
2198
2199 return ReadMemoryFromInferior(addr, buf, size, error);
2200 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002201}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002202
2203size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00002204 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002205 char buf[256];
2206 out_str.clear();
2207 addr_t curr_addr = addr;
2208 while (true) {
2209 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2210 if (length == 0)
2211 break;
2212 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00002213 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2214 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00002215 if (length == sizeof(buf) - 1)
2216 curr_addr += length;
2217 else
2218 break;
2219 }
2220 return out_str.size();
2221}
2222
2223size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00002224 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002225 size_t total_bytes_read = 0;
2226 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00002227 // Ensure a null terminator independent of the number of bytes that is
2228 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002229 memset(dst, 0, max_bytes);
2230 size_t bytes_left = max_bytes - type_width;
2231
2232 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2233 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2234 "string with more than 4 bytes "
2235 "per character!");
2236
Greg Clayton4c82d422012-05-18 23:20:01 +00002237 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2239 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002240
Kate Stoneb9c1b512016-09-06 20:57:50 +00002241 error.Clear();
2242 while (bytes_left > 0 && error.Success()) {
2243 addr_t cache_line_bytes_left =
2244 cache_line_size - (curr_addr % cache_line_size);
2245 addr_t bytes_to_read =
2246 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2247 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002248
Kate Stoneb9c1b512016-09-06 20:57:50 +00002249 if (bytes_read == 0)
2250 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002251
Kate Stoneb9c1b512016-09-06 20:57:50 +00002252 // Search for a null terminator of correct size and alignment in
2253 // bytes_read
2254 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2255 for (size_t i = aligned_start;
2256 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2257 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2258 error.Clear();
2259 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002260 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002261
2262 total_bytes_read += bytes_read;
2263 curr_dst += bytes_read;
2264 curr_addr += bytes_read;
2265 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002266 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002267 } else {
2268 if (max_bytes)
2269 error.SetErrorString("invalid arguments");
2270 }
2271 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002272}
2273
Kate Stoneb9c1b512016-09-06 20:57:50 +00002274// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002275// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002276size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002277 size_t dst_max_len,
2278 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002279 size_t total_cstr_len = 0;
2280 if (dst && dst_max_len) {
2281 result_error.Clear();
2282 // NULL out everything just to be safe
2283 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002284 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002285 addr_t curr_addr = addr;
2286 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2287 size_t bytes_left = dst_max_len - 1;
2288 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002289
Kate Stoneb9c1b512016-09-06 20:57:50 +00002290 while (bytes_left > 0) {
2291 addr_t cache_line_bytes_left =
2292 cache_line_size - (curr_addr % cache_line_size);
2293 addr_t bytes_to_read =
2294 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2295 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002296
Kate Stoneb9c1b512016-09-06 20:57:50 +00002297 if (bytes_read == 0) {
2298 result_error = error;
2299 dst[total_cstr_len] = '\0';
2300 break;
2301 }
2302 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002303
Kate Stoneb9c1b512016-09-06 20:57:50 +00002304 total_cstr_len += len;
2305
2306 if (len < bytes_to_read)
2307 break;
2308
2309 curr_dst += bytes_read;
2310 curr_addr += bytes_read;
2311 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002312 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002313 } else {
2314 if (dst == nullptr)
2315 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002316 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002317 result_error.Clear();
2318 }
2319 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002320}
2321
Kate Stoneb9c1b512016-09-06 20:57:50 +00002322size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002323 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324 if (buf == nullptr || size == 0)
2325 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326
Kate Stoneb9c1b512016-09-06 20:57:50 +00002327 size_t bytes_read = 0;
2328 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002329
Kate Stoneb9c1b512016-09-06 20:57:50 +00002330 while (bytes_read < size) {
2331 const size_t curr_size = size - bytes_read;
2332 const size_t curr_bytes_read =
2333 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2334 bytes_read += curr_bytes_read;
2335 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2336 break;
2337 }
2338
2339 // Replace any software breakpoint opcodes that fall into this range back
2340 // into "buf" before we return
2341 if (bytes_read > 0)
2342 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2343 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344}
2345
Kate Stoneb9c1b512016-09-06 20:57:50 +00002346uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2347 size_t integer_byte_size,
2348 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002349 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002350 Scalar scalar;
2351 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2352 error))
2353 return scalar.ULongLong(fail_value);
2354 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002355}
2356
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2358 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002359 int64_t fail_value,
2360 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002361 Scalar scalar;
2362 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2363 error))
2364 return scalar.SLongLong(fail_value);
2365 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002366}
2367
Zachary Turner97206d52017-05-12 04:51:55 +00002368addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002369 Scalar scalar;
2370 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2371 error))
2372 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2373 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002374}
2375
Kate Stoneb9c1b512016-09-06 20:57:50 +00002376bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002377 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002378 Scalar scalar;
2379 const uint32_t addr_byte_size = GetAddressByteSize();
2380 if (addr_byte_size <= 4)
2381 scalar = (uint32_t)ptr_value;
2382 else
2383 scalar = ptr_value;
2384 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2385 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002386}
2387
Kate Stoneb9c1b512016-09-06 20:57:50 +00002388size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002389 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002390 size_t bytes_written = 0;
2391 const uint8_t *bytes = (const uint8_t *)buf;
2392
2393 while (bytes_written < size) {
2394 const size_t curr_size = size - bytes_written;
2395 const size_t curr_bytes_written = DoWriteMemory(
2396 addr + bytes_written, bytes + bytes_written, curr_size, error);
2397 bytes_written += curr_bytes_written;
2398 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2399 break;
2400 }
2401 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002402}
2403
Kate Stoneb9c1b512016-09-06 20:57:50 +00002404size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002405 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002406#if defined(ENABLE_MEMORY_CACHING)
2407 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002408#endif
2409
Kate Stoneb9c1b512016-09-06 20:57:50 +00002410 if (buf == nullptr || size == 0)
2411 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002412
Kate Stoneb9c1b512016-09-06 20:57:50 +00002413 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002414
Kate Stoneb9c1b512016-09-06 20:57:50 +00002415 // We need to write any data that would go where any current software traps
2416 // (enabled software breakpoints) any software traps (breakpoints) that we
2417 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002418
Kate Stoneb9c1b512016-09-06 20:57:50 +00002419 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002420
Kate Stoneb9c1b512016-09-06 20:57:50 +00002421 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2422 bp_sites_in_range)) {
2423 // No breakpoint sites overlap
2424 if (bp_sites_in_range.IsEmpty())
2425 return WriteMemoryPrivate(addr, buf, size, error);
2426 else {
2427 const uint8_t *ubuf = (const uint8_t *)buf;
2428 uint64_t bytes_written = 0;
2429
2430 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2431 &error](BreakpointSite *bp) -> void {
2432
2433 if (error.Success()) {
2434 addr_t intersect_addr;
2435 size_t intersect_size;
2436 size_t opcode_offset;
2437 const bool intersects = bp->IntersectsRange(
2438 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2439 UNUSED_IF_ASSERT_DISABLED(intersects);
2440 assert(intersects);
2441 assert(addr <= intersect_addr && intersect_addr < addr + size);
2442 assert(addr < intersect_addr + intersect_size &&
2443 intersect_addr + intersect_size <= addr + size);
2444 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2445
2446 // Check for bytes before this breakpoint
2447 const addr_t curr_addr = addr + bytes_written;
2448 if (intersect_addr > curr_addr) {
Adrian Prantl05097242018-04-30 16:49:04 +00002449 // There are some bytes before this breakpoint that we need to just
2450 // write to memory
Kate Stoneb9c1b512016-09-06 20:57:50 +00002451 size_t curr_size = intersect_addr - curr_addr;
2452 size_t curr_bytes_written = WriteMemoryPrivate(
2453 curr_addr, ubuf + bytes_written, curr_size, error);
2454 bytes_written += curr_bytes_written;
2455 if (curr_bytes_written != curr_size) {
Adrian Prantl05097242018-04-30 16:49:04 +00002456 // We weren't able to write all of the requested bytes, we are
2457 // done looping and will return the number of bytes that we have
2458 // written so far.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002459 if (error.Success())
2460 error.SetErrorToGenericError();
2461 }
2462 }
2463 // Now write any bytes that would cover up any software breakpoints
2464 // directly into the breakpoint opcode buffer
2465 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2466 ubuf + bytes_written, intersect_size);
2467 bytes_written += intersect_size;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002468 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002469 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002470
Kate Stoneb9c1b512016-09-06 20:57:50 +00002471 if (bytes_written < size)
2472 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2473 size - bytes_written, error);
2474 }
2475 } else {
2476 return WriteMemoryPrivate(addr, buf, size, error);
2477 }
2478
2479 // Write any remaining bytes after the last breakpoint if we have any left
2480 return 0; // bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002481}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002482
Kate Stoneb9c1b512016-09-06 20:57:50 +00002483size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002484 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002485 if (byte_size == UINT32_MAX)
2486 byte_size = scalar.GetByteSize();
2487 if (byte_size > 0) {
2488 uint8_t buf[32];
2489 const size_t mem_size =
2490 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2491 if (mem_size > 0)
2492 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002493 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002494 error.SetErrorString("failed to get scalar as memory data");
2495 } else {
2496 error.SetErrorString("invalid scalar value");
2497 }
2498 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002499}
2500
Kate Stoneb9c1b512016-09-06 20:57:50 +00002501size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2502 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002503 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002504 uint64_t uval = 0;
2505 if (byte_size == 0) {
2506 error.SetErrorString("byte size is zero");
2507 } else if (byte_size & (byte_size - 1)) {
2508 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2509 byte_size);
2510 } else if (byte_size <= sizeof(uval)) {
2511 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2512 if (bytes_read == byte_size) {
2513 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2514 GetAddressByteSize());
2515 lldb::offset_t offset = 0;
2516 if (byte_size <= 4)
2517 scalar = data.GetMaxU32(&offset, byte_size);
2518 else
2519 scalar = data.GetMaxU64(&offset, byte_size);
2520 if (is_signed)
2521 scalar.SignExtend(byte_size * 8);
2522 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002523 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002524 } else {
2525 error.SetErrorStringWithFormat(
2526 "byte size of %u is too large for integer scalar type", byte_size);
2527 }
2528 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002529}
2530
Pavel Labath16064d32018-03-20 11:56:24 +00002531Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2532 Status error;
2533 for (const auto &Entry : entries) {
2534 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2535 error);
2536 if (!error.Success())
2537 break;
2538 }
2539 return error;
2540}
2541
Greg Claytond495c532011-05-17 03:37:42 +00002542#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002544 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002545 if (GetPrivateState() != eStateStopped) {
2546 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002547 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002548 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549
2550#if defined(USE_ALLOCATE_MEMORY_CACHE)
2551 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002552#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002553 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2554 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2555 if (log)
2556 log->Printf("Process::AllocateMemory(size=%" PRIu64
2557 ", permissions=%s) => 0x%16.16" PRIx64
2558 " (m_stop_id = %u m_memory_id = %u)",
2559 (uint64_t)size, GetPermissionsAsCString(permissions),
2560 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2561 m_mod_id.GetMemoryID());
2562 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002563#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002564}
2565
Kate Stoneb9c1b512016-09-06 20:57:50 +00002566addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002567 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002568 addr_t return_addr = AllocateMemory(size, permissions, error);
2569 if (error.Success()) {
2570 std::string buffer(size, 0);
2571 WriteMemory(return_addr, buffer.c_str(), size, error);
2572 }
2573 return return_addr;
2574}
2575
2576bool Process::CanJIT() {
2577 if (m_can_jit == eCanJITDontKnow) {
2578 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002579 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002580
2581 uint64_t allocated_memory = AllocateMemory(
2582 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2583 err);
2584
2585 if (err.Success()) {
2586 m_can_jit = eCanJITYes;
2587 if (log)
2588 log->Printf("Process::%s pid %" PRIu64
2589 " allocation test passed, CanJIT () is true",
2590 __FUNCTION__, GetID());
2591 } else {
2592 m_can_jit = eCanJITNo;
2593 if (log)
2594 log->Printf("Process::%s pid %" PRIu64
2595 " allocation test failed, CanJIT () is false: %s",
2596 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002597 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002598
2599 DeallocateMemory(allocated_memory);
2600 }
2601
2602 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002603}
2604
Kate Stoneb9c1b512016-09-06 20:57:50 +00002605void Process::SetCanJIT(bool can_jit) {
2606 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002607}
2608
Kate Stoneb9c1b512016-09-06 20:57:50 +00002609void Process::SetCanRunCode(bool can_run_code) {
2610 SetCanJIT(can_run_code);
2611 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002612}
2613
Zachary Turner97206d52017-05-12 04:51:55 +00002614Status Process::DeallocateMemory(addr_t ptr) {
2615 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002616#if defined(USE_ALLOCATE_MEMORY_CACHE)
2617 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2618 error.SetErrorStringWithFormat(
2619 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2620 }
Greg Claytond495c532011-05-17 03:37:42 +00002621#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002622 error = DoDeallocateMemory(ptr);
2623
2624 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2625 if (log)
2626 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2627 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2628 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2629 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002630#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002631 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002632}
2633
Kate Stoneb9c1b512016-09-06 20:57:50 +00002634ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2635 lldb::addr_t header_addr,
2636 size_t size_to_read) {
2637 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2638 if (log) {
2639 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2640 file_spec.GetPath().c_str());
2641 }
2642 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2643 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002644 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002645 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2646 shared_from_this(), header_addr, error, size_to_read);
2647 if (objfile)
2648 return module_sp;
2649 }
2650 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002651}
2652
Kate Stoneb9c1b512016-09-06 20:57:50 +00002653bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2654 uint32_t &permissions) {
2655 MemoryRegionInfo range_info;
2656 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002657 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002658 if (!error.Success())
2659 return false;
2660 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2661 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2662 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2663 return false;
2664 }
2665
2666 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2667 permissions |= lldb::ePermissionsReadable;
2668
2669 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2670 permissions |= lldb::ePermissionsWritable;
2671
2672 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2673 permissions |= lldb::ePermissionsExecutable;
2674
2675 return true;
2676}
2677
Zachary Turner97206d52017-05-12 04:51:55 +00002678Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2679 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002680 error.SetErrorString("watchpoints are not supported");
2681 return error;
2682}
2683
Zachary Turner97206d52017-05-12 04:51:55 +00002684Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2685 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002686 error.SetErrorString("watchpoints are not supported");
2687 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002688}
2689
2690StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002691Process::WaitForProcessStopPrivate(EventSP &event_sp,
2692 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002693 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002694
Kate Stoneb9c1b512016-09-06 20:57:50 +00002695 while (true) {
2696 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002697 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002698
Kate Stoneb9c1b512016-09-06 20:57:50 +00002699 if (StateIsStoppedState(state, false))
2700 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002701
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702 // If state is invalid, then we timed out
2703 if (state == eStateInvalid)
2704 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002705
Kate Stoneb9c1b512016-09-06 20:57:50 +00002706 if (event_sp)
2707 HandlePrivateEvent(event_sp);
2708 }
2709 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710}
2711
Kate Stoneb9c1b512016-09-06 20:57:50 +00002712void Process::LoadOperatingSystemPlugin(bool flush) {
2713 if (flush)
2714 m_thread_list.Clear();
2715 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2716 if (flush)
2717 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002718}
2719
Zachary Turner97206d52017-05-12 04:51:55 +00002720Status Process::Launch(ProcessLaunchInfo &launch_info) {
2721 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002722 m_abi_sp.reset();
2723 m_dyld_ap.reset();
2724 m_jit_loaders_ap.reset();
2725 m_system_runtime_ap.reset();
2726 m_os_ap.reset();
2727 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002728
Kate Stoneb9c1b512016-09-06 20:57:50 +00002729 Module *exe_module = GetTarget().GetExecutableModulePointer();
2730 if (exe_module) {
2731 char local_exec_file_path[PATH_MAX];
2732 char platform_exec_file_path[PATH_MAX];
2733 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2734 sizeof(local_exec_file_path));
2735 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2736 sizeof(platform_exec_file_path));
2737 if (exe_module->GetFileSpec().Exists()) {
2738 // Install anything that might need to be installed prior to launching.
2739 // For host systems, this will do nothing, but if we are connected to a
2740 // remote platform it will install any needed binaries
2741 error = GetTarget().Install(&launch_info);
2742 if (error.Fail())
2743 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002744
Kate Stoneb9c1b512016-09-06 20:57:50 +00002745 if (PrivateStateThreadIsValid())
2746 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002747
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 error = WillLaunch(exe_module);
2749 if (error.Success()) {
2750 const bool restarted = false;
2751 SetPublicState(eStateLaunching, restarted);
2752 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754 if (m_public_run_lock.TrySetRunning()) {
2755 // Now launch using these arguments.
2756 error = DoLaunch(exe_module, launch_info);
2757 } else {
2758 // This shouldn't happen
2759 error.SetErrorString("failed to acquire process run lock");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002760 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002761
Kate Stoneb9c1b512016-09-06 20:57:50 +00002762 if (error.Fail()) {
2763 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2764 SetID(LLDB_INVALID_PROCESS_ID);
2765 const char *error_string = error.AsCString();
2766 if (error_string == nullptr)
2767 error_string = "launch failed";
2768 SetExitStatus(-1, error_string);
2769 }
2770 } else {
2771 EventSP event_sp;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002772
2773 // Now wait for the process to launch and return control to us, and then call
2774 // DidLaunch:
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002775 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Greg Clayton35824e32015-02-20 20:59:47 +00002776
Kate Stoneb9c1b512016-09-06 20:57:50 +00002777 if (state == eStateInvalid || !event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002778 // We were able to launch the process, but we failed to catch the
2779 // initial stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002780 error.SetErrorString("failed to catch stop after launch");
2781 SetExitStatus(0, "failed to catch stop after launch");
2782 Destroy(false);
2783 } else if (state == eStateStopped || state == eStateCrashed) {
2784 DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002785
Kate Stoneb9c1b512016-09-06 20:57:50 +00002786 DynamicLoader *dyld = GetDynamicLoader();
2787 if (dyld)
2788 dyld->DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002789
Kate Stoneb9c1b512016-09-06 20:57:50 +00002790 GetJITLoaders().DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002791
Kate Stoneb9c1b512016-09-06 20:57:50 +00002792 SystemRuntime *system_runtime = GetSystemRuntime();
2793 if (system_runtime)
2794 system_runtime->DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002795
Greg Clayton29eeea02017-02-09 18:55:41 +00002796 if (!m_os_ap)
2797 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002798
Adrian Prantl05097242018-04-30 16:49:04 +00002799 // We successfully launched the process and stopped, now it the
2800 // right time to set up signal filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002801 UpdateAutomaticSignalFiltering();
2802
Kate Stoneb9c1b512016-09-06 20:57:50 +00002803 // Note, the stop event was consumed above, but not handled. This
Adrian Prantl05097242018-04-30 16:49:04 +00002804 // was done to give DidLaunch a chance to run. The target is either
2805 // stopped or crashed. Directly set the state. This is done to
2806 // prevent a stop message with a bunch of spurious output on thread
2807 // status, as well as not pop a ProcessIOHandler.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002808 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002809
Kate Stoneb9c1b512016-09-06 20:57:50 +00002810 if (PrivateStateThreadIsValid())
2811 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002812 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002813 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002814
Kate Stoneb9c1b512016-09-06 20:57:50 +00002815 // Target was stopped at entry as was intended. Need to notify the
Adrian Prantl05097242018-04-30 16:49:04 +00002816 // listeners about it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002817 if (state == eStateStopped &&
2818 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2819 HandlePrivateEvent(event_sp);
2820 } else if (state == eStateExited) {
2821 // We exited while trying to launch somehow. Don't call DidLaunch
Adrian Prantl05097242018-04-30 16:49:04 +00002822 // as that's not likely to work, and return an invalid pid.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002823 HandlePrivateEvent(event_sp);
2824 }
2825 }
2826 }
2827 } else {
2828 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2829 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002830 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002831 }
2832 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002833}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002834
Zachary Turner97206d52017-05-12 04:51:55 +00002835Status Process::LoadCore() {
2836 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002837 if (error.Success()) {
2838 ListenerSP listener_sp(
2839 Listener::MakeListener("lldb.process.load_core_listener"));
2840 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002841
Kate Stoneb9c1b512016-09-06 20:57:50 +00002842 if (PrivateStateThreadIsValid())
2843 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002844 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002846
Kate Stoneb9c1b512016-09-06 20:57:50 +00002847 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002848 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002849 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002850
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002851 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002852
Kate Stoneb9c1b512016-09-06 20:57:50 +00002853 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002854 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002855 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002856
Greg Clayton29eeea02017-02-09 18:55:41 +00002857 if (!m_os_ap)
2858 LoadOperatingSystemPlugin(false);
2859
Kate Stoneb9c1b512016-09-06 20:57:50 +00002860 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002861 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002862 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002863
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002864 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002865 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002866 StateType state =
2867 WaitForProcessToStop(seconds(10), &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002868
2869 if (!StateIsStoppedState(state, false)) {
2870 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2871 if (log)
2872 log->Printf("Process::Halt() failed to stop, state is: %s",
2873 StateAsCString(state));
2874 error.SetErrorString(
2875 "Did not get stopped event after loading the core file.");
2876 }
2877 RestoreProcessEvents();
2878 }
2879 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002880}
2881
Kate Stoneb9c1b512016-09-06 20:57:50 +00002882DynamicLoader *Process::GetDynamicLoader() {
2883 if (!m_dyld_ap)
2884 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2885 return m_dyld_ap.get();
2886}
2887
2888const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2889
2890JITLoaderList &Process::GetJITLoaders() {
2891 if (!m_jit_loaders_ap) {
2892 m_jit_loaders_ap.reset(new JITLoaderList());
2893 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2894 }
2895 return *m_jit_loaders_ap;
2896}
2897
2898SystemRuntime *Process::GetSystemRuntime() {
2899 if (!m_system_runtime_ap)
2900 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2901 return m_system_runtime_ap.get();
2902}
2903
2904Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2905 uint32_t exec_count)
2906 : NextEventAction(process), m_exec_count(exec_count) {
2907 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2908 if (log)
2909 log->Printf(
2910 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2911 __FUNCTION__, static_cast<void *>(process), exec_count);
2912}
2913
2914Process::NextEventAction::EventActionResult
2915Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2916 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2917
2918 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2919 if (log)
2920 log->Printf(
2921 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2922 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2923
2924 switch (state) {
2925 case eStateAttaching:
2926 return eEventActionSuccess;
2927
2928 case eStateRunning:
2929 case eStateConnected:
2930 return eEventActionRetry;
2931
2932 case eStateStopped:
2933 case eStateCrashed:
2934 // During attach, prior to sending the eStateStopped event,
2935 // lldb_private::Process subclasses must set the new process ID.
2936 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002937 // We don't want these events to be reported, so go set the
2938 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002939 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2940
2941 if (m_exec_count > 0) {
2942 --m_exec_count;
2943
2944 if (log)
2945 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2946 "remaining exec count to %" PRIu32 ", requesting resume",
2947 __FUNCTION__, StateAsCString(state), m_exec_count);
2948
2949 RequestResume();
2950 return eEventActionRetry;
2951 } else {
2952 if (log)
2953 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2954 "execs expected to start, continuing with attach",
2955 __FUNCTION__, StateAsCString(state));
2956
2957 m_process->CompleteAttach();
2958 return eEventActionSuccess;
2959 }
2960 break;
2961
2962 default:
2963 case eStateExited:
2964 case eStateInvalid:
2965 break;
2966 }
2967
2968 m_exit_string.assign("No valid Process");
2969 return eEventActionExit;
2970}
2971
2972Process::NextEventAction::EventActionResult
2973Process::AttachCompletionHandler::HandleBeingInterrupted() {
2974 return eEventActionSuccess;
2975}
2976
2977const char *Process::AttachCompletionHandler::GetExitString() {
2978 return m_exit_string.c_str();
2979}
2980
2981ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2982 if (m_listener_sp)
2983 return m_listener_sp;
2984 else
2985 return debugger.GetListener();
2986}
2987
Zachary Turner97206d52017-05-12 04:51:55 +00002988Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002989 m_abi_sp.reset();
2990 m_process_input_reader.reset();
2991 m_dyld_ap.reset();
2992 m_jit_loaders_ap.reset();
2993 m_system_runtime_ap.reset();
2994 m_os_ap.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002995
2996 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002997 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002998 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2999 char process_name[PATH_MAX];
3000
3001 if (attach_info.GetExecutableFile().GetPath(process_name,
3002 sizeof(process_name))) {
3003 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3004
3005 if (wait_for_launch) {
3006 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3007 if (error.Success()) {
3008 if (m_public_run_lock.TrySetRunning()) {
3009 m_should_detach = true;
3010 const bool restarted = false;
3011 SetPublicState(eStateAttaching, restarted);
3012 // Now attach using these arguments.
3013 error = DoAttachToProcessWithName(process_name, attach_info);
3014 } else {
3015 // This shouldn't happen
3016 error.SetErrorString("failed to acquire process run lock");
3017 }
3018
3019 if (error.Fail()) {
3020 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3021 SetID(LLDB_INVALID_PROCESS_ID);
3022 if (error.AsCString() == nullptr)
3023 error.SetErrorString("attach failed");
3024
3025 SetExitStatus(-1, error.AsCString());
3026 }
3027 } else {
3028 SetNextEventAction(new Process::AttachCompletionHandler(
3029 this, attach_info.GetResumeCount()));
3030 StartPrivateStateThread();
3031 }
3032 return error;
3033 }
3034 } else {
3035 ProcessInstanceInfoList process_infos;
3036 PlatformSP platform_sp(GetTarget().GetPlatform());
3037
3038 if (platform_sp) {
3039 ProcessInstanceInfoMatch match_info;
3040 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00003041 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003042 platform_sp->FindProcesses(match_info, process_infos);
3043 const uint32_t num_matches = process_infos.GetSize();
3044 if (num_matches == 1) {
3045 attach_pid = process_infos.GetProcessIDAtIndex(0);
3046 // Fall through and attach using the above process ID
3047 } else {
3048 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3049 process_name, sizeof(process_name));
3050 if (num_matches > 1) {
3051 StreamString s;
3052 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3053 false);
3054 for (size_t i = 0; i < num_matches; i++) {
3055 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3056 s, platform_sp.get(), true, false);
3057 }
3058 error.SetErrorStringWithFormat(
3059 "more than one process named %s:\n%s", process_name,
3060 s.GetData());
3061 } else
3062 error.SetErrorStringWithFormat(
3063 "could not find a process named %s", process_name);
3064 }
3065 } else {
3066 error.SetErrorString(
3067 "invalid platform, can't find processes by name");
3068 return error;
3069 }
3070 }
3071 } else {
3072 error.SetErrorString("invalid process name");
3073 }
3074 }
3075
3076 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3077 error = WillAttachToProcessWithID(attach_pid);
3078 if (error.Success()) {
3079
3080 if (m_public_run_lock.TrySetRunning()) {
3081 // Now attach using these arguments.
3082 m_should_detach = true;
3083 const bool restarted = false;
3084 SetPublicState(eStateAttaching, restarted);
3085 error = DoAttachToProcessWithID(attach_pid, attach_info);
3086 } else {
3087 // This shouldn't happen
3088 error.SetErrorString("failed to acquire process run lock");
3089 }
3090
3091 if (error.Success()) {
3092 SetNextEventAction(new Process::AttachCompletionHandler(
3093 this, attach_info.GetResumeCount()));
3094 StartPrivateStateThread();
3095 } else {
Greg Clayton71337622011-02-24 22:24:29 +00003096 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003097 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003098
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 const char *error_string = error.AsCString();
3100 if (error_string == nullptr)
3101 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00003102
Kate Stoneb9c1b512016-09-06 20:57:50 +00003103 SetExitStatus(-1, error_string);
3104 }
Greg Claytonb766a732011-02-04 01:58:07 +00003105 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003106 }
3107 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00003108}
3109
Kate Stoneb9c1b512016-09-06 20:57:50 +00003110void Process::CompleteAttach() {
3111 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3112 LIBLLDB_LOG_TARGET));
3113 if (log)
3114 log->Printf("Process::%s()", __FUNCTION__);
3115
3116 // Let the process subclass figure out at much as it can about the process
3117 // before we go looking for a dynamic loader plug-in.
3118 ArchSpec process_arch;
3119 DidAttach(process_arch);
3120
3121 if (process_arch.IsValid()) {
3122 GetTarget().SetArchitecture(process_arch);
3123 if (log) {
3124 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3125 log->Printf("Process::%s replacing process architecture with DidAttach() "
3126 "architecture: %s",
3127 __FUNCTION__, triple_str ? triple_str : "<null>");
3128 }
3129 }
3130
3131 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00003132 // architecture, and if it isn't the same as the one we've already set,
3133 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003134 PlatformSP platform_sp(GetTarget().GetPlatform());
3135 assert(platform_sp);
3136 if (platform_sp) {
3137 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3138 if (target_arch.IsValid() &&
3139 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3140 ArchSpec platform_arch;
3141 platform_sp =
3142 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3143 if (platform_sp) {
3144 GetTarget().SetPlatform(platform_sp);
3145 GetTarget().SetArchitecture(platform_arch);
3146 if (log)
3147 log->Printf("Process::%s switching platform to %s and architecture "
3148 "to %s based on info from attach",
3149 __FUNCTION__, platform_sp->GetName().AsCString(""),
3150 platform_arch.GetTriple().getTriple().c_str());
3151 }
3152 } else if (!process_arch.IsValid()) {
3153 ProcessInstanceInfo process_info;
3154 GetProcessInfo(process_info);
3155 const ArchSpec &process_arch = process_info.GetArchitecture();
3156 if (process_arch.IsValid() &&
3157 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3158 GetTarget().SetArchitecture(process_arch);
3159 if (log)
3160 log->Printf("Process::%s switching architecture to %s based on info "
3161 "the platform retrieved for pid %" PRIu64,
3162 __FUNCTION__,
3163 process_arch.GetTriple().getTriple().c_str(), GetID());
3164 }
3165 }
3166 }
3167
3168 // We have completed the attach, now it is time to find the dynamic loader
3169 // plug-in
3170 DynamicLoader *dyld = GetDynamicLoader();
3171 if (dyld) {
3172 dyld->DidAttach();
3173 if (log) {
3174 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3175 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3176 "executable is %s (using %s plugin)",
3177 __FUNCTION__,
3178 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3179 : "<none>",
3180 dyld->GetPluginName().AsCString("<unnamed>"));
3181 }
3182 }
3183
3184 GetJITLoaders().DidAttach();
3185
3186 SystemRuntime *system_runtime = GetSystemRuntime();
3187 if (system_runtime) {
3188 system_runtime->DidAttach();
3189 if (log) {
3190 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3191 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3192 "executable is %s (using %s plugin)",
3193 __FUNCTION__,
3194 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3195 : "<none>",
3196 system_runtime->GetPluginName().AsCString("<unnamed>"));
3197 }
3198 }
3199
Greg Clayton29eeea02017-02-09 18:55:41 +00003200 if (!m_os_ap)
3201 LoadOperatingSystemPlugin(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003202 // Figure out which one is the executable, and set that in our target:
3203 const ModuleList &target_modules = GetTarget().GetImages();
3204 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3205 size_t num_modules = target_modules.GetSize();
3206 ModuleSP new_executable_module_sp;
3207
3208 for (size_t i = 0; i < num_modules; i++) {
3209 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3210 if (module_sp && module_sp->IsExecutable()) {
3211 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3212 new_executable_module_sp = module_sp;
3213 break;
3214 }
3215 }
3216 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00003217 GetTarget().SetExecutableModule(new_executable_module_sp,
3218 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003219 if (log) {
3220 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3221 log->Printf(
3222 "Process::%s after looping through modules, target executable is %s",
3223 __FUNCTION__,
3224 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3225 : "<none>");
3226 }
3227 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003228}
3229
Zachary Turner97206d52017-05-12 04:51:55 +00003230Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003231 m_abi_sp.reset();
3232 m_process_input_reader.reset();
3233
3234 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003235 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003236
Zachary Turner97206d52017-05-12 04:51:55 +00003237 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003238 if (error.Success()) {
3239 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3240 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003241 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003242
3243 if (state == eStateStopped || state == eStateCrashed) {
3244 // If we attached and actually have a process on the other end, then
3245 // this ended up being the equivalent of an attach.
3246 CompleteAttach();
3247
3248 // This delays passing the stopped event to listeners till
3249 // CompleteAttach gets a chance to complete...
3250 HandlePrivateEvent(event_sp);
3251 }
3252 }
3253
3254 if (PrivateStateThreadIsValid())
3255 ResumePrivateStateThread();
3256 else
3257 StartPrivateStateThread();
3258 }
3259 return error;
3260}
3261
Zachary Turner97206d52017-05-12 04:51:55 +00003262Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003263 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3264 LIBLLDB_LOG_STEP));
3265 if (log)
3266 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3267 "private state: %s",
3268 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3269 StateAsCString(m_private_state.GetValue()));
3270
Adrian Prantl05097242018-04-30 16:49:04 +00003271 // If signals handing status changed we might want to update our signal
3272 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003273 UpdateAutomaticSignalFiltering();
3274
Zachary Turner97206d52017-05-12 04:51:55 +00003275 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003276 // Tell the process it is about to resume before the thread list
3277 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003278 // Now let the thread list know we are about to resume so it can let all of
3279 // our threads know that they are about to be resumed. Threads will each be
3280 // called with Thread::WillResume(StateType) where StateType contains the
3281 // state that they are supposed to have when the process is resumed
3282 // (suspended/running/stepping). Threads should also check their resume
3283 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3284 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003285 if (m_thread_list.WillResume()) {
3286 // Last thing, do the PreResumeActions.
3287 if (!RunPreResumeActions()) {
3288 error.SetErrorStringWithFormat(
3289 "Process::PrivateResume PreResumeActions failed, not resuming.");
3290 } else {
3291 m_mod_id.BumpResumeID();
3292 error = DoResume();
3293 if (error.Success()) {
3294 DidResume();
3295 m_thread_list.DidResume();
3296 if (log)
3297 log->Printf("Process thinks the process has resumed.");
3298 }
3299 }
3300 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003301 // Somebody wanted to run without running (e.g. we were faking a step
3302 // from one frame of a set of inlined frames that share the same PC to
3303 // another.) So generate a continue & a stopped event, and let the world
3304 // handle them.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003305 if (log)
3306 log->Printf(
3307 "Process::PrivateResume() asked to simulate a start & stop.");
3308
3309 SetPrivateState(eStateRunning);
3310 SetPrivateState(eStateStopped);
3311 }
3312 } else if (log)
3313 log->Printf("Process::PrivateResume() got an error \"%s\".",
3314 error.AsCString("<unknown error>"));
3315 return error;
3316}
3317
Zachary Turner97206d52017-05-12 04:51:55 +00003318Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003319 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003320 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003321
Adrian Prantl05097242018-04-30 16:49:04 +00003322 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3323 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003324 m_clear_thread_plans_on_stop |= clear_thread_plans;
3325
3326 ListenerSP halt_listener_sp(
3327 Listener::MakeListener("lldb.process.halt_listener"));
3328 HijackProcessEvents(halt_listener_sp);
3329
3330 EventSP event_sp;
3331
3332 SendAsyncInterrupt();
3333
3334 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003335 // Don't hijack and eat the eStateExited as the code that was doing the
3336 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003337 RestoreProcessEvents();
3338 SetExitStatus(SIGKILL, "Cancelled async attach.");
3339 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003340 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003341 }
3342
3343 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003344 StateType state = WaitForProcessToStop(
3345 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003346 RestoreProcessEvents();
3347
3348 if (state == eStateInvalid || !event_sp) {
3349 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003350 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003351 }
3352
3353 BroadcastEvent(event_sp);
3354
Zachary Turner97206d52017-05-12 04:51:55 +00003355 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003356}
3357
Zachary Turner97206d52017-05-12 04:51:55 +00003358Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3359 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003360
3361 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003362 // expression, for instance, then the public state will be stopped, but we
3363 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003364 if (m_public_state.GetValue() == eStateRunning ||
3365 m_private_state.GetValue() == eStateRunning) {
3366 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003367 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003368 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003369
Kate Stoneb9c1b512016-09-06 20:57:50 +00003370 ListenerSP listener_sp(
3371 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3372 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003373
Pavel Labath19da1f12015-12-07 12:36:52 +00003374 SendAsyncInterrupt();
3375
Kate Stoneb9c1b512016-09-06 20:57:50 +00003376 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003377 StateType state =
3378 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003379
Pavel Labath19da1f12015-12-07 12:36:52 +00003380 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003381
Kate Stoneb9c1b512016-09-06 20:57:50 +00003382 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003383 // exited event into the shared pointer passed in and return. Our caller
3384 // doesn't need to do anything else, since they don't have a process
3385 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003386
3387 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3388 if (log)
3389 log->Printf("Process::%s() Process exited while waiting to stop.",
3390 __FUNCTION__);
3391 return error;
3392 } else
3393 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3394
3395 if (state != eStateStopped) {
3396 if (log)
3397 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3398 StateAsCString(state));
3399 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003400 // here, but if the lower levels just bobbled sending the event and we
3401 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003402 StateType private_state = m_private_state.GetValue();
3403 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003404 return Status(
3405 "Attempt to stop the target in order to detach timed out. "
3406 "State = %s",
3407 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003408 }
3409 }
3410 }
3411 return error;
3412}
3413
Zachary Turner97206d52017-05-12 04:51:55 +00003414Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003415 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003416 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003417 m_destroy_in_process = true;
3418
3419 error = WillDetach();
3420
3421 if (error.Success()) {
3422 if (DetachRequiresHalt()) {
3423 error = StopForDestroyOrDetach(exit_event_sp);
3424 if (!error.Success()) {
3425 m_destroy_in_process = false;
3426 return error;
3427 } else if (exit_event_sp) {
3428 // We shouldn't need to do anything else here. There's no process left
3429 // to detach from...
3430 StopPrivateStateThread();
3431 m_destroy_in_process = false;
3432 return error;
3433 }
3434 }
3435
3436 m_thread_list.DiscardThreadPlans();
3437 DisableAllBreakpointSites();
3438
3439 error = DoDetach(keep_stopped);
3440 if (error.Success()) {
3441 DidDetach();
3442 StopPrivateStateThread();
3443 } else {
3444 return error;
3445 }
3446 }
3447 m_destroy_in_process = false;
3448
Adrian Prantl05097242018-04-30 16:49:04 +00003449 // If we exited when we were waiting for a process to stop, then forward the
3450 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003451 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003452 // Directly broadcast our exited event because we shut down our private
3453 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003454 BroadcastEvent(exit_event_sp);
3455 }
3456
3457 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003458 // not end up propagating the last events through the event system, in which
3459 // case we might strand the write lock. Unlock it here so when we do to tear
3460 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003461
3462 m_public_run_lock.SetStopped();
3463 return error;
3464}
3465
Zachary Turner97206d52017-05-12 04:51:55 +00003466Status Process::Destroy(bool force_kill) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003467
3468 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003469 // don't do any unnecessary work that might hinder the destruction. Remember
3470 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003471 // failed and the process stays around for some reason it won't be in a
3472 // confused state.
3473
3474 if (force_kill)
3475 m_should_detach = false;
3476
3477 if (GetShouldDetach()) {
3478 // FIXME: This will have to be a process setting:
3479 bool keep_stopped = false;
3480 Detach(keep_stopped);
3481 }
3482
3483 m_destroy_in_process = true;
3484
Zachary Turner97206d52017-05-12 04:51:55 +00003485 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003486 if (error.Success()) {
3487 EventSP exit_event_sp;
3488 if (DestroyRequiresHalt()) {
3489 error = StopForDestroyOrDetach(exit_event_sp);
3490 }
3491
3492 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003493 // Ditch all thread plans, and remove all our breakpoints: in case we
3494 // have to restart the target to kill it, we don't want it hitting a
3495 // breakpoint... Only do this if we've stopped, however, since if we
3496 // didn't manage to halt it above, then we're not going to have much luck
3497 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003498 m_thread_list.DiscardThreadPlans();
3499 DisableAllBreakpointSites();
3500 }
3501
3502 error = DoDestroy();
3503 if (error.Success()) {
3504 DidDestroy();
3505 StopPrivateStateThread();
3506 }
3507 m_stdio_communication.Disconnect();
3508 m_stdio_communication.StopReadThread();
3509 m_stdin_forward = false;
3510
3511 if (m_process_input_reader) {
3512 m_process_input_reader->SetIsDone(true);
3513 m_process_input_reader->Cancel();
3514 m_process_input_reader.reset();
3515 }
3516
Adrian Prantl05097242018-04-30 16:49:04 +00003517 // If we exited when we were waiting for a process to stop, then forward
3518 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003519 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003520 // Directly broadcast our exited event because we shut down our private
3521 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003522 BroadcastEvent(exit_event_sp);
3523 }
3524
Adrian Prantl05097242018-04-30 16:49:04 +00003525 // If we have been interrupted (to kill us) in the middle of running, we
3526 // may not end up propagating the last events through the event system, in
3527 // which case we might strand the write lock. Unlock it here so when we do
3528 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003529 m_public_run_lock.SetStopped();
3530 }
3531
3532 m_destroy_in_process = false;
3533
3534 return error;
3535}
3536
Zachary Turner97206d52017-05-12 04:51:55 +00003537Status Process::Signal(int signal) {
3538 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003539 if (error.Success()) {
3540 error = DoSignal(signal);
3541 if (error.Success())
3542 DidSignal();
3543 }
3544 return error;
3545}
3546
3547void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3548 assert(signals_sp && "null signals_sp");
3549 m_unix_signals_sp = signals_sp;
3550}
3551
3552const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3553 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3554 return m_unix_signals_sp;
3555}
3556
3557lldb::ByteOrder Process::GetByteOrder() const {
3558 return GetTarget().GetArchitecture().GetByteOrder();
3559}
3560
3561uint32_t Process::GetAddressByteSize() const {
3562 return GetTarget().GetArchitecture().GetAddressByteSize();
3563}
3564
3565bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3566 const StateType state =
3567 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3568 bool return_value = true;
3569 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3570 LIBLLDB_LOG_PROCESS));
3571
3572 switch (state) {
3573 case eStateDetached:
3574 case eStateExited:
3575 case eStateUnloaded:
3576 m_stdio_communication.SynchronizeWithReadThread();
3577 m_stdio_communication.Disconnect();
3578 m_stdio_communication.StopReadThread();
3579 m_stdin_forward = false;
3580
3581 LLVM_FALLTHROUGH;
3582 case eStateConnected:
3583 case eStateAttaching:
3584 case eStateLaunching:
3585 // These events indicate changes in the state of the debugging session,
3586 // always report them.
3587 return_value = true;
3588 break;
3589 case eStateInvalid:
3590 // We stopped for no apparent reason, don't report it.
3591 return_value = false;
3592 break;
3593 case eStateRunning:
3594 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003595 // If we've started the target running, we handle the cases where we are
3596 // already running and where there is a transition from stopped to running
3597 // differently. running -> running: Automatically suppress extra running
3598 // events stopped -> running: Report except when there is one or more no
3599 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003600 // and no yes votes.
3601 SynchronouslyNotifyStateChanged(state);
3602 if (m_force_next_event_delivery)
3603 return_value = true;
3604 else {
3605 switch (m_last_broadcast_state) {
3606 case eStateRunning:
3607 case eStateStepping:
3608 // We always suppress multiple runnings with no PUBLIC stop in between.
3609 return_value = false;
3610 break;
3611 default:
3612 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003613 // run if we aren't running so we don't miss any running events. If I
3614 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3615 // and hit the breakpoints on multiple threads, then somehow during the
3616 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003617
3618 // This is a transition from stop to run.
3619 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3620 case eVoteYes:
3621 case eVoteNoOpinion:
3622 return_value = true;
3623 break;
3624 case eVoteNo:
3625 return_value = false;
3626 break;
3627 }
3628 break;
3629 }
3630 }
3631 break;
3632 case eStateStopped:
3633 case eStateCrashed:
3634 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003635 // We've stopped. First see if we're going to restart the target. If we
3636 // are going to stop, then we always broadcast the event. If we aren't
3637 // going to stop, let the thread plans decide if we're going to report this
3638 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003639
3640 m_stdio_communication.SynchronizeWithReadThread();
3641 RefreshStateAfterStop();
3642 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3643 if (log)
3644 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3645 "interrupt, state: %s",
3646 static_cast<void *>(event_ptr), StateAsCString(state));
3647 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003648 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003649 m_thread_list.ShouldStop(event_ptr);
3650 return_value = true;
3651 } else {
3652 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3653 bool should_resume = false;
3654
3655 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003656 // restarted... Asking the thread list is also not likely to go well,
3657 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003658
3659 if (!was_restarted)
3660 should_resume = !m_thread_list.ShouldStop(event_ptr);
3661
3662 if (was_restarted || should_resume || m_resume_requested) {
3663 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3664 if (log)
3665 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3666 "%s was_restarted: %i stop_vote: %d.",
3667 should_resume, StateAsCString(state), was_restarted,
3668 stop_vote);
3669
3670 switch (stop_vote) {
3671 case eVoteYes:
3672 return_value = true;
3673 break;
3674 case eVoteNoOpinion:
3675 case eVoteNo:
3676 return_value = false;
3677 break;
3678 }
3679
3680 if (!was_restarted) {
3681 if (log)
3682 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3683 "from state: %s",
3684 static_cast<void *>(event_ptr), StateAsCString(state));
3685 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3686 PrivateResume();
3687 }
3688 } else {
3689 return_value = true;
3690 SynchronouslyNotifyStateChanged(state);
3691 }
3692 }
3693 break;
3694 }
3695
3696 // Forcing the next event delivery is a one shot deal. So reset it here.
3697 m_force_next_event_delivery = false;
3698
3699 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003700 // events get coalesced.) But we only coalesce against events we actually
3701 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3702 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3703 // done, because the PublicState reflects the last event pulled off the
3704 // queue, and there may be several events stacked up on the queue unserviced.
3705 // So the PublicState may not reflect the last broadcasted event yet.
3706 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003707
3708 if (return_value)
3709 m_last_broadcast_state = state;
3710
3711 if (log)
3712 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3713 "broadcast state: %s - %s",
3714 static_cast<void *>(event_ptr), StateAsCString(state),
3715 StateAsCString(m_last_broadcast_state),
3716 return_value ? "YES" : "NO");
3717 return return_value;
3718}
3719
3720bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3721 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3722
3723 bool already_running = PrivateStateThreadIsValid();
3724 if (log)
3725 log->Printf("Process::%s()%s ", __FUNCTION__,
3726 already_running ? " already running"
3727 : " starting private state thread");
3728
3729 if (!is_secondary_thread && already_running)
3730 return true;
3731
Adrian Prantl05097242018-04-30 16:49:04 +00003732 // Create a thread that watches our internal state and controls which events
3733 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003734 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003735 uint32_t max_len = llvm::get_max_thread_name_length();
3736 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003737 // On platforms with abbreviated thread name lengths, choose thread names
3738 // that fit within the limit.
3739 if (already_running)
3740 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3741 else
3742 snprintf(thread_name, sizeof(thread_name), "intern-state");
3743 } else {
3744 if (already_running)
3745 snprintf(thread_name, sizeof(thread_name),
3746 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3747 GetID());
3748 else
3749 snprintf(thread_name, sizeof(thread_name),
3750 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3751 }
3752
3753 // Create the private state thread, and start it running.
3754 PrivateStateThreadArgs *args_ptr =
3755 new PrivateStateThreadArgs(this, is_secondary_thread);
3756 m_private_state_thread =
3757 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3758 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3759 if (m_private_state_thread.IsJoinable()) {
3760 ResumePrivateStateThread();
3761 return true;
3762 } else
3763 return false;
3764}
3765
3766void Process::PausePrivateStateThread() {
3767 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3768}
3769
3770void Process::ResumePrivateStateThread() {
3771 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3772}
3773
3774void Process::StopPrivateStateThread() {
3775 if (m_private_state_thread.IsJoinable())
3776 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3777 else {
3778 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3779 if (log)
3780 log->Printf(
3781 "Went to stop the private state thread, but it was already invalid.");
3782 }
3783}
3784
3785void Process::ControlPrivateStateThread(uint32_t signal) {
3786 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3787
3788 assert(signal == eBroadcastInternalStateControlStop ||
3789 signal == eBroadcastInternalStateControlPause ||
3790 signal == eBroadcastInternalStateControlResume);
3791
3792 if (log)
3793 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3794
3795 // Signal the private state thread
3796 if (m_private_state_thread.IsJoinable()) {
3797 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003798 // It is important to do this outside of the if below, because it's
3799 // possible that the thread state is invalid but that the thread is waiting
3800 // on a control event instead of simply being on its way out (this should
3801 // not happen, but it apparently can).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003802 if (log)
3803 log->Printf("Sending control event of type: %d.", signal);
3804 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3805 m_private_state_control_broadcaster.BroadcastEvent(signal,
3806 event_receipt_sp);
3807
3808 // Wait for the event receipt or for the private state thread to exit
3809 bool receipt_received = false;
3810 if (PrivateStateThreadIsValid()) {
3811 while (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003812 // Check for a receipt for 2 seconds and then check if the private
3813 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003814 receipt_received =
3815 event_receipt_sp->WaitForEventReceived(std::chrono::seconds(2));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003816 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003817 // Check if the private state thread is still around. If it isn't
3818 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003819 if (!PrivateStateThreadIsValid())
3820 break; // Private state thread exited or is exiting, we are done
3821 }
3822 }
3823 }
3824
3825 if (signal == eBroadcastInternalStateControlStop) {
3826 thread_result_t result = NULL;
3827 m_private_state_thread.Join(&result);
3828 m_private_state_thread.Reset();
3829 }
3830 } else {
3831 if (log)
3832 log->Printf(
3833 "Private state thread already dead, no need to signal it to stop.");
3834 }
3835}
3836
3837void Process::SendAsyncInterrupt() {
3838 if (PrivateStateThreadIsValid())
3839 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3840 nullptr);
3841 else
3842 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3843}
3844
3845void Process::HandlePrivateEvent(EventSP &event_sp) {
3846 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3847 m_resume_requested = false;
3848
3849 const StateType new_state =
3850 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3851
3852 // First check to see if anybody wants a shot at this event:
3853 if (m_next_event_action_ap) {
3854 NextEventAction::EventActionResult action_result =
3855 m_next_event_action_ap->PerformAction(event_sp);
3856 if (log)
3857 log->Printf("Ran next event action, result was %d.", action_result);
3858
3859 switch (action_result) {
3860 case NextEventAction::eEventActionSuccess:
3861 SetNextEventAction(nullptr);
3862 break;
3863
3864 case NextEventAction::eEventActionRetry:
3865 break;
3866
3867 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003868 // Handle Exiting Here. If we already got an exited event, we should
3869 // just propagate it. Otherwise, swallow this event, and set our state
3870 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003871 if (new_state != eStateExited) {
3872 // FIXME: should cons up an exited event, and discard this one.
3873 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3874 SetNextEventAction(nullptr);
3875 return;
3876 }
3877 SetNextEventAction(nullptr);
3878 break;
3879 }
3880 }
3881
3882 // See if we should broadcast this state to external clients?
3883 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3884
3885 if (should_broadcast) {
3886 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3887 if (log) {
3888 log->Printf("Process::%s (pid = %" PRIu64
3889 ") broadcasting new state %s (old state %s) to %s",
3890 __FUNCTION__, GetID(), StateAsCString(new_state),
3891 StateAsCString(GetState()),
3892 is_hijacked ? "hijacked" : "public");
3893 }
3894 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3895 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003896 // Only push the input handler if we aren't fowarding events, as this
3897 // means the curses GUI is in use... Or don't push it if we are launching
3898 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003899 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3900 new_state != eStateLaunching && new_state != eStateAttaching) {
3901 PushProcessIOHandler();
3902 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3903 eBroadcastAlways);
3904 if (log)
3905 log->Printf("Process::%s updated m_iohandler_sync to %d",
3906 __FUNCTION__, m_iohandler_sync.GetValue());
3907 }
3908 } else if (StateIsStoppedState(new_state, false)) {
3909 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003910 // If the lldb_private::Debugger is handling the events, we don't want
3911 // to pop the process IOHandler here, we want to do it when we receive
3912 // the stopped event so we can carefully control when the process
3913 // IOHandler is popped because when we stop we want to display some
3914 // text stating how and why we stopped, then maybe some
3915 // process/thread/frame info, and then we want the "(lldb) " prompt to
3916 // show up. If we pop the process IOHandler here, then we will cause
3917 // the command interpreter to become the top IOHandler after the
3918 // process pops off and it will update its prompt right away... See the
3919 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003920 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3921 // Otherwise we end up getting overlapping "(lldb) " prompts and
3922 // garbled output.
3923 //
3924 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003925 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3926 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003927 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003928 // thread plans, or when commands want to run in synchronous mode and
3929 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003930 // that will hijack the events is a simple expression:
3931 //
3932 // (lldb) expr (int)puts("hello")
3933 //
3934 // This will cause the internal process state thread to resume and halt
3935 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3936 // events) and we do need the IO handler to be pushed and popped
3937 // correctly.
3938
3939 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3940 PopProcessIOHandler();
3941 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003942 }
3943
3944 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003945 } else {
3946 if (log) {
3947 log->Printf(
3948 "Process::%s (pid = %" PRIu64
3949 ") suppressing state %s (old state %s): should_broadcast == false",
3950 __FUNCTION__, GetID(), StateAsCString(new_state),
3951 StateAsCString(GetState()));
3952 }
3953 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003954}
3955
Zachary Turner97206d52017-05-12 04:51:55 +00003956Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003957 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003958 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003959 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003960 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003961
3962 // Ask the process subclass to actually halt our process
3963 bool caused_stop;
3964 error = DoHalt(caused_stop);
3965
3966 DidHalt();
3967 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003968}
3969
Kate Stoneb9c1b512016-09-06 20:57:50 +00003970thread_result_t Process::PrivateStateThread(void *arg) {
3971 std::unique_ptr<PrivateStateThreadArgs> args_up(
3972 static_cast<PrivateStateThreadArgs *>(arg));
3973 thread_result_t result =
3974 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3975 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003976}
3977
Kate Stoneb9c1b512016-09-06 20:57:50 +00003978thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3979 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003980
Kate Stoneb9c1b512016-09-06 20:57:50 +00003981 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3982 if (log)
3983 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3984 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003985
Kate Stoneb9c1b512016-09-06 20:57:50 +00003986 bool exit_now = false;
3987 bool interrupt_requested = false;
3988 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003989 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003990 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003991 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3992 if (log)
3993 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3994 ") got a control event: %d",
3995 __FUNCTION__, static_cast<void *>(this), GetID(),
3996 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003997
Kate Stoneb9c1b512016-09-06 20:57:50 +00003998 switch (event_sp->GetType()) {
3999 case eBroadcastInternalStateControlStop:
4000 exit_now = true;
4001 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00004002
Kate Stoneb9c1b512016-09-06 20:57:50 +00004003 case eBroadcastInternalStateControlPause:
4004 control_only = true;
4005 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004006
Kate Stoneb9c1b512016-09-06 20:57:50 +00004007 case eBroadcastInternalStateControlResume:
4008 control_only = false;
4009 break;
4010 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004011
Kate Stoneb9c1b512016-09-06 20:57:50 +00004012 continue;
4013 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4014 if (m_public_state.GetValue() == eStateAttaching) {
4015 if (log)
4016 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4017 ") woke up with an interrupt while attaching - "
4018 "forwarding interrupt.",
4019 __FUNCTION__, static_cast<void *>(this), GetID());
4020 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4021 } else if (StateIsRunningState(m_last_broadcast_state)) {
4022 if (log)
4023 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4024 ") woke up with an interrupt - Halting.",
4025 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00004026 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004027 if (error.Fail() && log)
4028 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4029 ") failed to halt the process: %s",
4030 __FUNCTION__, static_cast<void *>(this), GetID(),
4031 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00004032 // Halt should generate a stopped event. Make a note of the fact that
4033 // we were doing the interrupt, so we can set the interrupted flag
4034 // after we receive the event. We deliberately set this to true even if
4035 // HaltPrivate failed, so that we can interrupt on the next natural
4036 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004037 interrupt_requested = true;
4038 } else {
4039 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00004040 // running and sends an interrupt request, but the process actually
4041 // stops before we receive it. In that case, we can just ignore the
4042 // request. We use m_last_broadcast_state, because the Stopped event
4043 // may not have been popped of the event queue yet, which is when the
4044 // public state gets updated.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004045 if (log)
4046 log->Printf(
4047 "Process::%s ignoring interrupt as we have already stopped.",
4048 __FUNCTION__);
4049 }
4050 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004051 }
4052
Kate Stoneb9c1b512016-09-06 20:57:50 +00004053 const StateType internal_state =
4054 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004055
Kate Stoneb9c1b512016-09-06 20:57:50 +00004056 if (internal_state != eStateInvalid) {
4057 if (m_clear_thread_plans_on_stop &&
4058 StateIsStoppedState(internal_state, true)) {
4059 m_clear_thread_plans_on_stop = false;
4060 m_thread_list.DiscardThreadPlans();
4061 }
4062
4063 if (interrupt_requested) {
4064 if (StateIsStoppedState(internal_state, true)) {
4065 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00004066 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00004067 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4068 interrupt_requested = false;
4069 } else if (log) {
4070 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4071 "state '%s' received.",
4072 __FUNCTION__, StateAsCString(internal_state));
4073 }
4074 }
4075
4076 HandlePrivateEvent(event_sp);
4077 }
4078
4079 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4080 internal_state == eStateDetached) {
4081 if (log)
4082 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4083 ") about to exit with internal state %s...",
4084 __FUNCTION__, static_cast<void *>(this), GetID(),
4085 StateAsCString(internal_state));
4086
4087 break;
4088 }
4089 }
4090
4091 // Verify log is still enabled before attempting to write to it...
4092 if (log)
4093 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4094 __FUNCTION__, static_cast<void *>(this), GetID());
4095
4096 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00004097 // will have already acquired the public_run_lock, and isn't done with what
4098 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004099 if (!is_secondary_thread)
4100 m_public_run_lock.SetStopped();
4101 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004102}
4103
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004104//------------------------------------------------------------------
4105// Process Event Data
4106//------------------------------------------------------------------
4107
Kate Stoneb9c1b512016-09-06 20:57:50 +00004108Process::ProcessEventData::ProcessEventData()
4109 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4110 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004111
Kate Stoneb9c1b512016-09-06 20:57:50 +00004112Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4113 StateType state)
4114 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4115 m_update_state(0), m_interrupted(false) {
4116 if (process_sp)
4117 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004118}
4119
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004120Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004121
Kate Stoneb9c1b512016-09-06 20:57:50 +00004122const ConstString &Process::ProcessEventData::GetFlavorString() {
4123 static ConstString g_flavor("Process::ProcessEventData");
4124 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004125}
4126
Kate Stoneb9c1b512016-09-06 20:57:50 +00004127const ConstString &Process::ProcessEventData::GetFlavor() const {
4128 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004129}
4130
Kate Stoneb9c1b512016-09-06 20:57:50 +00004131void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4132 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004133
Kate Stoneb9c1b512016-09-06 20:57:50 +00004134 if (!process_sp)
4135 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004136
Kate Stoneb9c1b512016-09-06 20:57:50 +00004137 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00004138 // pulled off of the private process event queue, and then any number of
4139 // times, first when it gets pulled off of the public event queue, then other
4140 // times when we're pretending that this is where we stopped at the end of
4141 // expression evaluation. m_update_state is used to distinguish these three
4142 // cases; it is 0 when we're just pulling it off for private handling, and >
4143 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00004144 // command handling then.
4145 if (m_update_state != 1)
4146 return;
4147
4148 process_sp->SetPublicState(
4149 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4150
Jason Molendab3a3cd12016-12-08 06:27:29 +00004151 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00004152 // Let process subclasses know we are about to do a public stop and do
4153 // anything they might need to in order to speed up register and memory
4154 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00004155 process_sp->WillPublicStop();
4156 }
4157
Kate Stoneb9c1b512016-09-06 20:57:50 +00004158 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00004159 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4160 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00004161 // end up restarting the process.
4162 if (m_interrupted)
4163 return;
4164
4165 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4166 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004167 ThreadList &curr_thread_list = process_sp->GetThreadList();
4168 uint32_t num_threads = curr_thread_list.GetSize();
4169 uint32_t idx;
4170
4171 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00004172 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004173
4174 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00004175 // target has run (except for expressions) and immediately exit, but if we
4176 // get that wrong (which is possible) then the thread list might have
4177 // changed, and that would cause our iteration here to crash. We could
4178 // make a copy of the thread list, but we'd really like to also know if it
4179 // has changed at all, so we make up a vector of the thread ID's and check
4180 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004181 std::vector<uint32_t> thread_index_array(num_threads);
4182 for (idx = 0; idx < num_threads; ++idx)
4183 thread_index_array[idx] =
4184 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4185
4186 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00004187 // continue the target running if no thread says we should stop. Of course
4188 // if some thread's PerformAction actually sets the target running, then it
4189 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004190
4191 bool still_should_stop = false;
4192
4193 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00004194 // we stop but no thread has a valid stop reason. In that case we should
4195 // just stop, because we have no way of telling what the right thing to do
4196 // is, and it's better to let the user decide than continue behind their
4197 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004198
4199 bool does_anybody_have_an_opinion = false;
4200
4201 for (idx = 0; idx < num_threads; ++idx) {
4202 curr_thread_list = process_sp->GetThreadList();
4203 if (curr_thread_list.GetSize() != num_threads) {
4204 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4205 LIBLLDB_LOG_PROCESS));
4206 if (log)
4207 log->Printf(
4208 "Number of threads changed from %u to %u while processing event.",
4209 num_threads, curr_thread_list.GetSize());
4210 break;
4211 }
4212
4213 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4214
4215 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4216 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4217 LIBLLDB_LOG_PROCESS));
4218 if (log)
4219 log->Printf("The thread at position %u changed from %u to %u while "
4220 "processing event.",
4221 idx, thread_index_array[idx], thread_sp->GetIndexID());
4222 break;
4223 }
4224
4225 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4226 if (stop_info_sp && stop_info_sp->IsValid()) {
4227 does_anybody_have_an_opinion = true;
4228 bool this_thread_wants_to_stop;
4229 if (stop_info_sp->GetOverrideShouldStop()) {
4230 this_thread_wants_to_stop =
4231 stop_info_sp->GetOverriddenShouldStopValue();
4232 } else {
4233 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00004234 // The stop action might restart the target. If it does, then we
4235 // want to mark that in the event so that whoever is receiving it
4236 // will know to wait for the running event and reflect that state
4237 // appropriately. We also need to stop processing actions, since they
4238 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004239
4240 // FIXME: we might have run.
4241 if (stop_info_sp->HasTargetRunSinceMe()) {
4242 SetRestarted(true);
4243 break;
4244 }
4245
4246 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004247 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004248
4249 if (!still_should_stop)
4250 still_should_stop = this_thread_wants_to_stop;
4251 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004252 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004253
4254 if (!GetRestarted()) {
4255 if (!still_should_stop && does_anybody_have_an_opinion) {
4256 // We've been asked to continue, so do that here.
4257 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004258 // Use the public resume method here, since this is just extending a
4259 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004260 process_sp->PrivateResume();
4261 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004262 // If we didn't restart, run the Stop Hooks here: They might also
4263 // restart the target, so watch for that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004264 process_sp->GetTarget().RunStopHooks();
4265 if (process_sp->GetPrivateState() == eStateRunning)
4266 SetRestarted(true);
4267 }
4268 }
4269 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004270}
4271
Kate Stoneb9c1b512016-09-06 20:57:50 +00004272void Process::ProcessEventData::Dump(Stream *s) const {
4273 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004274
Kate Stoneb9c1b512016-09-06 20:57:50 +00004275 if (process_sp)
4276 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4277 static_cast<void *>(process_sp.get()), process_sp->GetID());
4278 else
4279 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004280
Kate Stoneb9c1b512016-09-06 20:57:50 +00004281 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004282}
4283
4284const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004285Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4286 if (event_ptr) {
4287 const EventData *event_data = event_ptr->GetData();
4288 if (event_data &&
4289 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4290 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4291 }
4292 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004293}
4294
4295ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004296Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4297 ProcessSP process_sp;
4298 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4299 if (data)
4300 process_sp = data->GetProcessSP();
4301 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004302}
4303
Kate Stoneb9c1b512016-09-06 20:57:50 +00004304StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4305 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4306 if (data == nullptr)
4307 return eStateInvalid;
4308 else
4309 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004310}
4311
Kate Stoneb9c1b512016-09-06 20:57:50 +00004312bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4313 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4314 if (data == nullptr)
4315 return false;
4316 else
4317 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004318}
4319
Kate Stoneb9c1b512016-09-06 20:57:50 +00004320void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4321 bool new_value) {
4322 ProcessEventData *data =
4323 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4324 if (data != nullptr)
4325 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004326}
4327
Jim Ingham0161b492013-02-09 01:29:05 +00004328size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004329Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4330 ProcessEventData *data =
4331 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4332 if (data != nullptr)
4333 return data->GetNumRestartedReasons();
4334 else
4335 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004336}
4337
4338const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004339Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4340 size_t idx) {
4341 ProcessEventData *data =
4342 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4343 if (data != nullptr)
4344 return data->GetRestartedReasonAtIndex(idx);
4345 else
4346 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004347}
4348
Kate Stoneb9c1b512016-09-06 20:57:50 +00004349void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4350 const char *reason) {
4351 ProcessEventData *data =
4352 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4353 if (data != nullptr)
4354 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004355}
4356
Kate Stoneb9c1b512016-09-06 20:57:50 +00004357bool Process::ProcessEventData::GetInterruptedFromEvent(
4358 const Event *event_ptr) {
4359 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4360 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004361 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004362 else
4363 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004364}
4365
Kate Stoneb9c1b512016-09-06 20:57:50 +00004366void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4367 bool new_value) {
4368 ProcessEventData *data =
4369 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4370 if (data != nullptr)
4371 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004372}
4373
Kate Stoneb9c1b512016-09-06 20:57:50 +00004374bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4375 ProcessEventData *data =
4376 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4377 if (data) {
4378 data->SetUpdateStateOnRemoval();
4379 return true;
4380 }
4381 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004382}
4383
Jim Inghamb87b9e62018-06-26 23:38:58 +00004384lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004385
4386void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4387 exe_ctx.SetTargetPtr(&GetTarget());
4388 exe_ctx.SetProcessPtr(this);
4389 exe_ctx.SetThreadPtr(nullptr);
4390 exe_ctx.SetFramePtr(nullptr);
4391}
4392
4393// uint32_t
4394// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4395// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004396//{
4397// return 0;
4398//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004399//
4400// ArchSpec
4401// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004402//{
4403// return Host::GetArchSpecForExistingProcess (pid);
4404//}
4405//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004406// ArchSpec
4407// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004408//{
4409// return Host::GetArchSpecForExistingProcess (process_name);
4410//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004411
Kate Stoneb9c1b512016-09-06 20:57:50 +00004412void Process::AppendSTDOUT(const char *s, size_t len) {
4413 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4414 m_stdout_data.append(s, len);
4415 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4416 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004417}
4418
Kate Stoneb9c1b512016-09-06 20:57:50 +00004419void Process::AppendSTDERR(const char *s, size_t len) {
4420 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4421 m_stderr_data.append(s, len);
4422 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4423 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004424}
4425
Kate Stoneb9c1b512016-09-06 20:57:50 +00004426void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4427 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4428 m_profile_data.push_back(one_profile_data);
4429 BroadcastEventIfUnique(eBroadcastBitProfileData,
4430 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004431}
4432
Kate Stoneb9c1b512016-09-06 20:57:50 +00004433void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4434 const StructuredDataPluginSP &plugin_sp) {
4435 BroadcastEvent(
4436 eBroadcastBitStructuredData,
4437 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004438}
4439
4440StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004441Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4442 auto find_it = m_structured_data_plugin_map.find(type_name);
4443 if (find_it != m_structured_data_plugin_map.end())
4444 return find_it->second;
4445 else
4446 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004447}
4448
Zachary Turner97206d52017-05-12 04:51:55 +00004449size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004450 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4451 if (m_profile_data.empty())
4452 return 0;
4453
4454 std::string &one_profile_data = m_profile_data.front();
4455 size_t bytes_available = one_profile_data.size();
4456 if (bytes_available > 0) {
4457 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4458 if (log)
4459 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4460 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4461 if (bytes_available > buf_size) {
4462 memcpy(buf, one_profile_data.c_str(), buf_size);
4463 one_profile_data.erase(0, buf_size);
4464 bytes_available = buf_size;
4465 } else {
4466 memcpy(buf, one_profile_data.c_str(), bytes_available);
4467 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004468 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004469 }
4470 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004471}
4472
Greg Clayton93e86192011-11-13 04:45:22 +00004473//------------------------------------------------------------------
4474// Process STDIO
4475//------------------------------------------------------------------
4476
Zachary Turner97206d52017-05-12 04:51:55 +00004477size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004478 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4479 size_t bytes_available = m_stdout_data.size();
4480 if (bytes_available > 0) {
4481 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4482 if (log)
4483 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4484 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4485 if (bytes_available > buf_size) {
4486 memcpy(buf, m_stdout_data.c_str(), buf_size);
4487 m_stdout_data.erase(0, buf_size);
4488 bytes_available = buf_size;
4489 } else {
4490 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4491 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004492 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004493 }
4494 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004495}
4496
Zachary Turner97206d52017-05-12 04:51:55 +00004497size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004498 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4499 size_t bytes_available = m_stderr_data.size();
4500 if (bytes_available > 0) {
4501 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4502 if (log)
4503 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4504 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4505 if (bytes_available > buf_size) {
4506 memcpy(buf, m_stderr_data.c_str(), buf_size);
4507 m_stderr_data.erase(0, buf_size);
4508 bytes_available = buf_size;
4509 } else {
4510 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4511 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004512 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004513 }
4514 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004515}
4516
Kate Stoneb9c1b512016-09-06 20:57:50 +00004517void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4518 size_t src_len) {
4519 Process *process = (Process *)baton;
4520 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004521}
4522
Kate Stoneb9c1b512016-09-06 20:57:50 +00004523class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004524public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004525 IOHandlerProcessSTDIO(Process *process, int write_fd)
4526 : IOHandler(process->GetTarget().GetDebugger(),
4527 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004528 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004529 m_pipe.CreateNew(false);
4530 m_read_file.SetDescriptor(GetInputFD(), false);
4531 }
4532
4533 ~IOHandlerProcessSTDIO() override = default;
4534
Adrian Prantl05097242018-04-30 16:49:04 +00004535 // Each IOHandler gets to run until it is done. It should read data from the
4536 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004537 void Run() override {
4538 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4539 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4540 SetIsDone(true);
4541 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004542 }
4543
Kate Stoneb9c1b512016-09-06 20:57:50 +00004544 SetIsDone(false);
4545 const int read_fd = m_read_file.GetDescriptor();
4546 TerminalState terminal_state;
4547 terminal_state.Save(read_fd, false);
4548 Terminal terminal(read_fd);
4549 terminal.SetCanonical(false);
4550 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004551// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004552#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004553 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4554 m_is_running = true;
4555 while (!GetIsDone()) {
4556 SelectHelper select_helper;
4557 select_helper.FDSetRead(read_fd);
4558 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004559 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004560
Kate Stoneb9c1b512016-09-06 20:57:50 +00004561 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004562 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004563 } else {
4564 char ch = 0;
4565 size_t n;
4566 if (select_helper.FDIsSetRead(read_fd)) {
4567 n = 1;
4568 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4569 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4570 SetIsDone(true);
4571 } else
4572 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004573 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004574 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4575 size_t bytes_read;
4576 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004577 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004578 if (error.Success()) {
4579 switch (ch) {
4580 case 'q':
4581 SetIsDone(true);
4582 break;
4583 case 'i':
4584 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004585 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004586 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004587 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004588 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004589 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004590 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004591 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004592 m_is_running = false;
4593#endif
4594 terminal_state.Restore();
4595 }
4596
4597 void Cancel() override {
4598 SetIsDone(true);
4599 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004600 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4601 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004602 //
4603 // (lldb) step_process_thousands_of_times
4604 //
4605 // In this case the command interpreter will be in the middle of handling
4606 // the command and if the process pushes and pops the IOHandler thousands
4607 // of times, we can end up writing to m_pipe without ever consuming the
4608 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4609 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4610 if (m_is_running) {
4611 char ch = 'q'; // Send 'q' for quit
4612 size_t bytes_written = 0;
4613 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004614 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004615 }
4616
4617 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004618 // Do only things that are safe to do in an interrupt context (like in a
4619 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004620 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4621 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004622 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004623 if (m_active) {
4624 char ch = 'i'; // Send 'i' for interrupt
4625 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004626 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004627 return result.Success();
4628 } else {
4629 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004630 // currently so do the right thing if we aren't actively watching for
4631 // STDIN by sending the interrupt to the process. Otherwise the write to
4632 // the pipe above would do nothing. This can happen when the command
4633 // interpreter is running and gets a "expression ...". It will be on the
4634 // IOHandler thread and sending the input is complete to the delegate
4635 // which will cause the expression to run, which will push the process IO
4636 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004637
4638 if (StateIsRunningState(m_process->GetState())) {
4639 m_process->SendAsyncInterrupt();
4640 return true;
4641 }
4642 }
4643 return false;
4644 }
4645
4646 void GotEOF() override {}
4647
Greg Clayton44d93782014-01-27 23:43:24 +00004648protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004649 Process *m_process;
4650 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4651 File m_write_file; // Write to this file (usually the master pty for getting
4652 // io to debuggee)
4653 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004654 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004655};
4656
Kate Stoneb9c1b512016-09-06 20:57:50 +00004657void Process::SetSTDIOFileDescriptor(int fd) {
4658 // First set up the Read Thread for reading/handling process I/O
4659
4660 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4661 new ConnectionFileDescriptor(fd, true));
4662
4663 if (conn_ap) {
4664 m_stdio_communication.SetConnection(conn_ap.release());
4665 if (m_stdio_communication.IsConnected()) {
4666 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4667 STDIOReadThreadBytesReceived, this);
4668 m_stdio_communication.StartReadThread();
4669
4670 // Now read thread is set up, set up input reader.
4671
4672 if (!m_process_input_reader)
4673 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004674 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004675 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004676}
4677
Kate Stoneb9c1b512016-09-06 20:57:50 +00004678bool Process::ProcessIOHandlerIsActive() {
4679 IOHandlerSP io_handler_sp(m_process_input_reader);
4680 if (io_handler_sp)
4681 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4682 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004683}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004684bool Process::PushProcessIOHandler() {
4685 IOHandlerSP io_handler_sp(m_process_input_reader);
4686 if (io_handler_sp) {
4687 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4688 if (log)
4689 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004690
Kate Stoneb9c1b512016-09-06 20:57:50 +00004691 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004692 // If we evaluate an utility function, then we don't cancel the current
4693 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4694 // existing IOHandler that potentially provides the user interface (e.g.
4695 // the IOHandler for Editline).
4696 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4697 GetTarget().GetDebugger().PushIOHandler(io_handler_sp, cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004698 return true;
4699 }
4700 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004701}
4702
Kate Stoneb9c1b512016-09-06 20:57:50 +00004703bool Process::PopProcessIOHandler() {
4704 IOHandlerSP io_handler_sp(m_process_input_reader);
4705 if (io_handler_sp)
4706 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4707 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004708}
4709
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004710// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004711void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004712
Kate Stoneb9c1b512016-09-06 20:57:50 +00004713void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004714
Kate Stoneb9c1b512016-09-06 20:57:50 +00004715namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004716// RestorePlanState is used to record the "is private", "is master" and "okay
4717// to discard" fields of the plan we are running, and reset it on Clean or on
4718// destruction. It will only reset the state once, so you can call Clean and
4719// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004720
Kate Stoneb9c1b512016-09-06 20:57:50 +00004721class RestorePlanState {
4722public:
4723 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4724 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4725 if (m_thread_plan_sp) {
4726 m_private = m_thread_plan_sp->GetPrivate();
4727 m_is_master = m_thread_plan_sp->IsMasterPlan();
4728 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4729 }
4730 }
4731
4732 ~RestorePlanState() { Clean(); }
4733
4734 void Clean() {
4735 if (!m_already_reset && m_thread_plan_sp) {
4736 m_already_reset = true;
4737 m_thread_plan_sp->SetPrivate(m_private);
4738 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4739 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4740 }
4741 }
4742
4743private:
4744 lldb::ThreadPlanSP m_thread_plan_sp;
4745 bool m_already_reset;
4746 bool m_private;
4747 bool m_is_master;
4748 bool m_okay_to_discard;
4749};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004750} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004751
Pavel Labath2ce22162016-12-01 10:57:30 +00004752static microseconds
4753GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4754 const milliseconds default_one_thread_timeout(250);
4755
4756 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004757 if (!options.GetTimeout()) {
4758 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4759 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004760 }
4761
4762 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004763 if (options.GetOneThreadTimeout())
4764 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004765
4766 // Otherwise use half the total timeout, bounded by the
4767 // default_one_thread_timeout.
4768 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004769 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004770}
4771
4772static Timeout<std::micro>
4773GetExpressionTimeout(const EvaluateExpressionOptions &options,
4774 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004775 // If we are going to run all threads the whole time, or if we are only going
4776 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004777 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004778 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004779
4780 if (before_first_timeout)
4781 return GetOneThreadExpressionTimeout(options);
4782
Pavel Labath43d35412016-12-06 11:24:51 +00004783 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004784 return llvm::None;
4785 else
Pavel Labath43d35412016-12-06 11:24:51 +00004786 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004787}
4788
Pavel Labath45dde232017-05-25 10:50:06 +00004789static llvm::Optional<ExpressionResults>
4790HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4791 RestorePlanState &restorer, const EventSP &event_sp,
4792 EventSP &event_to_broadcast_sp,
4793 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4794 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4795
4796 ThreadPlanSP plan = thread.GetCompletedPlan();
4797 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4798 LLDB_LOG(log, "execution completed successfully");
4799
4800 // Restore the plan state so it will get reported as intended when we are
4801 // done.
4802 restorer.Clean();
4803 return eExpressionCompleted;
4804 }
4805
4806 StopInfoSP stop_info_sp = thread.GetStopInfo();
4807 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4808 stop_info_sp->ShouldNotify(event_sp.get())) {
4809 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4810 if (!options.DoesIgnoreBreakpoints()) {
4811 // Restore the plan state and then force Private to false. We are going
4812 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004813 // it won't report correctly when we continue to its termination later
4814 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004815 restorer.Clean();
4816 thread_plan_sp->SetPrivate(false);
4817 event_to_broadcast_sp = event_sp;
4818 }
4819 return eExpressionHitBreakpoint;
4820 }
4821
4822 if (!handle_interrupts &&
4823 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4824 return llvm::None;
4825
4826 LLDB_LOG(log, "thread plan did not successfully complete");
4827 if (!options.DoesUnwindOnError())
4828 event_to_broadcast_sp = event_sp;
4829 return eExpressionInterrupted;
4830}
4831
Jim Ingham1624a2d2014-05-05 02:26:40 +00004832ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004833Process::RunThreadPlan(ExecutionContext &exe_ctx,
4834 lldb::ThreadPlanSP &thread_plan_sp,
4835 const EvaluateExpressionOptions &options,
4836 DiagnosticManager &diagnostic_manager) {
4837 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004838
Kate Stoneb9c1b512016-09-06 20:57:50 +00004839 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4840
4841 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004842 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004843 eDiagnosticSeverityError,
4844 "RunThreadPlan called with empty thread plan.");
4845 return eExpressionSetupError;
4846 }
4847
4848 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004849 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004850 eDiagnosticSeverityError,
4851 "RunThreadPlan called with an invalid thread plan.");
4852 return eExpressionSetupError;
4853 }
4854
4855 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004856 diagnostic_manager.PutString(eDiagnosticSeverityError,
4857 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004858 return eExpressionSetupError;
4859 }
4860
4861 Thread *thread = exe_ctx.GetThreadPtr();
4862 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004863 diagnostic_manager.PutString(eDiagnosticSeverityError,
4864 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004865 return eExpressionSetupError;
4866 }
4867
4868 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004869 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004870
4871 RestorePlanState thread_plan_restorer(thread_plan_sp);
4872
Adrian Prantl05097242018-04-30 16:49:04 +00004873 // We rely on the thread plan we are running returning "PlanCompleted" if
4874 // when it successfully completes. For that to be true the plan can't be
4875 // private - since private plans suppress themselves in the GetCompletedPlan
4876 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004877
4878 thread_plan_sp->SetPrivate(false);
4879
4880 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004881 // when they are done we will end up asking the plan above us whether we
4882 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004883
4884 thread_plan_sp->SetIsMasterPlan(true);
4885 thread_plan_sp->SetOkayToDiscard(false);
4886
Raphael Isemannc01783a2018-08-29 22:50:54 +00004887 // If we are running some utility expression for LLDB, we now have to mark
4888 // this in the ProcesModID of this process. This RAII takes care of marking
4889 // and reverting the mark it once we are done running the expression.
4890 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4891
Kate Stoneb9c1b512016-09-06 20:57:50 +00004892 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004893 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004894 eDiagnosticSeverityError,
4895 "RunThreadPlan called while the private state was not stopped.");
4896 return eExpressionSetupError;
4897 }
4898
4899 // Save the thread & frame from the exe_ctx for restoration after we run
4900 const uint32_t thread_idx_id = thread->GetIndexID();
4901 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4902 if (!selected_frame_sp) {
4903 thread->SetSelectedFrame(nullptr);
4904 selected_frame_sp = thread->GetSelectedFrame();
4905 if (!selected_frame_sp) {
4906 diagnostic_manager.Printf(
4907 eDiagnosticSeverityError,
4908 "RunThreadPlan called without a selected frame on thread %d",
4909 thread_idx_id);
4910 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004911 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004912 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004913
Adrian Prantl05097242018-04-30 16:49:04 +00004914 // Make sure the timeout values make sense. The one thread timeout needs to
4915 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004916 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4917 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004918 diagnostic_manager.PutString(eDiagnosticSeverityError,
4919 "RunThreadPlan called with one thread "
4920 "timeout greater than total timeout");
4921 return eExpressionSetupError;
4922 }
4923
Kate Stoneb9c1b512016-09-06 20:57:50 +00004924 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004925
Kate Stoneb9c1b512016-09-06 20:57:50 +00004926 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004927 // We don't want to do that either, so we should arrange to reset them as
4928 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004929
Kate Stoneb9c1b512016-09-06 20:57:50 +00004930 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004931
Kate Stoneb9c1b512016-09-06 20:57:50 +00004932 uint32_t selected_tid;
4933 StackID selected_stack_id;
4934 if (selected_thread_sp) {
4935 selected_tid = selected_thread_sp->GetIndexID();
4936 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4937 } else {
4938 selected_tid = LLDB_INVALID_THREAD_ID;
4939 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004940
Kate Stoneb9c1b512016-09-06 20:57:50 +00004941 HostThread backup_private_state_thread;
4942 lldb::StateType old_state = eStateInvalid;
4943 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004944
Kate Stoneb9c1b512016-09-06 20:57:50 +00004945 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4946 LIBLLDB_LOG_PROCESS));
4947 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4948 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004949 // public events on this thread, since we are the thread that is generating
4950 // public events. The simplest thing to do is to spin up a temporary thread
4951 // to handle private state thread events while we are fielding public
4952 // events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004953 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004954 log->Printf("Running thread plan on private state thread, spinning up "
4955 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004956
Kate Stoneb9c1b512016-09-06 20:57:50 +00004957 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004958
Kate Stoneb9c1b512016-09-06 20:57:50 +00004959 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004960 // anything it pushes, and then stop, returning control here. But in the
4961 // normal course of things, the plan above us on the stack would be given a
4962 // shot at the stop event before deciding to stop, and we don't want that.
4963 // So we insert a "stopper" base plan on the stack before the plan we want
4964 // to run. Since base plans always stop and return control to the user,
4965 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004966 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4967 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4968 // Have to make sure our public state is stopped, since otherwise the
4969 // reporting logic below doesn't work correctly.
4970 old_state = m_public_state.GetValue();
4971 m_public_state.SetValueNoLock(eStateStopped);
4972
4973 // Now spin up the private state thread:
4974 StartPrivateStateThread(true);
4975 }
4976
4977 thread->QueueThreadPlan(
4978 thread_plan_sp, false); // This used to pass "true" does that make sense?
4979
4980 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004981 // In this case, we aren't actually going to run, we just want to stop
4982 // right away. Flush this thread so we will refetch the stacks and show the
4983 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004984 // FIXME: To make this prettier we should invent some stop reason for this,
4985 // but that
4986 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004987 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004988 thread->Flush();
4989 return eExpressionStoppedForDebug;
4990 }
4991
4992 ListenerSP listener_sp(
4993 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4994
4995 lldb::EventSP event_to_broadcast_sp;
4996
4997 {
4998 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004999 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005000 //
5001 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00005002 // exits during execution), then the event is put into
5003 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005004
5005 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5006
5007 if (log) {
5008 StreamString s;
5009 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5010 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5011 " to run thread plan \"%s\".",
5012 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00005013 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005014
5015 bool got_event;
5016 lldb::EventSP event_sp;
5017 lldb::StateType stop_state = lldb::eStateInvalid;
5018
5019 bool before_first_timeout = true; // This is set to false the first time
5020 // that we have to halt the target.
5021 bool do_resume = true;
5022 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005023
5024 // This is just for accounting:
5025 uint32_t num_resumes = 0;
5026
Kate Stoneb9c1b512016-09-06 20:57:50 +00005027 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00005028 // going to run one thread, then we don't need the first timeout. So we
5029 // pretend we are after the first timeout already.
5030 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00005031 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005032
Kate Stoneb9c1b512016-09-06 20:57:50 +00005033 if (log)
Pavel Labath2ce22162016-12-01 10:57:30 +00005034 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
5035 options.GetStopOthers(), options.GetTryAllThreads(),
5036 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005037
Adrian Prantl05097242018-04-30 16:49:04 +00005038 // This isn't going to work if there are unfetched events on the queue. Are
5039 // there cases where we might want to run the remaining events here, and
5040 // then try to call the function? That's probably being too tricky for our
5041 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005042
5043 Event *other_events = listener_sp->PeekAtNextEvent();
5044 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005045 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005046 eDiagnosticSeverityError,
5047 "RunThreadPlan called with pending events on the queue.");
5048 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00005049 }
5050
Kate Stoneb9c1b512016-09-06 20:57:50 +00005051 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00005052 // calling a function as part of a thread plan, in which case the last
5053 // delivered event could be the running event, and we don't want event
5054 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00005055 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00005056
Kate Stoneb9c1b512016-09-06 20:57:50 +00005057// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00005058// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00005059
Kate Stoneb9c1b512016-09-06 20:57:50 +00005060#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00005061 // It's pretty much impossible to write test cases for things like: One
5062 // thread timeout expires, I go to halt, but the process already stopped on
5063 // the function call stop breakpoint. Turning on this define will make us
5064 // not fetch the first event till after the halt. So if you run a quick
5065 // function, it will have completed, and the completion event will be
5066 // waiting, when you interrupt for halt. The expression evaluation should
5067 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005068 bool miss_first_event = true;
5069#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00005070 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00005071 // We usually want to resume the process if we get to the top of the
5072 // loop. The only exception is if we get two running events with no
5073 // intervening stop, which can happen, we will just wait for then next
5074 // stop event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005075 if (log)
5076 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5077 "before_first_timeout: %i.",
5078 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005079
Kate Stoneb9c1b512016-09-06 20:57:50 +00005080 if (do_resume || handle_running_event) {
5081 // Do the initial resume and wait for the running event before going
5082 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005083
Kate Stoneb9c1b512016-09-06 20:57:50 +00005084 if (do_resume) {
5085 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00005086 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005087 if (!resume_error.Success()) {
5088 diagnostic_manager.Printf(
5089 eDiagnosticSeverityError,
5090 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5091 resume_error.AsCString());
5092 return_value = eExpressionSetupError;
5093 break;
5094 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005095 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005096
Pavel Labathd35031e12016-11-30 10:41:42 +00005097 got_event =
5098 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005099 if (!got_event) {
5100 if (log)
5101 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5102 "resume %" PRIu32 ", exiting.",
5103 num_resumes);
5104
5105 diagnostic_manager.Printf(eDiagnosticSeverityError,
5106 "didn't get any event after resume %" PRIu32
5107 ", exiting.",
5108 num_resumes);
5109 return_value = eExpressionSetupError;
5110 break;
5111 }
5112
5113 stop_state =
5114 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5115
5116 if (stop_state != eStateRunning) {
5117 bool restarted = false;
5118
5119 if (stop_state == eStateStopped) {
5120 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5121 event_sp.get());
5122 if (log)
5123 log->Printf(
5124 "Process::RunThreadPlan(): didn't get running event after "
5125 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5126 "handle_running_event: %i).",
5127 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5128 handle_running_event);
5129 }
5130
5131 if (restarted) {
5132 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00005133 // should ever get a stopped & restarted event here. But if I do,
5134 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005135 const bool clear_thread_plans = false;
5136 const bool use_run_lock = false;
5137 Halt(clear_thread_plans, use_run_lock);
5138 }
5139
5140 diagnostic_manager.Printf(
5141 eDiagnosticSeverityError,
5142 "didn't get running event after initial resume, got %s instead.",
5143 StateAsCString(stop_state));
5144 return_value = eExpressionSetupError;
5145 break;
5146 }
5147
5148 if (log)
5149 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00005150 // We need to call the function synchronously, so spin waiting for it
5151 // to return. If we get interrupted while executing, we're going to
5152 // lose our context, and won't be able to gather the result at this
5153 // point. We set the timeout AFTER the resume, since the resume takes
5154 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005155 } else {
5156 if (log)
5157 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5158 }
5159
Kate Stoneb9c1b512016-09-06 20:57:50 +00005160 do_resume = true;
5161 handle_running_event = true;
5162
5163 // Now wait for the process to stop again:
5164 event_sp.reset();
5165
Pavel Labath2ce22162016-12-01 10:57:30 +00005166 Timeout<std::micro> timeout =
5167 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005168 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005169 if (timeout) {
5170 auto now = system_clock::now();
5171 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5172 "endpoint is %s",
5173 llvm::to_string(now).c_str(),
5174 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005175 } else {
5176 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005177 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005178 }
5179
5180#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5181 // See comment above...
5182 if (miss_first_event) {
5183 usleep(1000);
5184 miss_first_event = false;
5185 got_event = false;
5186 } else
5187#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005188 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005189
5190 if (got_event) {
5191 if (event_sp) {
5192 bool keep_going = false;
5193 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5194 const bool clear_thread_plans = false;
5195 const bool use_run_lock = false;
5196 Halt(clear_thread_plans, use_run_lock);
5197 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005198 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5199 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005200 if (log)
5201 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5202 "eBroadcastBitInterrupted, exiting.");
5203 break;
5204 } else {
5205 stop_state =
5206 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5207 if (log)
5208 log->Printf(
5209 "Process::RunThreadPlan(): in while loop, got event: %s.",
5210 StateAsCString(stop_state));
5211
5212 switch (stop_state) {
5213 case lldb::eStateStopped: {
5214 // We stopped, figure out what we are going to do now.
5215 ThreadSP thread_sp =
5216 GetThreadList().FindThreadByIndexID(thread_idx_id);
5217 if (!thread_sp) {
5218 // Ooh, our thread has vanished. Unlikely that this was
5219 // successful execution...
5220 if (log)
5221 log->Printf("Process::RunThreadPlan(): execution completed "
5222 "but our thread (index-id=%u) has vanished.",
5223 thread_idx_id);
5224 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00005225 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5226 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005227 // If we were restarted, we just need to go back up to fetch
5228 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00005229 if (log) {
5230 log->Printf("Process::RunThreadPlan(): Got a stop and "
5231 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005232 }
Pavel Labath45dde232017-05-25 10:50:06 +00005233 keep_going = true;
5234 do_resume = false;
5235 handle_running_event = true;
5236 } else {
5237 const bool handle_interrupts = true;
5238 return_value = *HandleStoppedEvent(
5239 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5240 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005241 }
5242 } break;
5243
5244 case lldb::eStateRunning:
5245 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005246 // running events without an intervening stop, and in that case
5247 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005248 do_resume = false;
5249 keep_going = true;
5250 handle_running_event = false;
5251 break;
5252
5253 default:
5254 if (log)
5255 log->Printf("Process::RunThreadPlan(): execution stopped with "
5256 "unexpected state: %s.",
5257 StateAsCString(stop_state));
5258
5259 if (stop_state == eStateExited)
5260 event_to_broadcast_sp = event_sp;
5261
Zachary Turnere2411fa2016-11-12 19:12:56 +00005262 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005263 eDiagnosticSeverityError,
5264 "execution stopped with unexpected state.");
5265 return_value = eExpressionInterrupted;
5266 break;
5267 }
5268 }
5269
5270 if (keep_going)
5271 continue;
5272 else
5273 break;
5274 } else {
5275 if (log)
5276 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5277 "the event pointer was null. How odd...");
5278 return_value = eExpressionInterrupted;
5279 break;
5280 }
5281 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005282 // If we didn't get an event that means we've timed out... We will
5283 // interrupt the process here. Depending on what we were asked to do
5284 // we will either exit, or try with all threads running for the same
5285 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005286
5287 if (log) {
5288 if (options.GetTryAllThreads()) {
5289 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005290 LLDB_LOG(log,
5291 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005292 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005293 LLDB_LOG(log, "Restarting function with all threads enabled and "
5294 "timeout: {0} timed out, abandoning execution.",
5295 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005296 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005297 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5298 "abandoning execution.",
5299 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005300 }
5301
5302 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005303 // around to calling Halt the target could have stopped. That's fine,
5304 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005305 // BUT it is also possible that we stopped & restarted (e.g. hit a
5306 // signal with "stop" set to false.) In
5307 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005308 // back to waiting for the Halt's stopped event. That's what this
5309 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005310
5311 bool back_to_top = true;
5312 uint32_t try_halt_again = 0;
5313 bool do_halt = true;
5314 const uint32_t num_retries = 5;
5315 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005316 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005317 if (do_halt) {
5318 if (log)
5319 log->Printf("Process::RunThreadPlan(): Running Halt.");
5320 const bool clear_thread_plans = false;
5321 const bool use_run_lock = false;
5322 Halt(clear_thread_plans, use_run_lock);
5323 }
5324 if (halt_error.Success()) {
5325 if (log)
5326 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5327
Pavel Labathd35031e12016-11-30 10:41:42 +00005328 got_event =
5329 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005330
5331 if (got_event) {
5332 stop_state =
5333 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5334 if (log) {
5335 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5336 StateAsCString(stop_state));
5337 if (stop_state == lldb::eStateStopped &&
5338 Process::ProcessEventData::GetInterruptedFromEvent(
5339 event_sp.get()))
5340 log->PutCString(" Event was the Halt interruption event.");
5341 }
5342
5343 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005344 if (Process::ProcessEventData::GetRestartedFromEvent(
5345 event_sp.get())) {
5346 if (log)
5347 log->PutCString("Process::RunThreadPlan(): Went to halt "
5348 "but got a restarted event, there must be "
5349 "an un-restarted stopped event so try "
5350 "again... "
5351 "Exiting wait loop.");
5352 try_halt_again++;
5353 do_halt = false;
5354 continue;
5355 }
5356
Pavel Labath45dde232017-05-25 10:50:06 +00005357 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005358 // delivered it, the process could have already finished its
5359 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005360 const bool handle_interrupts = false;
5361 if (auto result = HandleStoppedEvent(
5362 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5363 event_to_broadcast_sp, options, handle_interrupts)) {
5364 return_value = *result;
5365 back_to_top = false;
5366 break;
5367 }
5368
Kate Stoneb9c1b512016-09-06 20:57:50 +00005369 if (!options.GetTryAllThreads()) {
5370 if (log)
5371 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5372 "was false, we stopped so now we're "
5373 "quitting.");
5374 return_value = eExpressionInterrupted;
5375 back_to_top = false;
5376 break;
5377 }
5378
5379 if (before_first_timeout) {
5380 // Set all the other threads to run, and return to the top of
5381 // the loop, which will continue;
5382 before_first_timeout = false;
5383 thread_plan_sp->SetStopOthers(false);
5384 if (log)
5385 log->PutCString(
5386 "Process::RunThreadPlan(): about to resume.");
5387
5388 back_to_top = true;
5389 break;
5390 } else {
5391 // Running all threads failed, so return Interrupted.
5392 if (log)
5393 log->PutCString("Process::RunThreadPlan(): running all "
5394 "threads timed out.");
5395 return_value = eExpressionInterrupted;
5396 back_to_top = false;
5397 break;
5398 }
5399 }
5400 } else {
5401 if (log)
5402 log->PutCString("Process::RunThreadPlan(): halt said it "
5403 "succeeded, but I got no event. "
5404 "I'm getting out of here passing Interrupted.");
5405 return_value = eExpressionInterrupted;
5406 back_to_top = false;
5407 break;
5408 }
5409 } else {
5410 try_halt_again++;
5411 continue;
5412 }
5413 }
5414
5415 if (!back_to_top || try_halt_again > num_retries)
5416 break;
5417 else
5418 continue;
5419 }
5420 } // END WAIT LOOP
5421
Adrian Prantl05097242018-04-30 16:49:04 +00005422 // If we had to start up a temporary private state thread to run this
5423 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005424 if (backup_private_state_thread.IsJoinable()) {
5425 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005426 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005427 m_private_state_thread = backup_private_state_thread;
5428 if (stopper_base_plan_sp) {
5429 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5430 }
5431 if (old_state != eStateInvalid)
5432 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005433 }
5434
Kate Stoneb9c1b512016-09-06 20:57:50 +00005435 if (return_value != eExpressionCompleted && log) {
5436 // Print a backtrace into the log so we can figure out where we are:
5437 StreamString s;
5438 s.PutCString("Thread state after unsuccessful completion: \n");
5439 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005440 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005441 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005442 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005443 // There are three cases where this could happen: 1) The execution
5444 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5445 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005446 bool should_unwind = (return_value == eExpressionInterrupted &&
5447 options.DoesUnwindOnError()) ||
5448 (return_value == eExpressionHitBreakpoint &&
5449 options.DoesIgnoreBreakpoints());
5450
5451 if (return_value == eExpressionCompleted || should_unwind) {
5452 thread_plan_sp->RestoreThreadState();
5453 }
5454
5455 // Now do some processing on the results of the run:
5456 if (return_value == eExpressionInterrupted ||
5457 return_value == eExpressionHitBreakpoint) {
5458 if (log) {
5459 StreamString s;
5460 if (event_sp)
5461 event_sp->Dump(&s);
5462 else {
5463 log->PutCString("Process::RunThreadPlan(): Stop event that "
5464 "interrupted us is NULL.");
5465 }
5466
5467 StreamString ts;
5468
5469 const char *event_explanation = nullptr;
5470
5471 do {
5472 if (!event_sp) {
5473 event_explanation = "<no event>";
5474 break;
5475 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5476 event_explanation = "<user interrupt>";
5477 break;
5478 } else {
5479 const Process::ProcessEventData *event_data =
5480 Process::ProcessEventData::GetEventDataFromEvent(
5481 event_sp.get());
5482
5483 if (!event_data) {
5484 event_explanation = "<no event data>";
5485 break;
5486 }
5487
5488 Process *process = event_data->GetProcessSP().get();
5489
5490 if (!process) {
5491 event_explanation = "<no process>";
5492 break;
5493 }
5494
5495 ThreadList &thread_list = process->GetThreadList();
5496
5497 uint32_t num_threads = thread_list.GetSize();
5498 uint32_t thread_index;
5499
5500 ts.Printf("<%u threads> ", num_threads);
5501
5502 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5503 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5504
5505 if (!thread) {
5506 ts.Printf("<?> ");
5507 continue;
5508 }
5509
5510 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5511 RegisterContext *register_context =
5512 thread->GetRegisterContext().get();
5513
5514 if (register_context)
5515 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5516 else
5517 ts.Printf("[ip unknown] ");
5518
5519 // Show the private stop info here, the public stop info will be
5520 // from the last natural stop.
5521 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5522 if (stop_info_sp) {
5523 const char *stop_desc = stop_info_sp->GetDescription();
5524 if (stop_desc)
5525 ts.PutCString(stop_desc);
5526 }
5527 ts.Printf(">");
5528 }
5529
5530 event_explanation = ts.GetData();
5531 }
5532 } while (0);
5533
5534 if (event_explanation)
5535 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5536 s.GetData(), event_explanation);
5537 else
5538 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5539 s.GetData());
5540 }
5541
5542 if (should_unwind) {
5543 if (log)
5544 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5545 "discarding thread plans up to %p.",
5546 static_cast<void *>(thread_plan_sp.get()));
5547 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5548 } else {
5549 if (log)
5550 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5551 "plan: %p not discarding.",
5552 static_cast<void *>(thread_plan_sp.get()));
5553 }
5554 } else if (return_value == eExpressionSetupError) {
5555 if (log)
5556 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5557
5558 if (options.DoesUnwindOnError()) {
5559 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5560 }
5561 } else {
5562 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5563 if (log)
5564 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5565 return_value = eExpressionCompleted;
5566 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5567 if (log)
5568 log->PutCString(
5569 "Process::RunThreadPlan(): thread plan was discarded");
5570 return_value = eExpressionDiscarded;
5571 } else {
5572 if (log)
5573 log->PutCString(
5574 "Process::RunThreadPlan(): thread plan stopped in mid course");
5575 if (options.DoesUnwindOnError() && thread_plan_sp) {
5576 if (log)
5577 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5578 "'cause unwind_on_error is set.");
5579 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5580 }
5581 }
5582 }
5583
5584 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005585 // target Check that it's still there, and if it is put it back in the
5586 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005587 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5588 if (thread) {
5589 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5590 }
5591
5592 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005593 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005594
5595 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5596 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5597 selected_stack_id.IsValid()) {
5598 // We were able to restore the selected thread, now restore the frame:
5599 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5600 StackFrameSP old_frame_sp =
5601 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5602 selected_stack_id);
5603 if (old_frame_sp)
5604 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5605 old_frame_sp.get());
5606 }
5607 }
5608 }
5609
5610 // If the process exited during the run of the thread plan, notify everyone.
5611
5612 if (event_to_broadcast_sp) {
5613 if (log)
5614 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5615 BroadcastEvent(event_to_broadcast_sp);
5616 }
5617
5618 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005619}
5620
Kate Stoneb9c1b512016-09-06 20:57:50 +00005621const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5622 const char *result_name;
5623
5624 switch (result) {
5625 case eExpressionCompleted:
5626 result_name = "eExpressionCompleted";
5627 break;
5628 case eExpressionDiscarded:
5629 result_name = "eExpressionDiscarded";
5630 break;
5631 case eExpressionInterrupted:
5632 result_name = "eExpressionInterrupted";
5633 break;
5634 case eExpressionHitBreakpoint:
5635 result_name = "eExpressionHitBreakpoint";
5636 break;
5637 case eExpressionSetupError:
5638 result_name = "eExpressionSetupError";
5639 break;
5640 case eExpressionParseError:
5641 result_name = "eExpressionParseError";
5642 break;
5643 case eExpressionResultUnavailable:
5644 result_name = "eExpressionResultUnavailable";
5645 break;
5646 case eExpressionTimedOut:
5647 result_name = "eExpressionTimedOut";
5648 break;
5649 case eExpressionStoppedForDebug:
5650 result_name = "eExpressionStoppedForDebug";
5651 break;
5652 }
5653 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005654}
5655
Kate Stoneb9c1b512016-09-06 20:57:50 +00005656void Process::GetStatus(Stream &strm) {
5657 const StateType state = GetState();
5658 if (StateIsStoppedState(state, false)) {
5659 if (state == eStateExited) {
5660 int exit_status = GetExitStatus();
5661 const char *exit_description = GetExitDescription();
5662 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5663 GetID(), exit_status, exit_status,
5664 exit_description ? exit_description : "");
5665 } else {
5666 if (state == eStateConnected)
5667 strm.Printf("Connected to remote target.\n");
5668 else
5669 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5670 }
5671 } else {
5672 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5673 }
Pavel Labatha933d512016-04-05 13:07:16 +00005674}
5675
Kate Stoneb9c1b512016-09-06 20:57:50 +00005676size_t Process::GetThreadStatus(Stream &strm,
5677 bool only_threads_with_stop_reason,
5678 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005679 uint32_t num_frames_with_source,
5680 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005681 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005682
Kate Stoneb9c1b512016-09-06 20:57:50 +00005683 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005684 // very well might run code (e.g. if we need it to get return values or
5685 // arguments.) For that to work the process has to be able to acquire it.
5686 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005687
5688 uint32_t num_threads;
5689 std::vector<lldb::tid_t> thread_id_array;
5690 // Scope for thread list locker;
5691 {
5692 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5693 ThreadList &curr_thread_list = GetThreadList();
5694 num_threads = curr_thread_list.GetSize();
5695 uint32_t idx;
5696 thread_id_array.resize(num_threads);
5697 for (idx = 0; idx < num_threads; ++idx)
5698 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5699 }
5700
5701 for (uint32_t i = 0; i < num_threads; i++) {
5702 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5703 if (thread_sp) {
5704 if (only_threads_with_stop_reason) {
5705 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5706 if (!stop_info_sp || !stop_info_sp->IsValid())
5707 continue;
5708 }
5709 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005710 num_frames_with_source,
5711 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005712 ++num_thread_infos_dumped;
5713 } else {
5714 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5715 if (log)
5716 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5717 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005718 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005719 }
5720 return num_thread_infos_dumped;
5721}
5722
5723void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5724 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5725}
5726
5727bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5728 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5729 region.GetByteSize());
5730}
5731
5732void Process::AddPreResumeAction(PreResumeActionCallback callback,
5733 void *baton) {
5734 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5735}
5736
5737bool Process::RunPreResumeActions() {
5738 bool result = true;
5739 while (!m_pre_resume_actions.empty()) {
5740 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5741 m_pre_resume_actions.pop_back();
5742 bool this_result = action.callback(action.baton);
5743 if (result)
5744 result = this_result;
5745 }
5746 return result;
5747}
5748
5749void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5750
Jim Inghamffd91752016-10-20 22:50:00 +00005751void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5752{
5753 PreResumeCallbackAndBaton element(callback, baton);
5754 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5755 if (found_iter != m_pre_resume_actions.end())
5756 {
5757 m_pre_resume_actions.erase(found_iter);
5758 }
5759}
5760
Kate Stoneb9c1b512016-09-06 20:57:50 +00005761ProcessRunLock &Process::GetRunLock() {
5762 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5763 return m_private_run_lock;
5764 else
5765 return m_public_run_lock;
5766}
5767
5768void Process::Flush() {
5769 m_thread_list.Flush();
5770 m_extended_thread_list.Flush();
5771 m_extended_thread_stop_id = 0;
5772 m_queue_list.Clear();
5773 m_queue_list_stop_id = 0;
5774}
5775
5776void Process::DidExec() {
5777 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5778 if (log)
5779 log->Printf("Process::%s()", __FUNCTION__);
5780
5781 Target &target = GetTarget();
5782 target.CleanupProcess();
5783 target.ClearModules(false);
5784 m_dynamic_checkers_ap.reset();
5785 m_abi_sp.reset();
5786 m_system_runtime_ap.reset();
5787 m_os_ap.reset();
5788 m_dyld_ap.reset();
5789 m_jit_loaders_ap.reset();
5790 m_image_tokens.clear();
5791 m_allocated_memory_cache.Clear();
5792 m_language_runtimes.clear();
5793 m_instrumentation_runtimes.clear();
5794 m_thread_list.DiscardThreadPlans();
5795 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005796 DoDidExec();
5797 CompleteAttach();
5798 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005799 // CompleteAttach() in case the dynamic loader loaded things in new
5800 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005801 Flush();
5802
Adrian Prantl05097242018-04-30 16:49:04 +00005803 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5804 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005805 target.DidExec();
5806}
5807
Zachary Turner97206d52017-05-12 04:51:55 +00005808addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005809 if (address == nullptr) {
5810 error.SetErrorString("Invalid address argument");
5811 return LLDB_INVALID_ADDRESS;
5812 }
5813
5814 addr_t function_addr = LLDB_INVALID_ADDRESS;
5815
5816 addr_t addr = address->GetLoadAddress(&GetTarget());
5817 std::map<addr_t, addr_t>::const_iterator iter =
5818 m_resolved_indirect_addresses.find(addr);
5819 if (iter != m_resolved_indirect_addresses.end()) {
5820 function_addr = (*iter).second;
5821 } else {
5822 if (!InferiorCall(this, address, function_addr)) {
5823 Symbol *symbol = address->CalculateSymbolContextSymbol();
5824 error.SetErrorStringWithFormat(
5825 "Unable to call resolver for indirect function %s",
5826 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5827 function_addr = LLDB_INVALID_ADDRESS;
5828 } else {
5829 m_resolved_indirect_addresses.insert(
5830 std::pair<addr_t, addr_t>(addr, function_addr));
5831 }
5832 }
5833 return function_addr;
5834}
5835
5836void Process::ModulesDidLoad(ModuleList &module_list) {
5837 SystemRuntime *sys_runtime = GetSystemRuntime();
5838 if (sys_runtime) {
5839 sys_runtime->ModulesDidLoad(module_list);
5840 }
5841
5842 GetJITLoaders().ModulesDidLoad(module_list);
5843
5844 // Give runtimes a chance to be created.
5845 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5846 m_instrumentation_runtimes);
5847
5848 // Tell runtimes about new modules.
5849 for (auto pos = m_instrumentation_runtimes.begin();
5850 pos != m_instrumentation_runtimes.end(); ++pos) {
5851 InstrumentationRuntimeSP runtime = pos->second;
5852 runtime->ModulesDidLoad(module_list);
5853 }
5854
Adrian Prantl05097242018-04-30 16:49:04 +00005855 // Let any language runtimes we have already created know about the modules
5856 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005857
Adrian Prantl05097242018-04-30 16:49:04 +00005858 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005859 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005860 // unloaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005861 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5862 for (const auto &pair : language_runtimes) {
Adrian Prantl05097242018-04-30 16:49:04 +00005863 // We must check language_runtime_sp to make sure it is not nullptr as we
5864 // might cache the fact that we didn't have a language runtime for a
5865 // language.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005866 LanguageRuntimeSP language_runtime_sp = pair.second;
5867 if (language_runtime_sp)
5868 language_runtime_sp->ModulesDidLoad(module_list);
5869 }
5870
5871 // If we don't have an operating system plug-in, try to load one since
5872 // loading shared libraries might cause a new one to try and load
5873 if (!m_os_ap)
5874 LoadOperatingSystemPlugin(false);
5875
5876 // Give structured-data plugins a chance to see the modified modules.
5877 for (auto pair : m_structured_data_plugin_map) {
5878 if (pair.second)
5879 pair.second->ModulesDidLoad(*this, module_list);
5880 }
5881}
5882
5883void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5884 const char *fmt, ...) {
5885 bool print_warning = true;
5886
5887 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5888 if (!stream_sp)
5889 return;
5890 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5891 return;
5892 }
5893
5894 if (repeat_key != nullptr) {
5895 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5896 if (it == m_warnings_issued.end()) {
5897 m_warnings_issued[warning_type] = WarningsPointerSet();
5898 m_warnings_issued[warning_type].insert(repeat_key);
5899 } else {
5900 if (it->second.find(repeat_key) != it->second.end()) {
5901 print_warning = false;
5902 } else {
5903 it->second.insert(repeat_key);
5904 }
5905 }
5906 }
5907
5908 if (print_warning) {
5909 va_list args;
5910 va_start(args, fmt);
5911 stream_sp->PrintfVarArg(fmt, args);
5912 va_end(args);
5913 }
5914}
5915
5916void Process::PrintWarningOptimization(const SymbolContext &sc) {
5917 if (GetWarningsOptimization() && sc.module_sp &&
5918 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5919 sc.function->GetIsOptimized()) {
5920 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5921 "%s was compiled with optimization - stepping may behave "
5922 "oddly; variables may not be available.\n",
5923 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5924 }
5925}
5926
5927bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5928 info.Clear();
5929
5930 PlatformSP platform_sp = GetTarget().GetPlatform();
5931 if (!platform_sp)
5932 return false;
5933
5934 return platform_sp->GetProcessInfo(GetID(), info);
5935}
5936
5937ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5938 ThreadCollectionSP threads;
5939
5940 const MemoryHistorySP &memory_history =
5941 MemoryHistory::FindPlugin(shared_from_this());
5942
5943 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005944 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005945 }
5946
5947 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
5948
5949 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005950}
Kuba Brecka63927542014-10-11 01:59:32 +00005951
5952InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005953Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5954 InstrumentationRuntimeCollection::iterator pos;
5955 pos = m_instrumentation_runtimes.find(type);
5956 if (pos == m_instrumentation_runtimes.end()) {
5957 return InstrumentationRuntimeSP();
5958 } else
5959 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005960}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005961
Kate Stoneb9c1b512016-09-06 20:57:50 +00005962bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5963 const ArchSpec &arch, ModuleSpec &module_spec) {
5964 module_spec.Clear();
5965 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005966}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005967
Kate Stoneb9c1b512016-09-06 20:57:50 +00005968size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5969 m_image_tokens.push_back(image_ptr);
5970 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005971}
5972
Kate Stoneb9c1b512016-09-06 20:57:50 +00005973lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5974 if (token < m_image_tokens.size())
5975 return m_image_tokens[token];
5976 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005977}
5978
Kate Stoneb9c1b512016-09-06 20:57:50 +00005979void Process::ResetImageToken(size_t token) {
5980 if (token < m_image_tokens.size())
5981 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005982}
Jason Molendafd4cea52016-01-08 21:40:11 +00005983
5984Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005985Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5986 AddressRange range_bounds) {
5987 Target &target = GetTarget();
5988 DisassemblerSP disassembler_sp;
5989 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005990
Kate Stoneb9c1b512016-09-06 20:57:50 +00005991 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005992
Kate Stoneb9c1b512016-09-06 20:57:50 +00005993 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005994 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005995 if (!default_stop_addr.IsValid())
5996 return retval;
5997
5998 ExecutionContext exe_ctx(this);
5999 const char *plugin_name = nullptr;
6000 const char *flavor = nullptr;
6001 const bool prefer_file_cache = true;
6002 disassembler_sp = Disassembler::DisassembleRange(
6003 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6004 prefer_file_cache);
6005 if (disassembler_sp)
6006 insn_list = &disassembler_sp->GetInstructionList();
6007
6008 if (insn_list == nullptr) {
6009 return retval;
6010 }
6011
6012 size_t insn_offset =
6013 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6014 if (insn_offset == UINT32_MAX) {
6015 return retval;
6016 }
6017
6018 uint32_t branch_index =
6019 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6020 if (branch_index == UINT32_MAX) {
6021 return retval;
6022 }
6023
6024 if (branch_index > insn_offset) {
6025 Address next_branch_insn_address =
6026 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6027 if (next_branch_insn_address.IsValid() &&
6028 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6029 retval = next_branch_insn_address;
6030 }
6031 }
6032
6033 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00006034}
Howard Hellyerad007562016-07-07 08:21:28 +00006035
Zachary Turner97206d52017-05-12 04:51:55 +00006036Status
6037Process::GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00006038
Zachary Turner97206d52017-05-12 04:51:55 +00006039 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00006040
Kate Stoneb9c1b512016-09-06 20:57:50 +00006041 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00006042
Kate Stoneb9c1b512016-09-06 20:57:50 +00006043 region_list.clear();
6044 do {
6045 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6046 error = GetMemoryRegionInfo(range_end, *region_info);
6047 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6048 if (error.Fail()) {
6049 region_list.clear();
6050 break;
Todd Fiala75930012016-08-19 04:21:48 +00006051 }
6052
Kate Stoneb9c1b512016-09-06 20:57:50 +00006053 range_end = region_info->GetRange().GetRangeEnd();
6054 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6055 region_list.push_back(region_info);
6056 }
6057 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006058
Kate Stoneb9c1b512016-09-06 20:57:50 +00006059 return error;
6060}
6061
Zachary Turner97206d52017-05-12 04:51:55 +00006062Status
6063Process::ConfigureStructuredData(const ConstString &type_name,
6064 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00006065 // If you get this, the Process-derived class needs to implement a method to
6066 // enable an already-reported asynchronous structured data feature. See
6067 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00006068 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00006069}
6070
6071void Process::MapSupportedStructuredDataPlugins(
6072 const StructuredData::Array &supported_type_names) {
6073 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6074
6075 // Bail out early if there are no type names to map.
6076 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00006077 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006078 log->Printf("Process::%s(): no structured data types supported",
6079 __FUNCTION__);
6080 return;
6081 }
Todd Fiala75930012016-08-19 04:21:48 +00006082
Kate Stoneb9c1b512016-09-06 20:57:50 +00006083 // Convert StructuredData type names to ConstString instances.
6084 std::set<ConstString> const_type_names;
6085
6086 if (log)
6087 log->Printf("Process::%s(): the process supports the following async "
6088 "structured data types:",
6089 __FUNCTION__);
6090
6091 supported_type_names.ForEach(
6092 [&const_type_names, &log](StructuredData::Object *object) {
6093 if (!object) {
6094 // Invalid - shouldn't be null objects in the array.
6095 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006096 }
6097
6098 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006099 if (!type_name) {
6100 // Invalid format - all type names should be strings.
6101 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006102 }
6103
6104 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00006105 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00006106 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006107 });
Todd Fiala75930012016-08-19 04:21:48 +00006108
Adrian Prantl05097242018-04-30 16:49:04 +00006109 // For each StructuredDataPlugin, if the plugin handles any of the types in
6110 // the supported_type_names, map that type name to that plugin. Stop when
6111 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00006112 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00006113 // supports?
6114 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
6115 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00006116 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6117 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00006118 if (!create_instance)
6119 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00006120
Kate Stoneb9c1b512016-09-06 20:57:50 +00006121 // Create the plugin.
6122 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6123 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00006124 // This plugin doesn't think it can work with the process. Move on to the
6125 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006126 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006127 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006128
Adrian Prantl05097242018-04-30 16:49:04 +00006129 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006130 std::vector<ConstString> names_to_remove;
6131 for (auto &type_name : const_type_names) {
6132 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6133 m_structured_data_plugin_map.insert(
6134 std::make_pair(type_name, plugin_sp));
6135 names_to_remove.push_back(type_name);
6136 if (log)
6137 log->Printf("Process::%s(): using plugin %s for type name "
6138 "%s",
6139 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6140 type_name.GetCString());
6141 }
6142 }
6143
6144 // Remove the type names that were consumed by this plugin.
6145 for (auto &type_name : names_to_remove)
6146 const_type_names.erase(type_name);
6147 }
Todd Fiala75930012016-08-19 04:21:48 +00006148}
6149
Kate Stoneb9c1b512016-09-06 20:57:50 +00006150bool Process::RouteAsyncStructuredData(
6151 const StructuredData::ObjectSP object_sp) {
6152 // Nothing to do if there's no data.
6153 if (!object_sp)
6154 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006155
Adrian Prantl05097242018-04-30 16:49:04 +00006156 // The contract is this must be a dictionary, so we can look up the routing
6157 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006158 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6159 if (!dictionary)
6160 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006161
Kate Stoneb9c1b512016-09-06 20:57:50 +00006162 // Grab the async structured type name (i.e. the feature/plugin name).
6163 ConstString type_name;
6164 if (!dictionary->GetValueForKeyAsString("type", type_name))
6165 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006166
Kate Stoneb9c1b512016-09-06 20:57:50 +00006167 // Check if there's a plugin registered for this type name.
6168 auto find_it = m_structured_data_plugin_map.find(type_name);
6169 if (find_it == m_structured_data_plugin_map.end()) {
6170 // We don't have a mapping for this structured data type.
6171 return false;
6172 }
Todd Fiala75930012016-08-19 04:21:48 +00006173
Kate Stoneb9c1b512016-09-06 20:57:50 +00006174 // Route the structured data to the plugin.
6175 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6176 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006177}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006178
Zachary Turner97206d52017-05-12 04:51:55 +00006179Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006180 // Default implementation does nothign.
6181 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00006182 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006183}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006184
Frederic Rissd10d3792018-05-11 18:21:11 +00006185UtilityFunction *Process::GetLoadImageUtilityFunction(
6186 Platform *platform,
6187 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006188 if (platform != GetTarget().GetPlatform().get())
6189 return nullptr;
Frederic Rissd10d3792018-05-11 18:21:11 +00006190 std::call_once(m_dlopen_utility_func_flag_once,
6191 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006192 return m_dlopen_utility_func_up.get();
6193}