blob: ba3dadabfa08be2fc8a9872025333ef532db3077 [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
Greg Clayton5cc45e02016-02-26 19:41:49 +000010#include <atomic>
Greg Clayton04df8ee2016-02-26 19:38:18 +000011#include <mutex>
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +000012
Pavel Labath2ce22162016-12-01 10:57:30 +000013#include "llvm/Support/ScopedPrinter.h"
Zachary Turner777de772017-03-04 16:42:25 +000014#include "llvm/Support/Threading.h"
15
Sean Callanan579e70c2016-03-19 00:03:59 +000016#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000018#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Core/Debugger.h"
Greg Clayton1f746072012-08-29 21:13:06 +000020#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000021#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
Greg Clayton44d93782014-01-27 23:43:24 +000023#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000024#include "lldb/Expression/DiagnosticManager.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000025#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000026#include "lldb/Expression/UserExpression.h"
Jim Ingham1ecb34f2018-04-17 20:44:47 +000027#include "lldb/Expression/UtilityFunction.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000028#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000029#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000031#include "lldb/Host/HostInfo.h"
Zachary Turner3eb2b442017-03-22 23:33:16 +000032#include "lldb/Host/OptionParser.h"
Greg Clayton100eb932014-07-02 21:10:39 +000033#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000034#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000035#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000036#include "lldb/Interpreter/CommandInterpreter.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000037#include "lldb/Interpreter/OptionArgParser.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000038#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000039#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000040#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Target/ABI.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000042#include "lldb/Target/CPPLanguageRuntime.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000043#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000044#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000045#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000046#include "lldb/Target/JITLoaderList.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000047#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000048#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000049#include "lldb/Target/MemoryRegionInfo.h"
Jim Ingham22777012010-09-23 02:01:19 +000050#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000051#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000052#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000053#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000055#include "lldb/Target/StopInfo.h"
Todd Fiala75930012016-08-19 04:21:48 +000056#include "lldb/Target/StructuredDataPlugin.h"
Jason Molendaeef51062013-11-05 03:57:19 +000057#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000058#include "lldb/Target/Target.h"
59#include "lldb/Target/TargetList.h"
60#include "lldb/Target/Thread.h"
61#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000062#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000063#include "lldb/Target/UnixSignals.h"
Pavel Labath181b8232018-12-14 15:59:49 +000064#include "lldb/Utility/Event.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000065#include "lldb/Utility/Log.h"
Zachary Turner50232572015-03-18 21:31:45 +000066#include "lldb/Utility/NameMatches.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000067#include "lldb/Utility/SelectHelper.h"
Pavel Labathd821c992018-08-07 11:07:21 +000068#include "lldb/Utility/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069
70using namespace lldb;
71using namespace lldb_private;
Pavel Labathe3e21cf2016-11-30 11:56:32 +000072using namespace std::chrono;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073
Kate Stoneb9c1b512016-09-06 20:57:50 +000074// Comment out line below to disable memory caching, overriding the process
Pavel Labath43d35412016-12-06 11:24:51 +000075// setting target.process.disable-memory-cache
Greg Clayton67cc0632012-08-22 17:17:09 +000076#define ENABLE_MEMORY_CACHING
77
78#ifdef ENABLE_MEMORY_CACHING
79#define DISABLE_MEM_CACHE_DEFAULT false
80#else
81#define DISABLE_MEM_CACHE_DEFAULT true
82#endif
83
Kate Stoneb9c1b512016-09-06 20:57:50 +000084class ProcessOptionValueProperties : public OptionValueProperties {
Greg Clayton67cc0632012-08-22 17:17:09 +000085public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000086 ProcessOptionValueProperties(const ConstString &name)
87 : OptionValueProperties(name) {}
88
Adrian Prantl05097242018-04-30 16:49:04 +000089 // This constructor is used when creating ProcessOptionValueProperties when
90 // it is part of a new lldb_private::Process instance. It will copy all
91 // current global property values as needed
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 ProcessOptionValueProperties(ProcessProperties *global_properties)
93 : OptionValueProperties(*global_properties->GetValueProperties()) {}
94
95 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
96 bool will_modify,
97 uint32_t idx) const override {
Adrian Prantl05097242018-04-30 16:49:04 +000098 // When getting the value for a key from the process options, we will
99 // always try and grab the setting from the current process if there is
100 // one. Else we just use the one from this instance.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101 if (exe_ctx) {
102 Process *process = exe_ctx->GetProcessPtr();
103 if (process) {
104 ProcessOptionValueProperties *instance_properties =
105 static_cast<ProcessOptionValueProperties *>(
106 process->GetValueProperties().get());
107 if (this != instance_properties)
108 return instance_properties->ProtectedGetPropertyAtIndex(idx);
109 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000110 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 return ProtectedGetPropertyAtIndex(idx);
112 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000113};
114
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000115static constexpr PropertyDefinition g_properties[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 {"disable-memory-cache", OptionValue::eTypeBoolean, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000117 DISABLE_MEM_CACHE_DEFAULT, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 "Disable reading and caching of memory in fixed-size units."},
119 {"extra-startup-command", OptionValue::eTypeArray, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000120 OptionValue::eTypeString, nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121 "A list containing extra commands understood by the particular process "
122 "plugin used. "
123 "For instance, to turn on debugserver logging set this to "
124 "\"QSetLogging:bitmask=LOG_DEFAULT;\""},
125 {"ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000126 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127 "If true, breakpoints will be ignored during expression evaluation."},
128 {"unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000129 nullptr, {}, "If true, errors in expression evaluation will unwind "
130 "the stack back to the state before the call."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 {"python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000132 {}, "A path to a python OS plug-in module file that contains a "
133 "OperatingSystemPlugIn class."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134 {"stop-on-sharedlibrary-events", OptionValue::eTypeBoolean, true, false,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000135 nullptr, {},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136 "If true, stop when a shared library is loaded or unloaded."},
137 {"detach-keeps-stopped", OptionValue::eTypeBoolean, true, false, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000138 {}, "If true, detach will attempt to keep the process stopped."},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 {"memory-cache-line-size", OptionValue::eTypeUInt64, false, 512, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000140 {}, "The memory cache line size"},
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 {"optimization-warnings", OptionValue::eTypeBoolean, false, true, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000142 {}, "If true, warn when stopped in code that is optimized where "
143 "stepping and variable availability may not behave as expected."},
Jim Inghamba205c12017-12-05 02:50:45 +0000144 {"stop-on-exec", OptionValue::eTypeBoolean, true, true,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000145 nullptr, {},
Tatyana Krasnukhae40db052018-09-27 07:11:58 +0000146 "If true, stop when a shared library is loaded or unloaded."}};
Greg Clayton67cc0632012-08-22 17:17:09 +0000147
148enum {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 ePropertyDisableMemCache,
150 ePropertyExtraStartCommand,
151 ePropertyIgnoreBreakpointsInExpressions,
152 ePropertyUnwindOnErrorInExpressions,
153 ePropertyPythonOSPluginPath,
154 ePropertyStopOnSharedLibraryEvents,
155 ePropertyDetachKeepsStopped,
156 ePropertyMemCacheLineSize,
Jim Inghamba205c12017-12-05 02:50:45 +0000157 ePropertyWarningOptimization,
158 ePropertyStopOnExec
Greg Clayton67cc0632012-08-22 17:17:09 +0000159};
160
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161ProcessProperties::ProcessProperties(lldb_private::Process *process)
162 : Properties(),
163 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000164{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165 if (process == nullptr) {
166 // Global process properties, set them up one time
167 m_collection_sp.reset(
168 new ProcessOptionValueProperties(ConstString("process")));
169 m_collection_sp->Initialize(g_properties);
170 m_collection_sp->AppendProperty(
171 ConstString("thread"), ConstString("Settings specific to threads."),
172 true, Thread::GetGlobalProperties()->GetValueProperties());
173 } else {
174 m_collection_sp.reset(
175 new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
176 m_collection_sp->SetValueChangedCallback(
177 ePropertyPythonOSPluginPath,
178 ProcessProperties::OptionValueChangedCallback, this);
179 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000180}
181
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000182ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000183
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184void ProcessProperties::OptionValueChangedCallback(void *baton,
185 OptionValue *option_value) {
186 ProcessProperties *properties = (ProcessProperties *)baton;
187 if (properties->m_process)
188 properties->m_process->LoadOperatingSystemPlugin(true);
Greg Clayton332e8b12015-01-13 21:13:08 +0000189}
190
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191bool ProcessProperties::GetDisableMemoryCache() const {
192 const uint32_t idx = ePropertyDisableMemCache;
193 return m_collection_sp->GetPropertyAtIndexAsBoolean(
194 nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000195}
196
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
198 const uint32_t idx = ePropertyMemCacheLineSize;
199 return m_collection_sp->GetPropertyAtIndexAsUInt64(
200 nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000201}
202
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203Args ProcessProperties::GetExtraStartupCommands() const {
204 Args args;
205 const uint32_t idx = ePropertyExtraStartCommand;
206 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
207 return args;
Greg Clayton67cc0632012-08-22 17:17:09 +0000208}
209
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210void ProcessProperties::SetExtraStartupCommands(const Args &args) {
211 const uint32_t idx = ePropertyExtraStartCommand;
212 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000213}
214
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215FileSpec ProcessProperties::GetPythonOSPluginPath() const {
216 const uint32_t idx = ePropertyPythonOSPluginPath;
217 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000218}
219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
221 const uint32_t idx = ePropertyPythonOSPluginPath;
222 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000223}
224
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
226 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
227 return m_collection_sp->GetPropertyAtIndexAsBoolean(
228 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000229}
230
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
232 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
233 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000234}
235
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
237 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
238 return m_collection_sp->GetPropertyAtIndexAsBoolean(
239 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000240}
241
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
243 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
244 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Inghamacff8952013-05-02 00:27:30 +0000245}
246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
248 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
249 return m_collection_sp->GetPropertyAtIndexAsBoolean(
250 nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000251}
252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
254 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
255 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
256}
257
258bool ProcessProperties::GetDetachKeepsStopped() const {
259 const uint32_t idx = ePropertyDetachKeepsStopped;
260 return m_collection_sp->GetPropertyAtIndexAsBoolean(
261 nullptr, idx, g_properties[idx].default_uint_value != 0);
262}
263
264void ProcessProperties::SetDetachKeepsStopped(bool stop) {
265 const uint32_t idx = ePropertyDetachKeepsStopped;
266 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
267}
268
269bool ProcessProperties::GetWarningsOptimization() const {
270 const uint32_t idx = ePropertyWarningOptimization;
271 return m_collection_sp->GetPropertyAtIndexAsBoolean(
272 nullptr, idx, g_properties[idx].default_uint_value != 0);
273}
274
Jim Inghamba205c12017-12-05 02:50:45 +0000275bool ProcessProperties::GetStopOnExec() const {
276 const uint32_t idx = ePropertyStopOnExec;
277 return m_collection_sp->GetPropertyAtIndexAsBoolean(
278 nullptr, idx, g_properties[idx].default_uint_value != 0);
279}
280
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281void ProcessInstanceInfo::Dump(Stream &s, Platform *platform) const {
282 const char *cstr;
283 if (m_pid != LLDB_INVALID_PROCESS_ID)
284 s.Printf(" pid = %" PRIu64 "\n", m_pid);
285
286 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
287 s.Printf(" parent = %" PRIu64 "\n", m_parent_pid);
288
289 if (m_executable) {
290 s.Printf(" name = %s\n", m_executable.GetFilename().GetCString());
291 s.PutCString(" file = ");
292 m_executable.Dump(&s);
293 s.EOL();
294 }
295 const uint32_t argc = m_arguments.GetArgumentCount();
296 if (argc > 0) {
297 for (uint32_t i = 0; i < argc; i++) {
298 const char *arg = m_arguments.GetArgumentAtIndex(i);
299 if (i < 10)
300 s.Printf(" arg[%u] = %s\n", i, arg);
301 else
302 s.Printf("arg[%u] = %s\n", i, arg);
303 }
304 }
305
Pavel Labath62930e52018-01-10 11:57:31 +0000306 s.Format("{0}", m_environment);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000307
308 if (m_arch.IsValid()) {
309 s.Printf(" arch = ");
310 m_arch.DumpTriple(s);
311 s.EOL();
312 }
313
314 if (m_uid != UINT32_MAX) {
315 cstr = platform->GetUserName(m_uid);
316 s.Printf(" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
317 }
318 if (m_gid != UINT32_MAX) {
319 cstr = platform->GetGroupName(m_gid);
320 s.Printf(" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
321 }
322 if (m_euid != UINT32_MAX) {
323 cstr = platform->GetUserName(m_euid);
324 s.Printf(" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
325 }
326 if (m_egid != UINT32_MAX) {
327 cstr = platform->GetGroupName(m_egid);
328 s.Printf(" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
329 }
330}
331
332void ProcessInstanceInfo::DumpTableHeader(Stream &s, Platform *platform,
333 bool show_args, bool verbose) {
334 const char *label;
335 if (show_args || verbose)
336 label = "ARGUMENTS";
337 else
338 label = "NAME";
339
340 if (verbose) {
341 s.Printf("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE "
342 " %s\n",
343 label);
344 s.PutCString("====== ====== ========== ========== ========== ========== "
345 "======================== ============================\n");
346 } else {
347 s.Printf("PID PARENT USER TRIPLE %s\n", label);
348 s.PutCString("====== ====== ========== ======================== "
349 "============================\n");
350 }
351}
352
353void ProcessInstanceInfo::DumpAsTableRow(Stream &s, Platform *platform,
354 bool show_args, bool verbose) const {
355 if (m_pid != LLDB_INVALID_PROCESS_ID) {
Greg Clayton32e0a752011-03-30 18:16:51 +0000356 const char *cstr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357 s.Printf("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000358
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 StreamString arch_strm;
Todd Fiala7df337f2015-10-13 23:41:19 +0000360 if (m_arch.IsValid())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 m_arch.DumpTriple(arch_strm);
362
363 if (verbose) {
364 cstr = platform->GetUserName(m_uid);
365 if (cstr &&
366 cstr[0]) // Watch for empty string that indicates lookup failed
367 s.Printf("%-10s ", cstr);
368 else
369 s.Printf("%-10u ", m_uid);
370
371 cstr = platform->GetGroupName(m_gid);
372 if (cstr &&
373 cstr[0]) // Watch for empty string that indicates lookup failed
374 s.Printf("%-10s ", cstr);
375 else
376 s.Printf("%-10u ", m_gid);
377
378 cstr = platform->GetUserName(m_euid);
379 if (cstr &&
380 cstr[0]) // Watch for empty string that indicates lookup failed
381 s.Printf("%-10s ", cstr);
382 else
383 s.Printf("%-10u ", m_euid);
384
385 cstr = platform->GetGroupName(m_egid);
386 if (cstr &&
387 cstr[0]) // Watch for empty string that indicates lookup failed
388 s.Printf("%-10s ", cstr);
389 else
390 s.Printf("%-10u ", m_egid);
391
Zachary Turnerc1564272016-11-16 21:15:24 +0000392 s.Printf("%-24s ", arch_strm.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 } else {
394 s.Printf("%-10s %-24s ", platform->GetUserName(m_euid),
Zachary Turnerc1564272016-11-16 21:15:24 +0000395 arch_strm.GetData());
Todd Fiala7df337f2015-10-13 23:41:19 +0000396 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 if (verbose || show_args) {
399 const uint32_t argc = m_arguments.GetArgumentCount();
400 if (argc > 0) {
401 for (uint32_t i = 0; i < argc; i++) {
402 if (i > 0)
403 s.PutChar(' ');
404 s.PutCString(m_arguments.GetArgumentAtIndex(i));
405 }
406 }
407 } else {
408 s.PutCString(GetName());
Greg Clayton32e0a752011-03-30 18:16:51 +0000409 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410
411 s.EOL();
412 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000413}
414
Zachary Turner97206d52017-05-12 04:51:55 +0000415Status ProcessLaunchCommandOptions::SetOptionValue(
Zachary Turnerfe114832016-11-12 16:56:47 +0000416 uint32_t option_idx, llvm::StringRef option_arg,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 ExecutionContext *execution_context) {
Zachary Turner97206d52017-05-12 04:51:55 +0000418 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 const int short_option = m_getopt_table[option_idx].val;
420
421 switch (short_option) {
422 case 's': // Stop at program entry point
423 launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
424 break;
425
426 case 'i': // STDIN for read only
427 {
428 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000429 if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 launch_info.AppendFileAction(action);
431 break;
432 }
433
434 case 'o': // Open STDOUT for write only
435 {
436 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000437 if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 launch_info.AppendFileAction(action);
439 break;
440 }
441
442 case 'e': // STDERR for write only
443 {
444 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000445 if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 launch_info.AppendFileAction(action);
447 break;
448 }
449
450 case 'p': // Process plug-in name
451 launch_info.SetProcessPluginName(option_arg);
452 break;
453
454 case 'n': // Disable STDIO
455 {
456 FileAction action;
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000457 const FileSpec dev_null(FileSystem::DEV_NULL);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 if (action.Open(STDIN_FILENO, dev_null, true, false))
459 launch_info.AppendFileAction(action);
460 if (action.Open(STDOUT_FILENO, dev_null, false, true))
461 launch_info.AppendFileAction(action);
462 if (action.Open(STDERR_FILENO, dev_null, false, true))
463 launch_info.AppendFileAction(action);
464 break;
465 }
466
467 case 'w':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000468 launch_info.SetWorkingDirectory(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 break;
470
471 case 't': // Open process in new terminal window
472 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
473 break;
474
475 case 'a': {
476 TargetSP target_sp =
477 execution_context ? execution_context->GetTargetSP() : TargetSP();
478 PlatformSP platform_sp =
479 target_sp ? target_sp->GetPlatform() : PlatformSP();
Pavel Labath7263f1b2017-10-31 10:56:03 +0000480 launch_info.GetArchitecture() =
481 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 } break;
483
484 case 'A': // Disable ASLR.
485 {
486 bool success;
487 const bool disable_aslr_arg =
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000488 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 if (success)
490 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
Greg Clayton8b82f082011-04-12 05:54:46 +0000491 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 error.SetErrorStringWithFormat(
493 "Invalid boolean value for disable-aslr option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000494 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495 break;
496 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000497
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498 case 'X': // shell expand args.
499 {
500 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000501 const bool expand_args =
502 OptionArgParser::ToBoolean(option_arg, true, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503 if (success)
504 launch_info.SetShellExpandArguments(expand_args);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000505 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000506 error.SetErrorStringWithFormat(
507 "Invalid boolean value for shell-expand-args option: '%s'",
Zachary Turnerfe114832016-11-12 16:56:47 +0000508 option_arg.empty() ? "<null>" : option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509 break;
510 }
511
512 case 'c':
Zachary Turnerfe114832016-11-12 16:56:47 +0000513 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000514 launch_info.SetShell(FileSpec(option_arg));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 else
516 launch_info.SetShell(HostInfo::GetDefaultShell());
517 break;
518
519 case 'v':
Pavel Labath62930e52018-01-10 11:57:31 +0000520 launch_info.GetEnvironment().insert(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 break;
522
523 default:
524 error.SetErrorStringWithFormat("unrecognized short option character '%c'",
525 short_option);
526 break;
527 }
528 return error;
Greg Clayton32e0a752011-03-30 18:16:51 +0000529}
530
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000531static constexpr OptionDefinition g_process_launch_options[] = {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000532 {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000533 nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 "Stop at the entry point of the program when launching a process."},
535 {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000536 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537 "Set whether to disable address space layout randomization when launching "
538 "a process."},
539 {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000540 nullptr, {}, 0, eArgTypePlugin,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 "Name of the process plugin you want to use."},
542 {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000543 OptionParser::eRequiredArgument, nullptr, {}, 0,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 eArgTypeDirectoryName,
545 "Set the current working directory to <path> when running the inferior."},
546 {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000547 nullptr, {}, 0, eArgTypeArchitecture,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 "Set the architecture for the process to launch when ambiguous."},
549 {LLDB_OPT_SET_ALL, false, "environment", 'v',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000550 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 "Specify an environment variable name/value string (--environment "
552 "NAME=VALUE). Can be specified multiple times for subsequent environment "
553 "entries."},
554 {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000555 OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 "Run the process in a shell (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000557
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000559 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 "Redirect stdin for the process to <filename>."},
561 {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000562 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 "Redirect stdout for the process to <filename>."},
564 {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000565 nullptr, {}, 0, eArgTypeFilename,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 "Redirect stderr for the process to <filename>."},
Todd Fiala7df337f2015-10-13 23:41:19 +0000567
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000569 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton32e0a752011-03-30 18:16:51 +0000571
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000573 {}, 0, eArgTypeNone,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 "Do not set up for terminal I/O to go to running process."},
575 {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000576 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 "Set whether to shell expand arguments to the process when launching."},
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000578};
579
580llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
Zachary Turner70602432016-09-22 21:06:13 +0000581 return llvm::makeArrayRef(g_process_launch_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000582}
Greg Clayton32e0a752011-03-30 18:16:51 +0000583
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584bool ProcessInstanceInfoMatch::NameMatches(const char *process_name) const {
Pavel Labathc4a33952017-02-20 11:35:33 +0000585 if (m_name_match_type == NameMatch::Ignore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000586 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000587 const char *match_name = m_match_info.GetName();
588 if (!match_name)
Greg Clayton32e0a752011-03-30 18:16:51 +0000589 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590
591 return lldb_private::NameMatches(process_name, m_name_match_type, match_name);
Greg Clayton32e0a752011-03-30 18:16:51 +0000592}
593
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594bool ProcessInstanceInfoMatch::Matches(
595 const ProcessInstanceInfo &proc_info) const {
596 if (!NameMatches(proc_info.GetName()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000597 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000598
599 if (m_match_info.ProcessIDIsValid() &&
600 m_match_info.GetProcessID() != proc_info.GetProcessID())
601 return false;
602
603 if (m_match_info.ParentProcessIDIsValid() &&
604 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
605 return false;
606
607 if (m_match_info.UserIDIsValid() &&
608 m_match_info.GetUserID() != proc_info.GetUserID())
609 return false;
610
611 if (m_match_info.GroupIDIsValid() &&
612 m_match_info.GetGroupID() != proc_info.GetGroupID())
613 return false;
614
615 if (m_match_info.EffectiveUserIDIsValid() &&
616 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
617 return false;
618
619 if (m_match_info.EffectiveGroupIDIsValid() &&
620 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
621 return false;
622
623 if (m_match_info.GetArchitecture().IsValid() &&
624 !m_match_info.GetArchitecture().IsCompatibleMatch(
625 proc_info.GetArchitecture()))
626 return false;
627 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000628}
629
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630bool ProcessInstanceInfoMatch::MatchAllProcesses() const {
Pavel Labathc4a33952017-02-20 11:35:33 +0000631 if (m_name_match_type != NameMatch::Ignore)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632 return false;
633
634 if (m_match_info.ProcessIDIsValid())
635 return false;
636
637 if (m_match_info.ParentProcessIDIsValid())
638 return false;
639
640 if (m_match_info.UserIDIsValid())
641 return false;
642
643 if (m_match_info.GroupIDIsValid())
644 return false;
645
646 if (m_match_info.EffectiveUserIDIsValid())
647 return false;
648
649 if (m_match_info.EffectiveGroupIDIsValid())
650 return false;
651
652 if (m_match_info.GetArchitecture().IsValid())
653 return false;
654
655 if (m_match_all_users)
656 return false;
657
658 return true;
659}
660
661void ProcessInstanceInfoMatch::Clear() {
662 m_match_info.Clear();
Pavel Labathc4a33952017-02-20 11:35:33 +0000663 m_name_match_type = NameMatch::Ignore;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 m_match_all_users = false;
665}
666
Zachary Turner31659452016-11-17 21:15:14 +0000667ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
668 llvm::StringRef plugin_name,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 ListenerSP listener_sp,
670 const FileSpec *crash_file_path) {
671 static uint32_t g_process_unique_id = 0;
672
673 ProcessSP process_sp;
674 ProcessCreateInstance create_callback = nullptr;
Zachary Turner31659452016-11-17 21:15:14 +0000675 if (!plugin_name.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000676 ConstString const_plugin_name(plugin_name);
677 create_callback =
678 PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
679 if (create_callback) {
680 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
681 if (process_sp) {
682 if (process_sp->CanDebug(target_sp, true)) {
683 process_sp->m_process_unique_id = ++g_process_unique_id;
684 } else
685 process_sp.reset();
686 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000687 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 } else {
689 for (uint32_t idx = 0;
690 (create_callback =
691 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
692 ++idx) {
693 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
694 if (process_sp) {
695 if (process_sp->CanDebug(target_sp, false)) {
696 process_sp->m_process_unique_id = ++g_process_unique_id;
697 break;
698 } else
699 process_sp.reset();
700 }
701 }
702 }
703 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704}
705
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706ConstString &Process::GetStaticBroadcasterClass() {
707 static ConstString class_name("lldb.process");
708 return class_name;
709}
710
711Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
712 : Process(target_sp, listener_sp,
713 UnixSignals::Create(HostInfo::GetArchitecture())) {
714 // This constructor just delegates to the full Process constructor,
715 // defaulting to using the Host's UnixSignals.
716}
717
718Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
719 const UnixSignalsSP &unix_signals_sp)
720 : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
721 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
722 Process::GetStaticBroadcasterClass().AsCString()),
Jim Inghamb87b9e62018-06-26 23:38:58 +0000723 m_target_wp(target_sp), m_public_state(eStateUnloaded),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 m_private_state(eStateUnloaded),
725 m_private_state_broadcaster(nullptr,
726 "lldb.process.internal_state_broadcaster"),
727 m_private_state_control_broadcaster(
728 nullptr, "lldb.process.internal_state_control_broadcaster"),
729 m_private_state_listener_sp(
730 Listener::MakeListener("lldb.process.internal_state_listener")),
731 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
732 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
733 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
734 m_thread_list(this), m_extended_thread_list(this),
735 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
736 m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
737 m_breakpoint_site_list(), m_dynamic_checkers_ap(),
738 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
739 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
740 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
741 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
742 m_memory_cache(*this), m_allocated_memory_cache(*this),
743 m_should_detach(false), m_next_event_action_ap(), m_public_run_lock(),
Pavel Labath13e37d42017-10-25 21:05:31 +0000744 m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
746 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
747 m_can_interpret_function_calls(false), m_warnings_issued(),
748 m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
749 CheckInWithManager();
750
751 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
752 if (log)
753 log->Printf("%p Process::Process()", static_cast<void *>(this));
754
755 if (!m_unix_signals_sp)
756 m_unix_signals_sp = std::make_shared<UnixSignals>();
757
758 SetEventName(eBroadcastBitStateChanged, "state-changed");
759 SetEventName(eBroadcastBitInterrupt, "interrupt");
760 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
761 SetEventName(eBroadcastBitSTDERR, "stderr-available");
762 SetEventName(eBroadcastBitProfileData, "profile-data-available");
763 SetEventName(eBroadcastBitStructuredData, "structured-data-available");
764
765 m_private_state_control_broadcaster.SetEventName(
766 eBroadcastInternalStateControlStop, "control-stop");
767 m_private_state_control_broadcaster.SetEventName(
768 eBroadcastInternalStateControlPause, "control-pause");
769 m_private_state_control_broadcaster.SetEventName(
770 eBroadcastInternalStateControlResume, "control-resume");
771
772 m_listener_sp->StartListeningForEvents(
773 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
774 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
775 eBroadcastBitProfileData | eBroadcastBitStructuredData);
776
777 m_private_state_listener_sp->StartListeningForEvents(
778 &m_private_state_broadcaster,
779 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
780
781 m_private_state_listener_sp->StartListeningForEvents(
782 &m_private_state_control_broadcaster,
783 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
784 eBroadcastInternalStateControlResume);
785 // We need something valid here, even if just the default UnixSignalsSP.
786 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
787
788 // Allow the platform to override the default cache line size
789 OptionValueSP value_sp =
790 m_collection_sp
791 ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
792 ->GetValue();
793 uint32_t platform_cache_line_size =
794 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
795 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
796 value_sp->SetUInt64Value(platform_cache_line_size);
797}
798
799Process::~Process() {
800 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
801 if (log)
802 log->Printf("%p Process::~Process()", static_cast<void *>(this));
803 StopPrivateStateThread();
804
805 // ThreadList::Clear() will try to acquire this process's mutex, so
Adrian Prantl05097242018-04-30 16:49:04 +0000806 // explicitly clear the thread list here to ensure that the mutex is not
807 // destroyed before the thread list.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000808 m_thread_list.Clear();
809}
810
811const ProcessPropertiesSP &Process::GetGlobalProperties() {
812 // NOTE: intentional leak so we don't crash if global destructor chain gets
813 // called as other threads still use the result of this function
Pavel Labath5f05ea82016-10-19 15:12:45 +0000814 static ProcessPropertiesSP *g_settings_sp_ptr =
815 new ProcessPropertiesSP(new ProcessProperties(nullptr));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 return *g_settings_sp_ptr;
817}
818
819void Process::Finalize() {
820 m_finalizing = true;
821
822 // Destroy this process if needed
823 switch (GetPrivateState()) {
824 case eStateConnected:
825 case eStateAttaching:
826 case eStateLaunching:
827 case eStateStopped:
828 case eStateRunning:
829 case eStateStepping:
830 case eStateCrashed:
831 case eStateSuspended:
832 Destroy(false);
833 break;
834
835 case eStateInvalid:
836 case eStateUnloaded:
837 case eStateDetached:
838 case eStateExited:
839 break;
840 }
841
842 // Clear our broadcaster before we proceed with destroying
843 Broadcaster::Clear();
844
Adrian Prantl05097242018-04-30 16:49:04 +0000845 // Do any cleanup needed prior to being destructed... Subclasses that
846 // override this method should call this superclass method as well.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847
848 // We need to destroy the loader before the derived Process class gets
Adrian Prantl05097242018-04-30 16:49:04 +0000849 // destroyed since it is very likely that undoing the loader will require
850 // access to the real process.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 m_dynamic_checkers_ap.reset();
852 m_abi_sp.reset();
853 m_os_ap.reset();
854 m_system_runtime_ap.reset();
855 m_dyld_ap.reset();
856 m_jit_loaders_ap.reset();
857 m_thread_list_real.Destroy();
858 m_thread_list.Destroy();
859 m_extended_thread_list.Destroy();
860 m_queue_list.Clear();
861 m_queue_list_stop_id = 0;
862 std::vector<Notifications> empty_notifications;
863 m_notifications.swap(empty_notifications);
864 m_image_tokens.clear();
865 m_memory_cache.Clear();
866 m_allocated_memory_cache.Clear();
867 m_language_runtimes.clear();
868 m_instrumentation_runtimes.clear();
869 m_next_event_action_ap.reset();
Adrian Prantl05097242018-04-30 16:49:04 +0000870 // Clear the last natural stop ID since it has a strong reference to this
871 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
873 //#ifdef LLDB_CONFIGURATION_DEBUG
874 // StreamFile s(stdout, false);
875 // EventSP event_sp;
876 // while (m_private_state_listener_sp->GetNextEvent(event_sp))
877 // {
878 // event_sp->Dump (&s);
879 // s.EOL();
880 // }
881 //#endif
882 // We have to be very careful here as the m_private_state_listener might
883 // contain events that have ProcessSP values in them which can keep this
884 // process around forever. These events need to be cleared out.
885 m_private_state_listener_sp->Clear();
886 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
887 m_public_run_lock.SetStopped();
888 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
889 m_private_run_lock.SetStopped();
Jason Molenda38267272016-12-16 02:48:39 +0000890 m_structured_data_plugin_map.clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000891 m_finalize_called = true;
892}
893
894void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
895 m_notifications.push_back(callbacks);
896 if (callbacks.initialize != nullptr)
897 callbacks.initialize(callbacks.baton, this);
898}
899
900bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
901 std::vector<Notifications>::iterator pos, end = m_notifications.end();
902 for (pos = m_notifications.begin(); pos != end; ++pos) {
903 if (pos->baton == callbacks.baton &&
904 pos->initialize == callbacks.initialize &&
905 pos->process_state_changed == callbacks.process_state_changed) {
906 m_notifications.erase(pos);
907 return true;
908 }
909 }
910 return false;
911}
912
913void Process::SynchronouslyNotifyStateChanged(StateType state) {
914 std::vector<Notifications>::iterator notification_pos,
915 notification_end = m_notifications.end();
916 for (notification_pos = m_notifications.begin();
917 notification_pos != notification_end; ++notification_pos) {
918 if (notification_pos->process_state_changed)
919 notification_pos->process_state_changed(notification_pos->baton, this,
920 state);
921 }
922}
923
924// FIXME: We need to do some work on events before the general Listener sees
925// them.
926// For instance if we are continuing from a breakpoint, we need to ensure that
Adrian Prantl05097242018-04-30 16:49:04 +0000927// we do the little "insert real insn, step & stop" trick. But we can't do
928// that when the event is delivered by the broadcaster - since that is done on
929// the thread that is waiting for new events, so if we needed more than one
930// event for our handling, we would stall. So instead we do it when we fetch
931// the event off of the queue.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000932//
933
Kate Stoneb9c1b512016-09-06 20:57:50 +0000934StateType Process::GetNextEvent(EventSP &event_sp) {
935 StateType state = eStateInvalid;
936
Pavel Labathd35031e12016-11-30 10:41:42 +0000937 if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
938 std::chrono::seconds(0)) &&
939 event_sp)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
941
942 return state;
943}
944
Pavel Labath3879fe02018-05-09 14:29:30 +0000945void Process::SyncIOHandler(uint32_t iohandler_id,
946 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947 // don't sync (potentially context switch) in case where there is no process
948 // IO
949 if (!m_process_input_reader)
950 return;
951
Pavel Labath3879fe02018-05-09 14:29:30 +0000952 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000953
954 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labath3879fe02018-05-09 14:29:30 +0000955 if (Result) {
956 LLDB_LOG(
957 log,
958 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
959 iohandler_id, *Result);
960 } else {
961 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
962 iohandler_id);
963 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964}
965
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000966StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
967 EventSP *event_sp_ptr, bool wait_always,
968 ListenerSP hijack_listener_sp,
969 Stream *stream, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970 // We can't just wait for a "stopped" event, because the stopped event may
Adrian Prantl05097242018-04-30 16:49:04 +0000971 // have restarted the target. We have to actually check each event, and in
972 // the case of a stopped event check the restarted flag on the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 if (event_sp_ptr)
974 event_sp_ptr->reset();
975 StateType state = GetState();
Adrian Prantl05097242018-04-30 16:49:04 +0000976 // If we are exited or detached, we won't ever get back to any other valid
977 // state...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 if (state == eStateDetached || state == eStateExited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +0000982 LLDB_LOG(log, "timeout = {0}", timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000983
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984 if (!wait_always && StateIsStoppedState(state, true) &&
985 StateIsStoppedState(GetPrivateState(), true)) {
Pavel Labath44464872015-05-27 12:40:32 +0000986 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 log->Printf("Process::%s returning without waiting for events; process "
988 "private and public states are already 'stopped'.",
989 __FUNCTION__);
990 // We need to toggle the run lock as this won't get done in
991 // SetPublicState() if the process is hijacked.
992 if (hijack_listener_sp && use_run_lock)
993 m_public_run_lock.SetStopped();
994 return state;
995 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000996
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997 while (state != eStateInvalid) {
998 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +0000999 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 if (event_sp_ptr && event_sp)
1001 *event_sp_ptr = event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
1004 Process::HandleProcessStateChangedEvent(event_sp, stream,
1005 pop_process_io_handler);
Daniel Malea9e9919f2013-10-09 16:56:28 +00001006
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 switch (state) {
1008 case eStateCrashed:
1009 case eStateDetached:
1010 case eStateExited:
1011 case eStateUnloaded:
1012 // We need to toggle the run lock as this won't get done in
1013 // SetPublicState() if the process is hijacked.
1014 if (hijack_listener_sp && use_run_lock)
1015 m_public_run_lock.SetStopped();
1016 return state;
1017 case eStateStopped:
1018 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1019 continue;
1020 else {
Pavel Labath78521ef2015-03-06 10:52:47 +00001021 // We need to toggle the run lock as this won't get done in
1022 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001023 if (hijack_listener_sp && use_run_lock)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001024 m_public_run_lock.SetStopped();
1025 return state;
1026 }
1027 default:
1028 continue;
1029 }
1030 }
1031 return state;
1032}
1033
1034bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
1035 Stream *stream,
1036 bool &pop_process_io_handler) {
1037 const bool handle_pop = pop_process_io_handler;
1038
1039 pop_process_io_handler = false;
1040 ProcessSP process_sp =
1041 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1042
1043 if (!process_sp)
1044 return false;
1045
1046 StateType event_state =
1047 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1048 if (event_state == eStateInvalid)
1049 return false;
1050
1051 switch (event_state) {
1052 case eStateInvalid:
1053 case eStateUnloaded:
1054 case eStateAttaching:
1055 case eStateLaunching:
1056 case eStateStepping:
1057 case eStateDetached:
1058 if (stream)
1059 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
1060 StateAsCString(event_state));
1061 if (event_state == eStateDetached)
1062 pop_process_io_handler = true;
1063 break;
1064
1065 case eStateConnected:
1066 case eStateRunning:
1067 // Don't be chatty when we run...
1068 break;
1069
1070 case eStateExited:
1071 if (stream)
1072 process_sp->GetStatus(*stream);
1073 pop_process_io_handler = true;
1074 break;
1075
1076 case eStateStopped:
1077 case eStateCrashed:
1078 case eStateSuspended:
1079 // Make sure the program hasn't been auto-restarted:
1080 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
1081 if (stream) {
1082 size_t num_reasons =
1083 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1084 if (num_reasons > 0) {
1085 // FIXME: Do we want to report this, or would that just be annoyingly
1086 // chatty?
1087 if (num_reasons == 1) {
1088 const char *reason =
1089 Process::ProcessEventData::GetRestartedReasonAtIndex(
1090 event_sp.get(), 0);
1091 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
1092 process_sp->GetID(),
1093 reason ? reason : "<UNKNOWN REASON>");
1094 } else {
1095 stream->Printf("Process %" PRIu64
1096 " stopped and restarted, reasons:\n",
1097 process_sp->GetID());
1098
1099 for (size_t i = 0; i < num_reasons; i++) {
1100 const char *reason =
1101 Process::ProcessEventData::GetRestartedReasonAtIndex(
1102 event_sp.get(), i);
1103 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1104 }
1105 }
1106 }
1107 }
1108 } else {
1109 StopInfoSP curr_thread_stop_info_sp;
1110 // Lock the thread list so it doesn't change on us, this is the scope for
1111 // the locker:
1112 {
1113 ThreadList &thread_list = process_sp->GetThreadList();
1114 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
1115
1116 ThreadSP curr_thread(thread_list.GetSelectedThread());
1117 ThreadSP thread;
1118 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1119 if (curr_thread) {
1120 curr_thread_stop_reason = curr_thread->GetStopReason();
1121 curr_thread_stop_info_sp = curr_thread->GetStopInfo();
1122 }
1123 if (!curr_thread || !curr_thread->IsValid() ||
1124 curr_thread_stop_reason == eStopReasonInvalid ||
1125 curr_thread_stop_reason == eStopReasonNone) {
1126 // Prefer a thread that has just completed its plan over another
1127 // thread as current thread.
1128 ThreadSP plan_thread;
1129 ThreadSP other_thread;
1130
1131 const size_t num_threads = thread_list.GetSize();
1132 size_t i;
1133 for (i = 0; i < num_threads; ++i) {
1134 thread = thread_list.GetThreadAtIndex(i);
1135 StopReason thread_stop_reason = thread->GetStopReason();
1136 switch (thread_stop_reason) {
1137 case eStopReasonInvalid:
1138 case eStopReasonNone:
1139 break;
1140
1141 case eStopReasonSignal: {
1142 // Don't select a signal thread if we weren't going to stop at
Adrian Prantl05097242018-04-30 16:49:04 +00001143 // that signal. We have to have had another reason for stopping
1144 // here, and the user doesn't want to see this thread.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145 uint64_t signo = thread->GetStopInfo()->GetValue();
1146 if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
1147 if (!other_thread)
1148 other_thread = thread;
1149 }
1150 break;
1151 }
1152 case eStopReasonTrace:
1153 case eStopReasonBreakpoint:
1154 case eStopReasonWatchpoint:
1155 case eStopReasonException:
1156 case eStopReasonExec:
1157 case eStopReasonThreadExiting:
1158 case eStopReasonInstrumentation:
1159 if (!other_thread)
1160 other_thread = thread;
1161 break;
1162 case eStopReasonPlanComplete:
1163 if (!plan_thread)
1164 plan_thread = thread;
1165 break;
1166 }
1167 }
1168 if (plan_thread)
1169 thread_list.SetSelectedThreadByID(plan_thread->GetID());
1170 else if (other_thread)
1171 thread_list.SetSelectedThreadByID(other_thread->GetID());
1172 else {
1173 if (curr_thread && curr_thread->IsValid())
1174 thread = curr_thread;
1175 else
1176 thread = thread_list.GetThreadAtIndex(0);
1177
1178 if (thread)
1179 thread_list.SetSelectedThreadByID(thread->GetID());
1180 }
1181 }
1182 }
1183 // Drop the ThreadList mutex by here, since GetThreadStatus below might
Adrian Prantl05097242018-04-30 16:49:04 +00001184 // have to run code, e.g. for Data formatters, and if we hold the
1185 // ThreadList mutex, then the process is going to have a hard time
1186 // restarting the process.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001187 if (stream) {
1188 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1189 if (debugger.GetTargetList().GetSelectedTarget().get() ==
1190 &process_sp->GetTarget()) {
1191 const bool only_threads_with_stop_reason = true;
1192 const uint32_t start_frame = 0;
1193 const uint32_t num_frames = 1;
1194 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001195 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196 process_sp->GetStatus(*stream);
1197 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
1198 start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001199 num_frames_with_source,
1200 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201 if (curr_thread_stop_info_sp) {
1202 lldb::addr_t crashing_address;
1203 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
1204 curr_thread_stop_info_sp, &crashing_address);
1205 if (valobj_sp) {
1206 const bool qualify_cxx_base_classes = false;
1207
1208 const ValueObject::GetExpressionPathFormat format =
1209 ValueObject::GetExpressionPathFormat::
1210 eGetExpressionPathFormatHonorPointers;
1211 stream->PutCString("Likely cause: ");
1212 valobj_sp->GetExpressionPath(*stream, qualify_cxx_base_classes,
1213 format);
1214 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
1215 }
1216 }
1217 } else {
1218 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
1219 process_sp->GetTarget().shared_from_this());
1220 if (target_idx != UINT32_MAX)
1221 stream->Printf("Target %d: (", target_idx);
1222 else
1223 stream->Printf("Target <unknown index>: (");
1224 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
1225 stream->Printf(") stopped.\n");
1226 }
1227 }
1228
1229 // Pop the process IO handler
1230 pop_process_io_handler = true;
1231 }
1232 break;
1233 }
1234
1235 if (handle_pop && pop_process_io_handler)
1236 process_sp->PopProcessIOHandler();
1237
1238 return true;
1239}
1240
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241bool Process::HijackProcessEvents(ListenerSP listener_sp) {
1242 if (listener_sp) {
1243 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
1244 eBroadcastBitInterrupt);
1245 } else
1246 return false;
1247}
Greg Claytondc6224e2014-10-21 01:00:42 +00001248
Kate Stoneb9c1b512016-09-06 20:57:50 +00001249void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
Greg Claytondc6224e2014-10-21 01:00:42 +00001250
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001251StateType Process::GetStateChangedEvents(EventSP &event_sp,
1252 const Timeout<std::micro> &timeout,
1253 ListenerSP hijack_listener_sp) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001255 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Greg Claytondc6224e2014-10-21 01:00:42 +00001256
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 ListenerSP listener_sp = hijack_listener_sp;
1258 if (!listener_sp)
1259 listener_sp = m_listener_sp;
Greg Claytondc6224e2014-10-21 01:00:42 +00001260
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001262 if (listener_sp->GetEventForBroadcasterWithType(
1263 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001264 timeout)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1266 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Pavel Labathd02b1c82017-02-10 11:49:33 +00001267 else
1268 LLDB_LOG(log, "got no event or was interrupted.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001270
Pavel Labathd02b1c82017-02-10 11:49:33 +00001271 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001272 return state;
1273}
Greg Claytondc6224e2014-10-21 01:00:42 +00001274
Kate Stoneb9c1b512016-09-06 20:57:50 +00001275Event *Process::PeekAtStateChangedEvents() {
1276 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Greg Claytondc6224e2014-10-21 01:00:42 +00001277
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 if (log)
1279 log->Printf("Process::%s...", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001280
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281 Event *event_ptr;
1282 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1283 this, eBroadcastBitStateChanged);
1284 if (log) {
1285 if (event_ptr) {
1286 log->Printf(
1287 "Process::%s (event_ptr) => %s", __FUNCTION__,
1288 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1289 } else {
1290 log->Printf("Process::%s no events found", __FUNCTION__);
Greg Claytondc6224e2014-10-21 01:00:42 +00001291 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001292 }
1293 return event_ptr;
1294}
Greg Claytondc6224e2014-10-21 01:00:42 +00001295
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001296StateType
1297Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1298 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001300 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301
1302 StateType state = eStateInvalid;
Pavel Labathd35031e12016-11-30 10:41:42 +00001303 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1304 &m_private_state_broadcaster,
1305 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001306 timeout))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1308 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1309
Pavel Labathd02b1c82017-02-10 11:49:33 +00001310 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1311 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 return state;
1313}
1314
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001315bool Process::GetEventsPrivate(EventSP &event_sp,
1316 const Timeout<std::micro> &timeout,
1317 bool control_only) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001318 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Pavel Labathd02b1c82017-02-10 11:49:33 +00001319 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320
1321 if (control_only)
Pavel Labathd35031e12016-11-30 10:41:42 +00001322 return m_private_state_listener_sp->GetEventForBroadcaster(
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001323 &m_private_state_control_broadcaster, event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324 else
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001325 return m_private_state_listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326}
1327
1328bool Process::IsRunning() const {
1329 return StateIsRunningState(m_public_state.GetValue());
1330}
1331
1332int Process::GetExitStatus() {
1333 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1334
1335 if (m_public_state.GetValue() == eStateExited)
1336 return m_exit_status;
1337 return -1;
1338}
1339
1340const char *Process::GetExitDescription() {
1341 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1342
1343 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1344 return m_exit_string.c_str();
1345 return nullptr;
1346}
1347
1348bool Process::SetExitStatus(int status, const char *cstr) {
1349 // Use a mutex to protect setting the exit status.
1350 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1351
1352 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1353 LIBLLDB_LOG_PROCESS));
1354 if (log)
1355 log->Printf(
1356 "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1357 status, status, cstr ? "\"" : "", cstr ? cstr : "NULL",
1358 cstr ? "\"" : "");
1359
1360 // We were already in the exited state
1361 if (m_private_state.GetValue() == eStateExited) {
1362 if (log)
1363 log->Printf("Process::SetExitStatus () ignoring exit status because "
1364 "state was already set to eStateExited");
1365 return false;
1366 }
1367
1368 m_exit_status = status;
1369 if (cstr)
1370 m_exit_string = cstr;
1371 else
1372 m_exit_string.clear();
1373
Adrian Prantl05097242018-04-30 16:49:04 +00001374 // Clear the last natural stop ID since it has a strong reference to this
1375 // process
Kate Stoneb9c1b512016-09-06 20:57:50 +00001376 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1377
1378 SetPrivateState(eStateExited);
1379
1380 // Allow subclasses to do some cleanup
1381 DidExit();
1382
1383 return true;
1384}
1385
1386bool Process::IsAlive() {
1387 switch (m_private_state.GetValue()) {
1388 case eStateConnected:
1389 case eStateAttaching:
1390 case eStateLaunching:
1391 case eStateStopped:
1392 case eStateRunning:
1393 case eStateStepping:
1394 case eStateCrashed:
1395 case eStateSuspended:
Greg Claytondc6224e2014-10-21 01:00:42 +00001396 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001397 default:
1398 return false;
1399 }
Jason Molendaa814f702015-11-05 23:03:44 +00001400}
1401
Adrian Prantl05097242018-04-30 16:49:04 +00001402// This static callback can be used to watch for local child processes on the
1403// current host. The child process exits, the process will be found in the
1404// global target list (we want to be completely sure that the
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405// lldb_private::Process doesn't go away before we can deliver the signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406bool Process::SetProcessExitStatus(
1407 lldb::pid_t pid, bool exited,
1408 int signo, // Zero for no signal
1409 int exit_status // Exit value of process if signal is zero
1410 ) {
1411 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1412 if (log)
1413 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64
1414 ", exited=%i, signal=%i, exit_status=%i)\n",
1415 pid, exited, signo, exit_status);
1416
1417 if (exited) {
1418 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1419 if (target_sp) {
1420 ProcessSP process_sp(target_sp->GetProcessSP());
1421 if (process_sp) {
1422 const char *signal_cstr = nullptr;
1423 if (signo)
1424 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1425
1426 process_sp->SetExitStatus(exit_status, signal_cstr);
1427 }
1428 }
1429 return true;
1430 }
1431 return false;
1432}
1433
1434void Process::UpdateThreadListIfNeeded() {
1435 const uint32_t stop_id = GetStopID();
1436 if (m_thread_list.GetSize(false) == 0 ||
1437 stop_id != m_thread_list.GetStopID()) {
1438 const StateType state = GetPrivateState();
1439 if (StateIsStoppedState(state, true)) {
1440 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Adrian Prantl05097242018-04-30 16:49:04 +00001441 // m_thread_list does have its own mutex, but we need to hold onto the
1442 // mutex between the call to UpdateThreadList(...) and the
1443 // os->UpdateThreadList(...) so it doesn't change on us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 ThreadList &old_thread_list = m_thread_list;
1445 ThreadList real_thread_list(this);
1446 ThreadList new_thread_list(this);
Adrian Prantl05097242018-04-30 16:49:04 +00001447 // Always update the thread list with the protocol specific thread list,
1448 // but only update if "true" is returned
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1450 // Don't call into the OperatingSystem to update the thread list if we
Adrian Prantl05097242018-04-30 16:49:04 +00001451 // are shutting down, since that may call back into the SBAPI's,
1452 // requiring the API lock which is already held by whoever is shutting
1453 // us down, causing a deadlock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 OperatingSystem *os = GetOperatingSystem();
1455 if (os && !m_destroy_in_process) {
1456 // Clear any old backing threads where memory threads might have been
1457 // backed by actual threads from the lldb_private::Process subclass
1458 size_t num_old_threads = old_thread_list.GetSize(false);
1459 for (size_t i = 0; i < num_old_threads; ++i)
1460 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1461
1462 // Turn off dynamic types to ensure we don't run any expressions.
Adrian Prantl4e8be2c2018-06-13 16:21:24 +00001463 // Objective-C can run an expression to determine if a SBValue is a
Adrian Prantl05097242018-04-30 16:49:04 +00001464 // dynamic type or not and we need to avoid this. OperatingSystem
1465 // plug-ins can't run expressions that require running code...
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466
1467 Target &target = GetTarget();
1468 const lldb::DynamicValueType saved_prefer_dynamic =
1469 target.GetPreferDynamicValue();
1470 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1471 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1472
1473 // Now let the OperatingSystem plug-in update the thread list
1474
1475 os->UpdateThreadList(
1476 old_thread_list, // Old list full of threads created by OS plug-in
1477 real_thread_list, // The actual thread list full of threads
1478 // created by each lldb_private::Process
1479 // subclass
1480 new_thread_list); // The new thread list that we will show to the
1481 // user that gets filled in
1482
1483 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1484 target.SetPreferDynamicValue(saved_prefer_dynamic);
1485 } else {
1486 // No OS plug-in, the new thread list is the same as the real thread
1487 // list
1488 new_thread_list = real_thread_list;
1489 }
1490
1491 m_thread_list_real.Update(real_thread_list);
1492 m_thread_list.Update(new_thread_list);
1493 m_thread_list.SetStopID(stop_id);
1494
1495 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1496 // Clear any extended threads that we may have accumulated previously
1497 m_extended_thread_list.Clear();
1498 m_extended_thread_stop_id = GetLastNaturalStopID();
1499
1500 m_queue_list.Clear();
1501 m_queue_list_stop_id = GetLastNaturalStopID();
1502 }
1503 }
1504 }
1505 }
1506}
1507
1508void Process::UpdateQueueListIfNeeded() {
1509 if (m_system_runtime_ap) {
1510 if (m_queue_list.GetSize() == 0 ||
1511 m_queue_list_stop_id != GetLastNaturalStopID()) {
1512 const StateType state = GetPrivateState();
1513 if (StateIsStoppedState(state, true)) {
1514 m_system_runtime_ap->PopulateQueueList(m_queue_list);
1515 m_queue_list_stop_id = GetLastNaturalStopID();
1516 }
1517 }
1518 }
1519}
1520
1521ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1522 OperatingSystem *os = GetOperatingSystem();
1523 if (os)
1524 return os->CreateThread(tid, context);
1525 return ThreadSP();
1526}
1527
1528uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1529 return AssignIndexIDToThread(thread_id);
1530}
1531
1532bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1533 return (m_thread_id_to_index_id_map.find(thread_id) !=
1534 m_thread_id_to_index_id_map.end());
1535}
1536
1537uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1538 uint32_t result = 0;
1539 std::map<uint64_t, uint32_t>::iterator iterator =
1540 m_thread_id_to_index_id_map.find(thread_id);
1541 if (iterator == m_thread_id_to_index_id_map.end()) {
1542 result = ++m_thread_index_id;
1543 m_thread_id_to_index_id_map[thread_id] = result;
1544 } else {
1545 result = iterator->second;
1546 }
1547
1548 return result;
1549}
1550
1551StateType Process::GetState() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001552 return m_public_state.GetValue();
1553}
1554
1555bool Process::StateChangedIsExternallyHijacked() {
1556 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1557 const char *hijacking_name = GetHijackingListenerName();
1558 if (hijacking_name &&
1559 strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
1560 return true;
1561 }
1562 return false;
1563}
1564
1565void Process::SetPublicState(StateType new_state, bool restarted) {
1566 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1567 LIBLLDB_LOG_PROCESS));
1568 if (log)
1569 log->Printf("Process::SetPublicState (state = %s, restarted = %i)",
1570 StateAsCString(new_state), restarted);
1571 const StateType old_state = m_public_state.GetValue();
1572 m_public_state.SetValue(new_state);
1573
Adrian Prantl05097242018-04-30 16:49:04 +00001574 // On the transition from Run to Stopped, we unlock the writer end of the run
1575 // lock. The lock gets locked in Resume, which is the public API to tell the
1576 // program to run.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001577 if (!StateChangedIsExternallyHijacked()) {
1578 if (new_state == eStateDetached) {
1579 if (log)
1580 log->Printf(
1581 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1582 StateAsCString(new_state));
1583 m_public_run_lock.SetStopped();
1584 } else {
1585 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1586 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1587 if ((old_state_is_stopped != new_state_is_stopped)) {
1588 if (new_state_is_stopped && !restarted) {
1589 if (log)
1590 log->Printf("Process::SetPublicState (%s) -- unlocking run lock",
1591 StateAsCString(new_state));
1592 m_public_run_lock.SetStopped();
1593 }
1594 }
1595 }
1596 }
1597}
1598
Zachary Turner97206d52017-05-12 04:51:55 +00001599Status Process::Resume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001600 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1601 LIBLLDB_LOG_PROCESS));
1602 if (log)
1603 log->Printf("Process::Resume -- locking run lock");
1604 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001605 Status error("Resume request failed - process still running.");
Greg Claytone4e45922011-11-16 05:37:56 +00001606 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001607 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
Greg Claytondc6224e2014-10-21 01:00:42 +00001608 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001609 }
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001610 Status error = PrivateResume();
1611 if (!error.Success()) {
1612 // Undo running state change
1613 m_public_run_lock.SetStopped();
1614 }
1615 return error;
Greg Claytondc6224e2014-10-21 01:00:42 +00001616}
1617
Zachary Turner97206d52017-05-12 04:51:55 +00001618Status Process::ResumeSynchronous(Stream *stream) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001619 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1620 LIBLLDB_LOG_PROCESS));
1621 if (log)
1622 log->Printf("Process::ResumeSynchronous -- locking run lock");
1623 if (!m_public_run_lock.TrySetRunning()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001624 Status error("Resume request failed - process still running.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001625 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001626 log->Printf("Process::Resume: -- TrySetRunning failed, not resuming.");
1627 return error;
1628 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001629
Kate Stoneb9c1b512016-09-06 20:57:50 +00001630 ListenerSP listener_sp(
1631 Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1632 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001633
Zachary Turner97206d52017-05-12 04:51:55 +00001634 Status error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001635 if (error.Success()) {
Pavel Labathe3e21cf2016-11-30 11:56:32 +00001636 StateType state =
1637 WaitForProcessToStop(llvm::None, NULL, true, listener_sp, stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001638 const bool must_be_alive =
1639 false; // eStateExited is ok, so this must be false
1640 if (!StateIsStoppedState(state, must_be_alive))
1641 error.SetErrorStringWithFormat(
1642 "process not in stopped state after synchronous resume: %s",
1643 StateAsCString(state));
Adrian McCarthy3887ba82017-09-19 18:07:33 +00001644 } else {
1645 // Undo running state change
1646 m_public_run_lock.SetStopped();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001647 }
Ed Mastec29693f2013-07-02 16:35:47 +00001648
Kate Stoneb9c1b512016-09-06 20:57:50 +00001649 // Undo the hijacking of process events...
1650 RestoreProcessEvents();
Andrew Kaylor93132f52013-05-28 23:04:25 +00001651
Kate Stoneb9c1b512016-09-06 20:57:50 +00001652 return error;
1653}
Andrew Kaylor29d65742013-05-10 17:19:04 +00001654
Kate Stoneb9c1b512016-09-06 20:57:50 +00001655StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
Ilia K38810f42015-05-20 10:15:47 +00001656
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657void Process::SetPrivateState(StateType new_state) {
1658 if (m_finalize_called)
1659 return;
1660
1661 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1662 LIBLLDB_LOG_PROCESS));
1663 bool state_changed = false;
1664
1665 if (log)
1666 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1667
1668 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1669 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1670
1671 const StateType old_state = m_private_state.GetValueNoLock();
1672 state_changed = old_state != new_state;
1673
1674 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1675 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1676 if (old_state_is_stopped != new_state_is_stopped) {
1677 if (new_state_is_stopped)
1678 m_private_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001679 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001680 m_private_run_lock.SetRunning();
1681 }
1682
1683 if (state_changed) {
1684 m_private_state.SetValueNoLock(new_state);
1685 EventSP event_sp(
1686 new Event(eBroadcastBitStateChanged,
1687 new ProcessEventData(shared_from_this(), new_state)));
1688 if (StateIsStoppedState(new_state, false)) {
Adrian Prantl05097242018-04-30 16:49:04 +00001689 // Note, this currently assumes that all threads in the list stop when
1690 // the process stops. In the future we will want to support a debugging
1691 // model where some threads continue to run while others are stopped.
1692 // When that happens we will either need a way for the thread list to
1693 // identify which threads are stopping or create a special thread list
1694 // containing only threads which actually stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001695 //
Adrian Prantl05097242018-04-30 16:49:04 +00001696 // The process plugin is responsible for managing the actual behavior of
1697 // the threads and should have stopped any threads that are going to stop
1698 // before we get here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001699 m_thread_list.DidStop();
1700
1701 m_mod_id.BumpStopID();
1702 if (!m_mod_id.IsLastResumeForUserExpression())
1703 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1704 m_memory_cache.Clear();
1705 if (log)
1706 log->Printf("Process::SetPrivateState (%s) stop_id = %u",
1707 StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001708 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001709
Kate Stoneb9c1b512016-09-06 20:57:50 +00001710 // Use our target to get a shared pointer to ourselves...
1711 if (m_finalize_called && !PrivateStateThreadIsValid())
1712 BroadcastEvent(event_sp);
Jim Ingham22777012010-09-23 02:01:19 +00001713 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001714 m_private_state_broadcaster.BroadcastEvent(event_sp);
1715 } else {
1716 if (log)
1717 log->Printf(
1718 "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1719 StateAsCString(new_state));
1720 }
Jim Ingham22777012010-09-23 02:01:19 +00001721}
1722
Kate Stoneb9c1b512016-09-06 20:57:50 +00001723void Process::SetRunningUserExpression(bool on) {
1724 m_mod_id.SetRunningUserExpression(on);
1725}
1726
Raphael Isemannc01783a2018-08-29 22:50:54 +00001727void Process::SetRunningUtilityFunction(bool on) {
1728 m_mod_id.SetRunningUtilityFunction(on);
1729}
1730
Kate Stoneb9c1b512016-09-06 20:57:50 +00001731addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1732
1733const lldb::ABISP &Process::GetABI() {
1734 if (!m_abi_sp)
Jason Molenda43294c92017-06-29 02:57:03 +00001735 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001736 return m_abi_sp;
1737}
1738
1739LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language,
1740 bool retry_if_null) {
1741 if (m_finalizing)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001742 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001743
1744 LanguageRuntimeCollection::iterator pos;
1745 pos = m_language_runtimes.find(language);
1746 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second)) {
1747 lldb::LanguageRuntimeSP runtime_sp(
1748 LanguageRuntime::FindPlugin(this, language));
1749
1750 m_language_runtimes[language] = runtime_sp;
1751 return runtime_sp.get();
1752 } else
1753 return (*pos).second.get();
Jim Ingham22777012010-09-23 02:01:19 +00001754}
1755
Kate Stoneb9c1b512016-09-06 20:57:50 +00001756CPPLanguageRuntime *Process::GetCPPLanguageRuntime(bool retry_if_null) {
1757 LanguageRuntime *runtime =
1758 GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
1759 if (runtime != nullptr &&
1760 runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1761 return static_cast<CPPLanguageRuntime *>(runtime);
1762 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001763}
1764
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765ObjCLanguageRuntime *Process::GetObjCLanguageRuntime(bool retry_if_null) {
1766 LanguageRuntime *runtime =
1767 GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
1768 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
1769 return static_cast<ObjCLanguageRuntime *>(runtime);
1770 return nullptr;
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001771}
1772
Kate Stoneb9c1b512016-09-06 20:57:50 +00001773bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1774 if (m_finalizing)
1775 return false;
1776
1777 if (in_value.IsDynamic())
1778 return false;
1779 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1780
1781 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1782 LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1783 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1784 }
1785
1786 LanguageRuntime *cpp_runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1787 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1788 return true;
1789
1790 LanguageRuntime *objc_runtime = GetLanguageRuntime(eLanguageTypeObjC);
1791 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
Zachary Turner93749ab2015-03-03 21:51:25 +00001792}
1793
Kate Stoneb9c1b512016-09-06 20:57:50 +00001794void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1795 m_dynamic_checkers_ap.reset(dynamic_checkers);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001796}
1797
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798BreakpointSiteList &Process::GetBreakpointSiteList() {
1799 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001800}
1801
Kate Stoneb9c1b512016-09-06 20:57:50 +00001802const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1803 return m_breakpoint_site_list;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001804}
1805
Kate Stoneb9c1b512016-09-06 20:57:50 +00001806void Process::DisableAllBreakpointSites() {
1807 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1808 // bp_site->SetEnabled(true);
1809 DisableBreakpointSite(bp_site);
1810 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001811}
1812
Zachary Turner97206d52017-05-12 04:51:55 +00001813Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1814 Status error(DisableBreakpointSiteByID(break_id));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001815
Kate Stoneb9c1b512016-09-06 20:57:50 +00001816 if (error.Success())
1817 m_breakpoint_site_list.Remove(break_id);
1818
1819 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001820}
1821
Zachary Turner97206d52017-05-12 04:51:55 +00001822Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1823 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001824 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1825 if (bp_site_sp) {
1826 if (bp_site_sp->IsEnabled())
1827 error = DisableBreakpointSite(bp_site_sp.get());
1828 } else {
1829 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1830 break_id);
1831 }
1832
1833 return error;
1834}
1835
Zachary Turner97206d52017-05-12 04:51:55 +00001836Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1837 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001838 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1839 if (bp_site_sp) {
1840 if (!bp_site_sp->IsEnabled())
1841 error = EnableBreakpointSite(bp_site_sp.get());
1842 } else {
1843 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1844 break_id);
1845 }
1846 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001847}
1848
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001849lldb::break_id_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001850Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1851 bool use_hardware) {
1852 addr_t load_addr = LLDB_INVALID_ADDRESS;
Jim Ingham1460e4b2014-01-10 23:46:59 +00001853
Kate Stoneb9c1b512016-09-06 20:57:50 +00001854 bool show_error = true;
1855 switch (GetState()) {
1856 case eStateInvalid:
1857 case eStateUnloaded:
1858 case eStateConnected:
1859 case eStateAttaching:
1860 case eStateLaunching:
1861 case eStateDetached:
1862 case eStateExited:
1863 show_error = false;
1864 break;
1865
1866 case eStateStopped:
1867 case eStateRunning:
1868 case eStateStepping:
1869 case eStateCrashed:
1870 case eStateSuspended:
1871 show_error = IsAlive();
1872 break;
1873 }
1874
Adrian Prantl05097242018-04-30 16:49:04 +00001875 // Reset the IsIndirect flag here, in case the location changes from pointing
1876 // to a indirect symbol to a regular symbol.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001877 owner->SetIsIndirect(false);
1878
1879 if (owner->ShouldResolveIndirectFunctions()) {
1880 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1881 if (symbol && symbol->IsIndirect()) {
Zachary Turner97206d52017-05-12 04:51:55 +00001882 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001883 Address symbol_address = symbol->GetAddress();
1884 load_addr = ResolveIndirectFunction(&symbol_address, error);
1885 if (!error.Success() && show_error) {
1886 GetTarget().GetDebugger().GetErrorFile()->Printf(
1887 "warning: failed to resolve indirect function at 0x%" PRIx64
1888 " for breakpoint %i.%i: %s\n",
1889 symbol->GetLoadAddress(&GetTarget()),
1890 owner->GetBreakpoint().GetID(), owner->GetID(),
1891 error.AsCString() ? error.AsCString() : "unknown error");
1892 return LLDB_INVALID_BREAK_ID;
1893 }
1894 Address resolved_address(load_addr);
1895 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1896 owner->SetIsIndirect(true);
1897 } else
1898 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1899 } else
1900 load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1901
1902 if (load_addr != LLDB_INVALID_ADDRESS) {
1903 BreakpointSiteSP bp_site_sp;
1904
1905 // Look up this breakpoint site. If it exists, then add this new owner,
Adrian Prantl05097242018-04-30 16:49:04 +00001906 // otherwise create a new breakpoint site and add it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001907
1908 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1909
1910 if (bp_site_sp) {
1911 bp_site_sp->AddOwner(owner);
1912 owner->SetBreakpointSite(bp_site_sp);
1913 return bp_site_sp->GetID();
1914 } else {
1915 bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1916 load_addr, use_hardware));
1917 if (bp_site_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00001918 Status error = EnableBreakpointSite(bp_site_sp.get());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001919 if (error.Success()) {
1920 owner->SetBreakpointSite(bp_site_sp);
1921 return m_breakpoint_site_list.Add(bp_site_sp);
1922 } else {
Jonas Devliegheree103ae92018-11-15 01:18:15 +00001923 if (show_error || use_hardware) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001924 // Report error for setting breakpoint...
1925 GetTarget().GetDebugger().GetErrorFile()->Printf(
1926 "warning: failed to set breakpoint site at 0x%" PRIx64
1927 " for breakpoint %i.%i: %s\n",
1928 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1929 error.AsCString() ? error.AsCString() : "unknown error");
1930 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001931 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001932 }
Jim Ingham1460e4b2014-01-10 23:46:59 +00001933 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001934 }
1935 // We failed to enable the breakpoint
1936 return LLDB_INVALID_BREAK_ID;
1937}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001938
Kate Stoneb9c1b512016-09-06 20:57:50 +00001939void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1940 lldb::user_id_t owner_loc_id,
1941 BreakpointSiteSP &bp_site_sp) {
1942 uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1943 if (num_owners == 0) {
1944 // Don't try to disable the site if we don't have a live process anymore.
1945 if (IsAlive())
1946 DisableBreakpointSite(bp_site_sp.get());
1947 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1948 }
1949}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001950
Kate Stoneb9c1b512016-09-06 20:57:50 +00001951size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1952 uint8_t *buf) const {
1953 size_t bytes_removed = 0;
1954 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001955
Kate Stoneb9c1b512016-09-06 20:57:50 +00001956 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1957 bp_sites_in_range)) {
Zachary Turner3bc714b2017-03-02 00:05:25 +00001958 bp_sites_in_range.ForEach([bp_addr, size,
1959 buf](BreakpointSite *bp_site) -> void {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001960 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1961 addr_t intersect_addr;
1962 size_t intersect_size;
1963 size_t opcode_offset;
1964 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1965 &intersect_size, &opcode_offset)) {
1966 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1967 assert(bp_addr < intersect_addr + intersect_size &&
1968 intersect_addr + intersect_size <= bp_addr + size);
1969 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1970 size_t buf_offset = intersect_addr - bp_addr;
1971 ::memcpy(buf + buf_offset,
1972 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1973 intersect_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001974 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001975 }
1976 });
1977 }
1978 return bytes_removed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001979}
1980
Kate Stoneb9c1b512016-09-06 20:57:50 +00001981size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1982 PlatformSP platform_sp(GetTarget().GetPlatform());
1983 if (platform_sp)
1984 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1985 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001986}
1987
Zachary Turner97206d52017-05-12 04:51:55 +00001988Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1989 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001990 assert(bp_site != nullptr);
1991 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1992 const addr_t bp_addr = bp_site->GetLoadAddress();
1993 if (log)
1994 log->Printf(
1995 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1996 bp_site->GetID(), (uint64_t)bp_addr);
1997 if (bp_site->IsEnabled()) {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001998 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001999 log->Printf(
2000 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2001 " -- already enabled",
2002 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002003 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002004 }
2005
2006 if (bp_addr == LLDB_INVALID_ADDRESS) {
2007 error.SetErrorString("BreakpointSite contains an invalid load address.");
2008 return error;
2009 }
2010 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2011 // trap for the breakpoint site
2012 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2013
2014 if (bp_opcode_size == 0) {
2015 error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
2016 "returned zero, unable to get breakpoint "
2017 "trap for address 0x%" PRIx64,
2018 bp_addr);
2019 } else {
2020 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2021
2022 if (bp_opcode_bytes == nullptr) {
2023 error.SetErrorString(
2024 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2025 return error;
2026 }
2027
2028 // Save the original opcode by reading it
2029 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
2030 error) == bp_opcode_size) {
2031 // Write a software breakpoint in place of the original opcode
2032 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
2033 bp_opcode_size) {
2034 uint8_t verify_bp_opcode_bytes[64];
2035 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
2036 error) == bp_opcode_size) {
2037 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
2038 bp_opcode_size) == 0) {
2039 bp_site->SetEnabled(true);
2040 bp_site->SetType(BreakpointSite::eSoftware);
2041 if (log)
2042 log->Printf("Process::EnableSoftwareBreakpoint (site_id = %d) "
2043 "addr = 0x%" PRIx64 " -- SUCCESS",
2044 bp_site->GetID(), (uint64_t)bp_addr);
2045 } else
2046 error.SetErrorString(
2047 "failed to verify the breakpoint trap in memory.");
2048 } else
2049 error.SetErrorString(
2050 "Unable to read memory to verify breakpoint trap.");
2051 } else
2052 error.SetErrorString("Unable to write breakpoint trap to memory.");
2053 } else
2054 error.SetErrorString("Unable to read memory at breakpoint address.");
2055 }
2056 if (log && error.Fail())
2057 log->Printf(
2058 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2059 " -- FAILED: %s",
2060 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2061 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002062}
2063
Zachary Turner97206d52017-05-12 04:51:55 +00002064Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
2065 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002066 assert(bp_site != nullptr);
2067 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2068 addr_t bp_addr = bp_site->GetLoadAddress();
2069 lldb::user_id_t breakID = bp_site->GetID();
2070 if (log)
2071 log->Printf("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
2072 ") addr = 0x%" PRIx64,
2073 breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074
Kate Stoneb9c1b512016-09-06 20:57:50 +00002075 if (bp_site->IsHardware()) {
2076 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2077 } else if (bp_site->IsEnabled()) {
2078 const size_t break_op_size = bp_site->GetByteSize();
2079 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
2080 if (break_op_size > 0) {
2081 // Clear a software breakpoint instruction
2082 uint8_t curr_break_op[8];
2083 assert(break_op_size <= sizeof(curr_break_op));
2084 bool break_op_found = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002085
Kate Stoneb9c1b512016-09-06 20:57:50 +00002086 // Read the breakpoint opcode
2087 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
2088 break_op_size) {
2089 bool verify = false;
2090 // Make sure the breakpoint opcode exists at this address
2091 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
2092 break_op_found = true;
2093 // We found a valid breakpoint opcode at this address, now restore
2094 // the saved opcode.
2095 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
2096 break_op_size, error) == break_op_size) {
2097 verify = true;
2098 } else
2099 error.SetErrorString(
2100 "Memory write failed when restoring original opcode.");
2101 } else {
2102 error.SetErrorString(
2103 "Original breakpoint trap is no longer in memory.");
2104 // Set verify to true and so we can check if the original opcode has
2105 // already been restored
2106 verify = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002107 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108
Kate Stoneb9c1b512016-09-06 20:57:50 +00002109 if (verify) {
2110 uint8_t verify_opcode[8];
2111 assert(break_op_size < sizeof(verify_opcode));
2112 // Verify that our original opcode made it back to the inferior
2113 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
2114 break_op_size) {
2115 // compare the memory we just read with the original opcode
2116 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
2117 break_op_size) == 0) {
2118 // SUCCESS
2119 bp_site->SetEnabled(false);
2120 if (log)
2121 log->Printf("Process::DisableSoftwareBreakpoint (site_id = %d) "
2122 "addr = 0x%" PRIx64 " -- SUCCESS",
2123 bp_site->GetID(), (uint64_t)bp_addr);
2124 return error;
2125 } else {
2126 if (break_op_found)
2127 error.SetErrorString("Failed to restore original opcode.");
2128 }
2129 } else
2130 error.SetErrorString("Failed to read memory to verify that "
2131 "breakpoint trap was restored.");
2132 }
2133 } else
2134 error.SetErrorString(
2135 "Unable to read memory that should contain the breakpoint trap.");
2136 }
2137 } else {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002139 log->Printf(
2140 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2141 " -- already disabled",
2142 bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002143 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002144 }
2145
2146 if (log)
2147 log->Printf(
2148 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2149 " -- FAILED: %s",
2150 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2151 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002152}
2153
Adrian Prantl05097242018-04-30 16:49:04 +00002154// Uncomment to verify memory caching works after making changes to caching
2155// code
Greg Clayton58be07b2011-01-07 06:08:19 +00002156//#define VERIFY_MEMORY_READS
2157
Zachary Turner97206d52017-05-12 04:51:55 +00002158size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159 error.Clear();
2160 if (!GetDisableMemoryCache()) {
2161#if defined(VERIFY_MEMORY_READS)
2162 // Memory caching is enabled, with debug verification
2163
2164 if (buf && size) {
2165 // Uncomment the line below to make sure memory caching is working.
2166 // I ran this through the test suite and got no assertions, so I am
2167 // pretty confident this is working well. If any changes are made to
2168 // memory caching, uncomment the line below and test your changes!
2169
2170 // Verify all memory reads by using the cache first, then redundantly
2171 // reading the same memory from the inferior and comparing to make sure
2172 // everything is exactly the same.
2173 std::string verify_buf(size, '\0');
2174 assert(verify_buf.size() == size);
2175 const size_t cache_bytes_read =
2176 m_memory_cache.Read(this, addr, buf, size, error);
Zachary Turner97206d52017-05-12 04:51:55 +00002177 Status verify_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002178 const size_t verify_bytes_read =
2179 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2180 verify_buf.size(), verify_error);
2181 assert(cache_bytes_read == verify_bytes_read);
2182 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2183 assert(verify_error.Success() == error.Success());
2184 return cache_bytes_read;
2185 }
2186 return 0;
2187#else // !defined(VERIFY_MEMORY_READS)
2188 // Memory caching is enabled, without debug verification
2189
2190 return m_memory_cache.Read(addr, buf, size, error);
Sean Callanan64c0cf22012-06-07 22:26:42 +00002191#endif // defined (VERIFY_MEMORY_READS)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002192 } else {
2193 // Memory caching is disabled
2194
2195 return ReadMemoryFromInferior(addr, buf, size, error);
2196 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002197}
Kate Stoneb9c1b512016-09-06 20:57:50 +00002198
2199size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
Zachary Turner97206d52017-05-12 04:51:55 +00002200 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002201 char buf[256];
2202 out_str.clear();
2203 addr_t curr_addr = addr;
2204 while (true) {
2205 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2206 if (length == 0)
2207 break;
2208 out_str.append(buf, length);
Adrian Prantl05097242018-04-30 16:49:04 +00002209 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2210 // to read some more characters
Kate Stoneb9c1b512016-09-06 20:57:50 +00002211 if (length == sizeof(buf) - 1)
2212 curr_addr += length;
2213 else
2214 break;
2215 }
2216 return out_str.size();
2217}
2218
2219size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
Zachary Turner97206d52017-05-12 04:51:55 +00002220 Status &error, size_t type_width) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002221 size_t total_bytes_read = 0;
2222 if (dst && max_bytes && type_width && max_bytes >= type_width) {
Adrian Prantl05097242018-04-30 16:49:04 +00002223 // Ensure a null terminator independent of the number of bytes that is
2224 // read.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002225 memset(dst, 0, max_bytes);
2226 size_t bytes_left = max_bytes - type_width;
2227
2228 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2229 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2230 "string with more than 4 bytes "
2231 "per character!");
2232
Greg Clayton4c82d422012-05-18 23:20:01 +00002233 addr_t curr_addr = addr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002234 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2235 char *curr_dst = dst;
Greg Clayton4c82d422012-05-18 23:20:01 +00002236
Kate Stoneb9c1b512016-09-06 20:57:50 +00002237 error.Clear();
2238 while (bytes_left > 0 && error.Success()) {
2239 addr_t cache_line_bytes_left =
2240 cache_line_size - (curr_addr % cache_line_size);
2241 addr_t bytes_to_read =
2242 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2243 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002244
Kate Stoneb9c1b512016-09-06 20:57:50 +00002245 if (bytes_read == 0)
2246 break;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002247
Kate Stoneb9c1b512016-09-06 20:57:50 +00002248 // Search for a null terminator of correct size and alignment in
2249 // bytes_read
2250 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2251 for (size_t i = aligned_start;
2252 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2253 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2254 error.Clear();
2255 return i;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002256 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257
2258 total_bytes_read += bytes_read;
2259 curr_dst += bytes_read;
2260 curr_addr += bytes_read;
2261 bytes_left -= bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002262 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002263 } else {
2264 if (max_bytes)
2265 error.SetErrorString("invalid arguments");
2266 }
2267 return total_bytes_read;
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002268}
2269
Kate Stoneb9c1b512016-09-06 20:57:50 +00002270// Deprecated in favor of ReadStringFromMemory which has wchar support and
Adrian Prantl05097242018-04-30 16:49:04 +00002271// correct code to find null terminators.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002272size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
Zachary Turner97206d52017-05-12 04:51:55 +00002273 size_t dst_max_len,
2274 Status &result_error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002275 size_t total_cstr_len = 0;
2276 if (dst && dst_max_len) {
2277 result_error.Clear();
2278 // NULL out everything just to be safe
2279 memset(dst, 0, dst_max_len);
Zachary Turner97206d52017-05-12 04:51:55 +00002280 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002281 addr_t curr_addr = addr;
2282 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2283 size_t bytes_left = dst_max_len - 1;
2284 char *curr_dst = dst;
Greg Clayton8b82f082011-04-12 05:54:46 +00002285
Kate Stoneb9c1b512016-09-06 20:57:50 +00002286 while (bytes_left > 0) {
2287 addr_t cache_line_bytes_left =
2288 cache_line_size - (curr_addr % cache_line_size);
2289 addr_t bytes_to_read =
2290 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2291 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
Greg Clayton8b82f082011-04-12 05:54:46 +00002292
Kate Stoneb9c1b512016-09-06 20:57:50 +00002293 if (bytes_read == 0) {
2294 result_error = error;
2295 dst[total_cstr_len] = '\0';
2296 break;
2297 }
2298 const size_t len = strlen(curr_dst);
Greg Clayton8b82f082011-04-12 05:54:46 +00002299
Kate Stoneb9c1b512016-09-06 20:57:50 +00002300 total_cstr_len += len;
2301
2302 if (len < bytes_to_read)
2303 break;
2304
2305 curr_dst += bytes_read;
2306 curr_addr += bytes_read;
2307 bytes_left -= bytes_read;
Greg Clayton8b82f082011-04-12 05:54:46 +00002308 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002309 } else {
2310 if (dst == nullptr)
2311 result_error.SetErrorString("invalid arguments");
Greg Claytone91b7952011-12-15 03:14:23 +00002312 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002313 result_error.Clear();
2314 }
2315 return total_cstr_len;
Greg Clayton8b82f082011-04-12 05:54:46 +00002316}
2317
Kate Stoneb9c1b512016-09-06 20:57:50 +00002318size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002319 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002320 if (buf == nullptr || size == 0)
2321 return 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002322
Kate Stoneb9c1b512016-09-06 20:57:50 +00002323 size_t bytes_read = 0;
2324 uint8_t *bytes = (uint8_t *)buf;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325
Kate Stoneb9c1b512016-09-06 20:57:50 +00002326 while (bytes_read < size) {
2327 const size_t curr_size = size - bytes_read;
2328 const size_t curr_bytes_read =
2329 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2330 bytes_read += curr_bytes_read;
2331 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2332 break;
2333 }
2334
2335 // Replace any software breakpoint opcodes that fall into this range back
2336 // into "buf" before we return
2337 if (bytes_read > 0)
2338 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2339 return bytes_read;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002340}
2341
Kate Stoneb9c1b512016-09-06 20:57:50 +00002342uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2343 size_t integer_byte_size,
2344 uint64_t fail_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002345 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002346 Scalar scalar;
2347 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2348 error))
2349 return scalar.ULongLong(fail_value);
2350 return fail_value;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002351}
2352
Kate Stoneb9c1b512016-09-06 20:57:50 +00002353int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2354 size_t integer_byte_size,
Zachary Turner97206d52017-05-12 04:51:55 +00002355 int64_t fail_value,
2356 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002357 Scalar scalar;
2358 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2359 error))
2360 return scalar.SLongLong(fail_value);
2361 return fail_value;
Greg Claytonc2267782016-05-23 20:37:24 +00002362}
2363
Zachary Turner97206d52017-05-12 04:51:55 +00002364addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002365 Scalar scalar;
2366 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2367 error))
2368 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2369 return LLDB_INVALID_ADDRESS;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002370}
2371
Kate Stoneb9c1b512016-09-06 20:57:50 +00002372bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
Zachary Turner97206d52017-05-12 04:51:55 +00002373 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002374 Scalar scalar;
2375 const uint32_t addr_byte_size = GetAddressByteSize();
2376 if (addr_byte_size <= 4)
2377 scalar = (uint32_t)ptr_value;
2378 else
2379 scalar = ptr_value;
2380 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2381 addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002382}
2383
Kate Stoneb9c1b512016-09-06 20:57:50 +00002384size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002385 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002386 size_t bytes_written = 0;
2387 const uint8_t *bytes = (const uint8_t *)buf;
2388
2389 while (bytes_written < size) {
2390 const size_t curr_size = size - bytes_written;
2391 const size_t curr_bytes_written = DoWriteMemory(
2392 addr + bytes_written, bytes + bytes_written, curr_size, error);
2393 bytes_written += curr_bytes_written;
2394 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2395 break;
2396 }
2397 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002398}
2399
Kate Stoneb9c1b512016-09-06 20:57:50 +00002400size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +00002401 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002402#if defined(ENABLE_MEMORY_CACHING)
2403 m_memory_cache.Flush(addr, size);
Greg Clayton58be07b2011-01-07 06:08:19 +00002404#endif
2405
Kate Stoneb9c1b512016-09-06 20:57:50 +00002406 if (buf == nullptr || size == 0)
2407 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002408
Kate Stoneb9c1b512016-09-06 20:57:50 +00002409 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002410
Kate Stoneb9c1b512016-09-06 20:57:50 +00002411 // We need to write any data that would go where any current software traps
2412 // (enabled software breakpoints) any software traps (breakpoints) that we
2413 // may have placed in our tasks memory.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002414
Kate Stoneb9c1b512016-09-06 20:57:50 +00002415 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002416
Kate Stoneb9c1b512016-09-06 20:57:50 +00002417 if (m_breakpoint_site_list.FindInRange(addr, addr + size,
2418 bp_sites_in_range)) {
2419 // No breakpoint sites overlap
2420 if (bp_sites_in_range.IsEmpty())
2421 return WriteMemoryPrivate(addr, buf, size, error);
2422 else {
2423 const uint8_t *ubuf = (const uint8_t *)buf;
2424 uint64_t bytes_written = 0;
2425
2426 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2427 &error](BreakpointSite *bp) -> void {
2428
2429 if (error.Success()) {
2430 addr_t intersect_addr;
2431 size_t intersect_size;
2432 size_t opcode_offset;
2433 const bool intersects = bp->IntersectsRange(
2434 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2435 UNUSED_IF_ASSERT_DISABLED(intersects);
2436 assert(intersects);
2437 assert(addr <= intersect_addr && intersect_addr < addr + size);
2438 assert(addr < intersect_addr + intersect_size &&
2439 intersect_addr + intersect_size <= addr + size);
2440 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2441
2442 // Check for bytes before this breakpoint
2443 const addr_t curr_addr = addr + bytes_written;
2444 if (intersect_addr > curr_addr) {
Adrian Prantl05097242018-04-30 16:49:04 +00002445 // There are some bytes before this breakpoint that we need to just
2446 // write to memory
Kate Stoneb9c1b512016-09-06 20:57:50 +00002447 size_t curr_size = intersect_addr - curr_addr;
2448 size_t curr_bytes_written = WriteMemoryPrivate(
2449 curr_addr, ubuf + bytes_written, curr_size, error);
2450 bytes_written += curr_bytes_written;
2451 if (curr_bytes_written != curr_size) {
Adrian Prantl05097242018-04-30 16:49:04 +00002452 // We weren't able to write all of the requested bytes, we are
2453 // done looping and will return the number of bytes that we have
2454 // written so far.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002455 if (error.Success())
2456 error.SetErrorToGenericError();
2457 }
2458 }
2459 // Now write any bytes that would cover up any software breakpoints
2460 // directly into the breakpoint opcode buffer
2461 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset,
2462 ubuf + bytes_written, intersect_size);
2463 bytes_written += intersect_size;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002464 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002465 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002466
Kate Stoneb9c1b512016-09-06 20:57:50 +00002467 if (bytes_written < size)
2468 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2469 size - bytes_written, error);
2470 }
2471 } else {
2472 return WriteMemoryPrivate(addr, buf, size, error);
2473 }
2474
2475 // Write any remaining bytes after the last breakpoint if we have any left
2476 return 0; // bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002477}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002478
Kate Stoneb9c1b512016-09-06 20:57:50 +00002479size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002480 size_t byte_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002481 if (byte_size == UINT32_MAX)
2482 byte_size = scalar.GetByteSize();
2483 if (byte_size > 0) {
2484 uint8_t buf[32];
2485 const size_t mem_size =
2486 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2487 if (mem_size > 0)
2488 return WriteMemory(addr, buf, mem_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002489 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002490 error.SetErrorString("failed to get scalar as memory data");
2491 } else {
2492 error.SetErrorString("invalid scalar value");
2493 }
2494 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002495}
2496
Kate Stoneb9c1b512016-09-06 20:57:50 +00002497size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2498 bool is_signed, Scalar &scalar,
Zachary Turner97206d52017-05-12 04:51:55 +00002499 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002500 uint64_t uval = 0;
2501 if (byte_size == 0) {
2502 error.SetErrorString("byte size is zero");
2503 } else if (byte_size & (byte_size - 1)) {
2504 error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2505 byte_size);
2506 } else if (byte_size <= sizeof(uval)) {
2507 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2508 if (bytes_read == byte_size) {
2509 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2510 GetAddressByteSize());
2511 lldb::offset_t offset = 0;
2512 if (byte_size <= 4)
2513 scalar = data.GetMaxU32(&offset, byte_size);
2514 else
2515 scalar = data.GetMaxU64(&offset, byte_size);
2516 if (is_signed)
2517 scalar.SignExtend(byte_size * 8);
2518 return bytes_read;
Greg Clayton7060f892013-05-01 23:41:30 +00002519 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002520 } else {
2521 error.SetErrorStringWithFormat(
2522 "byte size of %u is too large for integer scalar type", byte_size);
2523 }
2524 return 0;
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002525}
2526
Pavel Labath16064d32018-03-20 11:56:24 +00002527Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2528 Status error;
2529 for (const auto &Entry : entries) {
2530 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2531 error);
2532 if (!error.Success())
2533 break;
2534 }
2535 return error;
2536}
2537
Greg Claytond495c532011-05-17 03:37:42 +00002538#define USE_ALLOCATE_MEMORY_CACHE 1
Kate Stoneb9c1b512016-09-06 20:57:50 +00002539addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002540 Status &error) {
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002541 if (GetPrivateState() != eStateStopped) {
2542 error.SetErrorToGenericError();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002543 return LLDB_INVALID_ADDRESS;
Vedant Kumarc1cd8262018-05-30 19:39:10 +00002544 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002545
2546#if defined(USE_ALLOCATE_MEMORY_CACHE)
2547 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
Greg Claytond495c532011-05-17 03:37:42 +00002548#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002549 addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2550 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2551 if (log)
2552 log->Printf("Process::AllocateMemory(size=%" PRIu64
2553 ", permissions=%s) => 0x%16.16" PRIx64
2554 " (m_stop_id = %u m_memory_id = %u)",
2555 (uint64_t)size, GetPermissionsAsCString(permissions),
2556 (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2557 m_mod_id.GetMemoryID());
2558 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002559#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002560}
2561
Kate Stoneb9c1b512016-09-06 20:57:50 +00002562addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +00002563 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002564 addr_t return_addr = AllocateMemory(size, permissions, error);
2565 if (error.Success()) {
2566 std::string buffer(size, 0);
2567 WriteMemory(return_addr, buffer.c_str(), size, error);
2568 }
2569 return return_addr;
2570}
2571
2572bool Process::CanJIT() {
2573 if (m_can_jit == eCanJITDontKnow) {
2574 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Zachary Turner97206d52017-05-12 04:51:55 +00002575 Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002576
2577 uint64_t allocated_memory = AllocateMemory(
2578 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2579 err);
2580
2581 if (err.Success()) {
2582 m_can_jit = eCanJITYes;
2583 if (log)
2584 log->Printf("Process::%s pid %" PRIu64
2585 " allocation test passed, CanJIT () is true",
2586 __FUNCTION__, GetID());
2587 } else {
2588 m_can_jit = eCanJITNo;
2589 if (log)
2590 log->Printf("Process::%s pid %" PRIu64
2591 " allocation test failed, CanJIT () is false: %s",
2592 __FUNCTION__, GetID(), err.AsCString());
Jim Ingham2c381412015-11-04 20:32:27 +00002593 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002594
2595 DeallocateMemory(allocated_memory);
2596 }
2597
2598 return m_can_jit == eCanJITYes;
Jim Ingham2c381412015-11-04 20:32:27 +00002599}
2600
Kate Stoneb9c1b512016-09-06 20:57:50 +00002601void Process::SetCanJIT(bool can_jit) {
2602 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
Sean Callanan90539452011-09-20 23:01:51 +00002603}
2604
Kate Stoneb9c1b512016-09-06 20:57:50 +00002605void Process::SetCanRunCode(bool can_run_code) {
2606 SetCanJIT(can_run_code);
2607 m_can_interpret_function_calls = can_run_code;
Sean Callanan90539452011-09-20 23:01:51 +00002608}
2609
Zachary Turner97206d52017-05-12 04:51:55 +00002610Status Process::DeallocateMemory(addr_t ptr) {
2611 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002612#if defined(USE_ALLOCATE_MEMORY_CACHE)
2613 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2614 error.SetErrorStringWithFormat(
2615 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2616 }
Greg Claytond495c532011-05-17 03:37:42 +00002617#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002618 error = DoDeallocateMemory(ptr);
2619
2620 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2621 if (log)
2622 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64
2623 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2624 ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2625 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002626#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00002627 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002628}
2629
Kate Stoneb9c1b512016-09-06 20:57:50 +00002630ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2631 lldb::addr_t header_addr,
2632 size_t size_to_read) {
2633 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2634 if (log) {
2635 log->Printf("Process::ReadModuleFromMemory reading %s binary from memory",
2636 file_spec.GetPath().c_str());
2637 }
2638 ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2639 if (module_sp) {
Zachary Turner97206d52017-05-12 04:51:55 +00002640 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002641 ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2642 shared_from_this(), header_addr, error, size_to_read);
2643 if (objfile)
2644 return module_sp;
2645 }
2646 return ModuleSP();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002647}
2648
Kate Stoneb9c1b512016-09-06 20:57:50 +00002649bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2650 uint32_t &permissions) {
2651 MemoryRegionInfo range_info;
2652 permissions = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00002653 Status error(GetMemoryRegionInfo(load_addr, range_info));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002654 if (!error.Success())
2655 return false;
2656 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2657 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2658 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2659 return false;
2660 }
2661
2662 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2663 permissions |= lldb::ePermissionsReadable;
2664
2665 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2666 permissions |= lldb::ePermissionsWritable;
2667
2668 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2669 permissions |= lldb::ePermissionsExecutable;
2670
2671 return true;
2672}
2673
Zachary Turner97206d52017-05-12 04:51:55 +00002674Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2675 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002676 error.SetErrorString("watchpoints are not supported");
2677 return error;
2678}
2679
Zachary Turner97206d52017-05-12 04:51:55 +00002680Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2681 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002682 error.SetErrorString("watchpoints are not supported");
2683 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002684}
2685
2686StateType
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002687Process::WaitForProcessStopPrivate(EventSP &event_sp,
2688 const Timeout<std::micro> &timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002689 StateType state;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002690
Kate Stoneb9c1b512016-09-06 20:57:50 +00002691 while (true) {
2692 event_sp.reset();
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002693 state = GetStateChangedEventsPrivate(event_sp, timeout);
Greg Clayton6779606a2011-01-22 23:43:18 +00002694
Kate Stoneb9c1b512016-09-06 20:57:50 +00002695 if (StateIsStoppedState(state, false))
2696 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002697
Kate Stoneb9c1b512016-09-06 20:57:50 +00002698 // If state is invalid, then we timed out
2699 if (state == eStateInvalid)
2700 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002701
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702 if (event_sp)
2703 HandlePrivateEvent(event_sp);
2704 }
2705 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002706}
2707
Kate Stoneb9c1b512016-09-06 20:57:50 +00002708void Process::LoadOperatingSystemPlugin(bool flush) {
2709 if (flush)
2710 m_thread_list.Clear();
2711 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
2712 if (flush)
2713 Flush();
Greg Clayton332e8b12015-01-13 21:13:08 +00002714}
2715
Zachary Turner97206d52017-05-12 04:51:55 +00002716Status Process::Launch(ProcessLaunchInfo &launch_info) {
2717 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 m_abi_sp.reset();
2719 m_dyld_ap.reset();
2720 m_jit_loaders_ap.reset();
2721 m_system_runtime_ap.reset();
2722 m_os_ap.reset();
2723 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724
Kate Stoneb9c1b512016-09-06 20:57:50 +00002725 Module *exe_module = GetTarget().GetExecutableModulePointer();
2726 if (exe_module) {
2727 char local_exec_file_path[PATH_MAX];
2728 char platform_exec_file_path[PATH_MAX];
2729 exe_module->GetFileSpec().GetPath(local_exec_file_path,
2730 sizeof(local_exec_file_path));
2731 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2732 sizeof(platform_exec_file_path));
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00002733 if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 // Install anything that might need to be installed prior to launching.
2735 // For host systems, this will do nothing, but if we are connected to a
2736 // remote platform it will install any needed binaries
2737 error = GetTarget().Install(&launch_info);
2738 if (error.Fail())
2739 return error;
Greg Claytonfbb76342013-11-20 21:07:01 +00002740
Kate Stoneb9c1b512016-09-06 20:57:50 +00002741 if (PrivateStateThreadIsValid())
2742 PausePrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743
Kate Stoneb9c1b512016-09-06 20:57:50 +00002744 error = WillLaunch(exe_module);
2745 if (error.Success()) {
2746 const bool restarted = false;
2747 SetPublicState(eStateLaunching, restarted);
2748 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749
Kate Stoneb9c1b512016-09-06 20:57:50 +00002750 if (m_public_run_lock.TrySetRunning()) {
2751 // Now launch using these arguments.
2752 error = DoLaunch(exe_module, launch_info);
2753 } else {
2754 // This shouldn't happen
2755 error.SetErrorString("failed to acquire process run lock");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002757
Kate Stoneb9c1b512016-09-06 20:57:50 +00002758 if (error.Fail()) {
2759 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2760 SetID(LLDB_INVALID_PROCESS_ID);
2761 const char *error_string = error.AsCString();
2762 if (error_string == nullptr)
2763 error_string = "launch failed";
2764 SetExitStatus(-1, error_string);
2765 }
2766 } else {
2767 EventSP event_sp;
Stella Stamenova36d457c2018-06-01 19:14:53 +00002768
2769 // Now wait for the process to launch and return control to us, and then call
2770 // DidLaunch:
Pavel Labathe3e21cf2016-11-30 11:56:32 +00002771 StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
Greg Clayton35824e32015-02-20 20:59:47 +00002772
Kate Stoneb9c1b512016-09-06 20:57:50 +00002773 if (state == eStateInvalid || !event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00002774 // We were able to launch the process, but we failed to catch the
2775 // initial stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002776 error.SetErrorString("failed to catch stop after launch");
2777 SetExitStatus(0, "failed to catch stop after launch");
2778 Destroy(false);
2779 } else if (state == eStateStopped || state == eStateCrashed) {
2780 DidLaunch();
Greg Claytonc3776bf2012-02-09 06:16:32 +00002781
Kate Stoneb9c1b512016-09-06 20:57:50 +00002782 DynamicLoader *dyld = GetDynamicLoader();
2783 if (dyld)
2784 dyld->DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002785
Kate Stoneb9c1b512016-09-06 20:57:50 +00002786 GetJITLoaders().DidLaunch();
Jason Molendaeef51062013-11-05 03:57:19 +00002787
Kate Stoneb9c1b512016-09-06 20:57:50 +00002788 SystemRuntime *system_runtime = GetSystemRuntime();
2789 if (system_runtime)
2790 system_runtime->DidLaunch();
Greg Clayton35824e32015-02-20 20:59:47 +00002791
Greg Clayton29eeea02017-02-09 18:55:41 +00002792 if (!m_os_ap)
2793 LoadOperatingSystemPlugin(false);
Greg Clayton35824e32015-02-20 20:59:47 +00002794
Adrian Prantl05097242018-04-30 16:49:04 +00002795 // We successfully launched the process and stopped, now it the
2796 // right time to set up signal filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00002797 UpdateAutomaticSignalFiltering();
2798
Kate Stoneb9c1b512016-09-06 20:57:50 +00002799 // Note, the stop event was consumed above, but not handled. This
Adrian Prantl05097242018-04-30 16:49:04 +00002800 // was done to give DidLaunch a chance to run. The target is either
2801 // stopped or crashed. Directly set the state. This is done to
2802 // prevent a stop message with a bunch of spurious output on thread
2803 // status, as well as not pop a ProcessIOHandler.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002804 SetPublicState(state, false);
Greg Claytonc3776bf2012-02-09 06:16:32 +00002805
Kate Stoneb9c1b512016-09-06 20:57:50 +00002806 if (PrivateStateThreadIsValid())
2807 ResumePrivateStateThread();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002808 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 StartPrivateStateThread();
Todd Fiala76e0fc92014-08-27 22:58:26 +00002810
Kate Stoneb9c1b512016-09-06 20:57:50 +00002811 // Target was stopped at entry as was intended. Need to notify the
Adrian Prantl05097242018-04-30 16:49:04 +00002812 // listeners about it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002813 if (state == eStateStopped &&
2814 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2815 HandlePrivateEvent(event_sp);
2816 } else if (state == eStateExited) {
2817 // We exited while trying to launch somehow. Don't call DidLaunch
Adrian Prantl05097242018-04-30 16:49:04 +00002818 // as that's not likely to work, and return an invalid pid.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002819 HandlePrivateEvent(event_sp);
2820 }
2821 }
2822 }
2823 } else {
2824 error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2825 local_exec_file_path);
Jim Inghambb3a2832011-01-29 01:49:25 +00002826 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002827 }
2828 return error;
Jim Inghambb3a2832011-01-29 01:49:25 +00002829}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002830
Zachary Turner97206d52017-05-12 04:51:55 +00002831Status Process::LoadCore() {
2832 Status error = DoLoadCore();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833 if (error.Success()) {
2834 ListenerSP listener_sp(
2835 Listener::MakeListener("lldb.process.load_core_listener"));
2836 HijackProcessEvents(listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002837
Kate Stoneb9c1b512016-09-06 20:57:50 +00002838 if (PrivateStateThreadIsValid())
2839 ResumePrivateStateThread();
Jim Ingham583bbb12016-03-07 21:50:25 +00002840 else
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 StartPrivateStateThread();
Greg Clayton8012cad2014-11-17 19:39:20 +00002842
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843 DynamicLoader *dyld = GetDynamicLoader();
Greg Claytonc859e2d2012-02-13 23:10:39 +00002844 if (dyld)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002845 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002846
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00002847 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002848
Kate Stoneb9c1b512016-09-06 20:57:50 +00002849 SystemRuntime *system_runtime = GetSystemRuntime();
Jason Molendaeef51062013-11-05 03:57:19 +00002850 if (system_runtime)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002851 system_runtime->DidAttach();
Jason Molendaeef51062013-11-05 03:57:19 +00002852
Greg Clayton29eeea02017-02-09 18:55:41 +00002853 if (!m_os_ap)
2854 LoadOperatingSystemPlugin(false);
2855
Kate Stoneb9c1b512016-09-06 20:57:50 +00002856 // We successfully loaded a core file, now pretend we stopped so we can
Adrian Prantl05097242018-04-30 16:49:04 +00002857 // show all of the threads in the core file and explore the crashed state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002858 SetPrivateState(eStateStopped);
Greg Claytona97c4d22014-12-09 23:31:02 +00002859
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002860 // Wait for a stopped event since we just posted one above...
Kate Stoneb9c1b512016-09-06 20:57:50 +00002861 lldb::EventSP event_sp;
Jonas Devlieghere25486b72018-03-14 11:50:10 +00002862 StateType state =
2863 WaitForProcessToStop(seconds(10), &event_sp, true, listener_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002864
2865 if (!StateIsStoppedState(state, false)) {
2866 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2867 if (log)
2868 log->Printf("Process::Halt() failed to stop, state is: %s",
2869 StateAsCString(state));
2870 error.SetErrorString(
2871 "Did not get stopped event after loading the core file.");
2872 }
2873 RestoreProcessEvents();
2874 }
2875 return error;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002876}
2877
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878DynamicLoader *Process::GetDynamicLoader() {
2879 if (!m_dyld_ap)
2880 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
2881 return m_dyld_ap.get();
2882}
2883
2884const lldb::DataBufferSP Process::GetAuxvData() { return DataBufferSP(); }
2885
2886JITLoaderList &Process::GetJITLoaders() {
2887 if (!m_jit_loaders_ap) {
2888 m_jit_loaders_ap.reset(new JITLoaderList());
2889 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
2890 }
2891 return *m_jit_loaders_ap;
2892}
2893
2894SystemRuntime *Process::GetSystemRuntime() {
2895 if (!m_system_runtime_ap)
2896 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
2897 return m_system_runtime_ap.get();
2898}
2899
2900Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2901 uint32_t exec_count)
2902 : NextEventAction(process), m_exec_count(exec_count) {
2903 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2904 if (log)
2905 log->Printf(
2906 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2907 __FUNCTION__, static_cast<void *>(process), exec_count);
2908}
2909
2910Process::NextEventAction::EventActionResult
2911Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2912 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2913
2914 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2915 if (log)
2916 log->Printf(
2917 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2918 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2919
2920 switch (state) {
2921 case eStateAttaching:
2922 return eEventActionSuccess;
2923
2924 case eStateRunning:
2925 case eStateConnected:
2926 return eEventActionRetry;
2927
2928 case eStateStopped:
2929 case eStateCrashed:
2930 // During attach, prior to sending the eStateStopped event,
2931 // lldb_private::Process subclasses must set the new process ID.
2932 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Adrian Prantl05097242018-04-30 16:49:04 +00002933 // We don't want these events to be reported, so go set the
2934 // ShouldReportStop here:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002935 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2936
2937 if (m_exec_count > 0) {
2938 --m_exec_count;
2939
2940 if (log)
2941 log->Printf("Process::AttachCompletionHandler::%s state %s: reduced "
2942 "remaining exec count to %" PRIu32 ", requesting resume",
2943 __FUNCTION__, StateAsCString(state), m_exec_count);
2944
2945 RequestResume();
2946 return eEventActionRetry;
2947 } else {
2948 if (log)
2949 log->Printf("Process::AttachCompletionHandler::%s state %s: no more "
2950 "execs expected to start, continuing with attach",
2951 __FUNCTION__, StateAsCString(state));
2952
2953 m_process->CompleteAttach();
2954 return eEventActionSuccess;
2955 }
2956 break;
2957
2958 default:
2959 case eStateExited:
2960 case eStateInvalid:
2961 break;
2962 }
2963
2964 m_exit_string.assign("No valid Process");
2965 return eEventActionExit;
2966}
2967
2968Process::NextEventAction::EventActionResult
2969Process::AttachCompletionHandler::HandleBeingInterrupted() {
2970 return eEventActionSuccess;
2971}
2972
2973const char *Process::AttachCompletionHandler::GetExitString() {
2974 return m_exit_string.c_str();
2975}
2976
2977ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2978 if (m_listener_sp)
2979 return m_listener_sp;
2980 else
2981 return debugger.GetListener();
2982}
2983
Zachary Turner97206d52017-05-12 04:51:55 +00002984Status Process::Attach(ProcessAttachInfo &attach_info) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002985 m_abi_sp.reset();
2986 m_process_input_reader.reset();
2987 m_dyld_ap.reset();
2988 m_jit_loaders_ap.reset();
2989 m_system_runtime_ap.reset();
2990 m_os_ap.reset();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002991
2992 lldb::pid_t attach_pid = attach_info.GetProcessID();
Zachary Turner97206d52017-05-12 04:51:55 +00002993 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002994 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2995 char process_name[PATH_MAX];
2996
2997 if (attach_info.GetExecutableFile().GetPath(process_name,
2998 sizeof(process_name))) {
2999 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3000
3001 if (wait_for_launch) {
3002 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3003 if (error.Success()) {
3004 if (m_public_run_lock.TrySetRunning()) {
3005 m_should_detach = true;
3006 const bool restarted = false;
3007 SetPublicState(eStateAttaching, restarted);
3008 // Now attach using these arguments.
3009 error = DoAttachToProcessWithName(process_name, attach_info);
3010 } else {
3011 // This shouldn't happen
3012 error.SetErrorString("failed to acquire process run lock");
3013 }
3014
3015 if (error.Fail()) {
3016 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3017 SetID(LLDB_INVALID_PROCESS_ID);
3018 if (error.AsCString() == nullptr)
3019 error.SetErrorString("attach failed");
3020
3021 SetExitStatus(-1, error.AsCString());
3022 }
3023 } else {
3024 SetNextEventAction(new Process::AttachCompletionHandler(
3025 this, attach_info.GetResumeCount()));
3026 StartPrivateStateThread();
3027 }
3028 return error;
3029 }
3030 } else {
3031 ProcessInstanceInfoList process_infos;
3032 PlatformSP platform_sp(GetTarget().GetPlatform());
3033
3034 if (platform_sp) {
3035 ProcessInstanceInfoMatch match_info;
3036 match_info.GetProcessInfo() = attach_info;
Pavel Labathc4a33952017-02-20 11:35:33 +00003037 match_info.SetNameMatchType(NameMatch::Equals);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003038 platform_sp->FindProcesses(match_info, process_infos);
3039 const uint32_t num_matches = process_infos.GetSize();
3040 if (num_matches == 1) {
3041 attach_pid = process_infos.GetProcessIDAtIndex(0);
3042 // Fall through and attach using the above process ID
3043 } else {
3044 match_info.GetProcessInfo().GetExecutableFile().GetPath(
3045 process_name, sizeof(process_name));
3046 if (num_matches > 1) {
3047 StreamString s;
3048 ProcessInstanceInfo::DumpTableHeader(s, platform_sp.get(), true,
3049 false);
3050 for (size_t i = 0; i < num_matches; i++) {
3051 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
3052 s, platform_sp.get(), true, false);
3053 }
3054 error.SetErrorStringWithFormat(
3055 "more than one process named %s:\n%s", process_name,
3056 s.GetData());
3057 } else
3058 error.SetErrorStringWithFormat(
3059 "could not find a process named %s", process_name);
3060 }
3061 } else {
3062 error.SetErrorString(
3063 "invalid platform, can't find processes by name");
3064 return error;
3065 }
3066 }
3067 } else {
3068 error.SetErrorString("invalid process name");
3069 }
3070 }
3071
3072 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3073 error = WillAttachToProcessWithID(attach_pid);
3074 if (error.Success()) {
3075
3076 if (m_public_run_lock.TrySetRunning()) {
3077 // Now attach using these arguments.
3078 m_should_detach = true;
3079 const bool restarted = false;
3080 SetPublicState(eStateAttaching, restarted);
3081 error = DoAttachToProcessWithID(attach_pid, attach_info);
3082 } else {
3083 // This shouldn't happen
3084 error.SetErrorString("failed to acquire process run lock");
3085 }
3086
3087 if (error.Success()) {
3088 SetNextEventAction(new Process::AttachCompletionHandler(
3089 this, attach_info.GetResumeCount()));
3090 StartPrivateStateThread();
3091 } else {
Greg Clayton71337622011-02-24 22:24:29 +00003092 if (GetID() != LLDB_INVALID_PROCESS_ID)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003093 SetID(LLDB_INVALID_PROCESS_ID);
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003094
Kate Stoneb9c1b512016-09-06 20:57:50 +00003095 const char *error_string = error.AsCString();
3096 if (error_string == nullptr)
3097 error_string = "attach failed";
Greg Clayton32e0a752011-03-30 18:16:51 +00003098
Kate Stoneb9c1b512016-09-06 20:57:50 +00003099 SetExitStatus(-1, error_string);
3100 }
Greg Claytonb766a732011-02-04 01:58:07 +00003101 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003102 }
3103 return error;
Greg Claytonb766a732011-02-04 01:58:07 +00003104}
3105
Kate Stoneb9c1b512016-09-06 20:57:50 +00003106void Process::CompleteAttach() {
3107 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3108 LIBLLDB_LOG_TARGET));
3109 if (log)
3110 log->Printf("Process::%s()", __FUNCTION__);
3111
3112 // Let the process subclass figure out at much as it can about the process
3113 // before we go looking for a dynamic loader plug-in.
3114 ArchSpec process_arch;
3115 DidAttach(process_arch);
3116
3117 if (process_arch.IsValid()) {
3118 GetTarget().SetArchitecture(process_arch);
3119 if (log) {
3120 const char *triple_str = process_arch.GetTriple().getTriple().c_str();
3121 log->Printf("Process::%s replacing process architecture with DidAttach() "
3122 "architecture: %s",
3123 __FUNCTION__, triple_str ? triple_str : "<null>");
3124 }
3125 }
3126
3127 // We just attached. If we have a platform, ask it for the process
Adrian Prantl05097242018-04-30 16:49:04 +00003128 // architecture, and if it isn't the same as the one we've already set,
3129 // switch architectures.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130 PlatformSP platform_sp(GetTarget().GetPlatform());
3131 assert(platform_sp);
3132 if (platform_sp) {
3133 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3134 if (target_arch.IsValid() &&
3135 !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
3136 ArchSpec platform_arch;
3137 platform_sp =
3138 platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
3139 if (platform_sp) {
3140 GetTarget().SetPlatform(platform_sp);
3141 GetTarget().SetArchitecture(platform_arch);
3142 if (log)
3143 log->Printf("Process::%s switching platform to %s and architecture "
3144 "to %s based on info from attach",
3145 __FUNCTION__, platform_sp->GetName().AsCString(""),
3146 platform_arch.GetTriple().getTriple().c_str());
3147 }
3148 } else if (!process_arch.IsValid()) {
3149 ProcessInstanceInfo process_info;
3150 GetProcessInfo(process_info);
3151 const ArchSpec &process_arch = process_info.GetArchitecture();
3152 if (process_arch.IsValid() &&
3153 !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
3154 GetTarget().SetArchitecture(process_arch);
3155 if (log)
3156 log->Printf("Process::%s switching architecture to %s based on info "
3157 "the platform retrieved for pid %" PRIu64,
3158 __FUNCTION__,
3159 process_arch.GetTriple().getTriple().c_str(), GetID());
3160 }
3161 }
3162 }
3163
3164 // We have completed the attach, now it is time to find the dynamic loader
3165 // plug-in
3166 DynamicLoader *dyld = GetDynamicLoader();
3167 if (dyld) {
3168 dyld->DidAttach();
3169 if (log) {
3170 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3171 log->Printf("Process::%s after DynamicLoader::DidAttach(), target "
3172 "executable is %s (using %s plugin)",
3173 __FUNCTION__,
3174 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3175 : "<none>",
3176 dyld->GetPluginName().AsCString("<unnamed>"));
3177 }
3178 }
3179
3180 GetJITLoaders().DidAttach();
3181
3182 SystemRuntime *system_runtime = GetSystemRuntime();
3183 if (system_runtime) {
3184 system_runtime->DidAttach();
3185 if (log) {
3186 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3187 log->Printf("Process::%s after SystemRuntime::DidAttach(), target "
3188 "executable is %s (using %s plugin)",
3189 __FUNCTION__,
3190 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3191 : "<none>",
3192 system_runtime->GetPluginName().AsCString("<unnamed>"));
3193 }
3194 }
3195
Greg Clayton29eeea02017-02-09 18:55:41 +00003196 if (!m_os_ap)
3197 LoadOperatingSystemPlugin(false);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003198 // Figure out which one is the executable, and set that in our target:
3199 const ModuleList &target_modules = GetTarget().GetImages();
3200 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3201 size_t num_modules = target_modules.GetSize();
3202 ModuleSP new_executable_module_sp;
3203
3204 for (size_t i = 0; i < num_modules; i++) {
3205 ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3206 if (module_sp && module_sp->IsExecutable()) {
3207 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3208 new_executable_module_sp = module_sp;
3209 break;
3210 }
3211 }
3212 if (new_executable_module_sp) {
Jonas Devliegheref9a07e92018-09-20 09:09:05 +00003213 GetTarget().SetExecutableModule(new_executable_module_sp,
3214 eLoadDependentsNo);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003215 if (log) {
3216 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3217 log->Printf(
3218 "Process::%s after looping through modules, target executable is %s",
3219 __FUNCTION__,
3220 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3221 : "<none>");
3222 }
3223 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003224}
3225
Zachary Turner97206d52017-05-12 04:51:55 +00003226Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003227 m_abi_sp.reset();
3228 m_process_input_reader.reset();
3229
3230 // Find the process and its architecture. Make sure it matches the
Zachary Turner31659452016-11-17 21:15:14 +00003231 // architecture of the current Target, and if not adjust it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003232
Zachary Turner97206d52017-05-12 04:51:55 +00003233 Status error(DoConnectRemote(strm, remote_url));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003234 if (error.Success()) {
3235 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3236 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003237 StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003238
3239 if (state == eStateStopped || state == eStateCrashed) {
3240 // If we attached and actually have a process on the other end, then
3241 // this ended up being the equivalent of an attach.
3242 CompleteAttach();
3243
3244 // This delays passing the stopped event to listeners till
3245 // CompleteAttach gets a chance to complete...
3246 HandlePrivateEvent(event_sp);
3247 }
3248 }
3249
3250 if (PrivateStateThreadIsValid())
3251 ResumePrivateStateThread();
3252 else
3253 StartPrivateStateThread();
3254 }
3255 return error;
3256}
3257
Zachary Turner97206d52017-05-12 04:51:55 +00003258Status Process::PrivateResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003259 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3260 LIBLLDB_LOG_STEP));
3261 if (log)
3262 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s "
3263 "private state: %s",
3264 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3265 StateAsCString(m_private_state.GetValue()));
3266
Adrian Prantl05097242018-04-30 16:49:04 +00003267 // If signals handing status changed we might want to update our signal
3268 // filters before resuming.
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00003269 UpdateAutomaticSignalFiltering();
3270
Zachary Turner97206d52017-05-12 04:51:55 +00003271 Status error(WillResume());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003272 // Tell the process it is about to resume before the thread list
3273 if (error.Success()) {
Adrian Prantl05097242018-04-30 16:49:04 +00003274 // Now let the thread list know we are about to resume so it can let all of
3275 // our threads know that they are about to be resumed. Threads will each be
3276 // called with Thread::WillResume(StateType) where StateType contains the
3277 // state that they are supposed to have when the process is resumed
3278 // (suspended/running/stepping). Threads should also check their resume
3279 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3280 // start back up with a signal.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003281 if (m_thread_list.WillResume()) {
3282 // Last thing, do the PreResumeActions.
3283 if (!RunPreResumeActions()) {
3284 error.SetErrorStringWithFormat(
3285 "Process::PrivateResume PreResumeActions failed, not resuming.");
3286 } else {
3287 m_mod_id.BumpResumeID();
3288 error = DoResume();
3289 if (error.Success()) {
3290 DidResume();
3291 m_thread_list.DidResume();
3292 if (log)
3293 log->Printf("Process thinks the process has resumed.");
3294 }
3295 }
3296 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00003297 // Somebody wanted to run without running (e.g. we were faking a step
3298 // from one frame of a set of inlined frames that share the same PC to
3299 // another.) So generate a continue & a stopped event, and let the world
3300 // handle them.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003301 if (log)
3302 log->Printf(
3303 "Process::PrivateResume() asked to simulate a start & stop.");
3304
3305 SetPrivateState(eStateRunning);
3306 SetPrivateState(eStateStopped);
3307 }
3308 } else if (log)
3309 log->Printf("Process::PrivateResume() got an error \"%s\".",
3310 error.AsCString("<unknown error>"));
3311 return error;
3312}
3313
Zachary Turner97206d52017-05-12 04:51:55 +00003314Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003315 if (!StateIsRunningState(m_public_state.GetValue()))
Zachary Turner97206d52017-05-12 04:51:55 +00003316 return Status("Process is not running.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00003317
Adrian Prantl05097242018-04-30 16:49:04 +00003318 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3319 // case it was already set and some thread plan logic calls halt on its own.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003320 m_clear_thread_plans_on_stop |= clear_thread_plans;
3321
3322 ListenerSP halt_listener_sp(
3323 Listener::MakeListener("lldb.process.halt_listener"));
3324 HijackProcessEvents(halt_listener_sp);
3325
3326 EventSP event_sp;
3327
3328 SendAsyncInterrupt();
3329
3330 if (m_public_state.GetValue() == eStateAttaching) {
Adrian Prantl05097242018-04-30 16:49:04 +00003331 // Don't hijack and eat the eStateExited as the code that was doing the
3332 // attach will be waiting for this event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003333 RestoreProcessEvents();
3334 SetExitStatus(SIGKILL, "Cancelled async attach.");
3335 Destroy(false);
Zachary Turner97206d52017-05-12 04:51:55 +00003336 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003337 }
3338
3339 // Wait for 10 second for the process to stop.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003340 StateType state = WaitForProcessToStop(
3341 seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003342 RestoreProcessEvents();
3343
3344 if (state == eStateInvalid || !event_sp) {
3345 // We timed out and didn't get a stop event...
Zachary Turner97206d52017-05-12 04:51:55 +00003346 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003347 }
3348
3349 BroadcastEvent(event_sp);
3350
Zachary Turner97206d52017-05-12 04:51:55 +00003351 return Status();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003352}
3353
Zachary Turner97206d52017-05-12 04:51:55 +00003354Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3355 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003356
3357 // Check both the public & private states here. If we're hung evaluating an
Adrian Prantl05097242018-04-30 16:49:04 +00003358 // expression, for instance, then the public state will be stopped, but we
3359 // still need to interrupt.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003360 if (m_public_state.GetValue() == eStateRunning ||
3361 m_private_state.GetValue() == eStateRunning) {
3362 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003363 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00003364 log->Printf("Process::%s() About to stop.", __FUNCTION__);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365
Kate Stoneb9c1b512016-09-06 20:57:50 +00003366 ListenerSP listener_sp(
3367 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3368 HijackProcessEvents(listener_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003369
Pavel Labath19da1f12015-12-07 12:36:52 +00003370 SendAsyncInterrupt();
3371
Kate Stoneb9c1b512016-09-06 20:57:50 +00003372 // Consume the interrupt event.
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003373 StateType state =
3374 WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003375
Pavel Labath19da1f12015-12-07 12:36:52 +00003376 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003377
Kate Stoneb9c1b512016-09-06 20:57:50 +00003378 // If the process exited while we were waiting for it to stop, put the
Adrian Prantl05097242018-04-30 16:49:04 +00003379 // exited event into the shared pointer passed in and return. Our caller
3380 // doesn't need to do anything else, since they don't have a process
3381 // anymore...
Kate Stoneb9c1b512016-09-06 20:57:50 +00003382
3383 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3384 if (log)
3385 log->Printf("Process::%s() Process exited while waiting to stop.",
3386 __FUNCTION__);
3387 return error;
3388 } else
3389 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3390
3391 if (state != eStateStopped) {
3392 if (log)
3393 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__,
3394 StateAsCString(state));
3395 // If we really couldn't stop the process then we should just error out
Adrian Prantl05097242018-04-30 16:49:04 +00003396 // here, but if the lower levels just bobbled sending the event and we
3397 // really are stopped, then continue on.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003398 StateType private_state = m_private_state.GetValue();
3399 if (private_state != eStateStopped) {
Zachary Turner97206d52017-05-12 04:51:55 +00003400 return Status(
3401 "Attempt to stop the target in order to detach timed out. "
3402 "State = %s",
3403 StateAsCString(GetState()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003404 }
3405 }
3406 }
3407 return error;
3408}
3409
Zachary Turner97206d52017-05-12 04:51:55 +00003410Status Process::Detach(bool keep_stopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003411 EventSP exit_event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003412 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003413 m_destroy_in_process = true;
3414
3415 error = WillDetach();
3416
3417 if (error.Success()) {
3418 if (DetachRequiresHalt()) {
3419 error = StopForDestroyOrDetach(exit_event_sp);
3420 if (!error.Success()) {
3421 m_destroy_in_process = false;
3422 return error;
3423 } else if (exit_event_sp) {
3424 // We shouldn't need to do anything else here. There's no process left
3425 // to detach from...
3426 StopPrivateStateThread();
3427 m_destroy_in_process = false;
3428 return error;
3429 }
3430 }
3431
3432 m_thread_list.DiscardThreadPlans();
3433 DisableAllBreakpointSites();
3434
3435 error = DoDetach(keep_stopped);
3436 if (error.Success()) {
3437 DidDetach();
3438 StopPrivateStateThread();
3439 } else {
3440 return error;
3441 }
3442 }
3443 m_destroy_in_process = false;
3444
Adrian Prantl05097242018-04-30 16:49:04 +00003445 // If we exited when we were waiting for a process to stop, then forward the
3446 // event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003447 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003448 // Directly broadcast our exited event because we shut down our private
3449 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003450 BroadcastEvent(exit_event_sp);
3451 }
3452
3453 // If we have been interrupted (to kill us) in the middle of running, we may
Adrian Prantl05097242018-04-30 16:49:04 +00003454 // not end up propagating the last events through the event system, in which
3455 // case we might strand the write lock. Unlock it here so when we do to tear
3456 // down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003457
3458 m_public_run_lock.SetStopped();
3459 return error;
3460}
3461
Zachary Turner97206d52017-05-12 04:51:55 +00003462Status Process::Destroy(bool force_kill) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003463
3464 // Tell ourselves we are in the process of destroying the process, so that we
Adrian Prantl05097242018-04-30 16:49:04 +00003465 // don't do any unnecessary work that might hinder the destruction. Remember
3466 // to set this back to false when we are done. That way if the attempt
Kate Stoneb9c1b512016-09-06 20:57:50 +00003467 // failed and the process stays around for some reason it won't be in a
3468 // confused state.
3469
3470 if (force_kill)
3471 m_should_detach = false;
3472
3473 if (GetShouldDetach()) {
3474 // FIXME: This will have to be a process setting:
3475 bool keep_stopped = false;
3476 Detach(keep_stopped);
3477 }
3478
3479 m_destroy_in_process = true;
3480
Zachary Turner97206d52017-05-12 04:51:55 +00003481 Status error(WillDestroy());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003482 if (error.Success()) {
3483 EventSP exit_event_sp;
3484 if (DestroyRequiresHalt()) {
3485 error = StopForDestroyOrDetach(exit_event_sp);
3486 }
3487
3488 if (m_public_state.GetValue() != eStateRunning) {
Adrian Prantl05097242018-04-30 16:49:04 +00003489 // Ditch all thread plans, and remove all our breakpoints: in case we
3490 // have to restart the target to kill it, we don't want it hitting a
3491 // breakpoint... Only do this if we've stopped, however, since if we
3492 // didn't manage to halt it above, then we're not going to have much luck
3493 // doing this now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003494 m_thread_list.DiscardThreadPlans();
3495 DisableAllBreakpointSites();
3496 }
3497
3498 error = DoDestroy();
3499 if (error.Success()) {
3500 DidDestroy();
3501 StopPrivateStateThread();
3502 }
3503 m_stdio_communication.Disconnect();
3504 m_stdio_communication.StopReadThread();
3505 m_stdin_forward = false;
3506
3507 if (m_process_input_reader) {
3508 m_process_input_reader->SetIsDone(true);
3509 m_process_input_reader->Cancel();
3510 m_process_input_reader.reset();
3511 }
3512
Adrian Prantl05097242018-04-30 16:49:04 +00003513 // If we exited when we were waiting for a process to stop, then forward
3514 // the event here so we don't lose the event
Kate Stoneb9c1b512016-09-06 20:57:50 +00003515 if (exit_event_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00003516 // Directly broadcast our exited event because we shut down our private
3517 // state thread above
Kate Stoneb9c1b512016-09-06 20:57:50 +00003518 BroadcastEvent(exit_event_sp);
3519 }
3520
Adrian Prantl05097242018-04-30 16:49:04 +00003521 // If we have been interrupted (to kill us) in the middle of running, we
3522 // may not end up propagating the last events through the event system, in
3523 // which case we might strand the write lock. Unlock it here so when we do
3524 // to tear down the process we don't get an error destroying the lock.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003525 m_public_run_lock.SetStopped();
3526 }
3527
3528 m_destroy_in_process = false;
3529
3530 return error;
3531}
3532
Zachary Turner97206d52017-05-12 04:51:55 +00003533Status Process::Signal(int signal) {
3534 Status error(WillSignal());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003535 if (error.Success()) {
3536 error = DoSignal(signal);
3537 if (error.Success())
3538 DidSignal();
3539 }
3540 return error;
3541}
3542
3543void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3544 assert(signals_sp && "null signals_sp");
3545 m_unix_signals_sp = signals_sp;
3546}
3547
3548const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3549 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3550 return m_unix_signals_sp;
3551}
3552
3553lldb::ByteOrder Process::GetByteOrder() const {
3554 return GetTarget().GetArchitecture().GetByteOrder();
3555}
3556
3557uint32_t Process::GetAddressByteSize() const {
3558 return GetTarget().GetArchitecture().GetAddressByteSize();
3559}
3560
3561bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3562 const StateType state =
3563 Process::ProcessEventData::GetStateFromEvent(event_ptr);
3564 bool return_value = true;
3565 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3566 LIBLLDB_LOG_PROCESS));
3567
3568 switch (state) {
3569 case eStateDetached:
3570 case eStateExited:
3571 case eStateUnloaded:
3572 m_stdio_communication.SynchronizeWithReadThread();
3573 m_stdio_communication.Disconnect();
3574 m_stdio_communication.StopReadThread();
3575 m_stdin_forward = false;
3576
3577 LLVM_FALLTHROUGH;
3578 case eStateConnected:
3579 case eStateAttaching:
3580 case eStateLaunching:
3581 // These events indicate changes in the state of the debugging session,
3582 // always report them.
3583 return_value = true;
3584 break;
3585 case eStateInvalid:
3586 // We stopped for no apparent reason, don't report it.
3587 return_value = false;
3588 break;
3589 case eStateRunning:
3590 case eStateStepping:
Adrian Prantl05097242018-04-30 16:49:04 +00003591 // If we've started the target running, we handle the cases where we are
3592 // already running and where there is a transition from stopped to running
3593 // differently. running -> running: Automatically suppress extra running
3594 // events stopped -> running: Report except when there is one or more no
3595 // votes
Kate Stoneb9c1b512016-09-06 20:57:50 +00003596 // and no yes votes.
3597 SynchronouslyNotifyStateChanged(state);
3598 if (m_force_next_event_delivery)
3599 return_value = true;
3600 else {
3601 switch (m_last_broadcast_state) {
3602 case eStateRunning:
3603 case eStateStepping:
3604 // We always suppress multiple runnings with no PUBLIC stop in between.
3605 return_value = false;
3606 break;
3607 default:
3608 // TODO: make this work correctly. For now always report
Adrian Prantl05097242018-04-30 16:49:04 +00003609 // run if we aren't running so we don't miss any running events. If I
3610 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3611 // and hit the breakpoints on multiple threads, then somehow during the
3612 // stepping over of all breakpoints no run gets reported.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003613
3614 // This is a transition from stop to run.
3615 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3616 case eVoteYes:
3617 case eVoteNoOpinion:
3618 return_value = true;
3619 break;
3620 case eVoteNo:
3621 return_value = false;
3622 break;
3623 }
3624 break;
3625 }
3626 }
3627 break;
3628 case eStateStopped:
3629 case eStateCrashed:
3630 case eStateSuspended:
Adrian Prantl05097242018-04-30 16:49:04 +00003631 // We've stopped. First see if we're going to restart the target. If we
3632 // are going to stop, then we always broadcast the event. If we aren't
3633 // going to stop, let the thread plans decide if we're going to report this
3634 // event. If no thread has an opinion, we don't report it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003635
3636 m_stdio_communication.SynchronizeWithReadThread();
3637 RefreshStateAfterStop();
3638 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3639 if (log)
3640 log->Printf("Process::ShouldBroadcastEvent (%p) stopped due to an "
3641 "interrupt, state: %s",
3642 static_cast<void *>(event_ptr), StateAsCString(state));
3643 // Even though we know we are going to stop, we should let the threads
Adrian Prantl05097242018-04-30 16:49:04 +00003644 // have a look at the stop, so they can properly set their state.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003645 m_thread_list.ShouldStop(event_ptr);
3646 return_value = true;
3647 } else {
3648 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3649 bool should_resume = false;
3650
3651 // It makes no sense to ask "ShouldStop" if we've already been
Adrian Prantl05097242018-04-30 16:49:04 +00003652 // restarted... Asking the thread list is also not likely to go well,
3653 // since we are running again. So in that case just report the event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003654
3655 if (!was_restarted)
3656 should_resume = !m_thread_list.ShouldStop(event_ptr);
3657
3658 if (was_restarted || should_resume || m_resume_requested) {
3659 Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3660 if (log)
3661 log->Printf("Process::ShouldBroadcastEvent: should_resume: %i state: "
3662 "%s was_restarted: %i stop_vote: %d.",
3663 should_resume, StateAsCString(state), was_restarted,
3664 stop_vote);
3665
3666 switch (stop_vote) {
3667 case eVoteYes:
3668 return_value = true;
3669 break;
3670 case eVoteNoOpinion:
3671 case eVoteNo:
3672 return_value = false;
3673 break;
3674 }
3675
3676 if (!was_restarted) {
3677 if (log)
3678 log->Printf("Process::ShouldBroadcastEvent (%p) Restarting process "
3679 "from state: %s",
3680 static_cast<void *>(event_ptr), StateAsCString(state));
3681 ProcessEventData::SetRestartedInEvent(event_ptr, true);
3682 PrivateResume();
3683 }
3684 } else {
3685 return_value = true;
3686 SynchronouslyNotifyStateChanged(state);
3687 }
3688 }
3689 break;
3690 }
3691
3692 // Forcing the next event delivery is a one shot deal. So reset it here.
3693 m_force_next_event_delivery = false;
3694
3695 // We do some coalescing of events (for instance two consecutive running
Adrian Prantl05097242018-04-30 16:49:04 +00003696 // events get coalesced.) But we only coalesce against events we actually
3697 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3698 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3699 // done, because the PublicState reflects the last event pulled off the
3700 // queue, and there may be several events stacked up on the queue unserviced.
3701 // So the PublicState may not reflect the last broadcasted event yet.
3702 // m_last_broadcast_state gets updated here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003703
3704 if (return_value)
3705 m_last_broadcast_state = state;
3706
3707 if (log)
3708 log->Printf("Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3709 "broadcast state: %s - %s",
3710 static_cast<void *>(event_ptr), StateAsCString(state),
3711 StateAsCString(m_last_broadcast_state),
3712 return_value ? "YES" : "NO");
3713 return return_value;
3714}
3715
3716bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3717 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3718
3719 bool already_running = PrivateStateThreadIsValid();
3720 if (log)
3721 log->Printf("Process::%s()%s ", __FUNCTION__,
3722 already_running ? " already running"
3723 : " starting private state thread");
3724
3725 if (!is_secondary_thread && already_running)
3726 return true;
3727
Adrian Prantl05097242018-04-30 16:49:04 +00003728 // Create a thread that watches our internal state and controls which events
3729 // make it to clients (into the DCProcess event queue).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003730 char thread_name[1024];
Zachary Turner777de772017-03-04 16:42:25 +00003731 uint32_t max_len = llvm::get_max_thread_name_length();
3732 if (max_len > 0 && max_len <= 30) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003733 // On platforms with abbreviated thread name lengths, choose thread names
3734 // that fit within the limit.
3735 if (already_running)
3736 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3737 else
3738 snprintf(thread_name, sizeof(thread_name), "intern-state");
3739 } else {
3740 if (already_running)
3741 snprintf(thread_name, sizeof(thread_name),
3742 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3743 GetID());
3744 else
3745 snprintf(thread_name, sizeof(thread_name),
3746 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3747 }
3748
3749 // Create the private state thread, and start it running.
3750 PrivateStateThreadArgs *args_ptr =
3751 new PrivateStateThreadArgs(this, is_secondary_thread);
3752 m_private_state_thread =
3753 ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3754 (void *)args_ptr, nullptr, 8 * 1024 * 1024);
3755 if (m_private_state_thread.IsJoinable()) {
3756 ResumePrivateStateThread();
3757 return true;
3758 } else
3759 return false;
3760}
3761
3762void Process::PausePrivateStateThread() {
3763 ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3764}
3765
3766void Process::ResumePrivateStateThread() {
3767 ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3768}
3769
3770void Process::StopPrivateStateThread() {
3771 if (m_private_state_thread.IsJoinable())
3772 ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3773 else {
3774 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3775 if (log)
3776 log->Printf(
3777 "Went to stop the private state thread, but it was already invalid.");
3778 }
3779}
3780
3781void Process::ControlPrivateStateThread(uint32_t signal) {
3782 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3783
3784 assert(signal == eBroadcastInternalStateControlStop ||
3785 signal == eBroadcastInternalStateControlPause ||
3786 signal == eBroadcastInternalStateControlResume);
3787
3788 if (log)
3789 log->Printf("Process::%s (signal = %d)", __FUNCTION__, signal);
3790
3791 // Signal the private state thread
3792 if (m_private_state_thread.IsJoinable()) {
3793 // Broadcast the event.
Adrian Prantl05097242018-04-30 16:49:04 +00003794 // It is important to do this outside of the if below, because it's
3795 // possible that the thread state is invalid but that the thread is waiting
3796 // on a control event instead of simply being on its way out (this should
3797 // not happen, but it apparently can).
Kate Stoneb9c1b512016-09-06 20:57:50 +00003798 if (log)
3799 log->Printf("Sending control event of type: %d.", signal);
3800 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3801 m_private_state_control_broadcaster.BroadcastEvent(signal,
3802 event_receipt_sp);
3803
3804 // Wait for the event receipt or for the private state thread to exit
3805 bool receipt_received = false;
3806 if (PrivateStateThreadIsValid()) {
3807 while (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003808 // Check for a receipt for 2 seconds and then check if the private
3809 // state thread is still around.
Pavel Labath38d67db2018-05-03 15:33:41 +00003810 receipt_received =
3811 event_receipt_sp->WaitForEventReceived(std::chrono::seconds(2));
Kate Stoneb9c1b512016-09-06 20:57:50 +00003812 if (!receipt_received) {
Adrian Prantl05097242018-04-30 16:49:04 +00003813 // Check if the private state thread is still around. If it isn't
3814 // then we are done waiting
Kate Stoneb9c1b512016-09-06 20:57:50 +00003815 if (!PrivateStateThreadIsValid())
3816 break; // Private state thread exited or is exiting, we are done
3817 }
3818 }
3819 }
3820
3821 if (signal == eBroadcastInternalStateControlStop) {
3822 thread_result_t result = NULL;
3823 m_private_state_thread.Join(&result);
3824 m_private_state_thread.Reset();
3825 }
3826 } else {
3827 if (log)
3828 log->Printf(
3829 "Private state thread already dead, no need to signal it to stop.");
3830 }
3831}
3832
3833void Process::SendAsyncInterrupt() {
3834 if (PrivateStateThreadIsValid())
3835 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3836 nullptr);
3837 else
3838 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3839}
3840
3841void Process::HandlePrivateEvent(EventSP &event_sp) {
3842 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3843 m_resume_requested = false;
3844
3845 const StateType new_state =
3846 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3847
3848 // First check to see if anybody wants a shot at this event:
3849 if (m_next_event_action_ap) {
3850 NextEventAction::EventActionResult action_result =
3851 m_next_event_action_ap->PerformAction(event_sp);
3852 if (log)
3853 log->Printf("Ran next event action, result was %d.", action_result);
3854
3855 switch (action_result) {
3856 case NextEventAction::eEventActionSuccess:
3857 SetNextEventAction(nullptr);
3858 break;
3859
3860 case NextEventAction::eEventActionRetry:
3861 break;
3862
3863 case NextEventAction::eEventActionExit:
Adrian Prantl05097242018-04-30 16:49:04 +00003864 // Handle Exiting Here. If we already got an exited event, we should
3865 // just propagate it. Otherwise, swallow this event, and set our state
3866 // to exit so the next event will kill us.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003867 if (new_state != eStateExited) {
3868 // FIXME: should cons up an exited event, and discard this one.
3869 SetExitStatus(0, m_next_event_action_ap->GetExitString());
3870 SetNextEventAction(nullptr);
3871 return;
3872 }
3873 SetNextEventAction(nullptr);
3874 break;
3875 }
3876 }
3877
3878 // See if we should broadcast this state to external clients?
3879 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3880
3881 if (should_broadcast) {
3882 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3883 if (log) {
3884 log->Printf("Process::%s (pid = %" PRIu64
3885 ") broadcasting new state %s (old state %s) to %s",
3886 __FUNCTION__, GetID(), StateAsCString(new_state),
3887 StateAsCString(GetState()),
3888 is_hijacked ? "hijacked" : "public");
3889 }
3890 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3891 if (StateIsRunningState(new_state)) {
Adrian Prantl05097242018-04-30 16:49:04 +00003892 // Only push the input handler if we aren't fowarding events, as this
3893 // means the curses GUI is in use... Or don't push it if we are launching
3894 // since it will come up stopped.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003895 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3896 new_state != eStateLaunching && new_state != eStateAttaching) {
3897 PushProcessIOHandler();
3898 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3899 eBroadcastAlways);
3900 if (log)
3901 log->Printf("Process::%s updated m_iohandler_sync to %d",
3902 __FUNCTION__, m_iohandler_sync.GetValue());
3903 }
3904 } else if (StateIsStoppedState(new_state, false)) {
3905 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
Adrian Prantl05097242018-04-30 16:49:04 +00003906 // If the lldb_private::Debugger is handling the events, we don't want
3907 // to pop the process IOHandler here, we want to do it when we receive
3908 // the stopped event so we can carefully control when the process
3909 // IOHandler is popped because when we stop we want to display some
3910 // text stating how and why we stopped, then maybe some
3911 // process/thread/frame info, and then we want the "(lldb) " prompt to
3912 // show up. If we pop the process IOHandler here, then we will cause
3913 // the command interpreter to become the top IOHandler after the
3914 // process pops off and it will update its prompt right away... See the
3915 // Debugger.cpp file where it calls the function as
Kate Stoneb9c1b512016-09-06 20:57:50 +00003916 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3917 // Otherwise we end up getting overlapping "(lldb) " prompts and
3918 // garbled output.
3919 //
3920 // If we aren't handling the events in the debugger (which is indicated
Adrian Prantl05097242018-04-30 16:49:04 +00003921 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3922 // we are hijacked, then we always pop the process IO handler manually.
Kate Stoneb9c1b512016-09-06 20:57:50 +00003923 // Hijacking happens when the internal process state thread is running
Adrian Prantl05097242018-04-30 16:49:04 +00003924 // thread plans, or when commands want to run in synchronous mode and
3925 // they call "process->WaitForProcessToStop()". An example of something
Kate Stoneb9c1b512016-09-06 20:57:50 +00003926 // that will hijack the events is a simple expression:
3927 //
3928 // (lldb) expr (int)puts("hello")
3929 //
3930 // This will cause the internal process state thread to resume and halt
3931 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3932 // events) and we do need the IO handler to be pushed and popped
3933 // correctly.
3934
3935 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3936 PopProcessIOHandler();
3937 }
Pavel Labath19da1f12015-12-07 12:36:52 +00003938 }
3939
3940 BroadcastEvent(event_sp);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003941 } else {
3942 if (log) {
3943 log->Printf(
3944 "Process::%s (pid = %" PRIu64
3945 ") suppressing state %s (old state %s): should_broadcast == false",
3946 __FUNCTION__, GetID(), StateAsCString(new_state),
3947 StateAsCString(GetState()));
3948 }
3949 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003950}
3951
Zachary Turner97206d52017-05-12 04:51:55 +00003952Status Process::HaltPrivate() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003953 EventSP event_sp;
Zachary Turner97206d52017-05-12 04:51:55 +00003954 Status error(WillHalt());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003955 if (error.Fail())
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003956 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003957
3958 // Ask the process subclass to actually halt our process
3959 bool caused_stop;
3960 error = DoHalt(caused_stop);
3961
3962 DidHalt();
3963 return error;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003964}
3965
Kate Stoneb9c1b512016-09-06 20:57:50 +00003966thread_result_t Process::PrivateStateThread(void *arg) {
3967 std::unique_ptr<PrivateStateThreadArgs> args_up(
3968 static_cast<PrivateStateThreadArgs *>(arg));
3969 thread_result_t result =
3970 args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3971 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003972}
3973
Kate Stoneb9c1b512016-09-06 20:57:50 +00003974thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3975 bool control_only = true;
Pavel Labath19da1f12015-12-07 12:36:52 +00003976
Kate Stoneb9c1b512016-09-06 20:57:50 +00003977 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3978 if (log)
3979 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3980 __FUNCTION__, static_cast<void *>(this), GetID());
Jason Molendaede31932015-04-17 05:01:58 +00003981
Kate Stoneb9c1b512016-09-06 20:57:50 +00003982 bool exit_now = false;
3983 bool interrupt_requested = false;
3984 while (!exit_now) {
Pavel Labath19da1f12015-12-07 12:36:52 +00003985 EventSP event_sp;
Pavel Labathe3e21cf2016-11-30 11:56:32 +00003986 GetEventsPrivate(event_sp, llvm::None, control_only);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003987 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3988 if (log)
3989 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
3990 ") got a control event: %d",
3991 __FUNCTION__, static_cast<void *>(this), GetID(),
3992 event_sp->GetType());
Pavel Labath19da1f12015-12-07 12:36:52 +00003993
Kate Stoneb9c1b512016-09-06 20:57:50 +00003994 switch (event_sp->GetType()) {
3995 case eBroadcastInternalStateControlStop:
3996 exit_now = true;
3997 break; // doing any internal state management below
Pavel Labath19da1f12015-12-07 12:36:52 +00003998
Kate Stoneb9c1b512016-09-06 20:57:50 +00003999 case eBroadcastInternalStateControlPause:
4000 control_only = true;
4001 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004002
Kate Stoneb9c1b512016-09-06 20:57:50 +00004003 case eBroadcastInternalStateControlResume:
4004 control_only = false;
4005 break;
4006 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004007
Kate Stoneb9c1b512016-09-06 20:57:50 +00004008 continue;
4009 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4010 if (m_public_state.GetValue() == eStateAttaching) {
4011 if (log)
4012 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4013 ") woke up with an interrupt while attaching - "
4014 "forwarding interrupt.",
4015 __FUNCTION__, static_cast<void *>(this), GetID());
4016 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
4017 } else if (StateIsRunningState(m_last_broadcast_state)) {
4018 if (log)
4019 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4020 ") woke up with an interrupt - Halting.",
4021 __FUNCTION__, static_cast<void *>(this), GetID());
Zachary Turner97206d52017-05-12 04:51:55 +00004022 Status error = HaltPrivate();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004023 if (error.Fail() && log)
4024 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4025 ") failed to halt the process: %s",
4026 __FUNCTION__, static_cast<void *>(this), GetID(),
4027 error.AsCString());
Adrian Prantl05097242018-04-30 16:49:04 +00004028 // Halt should generate a stopped event. Make a note of the fact that
4029 // we were doing the interrupt, so we can set the interrupted flag
4030 // after we receive the event. We deliberately set this to true even if
4031 // HaltPrivate failed, so that we can interrupt on the next natural
4032 // stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004033 interrupt_requested = true;
4034 } else {
4035 // This can happen when someone (e.g. Process::Halt) sees that we are
Adrian Prantl05097242018-04-30 16:49:04 +00004036 // running and sends an interrupt request, but the process actually
4037 // stops before we receive it. In that case, we can just ignore the
4038 // request. We use m_last_broadcast_state, because the Stopped event
4039 // may not have been popped of the event queue yet, which is when the
4040 // public state gets updated.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004041 if (log)
4042 log->Printf(
4043 "Process::%s ignoring interrupt as we have already stopped.",
4044 __FUNCTION__);
4045 }
4046 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004047 }
4048
Kate Stoneb9c1b512016-09-06 20:57:50 +00004049 const StateType internal_state =
4050 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004051
Kate Stoneb9c1b512016-09-06 20:57:50 +00004052 if (internal_state != eStateInvalid) {
4053 if (m_clear_thread_plans_on_stop &&
4054 StateIsStoppedState(internal_state, true)) {
4055 m_clear_thread_plans_on_stop = false;
4056 m_thread_list.DiscardThreadPlans();
4057 }
4058
4059 if (interrupt_requested) {
4060 if (StateIsStoppedState(internal_state, true)) {
4061 // We requested the interrupt, so mark this as such in the stop event
Adrian Prantl05097242018-04-30 16:49:04 +00004062 // so clients can tell an interrupted process from a natural stop
Kate Stoneb9c1b512016-09-06 20:57:50 +00004063 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4064 interrupt_requested = false;
4065 } else if (log) {
4066 log->Printf("Process::%s interrupt_requested, but a non-stopped "
4067 "state '%s' received.",
4068 __FUNCTION__, StateAsCString(internal_state));
4069 }
4070 }
4071
4072 HandlePrivateEvent(event_sp);
4073 }
4074
4075 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4076 internal_state == eStateDetached) {
4077 if (log)
4078 log->Printf("Process::%s (arg = %p, pid = %" PRIu64
4079 ") about to exit with internal state %s...",
4080 __FUNCTION__, static_cast<void *>(this), GetID(),
4081 StateAsCString(internal_state));
4082
4083 break;
4084 }
4085 }
4086
4087 // Verify log is still enabled before attempting to write to it...
4088 if (log)
4089 log->Printf("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4090 __FUNCTION__, static_cast<void *>(this), GetID());
4091
4092 // If we are a secondary thread, then the primary thread we are working for
Adrian Prantl05097242018-04-30 16:49:04 +00004093 // will have already acquired the public_run_lock, and isn't done with what
4094 // it was doing yet, so don't try to change it on the way out.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004095 if (!is_secondary_thread)
4096 m_public_run_lock.SetStopped();
4097 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004098}
4099
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004100//------------------------------------------------------------------
4101// Process Event Data
4102//------------------------------------------------------------------
4103
Kate Stoneb9c1b512016-09-06 20:57:50 +00004104Process::ProcessEventData::ProcessEventData()
4105 : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
4106 m_update_state(0), m_interrupted(false) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004107
Kate Stoneb9c1b512016-09-06 20:57:50 +00004108Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
4109 StateType state)
4110 : EventData(), m_process_wp(), m_state(state), m_restarted(false),
4111 m_update_state(0), m_interrupted(false) {
4112 if (process_sp)
4113 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004114}
4115
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004116Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004117
Kate Stoneb9c1b512016-09-06 20:57:50 +00004118const ConstString &Process::ProcessEventData::GetFlavorString() {
4119 static ConstString g_flavor("Process::ProcessEventData");
4120 return g_flavor;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004121}
4122
Kate Stoneb9c1b512016-09-06 20:57:50 +00004123const ConstString &Process::ProcessEventData::GetFlavor() const {
4124 return ProcessEventData::GetFlavorString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004125}
4126
Kate Stoneb9c1b512016-09-06 20:57:50 +00004127void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
4128 ProcessSP process_sp(m_process_wp.lock());
Greg Clayton2e309072015-07-17 23:42:28 +00004129
Kate Stoneb9c1b512016-09-06 20:57:50 +00004130 if (!process_sp)
4131 return;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004132
Kate Stoneb9c1b512016-09-06 20:57:50 +00004133 // This function gets called twice for each event, once when the event gets
Adrian Prantl05097242018-04-30 16:49:04 +00004134 // pulled off of the private process event queue, and then any number of
4135 // times, first when it gets pulled off of the public event queue, then other
4136 // times when we're pretending that this is where we stopped at the end of
4137 // expression evaluation. m_update_state is used to distinguish these three
4138 // cases; it is 0 when we're just pulling it off for private handling, and >
4139 // 1 for expression evaluation, and we don't want to do the breakpoint
Kate Stoneb9c1b512016-09-06 20:57:50 +00004140 // command handling then.
4141 if (m_update_state != 1)
4142 return;
4143
4144 process_sp->SetPublicState(
4145 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
4146
Jason Molendab3a3cd12016-12-08 06:27:29 +00004147 if (m_state == eStateStopped && !m_restarted) {
Adrian Prantl05097242018-04-30 16:49:04 +00004148 // Let process subclasses know we are about to do a public stop and do
4149 // anything they might need to in order to speed up register and memory
4150 // accesses.
Jason Molendab3a3cd12016-12-08 06:27:29 +00004151 process_sp->WillPublicStop();
4152 }
4153
Kate Stoneb9c1b512016-09-06 20:57:50 +00004154 // If this is a halt event, even if the halt stopped with some reason other
Adrian Prantl05097242018-04-30 16:49:04 +00004155 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4156 // the halt request came through) don't do the StopInfo actions, as they may
Kate Stoneb9c1b512016-09-06 20:57:50 +00004157 // end up restarting the process.
4158 if (m_interrupted)
4159 return;
4160
4161 // If we're stopped and haven't restarted, then do the StopInfo actions here:
4162 if (m_state == eStateStopped && !m_restarted) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004163 ThreadList &curr_thread_list = process_sp->GetThreadList();
4164 uint32_t num_threads = curr_thread_list.GetSize();
4165 uint32_t idx;
4166
4167 // The actions might change one of the thread's stop_info's opinions about
Adrian Prantl05097242018-04-30 16:49:04 +00004168 // whether we should stop the process, so we need to query that as we go.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004169
4170 // One other complication here, is that we try to catch any case where the
Adrian Prantl05097242018-04-30 16:49:04 +00004171 // target has run (except for expressions) and immediately exit, but if we
4172 // get that wrong (which is possible) then the thread list might have
4173 // changed, and that would cause our iteration here to crash. We could
4174 // make a copy of the thread list, but we'd really like to also know if it
4175 // has changed at all, so we make up a vector of the thread ID's and check
4176 // what we get back against this list & bag out if anything differs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004177 std::vector<uint32_t> thread_index_array(num_threads);
4178 for (idx = 0; idx < num_threads; ++idx)
4179 thread_index_array[idx] =
4180 curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4181
4182 // Use this to track whether we should continue from here. We will only
Adrian Prantl05097242018-04-30 16:49:04 +00004183 // continue the target running if no thread says we should stop. Of course
4184 // if some thread's PerformAction actually sets the target running, then it
4185 // doesn't matter what the other threads say...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004186
4187 bool still_should_stop = false;
4188
4189 // Sometimes - for instance if we have a bug in the stub we are talking to,
Adrian Prantl05097242018-04-30 16:49:04 +00004190 // we stop but no thread has a valid stop reason. In that case we should
4191 // just stop, because we have no way of telling what the right thing to do
4192 // is, and it's better to let the user decide than continue behind their
4193 // backs.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004194
4195 bool does_anybody_have_an_opinion = false;
4196
4197 for (idx = 0; idx < num_threads; ++idx) {
4198 curr_thread_list = process_sp->GetThreadList();
4199 if (curr_thread_list.GetSize() != num_threads) {
4200 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4201 LIBLLDB_LOG_PROCESS));
4202 if (log)
4203 log->Printf(
4204 "Number of threads changed from %u to %u while processing event.",
4205 num_threads, curr_thread_list.GetSize());
4206 break;
4207 }
4208
4209 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4210
4211 if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4212 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4213 LIBLLDB_LOG_PROCESS));
4214 if (log)
4215 log->Printf("The thread at position %u changed from %u to %u while "
4216 "processing event.",
4217 idx, thread_index_array[idx], thread_sp->GetIndexID());
4218 break;
4219 }
4220
4221 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4222 if (stop_info_sp && stop_info_sp->IsValid()) {
4223 does_anybody_have_an_opinion = true;
4224 bool this_thread_wants_to_stop;
4225 if (stop_info_sp->GetOverrideShouldStop()) {
4226 this_thread_wants_to_stop =
4227 stop_info_sp->GetOverriddenShouldStopValue();
4228 } else {
4229 stop_info_sp->PerformAction(event_ptr);
Adrian Prantl05097242018-04-30 16:49:04 +00004230 // The stop action might restart the target. If it does, then we
4231 // want to mark that in the event so that whoever is receiving it
4232 // will know to wait for the running event and reflect that state
4233 // appropriately. We also need to stop processing actions, since they
4234 // aren't expecting the target to be running.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004235
4236 // FIXME: we might have run.
4237 if (stop_info_sp->HasTargetRunSinceMe()) {
4238 SetRestarted(true);
4239 break;
4240 }
4241
4242 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004243 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004244
4245 if (!still_should_stop)
4246 still_should_stop = this_thread_wants_to_stop;
4247 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004248 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004249
4250 if (!GetRestarted()) {
4251 if (!still_should_stop && does_anybody_have_an_opinion) {
4252 // We've been asked to continue, so do that here.
4253 SetRestarted(true);
Adrian Prantl05097242018-04-30 16:49:04 +00004254 // Use the public resume method here, since this is just extending a
4255 // public resume.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004256 process_sp->PrivateResume();
4257 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00004258 // If we didn't restart, run the Stop Hooks here: They might also
4259 // restart the target, so watch for that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004260 process_sp->GetTarget().RunStopHooks();
4261 if (process_sp->GetPrivateState() == eStateRunning)
4262 SetRestarted(true);
4263 }
4264 }
4265 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004266}
4267
Kate Stoneb9c1b512016-09-06 20:57:50 +00004268void Process::ProcessEventData::Dump(Stream *s) const {
4269 ProcessSP process_sp(m_process_wp.lock());
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004270
Kate Stoneb9c1b512016-09-06 20:57:50 +00004271 if (process_sp)
4272 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4273 static_cast<void *>(process_sp.get()), process_sp->GetID());
4274 else
4275 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004276
Kate Stoneb9c1b512016-09-06 20:57:50 +00004277 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004278}
4279
4280const Process::ProcessEventData *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004281Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4282 if (event_ptr) {
4283 const EventData *event_data = event_ptr->GetData();
4284 if (event_data &&
4285 event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4286 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4287 }
4288 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004289}
4290
4291ProcessSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004292Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4293 ProcessSP process_sp;
4294 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4295 if (data)
4296 process_sp = data->GetProcessSP();
4297 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004298}
4299
Kate Stoneb9c1b512016-09-06 20:57:50 +00004300StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4301 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4302 if (data == nullptr)
4303 return eStateInvalid;
4304 else
4305 return data->GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004306}
4307
Kate Stoneb9c1b512016-09-06 20:57:50 +00004308bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4309 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4310 if (data == nullptr)
4311 return false;
4312 else
4313 return data->GetRestarted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004314}
4315
Kate Stoneb9c1b512016-09-06 20:57:50 +00004316void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4317 bool new_value) {
4318 ProcessEventData *data =
4319 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4320 if (data != nullptr)
4321 data->SetRestarted(new_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004322}
4323
Jim Ingham0161b492013-02-09 01:29:05 +00004324size_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00004325Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4326 ProcessEventData *data =
4327 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4328 if (data != nullptr)
4329 return data->GetNumRestartedReasons();
4330 else
4331 return 0;
Jim Ingham0161b492013-02-09 01:29:05 +00004332}
4333
4334const char *
Kate Stoneb9c1b512016-09-06 20:57:50 +00004335Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4336 size_t idx) {
4337 ProcessEventData *data =
4338 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4339 if (data != nullptr)
4340 return data->GetRestartedReasonAtIndex(idx);
4341 else
4342 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004343}
4344
Kate Stoneb9c1b512016-09-06 20:57:50 +00004345void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4346 const char *reason) {
4347 ProcessEventData *data =
4348 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4349 if (data != nullptr)
4350 data->AddRestartedReason(reason);
Jim Ingham0161b492013-02-09 01:29:05 +00004351}
4352
Kate Stoneb9c1b512016-09-06 20:57:50 +00004353bool Process::ProcessEventData::GetInterruptedFromEvent(
4354 const Event *event_ptr) {
4355 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4356 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004357 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00004358 else
4359 return data->GetInterrupted();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004360}
4361
Kate Stoneb9c1b512016-09-06 20:57:50 +00004362void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4363 bool new_value) {
4364 ProcessEventData *data =
4365 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4366 if (data != nullptr)
4367 data->SetInterrupted(new_value);
Greg Claytond9e416c2012-02-18 05:35:26 +00004368}
4369
Kate Stoneb9c1b512016-09-06 20:57:50 +00004370bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4371 ProcessEventData *data =
4372 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4373 if (data) {
4374 data->SetUpdateStateOnRemoval();
4375 return true;
4376 }
4377 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004378}
4379
Jim Inghamb87b9e62018-06-26 23:38:58 +00004380lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004381
4382void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4383 exe_ctx.SetTargetPtr(&GetTarget());
4384 exe_ctx.SetProcessPtr(this);
4385 exe_ctx.SetThreadPtr(nullptr);
4386 exe_ctx.SetFramePtr(nullptr);
4387}
4388
4389// uint32_t
4390// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4391// std::vector<lldb::pid_t> &pids)
Greg Claytone996fd32011-03-08 22:40:15 +00004392//{
4393// return 0;
4394//}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004395//
4396// ArchSpec
4397// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
Greg Claytone996fd32011-03-08 22:40:15 +00004398//{
4399// return Host::GetArchSpecForExistingProcess (pid);
4400//}
4401//
Kate Stoneb9c1b512016-09-06 20:57:50 +00004402// ArchSpec
4403// Process::GetArchSpecForExistingProcess (const char *process_name)
Greg Claytone996fd32011-03-08 22:40:15 +00004404//{
4405// return Host::GetArchSpecForExistingProcess (process_name);
4406//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004407
Kate Stoneb9c1b512016-09-06 20:57:50 +00004408void Process::AppendSTDOUT(const char *s, size_t len) {
4409 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4410 m_stdout_data.append(s, len);
4411 BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4412 new ProcessEventData(shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004413}
4414
Kate Stoneb9c1b512016-09-06 20:57:50 +00004415void Process::AppendSTDERR(const char *s, size_t len) {
4416 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4417 m_stderr_data.append(s, len);
4418 BroadcastEventIfUnique(eBroadcastBitSTDERR,
4419 new ProcessEventData(shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004420}
4421
Kate Stoneb9c1b512016-09-06 20:57:50 +00004422void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4423 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4424 m_profile_data.push_back(one_profile_data);
4425 BroadcastEventIfUnique(eBroadcastBitProfileData,
4426 new ProcessEventData(shared_from_this(), GetState()));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004427}
4428
Kate Stoneb9c1b512016-09-06 20:57:50 +00004429void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4430 const StructuredDataPluginSP &plugin_sp) {
4431 BroadcastEvent(
4432 eBroadcastBitStructuredData,
4433 new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
Todd Fiala75930012016-08-19 04:21:48 +00004434}
4435
4436StructuredDataPluginSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00004437Process::GetStructuredDataPlugin(const ConstString &type_name) const {
4438 auto find_it = m_structured_data_plugin_map.find(type_name);
4439 if (find_it != m_structured_data_plugin_map.end())
4440 return find_it->second;
4441 else
4442 return StructuredDataPluginSP();
Todd Fiala75930012016-08-19 04:21:48 +00004443}
4444
Zachary Turner97206d52017-05-12 04:51:55 +00004445size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004446 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4447 if (m_profile_data.empty())
4448 return 0;
4449
4450 std::string &one_profile_data = m_profile_data.front();
4451 size_t bytes_available = one_profile_data.size();
4452 if (bytes_available > 0) {
4453 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4454 if (log)
4455 log->Printf("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4456 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4457 if (bytes_available > buf_size) {
4458 memcpy(buf, one_profile_data.c_str(), buf_size);
4459 one_profile_data.erase(0, buf_size);
4460 bytes_available = buf_size;
4461 } else {
4462 memcpy(buf, one_profile_data.c_str(), bytes_available);
4463 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004464 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004465 }
4466 return bytes_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004467}
4468
Greg Clayton93e86192011-11-13 04:45:22 +00004469//------------------------------------------------------------------
4470// Process STDIO
4471//------------------------------------------------------------------
4472
Zachary Turner97206d52017-05-12 04:51:55 +00004473size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004474 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4475 size_t bytes_available = m_stdout_data.size();
4476 if (bytes_available > 0) {
4477 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4478 if (log)
4479 log->Printf("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4480 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4481 if (bytes_available > buf_size) {
4482 memcpy(buf, m_stdout_data.c_str(), buf_size);
4483 m_stdout_data.erase(0, buf_size);
4484 bytes_available = buf_size;
4485 } else {
4486 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4487 m_stdout_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004488 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004489 }
4490 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004491}
4492
Zachary Turner97206d52017-05-12 04:51:55 +00004493size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004494 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4495 size_t bytes_available = m_stderr_data.size();
4496 if (bytes_available > 0) {
4497 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4498 if (log)
4499 log->Printf("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4500 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4501 if (bytes_available > buf_size) {
4502 memcpy(buf, m_stderr_data.c_str(), buf_size);
4503 m_stderr_data.erase(0, buf_size);
4504 bytes_available = buf_size;
4505 } else {
4506 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4507 m_stderr_data.clear();
Greg Clayton93e86192011-11-13 04:45:22 +00004508 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004509 }
4510 return bytes_available;
Greg Clayton93e86192011-11-13 04:45:22 +00004511}
4512
Kate Stoneb9c1b512016-09-06 20:57:50 +00004513void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4514 size_t src_len) {
4515 Process *process = (Process *)baton;
4516 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004517}
4518
Kate Stoneb9c1b512016-09-06 20:57:50 +00004519class IOHandlerProcessSTDIO : public IOHandler {
Greg Clayton44d93782014-01-27 23:43:24 +00004520public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004521 IOHandlerProcessSTDIO(Process *process, int write_fd)
4522 : IOHandler(process->GetTarget().GetDebugger(),
4523 IOHandler::Type::ProcessIO),
Sam McCall6f43d9d2016-11-15 10:58:16 +00004524 m_process(process), m_write_file(write_fd, false) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00004525 m_pipe.CreateNew(false);
4526 m_read_file.SetDescriptor(GetInputFD(), false);
4527 }
4528
4529 ~IOHandlerProcessSTDIO() override = default;
4530
Adrian Prantl05097242018-04-30 16:49:04 +00004531 // Each IOHandler gets to run until it is done. It should read data from the
4532 // "in" and place output into "out" and "err and return when done.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004533 void Run() override {
4534 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4535 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4536 SetIsDone(true);
4537 return;
Greg Clayton44d93782014-01-27 23:43:24 +00004538 }
4539
Kate Stoneb9c1b512016-09-06 20:57:50 +00004540 SetIsDone(false);
4541 const int read_fd = m_read_file.GetDescriptor();
4542 TerminalState terminal_state;
4543 terminal_state.Save(read_fd, false);
4544 Terminal terminal(read_fd);
4545 terminal.SetCanonical(false);
4546 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004547// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004548#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +00004549 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4550 m_is_running = true;
4551 while (!GetIsDone()) {
4552 SelectHelper select_helper;
4553 select_helper.FDSetRead(read_fd);
4554 select_helper.FDSetRead(pipe_read_fd);
Zachary Turner97206d52017-05-12 04:51:55 +00004555 Status error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004556
Kate Stoneb9c1b512016-09-06 20:57:50 +00004557 if (error.Fail()) {
Greg Clayton860582f2016-02-26 17:36:44 +00004558 SetIsDone(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004559 } else {
4560 char ch = 0;
4561 size_t n;
4562 if (select_helper.FDIsSetRead(read_fd)) {
4563 n = 1;
4564 if (m_read_file.Read(&ch, n).Success() && n == 1) {
4565 if (m_write_file.Write(&ch, n).Fail() || n != 1)
4566 SetIsDone(true);
4567 } else
4568 SetIsDone(true);
Greg Clayton860582f2016-02-26 17:36:44 +00004569 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004570 if (select_helper.FDIsSetRead(pipe_read_fd)) {
4571 size_t bytes_read;
4572 // Consume the interrupt byte
Zachary Turner97206d52017-05-12 04:51:55 +00004573 Status error = m_pipe.Read(&ch, 1, bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004574 if (error.Success()) {
4575 switch (ch) {
4576 case 'q':
4577 SetIsDone(true);
4578 break;
4579 case 'i':
4580 if (StateIsRunningState(m_process->GetState()))
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004581 m_process->SendAsyncInterrupt();
Kate Stoneb9c1b512016-09-06 20:57:50 +00004582 break;
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004583 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004584 }
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00004585 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004586 }
Greg Claytone68f5d62014-02-24 22:50:57 +00004587 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004588 m_is_running = false;
4589#endif
4590 terminal_state.Restore();
4591 }
4592
4593 void Cancel() override {
4594 SetIsDone(true);
4595 // Only write to our pipe to cancel if we are in
Adrian Prantl05097242018-04-30 16:49:04 +00004596 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4597 // is being run from the command interpreter:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004598 //
4599 // (lldb) step_process_thousands_of_times
4600 //
4601 // In this case the command interpreter will be in the middle of handling
4602 // the command and if the process pushes and pops the IOHandler thousands
4603 // of times, we can end up writing to m_pipe without ever consuming the
4604 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4605 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4606 if (m_is_running) {
4607 char ch = 'q'; // Send 'q' for quit
4608 size_t bytes_written = 0;
4609 m_pipe.Write(&ch, 1, bytes_written);
Greg Clayton44d93782014-01-27 23:43:24 +00004610 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004611 }
4612
4613 bool Interrupt() override {
Adrian Prantl05097242018-04-30 16:49:04 +00004614 // Do only things that are safe to do in an interrupt context (like in a
4615 // SIGINT handler), like write 1 byte to a file descriptor. This will
Kate Stoneb9c1b512016-09-06 20:57:50 +00004616 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4617 // that was written to the pipe and then call
Adrian Prantl05097242018-04-30 16:49:04 +00004618 // m_process->SendAsyncInterrupt() from a much safer location in code.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004619 if (m_active) {
4620 char ch = 'i'; // Send 'i' for interrupt
4621 size_t bytes_written = 0;
Zachary Turner97206d52017-05-12 04:51:55 +00004622 Status result = m_pipe.Write(&ch, 1, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004623 return result.Success();
4624 } else {
4625 // This IOHandler might be pushed on the stack, but not being run
Adrian Prantl05097242018-04-30 16:49:04 +00004626 // currently so do the right thing if we aren't actively watching for
4627 // STDIN by sending the interrupt to the process. Otherwise the write to
4628 // the pipe above would do nothing. This can happen when the command
4629 // interpreter is running and gets a "expression ...". It will be on the
4630 // IOHandler thread and sending the input is complete to the delegate
4631 // which will cause the expression to run, which will push the process IO
4632 // handler, but not run it.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004633
4634 if (StateIsRunningState(m_process->GetState())) {
4635 m_process->SendAsyncInterrupt();
4636 return true;
4637 }
4638 }
4639 return false;
4640 }
4641
4642 void GotEOF() override {}
4643
Greg Clayton44d93782014-01-27 23:43:24 +00004644protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004645 Process *m_process;
4646 File m_read_file; // Read from this file (usually actual STDIN for LLDB
4647 File m_write_file; // Write to this file (usually the master pty for getting
4648 // io to debuggee)
4649 Pipe m_pipe;
Sam McCall6f43d9d2016-11-15 10:58:16 +00004650 std::atomic<bool> m_is_running{false};
Greg Clayton44d93782014-01-27 23:43:24 +00004651};
4652
Kate Stoneb9c1b512016-09-06 20:57:50 +00004653void Process::SetSTDIOFileDescriptor(int fd) {
4654 // First set up the Read Thread for reading/handling process I/O
4655
4656 std::unique_ptr<ConnectionFileDescriptor> conn_ap(
4657 new ConnectionFileDescriptor(fd, true));
4658
4659 if (conn_ap) {
4660 m_stdio_communication.SetConnection(conn_ap.release());
4661 if (m_stdio_communication.IsConnected()) {
4662 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4663 STDIOReadThreadBytesReceived, this);
4664 m_stdio_communication.StartReadThread();
4665
4666 // Now read thread is set up, set up input reader.
4667
4668 if (!m_process_input_reader)
4669 m_process_input_reader.reset(new IOHandlerProcessSTDIO(this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004670 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004671 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004672}
4673
Kate Stoneb9c1b512016-09-06 20:57:50 +00004674bool Process::ProcessIOHandlerIsActive() {
4675 IOHandlerSP io_handler_sp(m_process_input_reader);
4676 if (io_handler_sp)
4677 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4678 return false;
Greg Clayton6fea17e2014-03-03 19:15:20 +00004679}
Kate Stoneb9c1b512016-09-06 20:57:50 +00004680bool Process::PushProcessIOHandler() {
4681 IOHandlerSP io_handler_sp(m_process_input_reader);
4682 if (io_handler_sp) {
4683 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4684 if (log)
4685 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
Pavel Labath44464872015-05-27 12:40:32 +00004686
Kate Stoneb9c1b512016-09-06 20:57:50 +00004687 io_handler_sp->SetIsDone(false);
Raphael Isemannc01783a2018-08-29 22:50:54 +00004688 // If we evaluate an utility function, then we don't cancel the current
4689 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4690 // existing IOHandler that potentially provides the user interface (e.g.
4691 // the IOHandler for Editline).
4692 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4693 GetTarget().GetDebugger().PushIOHandler(io_handler_sp, cancel_top_handler);
Kate Stoneb9c1b512016-09-06 20:57:50 +00004694 return true;
4695 }
4696 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004697}
4698
Kate Stoneb9c1b512016-09-06 20:57:50 +00004699bool Process::PopProcessIOHandler() {
4700 IOHandlerSP io_handler_sp(m_process_input_reader);
4701 if (io_handler_sp)
4702 return GetTarget().GetDebugger().PopIOHandler(io_handler_sp);
4703 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004704}
4705
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004706// The process needs to know about installed plug-ins
Kate Stoneb9c1b512016-09-06 20:57:50 +00004707void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004708
Kate Stoneb9c1b512016-09-06 20:57:50 +00004709void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004710
Kate Stoneb9c1b512016-09-06 20:57:50 +00004711namespace {
Adrian Prantl05097242018-04-30 16:49:04 +00004712// RestorePlanState is used to record the "is private", "is master" and "okay
4713// to discard" fields of the plan we are running, and reset it on Clean or on
4714// destruction. It will only reset the state once, so you can call Clean and
4715// then monkey with the state and it won't get reset on you again.
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004716
Kate Stoneb9c1b512016-09-06 20:57:50 +00004717class RestorePlanState {
4718public:
4719 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4720 : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4721 if (m_thread_plan_sp) {
4722 m_private = m_thread_plan_sp->GetPrivate();
4723 m_is_master = m_thread_plan_sp->IsMasterPlan();
4724 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4725 }
4726 }
4727
4728 ~RestorePlanState() { Clean(); }
4729
4730 void Clean() {
4731 if (!m_already_reset && m_thread_plan_sp) {
4732 m_already_reset = true;
4733 m_thread_plan_sp->SetPrivate(m_private);
4734 m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4735 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4736 }
4737 }
4738
4739private:
4740 lldb::ThreadPlanSP m_thread_plan_sp;
4741 bool m_already_reset;
4742 bool m_private;
4743 bool m_is_master;
4744 bool m_okay_to_discard;
4745};
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004746} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00004747
Pavel Labath2ce22162016-12-01 10:57:30 +00004748static microseconds
4749GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4750 const milliseconds default_one_thread_timeout(250);
4751
4752 // If the overall wait is forever, then we don't need to worry about it.
Pavel Labath43d35412016-12-06 11:24:51 +00004753 if (!options.GetTimeout()) {
4754 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4755 : default_one_thread_timeout;
Pavel Labath2ce22162016-12-01 10:57:30 +00004756 }
4757
4758 // If the one thread timeout is set, use it.
Pavel Labath43d35412016-12-06 11:24:51 +00004759 if (options.GetOneThreadTimeout())
4760 return *options.GetOneThreadTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004761
4762 // Otherwise use half the total timeout, bounded by the
4763 // default_one_thread_timeout.
4764 return std::min<microseconds>(default_one_thread_timeout,
Pavel Labath43d35412016-12-06 11:24:51 +00004765 *options.GetTimeout() / 2);
Pavel Labath2ce22162016-12-01 10:57:30 +00004766}
4767
4768static Timeout<std::micro>
4769GetExpressionTimeout(const EvaluateExpressionOptions &options,
4770 bool before_first_timeout) {
Adrian Prantl05097242018-04-30 16:49:04 +00004771 // If we are going to run all threads the whole time, or if we are only going
4772 // to run one thread, we can just return the overall timeout.
Pavel Labath2ce22162016-12-01 10:57:30 +00004773 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Pavel Labath43d35412016-12-06 11:24:51 +00004774 return options.GetTimeout();
Pavel Labath2ce22162016-12-01 10:57:30 +00004775
4776 if (before_first_timeout)
4777 return GetOneThreadExpressionTimeout(options);
4778
Pavel Labath43d35412016-12-06 11:24:51 +00004779 if (!options.GetTimeout())
Pavel Labath2ce22162016-12-01 10:57:30 +00004780 return llvm::None;
4781 else
Pavel Labath43d35412016-12-06 11:24:51 +00004782 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
Pavel Labath2ce22162016-12-01 10:57:30 +00004783}
4784
Pavel Labath45dde232017-05-25 10:50:06 +00004785static llvm::Optional<ExpressionResults>
4786HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4787 RestorePlanState &restorer, const EventSP &event_sp,
4788 EventSP &event_to_broadcast_sp,
4789 const EvaluateExpressionOptions &options, bool handle_interrupts) {
4790 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4791
4792 ThreadPlanSP plan = thread.GetCompletedPlan();
4793 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4794 LLDB_LOG(log, "execution completed successfully");
4795
4796 // Restore the plan state so it will get reported as intended when we are
4797 // done.
4798 restorer.Clean();
4799 return eExpressionCompleted;
4800 }
4801
4802 StopInfoSP stop_info_sp = thread.GetStopInfo();
4803 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4804 stop_info_sp->ShouldNotify(event_sp.get())) {
4805 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4806 if (!options.DoesIgnoreBreakpoints()) {
4807 // Restore the plan state and then force Private to false. We are going
4808 // to stop because of this plan so we need it to become a public plan or
Adrian Prantl05097242018-04-30 16:49:04 +00004809 // it won't report correctly when we continue to its termination later
4810 // on.
Pavel Labath45dde232017-05-25 10:50:06 +00004811 restorer.Clean();
4812 thread_plan_sp->SetPrivate(false);
4813 event_to_broadcast_sp = event_sp;
4814 }
4815 return eExpressionHitBreakpoint;
4816 }
4817
4818 if (!handle_interrupts &&
4819 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4820 return llvm::None;
4821
4822 LLDB_LOG(log, "thread plan did not successfully complete");
4823 if (!options.DoesUnwindOnError())
4824 event_to_broadcast_sp = event_sp;
4825 return eExpressionInterrupted;
4826}
4827
Jim Ingham1624a2d2014-05-05 02:26:40 +00004828ExpressionResults
Kate Stoneb9c1b512016-09-06 20:57:50 +00004829Process::RunThreadPlan(ExecutionContext &exe_ctx,
4830 lldb::ThreadPlanSP &thread_plan_sp,
4831 const EvaluateExpressionOptions &options,
4832 DiagnosticManager &diagnostic_manager) {
4833 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004834
Kate Stoneb9c1b512016-09-06 20:57:50 +00004835 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4836
4837 if (!thread_plan_sp) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004838 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004839 eDiagnosticSeverityError,
4840 "RunThreadPlan called with empty thread plan.");
4841 return eExpressionSetupError;
4842 }
4843
4844 if (!thread_plan_sp->ValidatePlan(nullptr)) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004845 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004846 eDiagnosticSeverityError,
4847 "RunThreadPlan called with an invalid thread plan.");
4848 return eExpressionSetupError;
4849 }
4850
4851 if (exe_ctx.GetProcessPtr() != this) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004852 diagnostic_manager.PutString(eDiagnosticSeverityError,
4853 "RunThreadPlan called on wrong process.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004854 return eExpressionSetupError;
4855 }
4856
4857 Thread *thread = exe_ctx.GetThreadPtr();
4858 if (thread == nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004859 diagnostic_manager.PutString(eDiagnosticSeverityError,
4860 "RunThreadPlan called with invalid thread.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00004861 return eExpressionSetupError;
4862 }
4863
4864 // We need to change some of the thread plan attributes for the thread plan
Adrian Prantl05097242018-04-30 16:49:04 +00004865 // runner. This will restore them when we are done:
Kate Stoneb9c1b512016-09-06 20:57:50 +00004866
4867 RestorePlanState thread_plan_restorer(thread_plan_sp);
4868
Adrian Prantl05097242018-04-30 16:49:04 +00004869 // We rely on the thread plan we are running returning "PlanCompleted" if
4870 // when it successfully completes. For that to be true the plan can't be
4871 // private - since private plans suppress themselves in the GetCompletedPlan
4872 // call.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004873
4874 thread_plan_sp->SetPrivate(false);
4875
4876 // The plans run with RunThreadPlan also need to be terminal master plans or
Adrian Prantl05097242018-04-30 16:49:04 +00004877 // when they are done we will end up asking the plan above us whether we
4878 // should stop, which may give the wrong answer.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004879
4880 thread_plan_sp->SetIsMasterPlan(true);
4881 thread_plan_sp->SetOkayToDiscard(false);
4882
Raphael Isemannc01783a2018-08-29 22:50:54 +00004883 // If we are running some utility expression for LLDB, we now have to mark
4884 // this in the ProcesModID of this process. This RAII takes care of marking
4885 // and reverting the mark it once we are done running the expression.
4886 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4887
Kate Stoneb9c1b512016-09-06 20:57:50 +00004888 if (m_private_state.GetValue() != eStateStopped) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00004889 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00004890 eDiagnosticSeverityError,
4891 "RunThreadPlan called while the private state was not stopped.");
4892 return eExpressionSetupError;
4893 }
4894
4895 // Save the thread & frame from the exe_ctx for restoration after we run
4896 const uint32_t thread_idx_id = thread->GetIndexID();
4897 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4898 if (!selected_frame_sp) {
4899 thread->SetSelectedFrame(nullptr);
4900 selected_frame_sp = thread->GetSelectedFrame();
4901 if (!selected_frame_sp) {
4902 diagnostic_manager.Printf(
4903 eDiagnosticSeverityError,
4904 "RunThreadPlan called without a selected frame on thread %d",
4905 thread_idx_id);
4906 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004907 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00004908 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004909
Adrian Prantl05097242018-04-30 16:49:04 +00004910 // Make sure the timeout values make sense. The one thread timeout needs to
4911 // be smaller than the overall timeout.
Pavel Labath43d35412016-12-06 11:24:51 +00004912 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4913 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
Pavel Labath2ce22162016-12-01 10:57:30 +00004914 diagnostic_manager.PutString(eDiagnosticSeverityError,
4915 "RunThreadPlan called with one thread "
4916 "timeout greater than total timeout");
4917 return eExpressionSetupError;
4918 }
4919
Kate Stoneb9c1b512016-09-06 20:57:50 +00004920 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004921
Kate Stoneb9c1b512016-09-06 20:57:50 +00004922 // N.B. Running the target may unset the currently selected thread and frame.
Adrian Prantl05097242018-04-30 16:49:04 +00004923 // We don't want to do that either, so we should arrange to reset them as
4924 // well.
Greg Claytonc14ee322011-09-22 04:58:26 +00004925
Kate Stoneb9c1b512016-09-06 20:57:50 +00004926 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004927
Kate Stoneb9c1b512016-09-06 20:57:50 +00004928 uint32_t selected_tid;
4929 StackID selected_stack_id;
4930 if (selected_thread_sp) {
4931 selected_tid = selected_thread_sp->GetIndexID();
4932 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4933 } else {
4934 selected_tid = LLDB_INVALID_THREAD_ID;
4935 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004936
Kate Stoneb9c1b512016-09-06 20:57:50 +00004937 HostThread backup_private_state_thread;
4938 lldb::StateType old_state = eStateInvalid;
4939 lldb::ThreadPlanSP stopper_base_plan_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004940
Kate Stoneb9c1b512016-09-06 20:57:50 +00004941 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4942 LIBLLDB_LOG_PROCESS));
4943 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4944 // Yikes, we are running on the private state thread! So we can't wait for
Adrian Prantl05097242018-04-30 16:49:04 +00004945 // public events on this thread, since we are the thread that is generating
4946 // public events. The simplest thing to do is to spin up a temporary thread
4947 // to handle private state thread events while we are fielding public
4948 // events here.
Todd Fiala76e0fc92014-08-27 22:58:26 +00004949 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00004950 log->Printf("Running thread plan on private state thread, spinning up "
4951 "another state thread to handle the events.");
Todd Fiala76e0fc92014-08-27 22:58:26 +00004952
Kate Stoneb9c1b512016-09-06 20:57:50 +00004953 backup_private_state_thread = m_private_state_thread;
Greg Clayton095eeaa2013-11-05 23:28:00 +00004954
Kate Stoneb9c1b512016-09-06 20:57:50 +00004955 // One other bit of business: we want to run just this thread plan and
Adrian Prantl05097242018-04-30 16:49:04 +00004956 // anything it pushes, and then stop, returning control here. But in the
4957 // normal course of things, the plan above us on the stack would be given a
4958 // shot at the stop event before deciding to stop, and we don't want that.
4959 // So we insert a "stopper" base plan on the stack before the plan we want
4960 // to run. Since base plans always stop and return control to the user,
4961 // that will do just what we want.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004962 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4963 thread->QueueThreadPlan(stopper_base_plan_sp, false);
4964 // Have to make sure our public state is stopped, since otherwise the
4965 // reporting logic below doesn't work correctly.
4966 old_state = m_public_state.GetValue();
4967 m_public_state.SetValueNoLock(eStateStopped);
4968
4969 // Now spin up the private state thread:
4970 StartPrivateStateThread(true);
4971 }
4972
4973 thread->QueueThreadPlan(
4974 thread_plan_sp, false); // This used to pass "true" does that make sense?
4975
4976 if (options.GetDebug()) {
Adrian Prantl05097242018-04-30 16:49:04 +00004977 // In this case, we aren't actually going to run, we just want to stop
4978 // right away. Flush this thread so we will refetch the stacks and show the
4979 // correct backtrace.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004980 // FIXME: To make this prettier we should invent some stop reason for this,
4981 // but that
4982 // is only cosmetic, and this functionality is only of use to lldb
Adrian Prantl05097242018-04-30 16:49:04 +00004983 // developers who can live with not pretty...
Kate Stoneb9c1b512016-09-06 20:57:50 +00004984 thread->Flush();
4985 return eExpressionStoppedForDebug;
4986 }
4987
4988 ListenerSP listener_sp(
4989 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4990
4991 lldb::EventSP event_to_broadcast_sp;
4992
4993 {
4994 // This process event hijacker Hijacks the Public events and its destructor
Adrian Prantl05097242018-04-30 16:49:04 +00004995 // makes sure that the process events get restored on exit to the function.
Kate Stoneb9c1b512016-09-06 20:57:50 +00004996 //
4997 // If the event needs to propagate beyond the hijacker (e.g., the process
Adrian Prantl05097242018-04-30 16:49:04 +00004998 // exits during execution), then the event is put into
4999 // event_to_broadcast_sp for rebroadcasting.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005000
5001 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5002
5003 if (log) {
5004 StreamString s;
5005 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5006 log->Printf("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5007 " to run thread plan \"%s\".",
5008 thread->GetIndexID(), thread->GetID(), s.GetData());
Jim Ingham1460e4b2014-01-10 23:46:59 +00005009 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005010
5011 bool got_event;
5012 lldb::EventSP event_sp;
5013 lldb::StateType stop_state = lldb::eStateInvalid;
5014
5015 bool before_first_timeout = true; // This is set to false the first time
5016 // that we have to halt the target.
5017 bool do_resume = true;
5018 bool handle_running_event = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005019
5020 // This is just for accounting:
5021 uint32_t num_resumes = 0;
5022
Kate Stoneb9c1b512016-09-06 20:57:50 +00005023 // If we are going to run all threads the whole time, or if we are only
Pavel Labath2ce22162016-12-01 10:57:30 +00005024 // going to run one thread, then we don't need the first timeout. So we
5025 // pretend we are after the first timeout already.
5026 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Kate Stoneb9c1b512016-09-06 20:57:50 +00005027 before_first_timeout = false;
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00005028
Kate Stoneb9c1b512016-09-06 20:57:50 +00005029 if (log)
Pavel Labath2ce22162016-12-01 10:57:30 +00005030 log->Printf("Stop others: %u, try all: %u, before_first: %u.\n",
5031 options.GetStopOthers(), options.GetTryAllThreads(),
5032 before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005033
Adrian Prantl05097242018-04-30 16:49:04 +00005034 // This isn't going to work if there are unfetched events on the queue. Are
5035 // there cases where we might want to run the remaining events here, and
5036 // then try to call the function? That's probably being too tricky for our
5037 // own good.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005038
5039 Event *other_events = listener_sp->PeekAtNextEvent();
5040 if (other_events != nullptr) {
Zachary Turnere2411fa2016-11-12 19:12:56 +00005041 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005042 eDiagnosticSeverityError,
5043 "RunThreadPlan called with pending events on the queue.");
5044 return eExpressionSetupError;
Kuba Breckaafdf8422014-10-10 23:43:03 +00005045 }
5046
Kate Stoneb9c1b512016-09-06 20:57:50 +00005047 // We also need to make sure that the next event is delivered. We might be
Adrian Prantl05097242018-04-30 16:49:04 +00005048 // calling a function as part of a thread plan, in which case the last
5049 // delivered event could be the running event, and we don't want event
5050 // coalescing to cause us to lose OUR running event...
Kate Stoneb9c1b512016-09-06 20:57:50 +00005051 ForceNextEventDelivery();
Ryan Brown65d4d5c2015-09-16 21:20:44 +00005052
Kate Stoneb9c1b512016-09-06 20:57:50 +00005053// This while loop must exit out the bottom, there's cleanup that we need to do
Adrian Prantl05097242018-04-30 16:49:04 +00005054// when we are done. So don't call return anywhere within it.
Todd Fiala75930012016-08-19 04:21:48 +00005055
Kate Stoneb9c1b512016-09-06 20:57:50 +00005056#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
Adrian Prantl05097242018-04-30 16:49:04 +00005057 // It's pretty much impossible to write test cases for things like: One
5058 // thread timeout expires, I go to halt, but the process already stopped on
5059 // the function call stop breakpoint. Turning on this define will make us
5060 // not fetch the first event till after the halt. So if you run a quick
5061 // function, it will have completed, and the completion event will be
5062 // waiting, when you interrupt for halt. The expression evaluation should
5063 // still succeed.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005064 bool miss_first_event = true;
5065#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00005066 while (true) {
Adrian Prantl05097242018-04-30 16:49:04 +00005067 // We usually want to resume the process if we get to the top of the
5068 // loop. The only exception is if we get two running events with no
5069 // intervening stop, which can happen, we will just wait for then next
5070 // stop event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005071 if (log)
5072 log->Printf("Top of while loop: do_resume: %i handle_running_event: %i "
5073 "before_first_timeout: %i.",
5074 do_resume, handle_running_event, before_first_timeout);
Jason Molendaef7d6412015-08-06 03:27:10 +00005075
Kate Stoneb9c1b512016-09-06 20:57:50 +00005076 if (do_resume || handle_running_event) {
5077 // Do the initial resume and wait for the running event before going
5078 // further.
Jason Molendaef7d6412015-08-06 03:27:10 +00005079
Kate Stoneb9c1b512016-09-06 20:57:50 +00005080 if (do_resume) {
5081 num_resumes++;
Zachary Turner97206d52017-05-12 04:51:55 +00005082 Status resume_error = PrivateResume();
Kate Stoneb9c1b512016-09-06 20:57:50 +00005083 if (!resume_error.Success()) {
5084 diagnostic_manager.Printf(
5085 eDiagnosticSeverityError,
5086 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5087 resume_error.AsCString());
5088 return_value = eExpressionSetupError;
5089 break;
5090 }
Jason Molendaef7d6412015-08-06 03:27:10 +00005091 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005092
Pavel Labathd35031e12016-11-30 10:41:42 +00005093 got_event =
5094 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005095 if (!got_event) {
5096 if (log)
5097 log->Printf("Process::RunThreadPlan(): didn't get any event after "
5098 "resume %" PRIu32 ", exiting.",
5099 num_resumes);
5100
5101 diagnostic_manager.Printf(eDiagnosticSeverityError,
5102 "didn't get any event after resume %" PRIu32
5103 ", exiting.",
5104 num_resumes);
5105 return_value = eExpressionSetupError;
5106 break;
5107 }
5108
5109 stop_state =
5110 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5111
5112 if (stop_state != eStateRunning) {
5113 bool restarted = false;
5114
5115 if (stop_state == eStateStopped) {
5116 restarted = Process::ProcessEventData::GetRestartedFromEvent(
5117 event_sp.get());
5118 if (log)
5119 log->Printf(
5120 "Process::RunThreadPlan(): didn't get running event after "
5121 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5122 "handle_running_event: %i).",
5123 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5124 handle_running_event);
5125 }
5126
5127 if (restarted) {
5128 // This is probably an overabundance of caution, I don't think I
Adrian Prantl05097242018-04-30 16:49:04 +00005129 // should ever get a stopped & restarted event here. But if I do,
5130 // the best thing is to Halt and then get out of here.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005131 const bool clear_thread_plans = false;
5132 const bool use_run_lock = false;
5133 Halt(clear_thread_plans, use_run_lock);
5134 }
5135
5136 diagnostic_manager.Printf(
5137 eDiagnosticSeverityError,
5138 "didn't get running event after initial resume, got %s instead.",
5139 StateAsCString(stop_state));
5140 return_value = eExpressionSetupError;
5141 break;
5142 }
5143
5144 if (log)
5145 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
Adrian Prantl05097242018-04-30 16:49:04 +00005146 // We need to call the function synchronously, so spin waiting for it
5147 // to return. If we get interrupted while executing, we're going to
5148 // lose our context, and won't be able to gather the result at this
5149 // point. We set the timeout AFTER the resume, since the resume takes
5150 // some time and we don't want to charge that to the timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005151 } else {
5152 if (log)
5153 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5154 }
5155
Kate Stoneb9c1b512016-09-06 20:57:50 +00005156 do_resume = true;
5157 handle_running_event = true;
5158
5159 // Now wait for the process to stop again:
5160 event_sp.reset();
5161
Pavel Labath2ce22162016-12-01 10:57:30 +00005162 Timeout<std::micro> timeout =
5163 GetExpressionTimeout(options, before_first_timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005164 if (log) {
Pavel Labath2ce22162016-12-01 10:57:30 +00005165 if (timeout) {
5166 auto now = system_clock::now();
5167 log->Printf("Process::RunThreadPlan(): about to wait - now is %s - "
5168 "endpoint is %s",
5169 llvm::to_string(now).c_str(),
5170 llvm::to_string(now + *timeout).c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00005171 } else {
5172 log->Printf("Process::RunThreadPlan(): about to wait forever.");
Jason Molendaef7d6412015-08-06 03:27:10 +00005173 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005174 }
5175
5176#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5177 // See comment above...
5178 if (miss_first_event) {
5179 usleep(1000);
5180 miss_first_event = false;
5181 got_event = false;
5182 } else
5183#endif
Pavel Labath2ce22162016-12-01 10:57:30 +00005184 got_event = listener_sp->GetEvent(event_sp, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005185
5186 if (got_event) {
5187 if (event_sp) {
5188 bool keep_going = false;
5189 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5190 const bool clear_thread_plans = false;
5191 const bool use_run_lock = false;
5192 Halt(clear_thread_plans, use_run_lock);
5193 return_value = eExpressionInterrupted;
Zachary Turnere2411fa2016-11-12 19:12:56 +00005194 diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5195 "execution halted by user interrupt.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005196 if (log)
5197 log->Printf("Process::RunThreadPlan(): Got interrupted by "
5198 "eBroadcastBitInterrupted, exiting.");
5199 break;
5200 } else {
5201 stop_state =
5202 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5203 if (log)
5204 log->Printf(
5205 "Process::RunThreadPlan(): in while loop, got event: %s.",
5206 StateAsCString(stop_state));
5207
5208 switch (stop_state) {
5209 case lldb::eStateStopped: {
5210 // We stopped, figure out what we are going to do now.
5211 ThreadSP thread_sp =
5212 GetThreadList().FindThreadByIndexID(thread_idx_id);
5213 if (!thread_sp) {
5214 // Ooh, our thread has vanished. Unlikely that this was
5215 // successful execution...
5216 if (log)
5217 log->Printf("Process::RunThreadPlan(): execution completed "
5218 "but our thread (index-id=%u) has vanished.",
5219 thread_idx_id);
5220 return_value = eExpressionInterrupted;
Pavel Labath45dde232017-05-25 10:50:06 +00005221 } else if (Process::ProcessEventData::GetRestartedFromEvent(
5222 event_sp.get())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005223 // If we were restarted, we just need to go back up to fetch
5224 // another event.
Pavel Labath45dde232017-05-25 10:50:06 +00005225 if (log) {
5226 log->Printf("Process::RunThreadPlan(): Got a stop and "
5227 "restart, so we'll continue waiting.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005228 }
Pavel Labath45dde232017-05-25 10:50:06 +00005229 keep_going = true;
5230 do_resume = false;
5231 handle_running_event = true;
5232 } else {
5233 const bool handle_interrupts = true;
5234 return_value = *HandleStoppedEvent(
5235 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5236 event_to_broadcast_sp, options, handle_interrupts);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005237 }
5238 } break;
5239
5240 case lldb::eStateRunning:
5241 // This shouldn't really happen, but sometimes we do get two
Adrian Prantl05097242018-04-30 16:49:04 +00005242 // running events without an intervening stop, and in that case
5243 // we should just go back to waiting for the stop.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005244 do_resume = false;
5245 keep_going = true;
5246 handle_running_event = false;
5247 break;
5248
5249 default:
5250 if (log)
5251 log->Printf("Process::RunThreadPlan(): execution stopped with "
5252 "unexpected state: %s.",
5253 StateAsCString(stop_state));
5254
5255 if (stop_state == eStateExited)
5256 event_to_broadcast_sp = event_sp;
5257
Zachary Turnere2411fa2016-11-12 19:12:56 +00005258 diagnostic_manager.PutString(
Kate Stoneb9c1b512016-09-06 20:57:50 +00005259 eDiagnosticSeverityError,
5260 "execution stopped with unexpected state.");
5261 return_value = eExpressionInterrupted;
5262 break;
5263 }
5264 }
5265
5266 if (keep_going)
5267 continue;
5268 else
5269 break;
5270 } else {
5271 if (log)
5272 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5273 "the event pointer was null. How odd...");
5274 return_value = eExpressionInterrupted;
5275 break;
5276 }
5277 } else {
Adrian Prantl05097242018-04-30 16:49:04 +00005278 // If we didn't get an event that means we've timed out... We will
5279 // interrupt the process here. Depending on what we were asked to do
5280 // we will either exit, or try with all threads running for the same
5281 // timeout.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005282
5283 if (log) {
5284 if (options.GetTryAllThreads()) {
5285 if (before_first_timeout) {
Pavel Labathd02b1c82017-02-10 11:49:33 +00005286 LLDB_LOG(log,
5287 "Running function with one thread timeout timed out.");
Kate Stoneb9c1b512016-09-06 20:57:50 +00005288 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005289 LLDB_LOG(log, "Restarting function with all threads enabled and "
5290 "timeout: {0} timed out, abandoning execution.",
5291 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005292 } else
Pavel Labathd02b1c82017-02-10 11:49:33 +00005293 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5294 "abandoning execution.",
5295 timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005296 }
5297
5298 // It is possible that between the time we issued the Halt, and we get
Adrian Prantl05097242018-04-30 16:49:04 +00005299 // around to calling Halt the target could have stopped. That's fine,
5300 // Halt will figure that out and send the appropriate Stopped event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005301 // BUT it is also possible that we stopped & restarted (e.g. hit a
5302 // signal with "stop" set to false.) In
5303 // that case, we'll get the stopped & restarted event, and we should go
Adrian Prantl05097242018-04-30 16:49:04 +00005304 // back to waiting for the Halt's stopped event. That's what this
5305 // while loop does.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005306
5307 bool back_to_top = true;
5308 uint32_t try_halt_again = 0;
5309 bool do_halt = true;
5310 const uint32_t num_retries = 5;
5311 while (try_halt_again < num_retries) {
Zachary Turner97206d52017-05-12 04:51:55 +00005312 Status halt_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005313 if (do_halt) {
5314 if (log)
5315 log->Printf("Process::RunThreadPlan(): Running Halt.");
5316 const bool clear_thread_plans = false;
5317 const bool use_run_lock = false;
5318 Halt(clear_thread_plans, use_run_lock);
5319 }
5320 if (halt_error.Success()) {
5321 if (log)
5322 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5323
Pavel Labathd35031e12016-11-30 10:41:42 +00005324 got_event =
5325 listener_sp->GetEvent(event_sp, std::chrono::milliseconds(500));
Kate Stoneb9c1b512016-09-06 20:57:50 +00005326
5327 if (got_event) {
5328 stop_state =
5329 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5330 if (log) {
5331 log->Printf("Process::RunThreadPlan(): Stopped with event: %s",
5332 StateAsCString(stop_state));
5333 if (stop_state == lldb::eStateStopped &&
5334 Process::ProcessEventData::GetInterruptedFromEvent(
5335 event_sp.get()))
5336 log->PutCString(" Event was the Halt interruption event.");
5337 }
5338
5339 if (stop_state == lldb::eStateStopped) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005340 if (Process::ProcessEventData::GetRestartedFromEvent(
5341 event_sp.get())) {
5342 if (log)
5343 log->PutCString("Process::RunThreadPlan(): Went to halt "
5344 "but got a restarted event, there must be "
5345 "an un-restarted stopped event so try "
5346 "again... "
5347 "Exiting wait loop.");
5348 try_halt_again++;
5349 do_halt = false;
5350 continue;
5351 }
5352
Pavel Labath45dde232017-05-25 10:50:06 +00005353 // Between the time we initiated the Halt and the time we
Adrian Prantl05097242018-04-30 16:49:04 +00005354 // delivered it, the process could have already finished its
5355 // job. Check that here:
Pavel Labath45dde232017-05-25 10:50:06 +00005356 const bool handle_interrupts = false;
5357 if (auto result = HandleStoppedEvent(
5358 *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5359 event_to_broadcast_sp, options, handle_interrupts)) {
5360 return_value = *result;
5361 back_to_top = false;
5362 break;
5363 }
5364
Kate Stoneb9c1b512016-09-06 20:57:50 +00005365 if (!options.GetTryAllThreads()) {
5366 if (log)
5367 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5368 "was false, we stopped so now we're "
5369 "quitting.");
5370 return_value = eExpressionInterrupted;
5371 back_to_top = false;
5372 break;
5373 }
5374
5375 if (before_first_timeout) {
5376 // Set all the other threads to run, and return to the top of
5377 // the loop, which will continue;
5378 before_first_timeout = false;
5379 thread_plan_sp->SetStopOthers(false);
5380 if (log)
5381 log->PutCString(
5382 "Process::RunThreadPlan(): about to resume.");
5383
5384 back_to_top = true;
5385 break;
5386 } else {
5387 // Running all threads failed, so return Interrupted.
5388 if (log)
5389 log->PutCString("Process::RunThreadPlan(): running all "
5390 "threads timed out.");
5391 return_value = eExpressionInterrupted;
5392 back_to_top = false;
5393 break;
5394 }
5395 }
5396 } else {
5397 if (log)
5398 log->PutCString("Process::RunThreadPlan(): halt said it "
5399 "succeeded, but I got no event. "
5400 "I'm getting out of here passing Interrupted.");
5401 return_value = eExpressionInterrupted;
5402 back_to_top = false;
5403 break;
5404 }
5405 } else {
5406 try_halt_again++;
5407 continue;
5408 }
5409 }
5410
5411 if (!back_to_top || try_halt_again > num_retries)
5412 break;
5413 else
5414 continue;
5415 }
5416 } // END WAIT LOOP
5417
Adrian Prantl05097242018-04-30 16:49:04 +00005418 // If we had to start up a temporary private state thread to run this
5419 // thread plan, shut it down now.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005420 if (backup_private_state_thread.IsJoinable()) {
5421 StopPrivateStateThread();
Zachary Turner97206d52017-05-12 04:51:55 +00005422 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005423 m_private_state_thread = backup_private_state_thread;
5424 if (stopper_base_plan_sp) {
5425 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5426 }
5427 if (old_state != eStateInvalid)
5428 m_public_state.SetValueNoLock(old_state);
Jason Molendaef7d6412015-08-06 03:27:10 +00005429 }
5430
Kate Stoneb9c1b512016-09-06 20:57:50 +00005431 if (return_value != eExpressionCompleted && log) {
5432 // Print a backtrace into the log so we can figure out where we are:
5433 StreamString s;
5434 s.PutCString("Thread state after unsuccessful completion: \n");
5435 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
Zachary Turnerc1564272016-11-16 21:15:24 +00005436 log->PutString(s.GetString());
Jason Molendaef7d6412015-08-06 03:27:10 +00005437 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005438 // Restore the thread state if we are going to discard the plan execution.
Adrian Prantl05097242018-04-30 16:49:04 +00005439 // There are three cases where this could happen: 1) The execution
5440 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5441 // was true 3) We got some other error, and discard_on_error was true
Kate Stoneb9c1b512016-09-06 20:57:50 +00005442 bool should_unwind = (return_value == eExpressionInterrupted &&
5443 options.DoesUnwindOnError()) ||
5444 (return_value == eExpressionHitBreakpoint &&
5445 options.DoesIgnoreBreakpoints());
5446
5447 if (return_value == eExpressionCompleted || should_unwind) {
5448 thread_plan_sp->RestoreThreadState();
5449 }
5450
5451 // Now do some processing on the results of the run:
5452 if (return_value == eExpressionInterrupted ||
5453 return_value == eExpressionHitBreakpoint) {
5454 if (log) {
5455 StreamString s;
5456 if (event_sp)
5457 event_sp->Dump(&s);
5458 else {
5459 log->PutCString("Process::RunThreadPlan(): Stop event that "
5460 "interrupted us is NULL.");
5461 }
5462
5463 StreamString ts;
5464
5465 const char *event_explanation = nullptr;
5466
5467 do {
5468 if (!event_sp) {
5469 event_explanation = "<no event>";
5470 break;
5471 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5472 event_explanation = "<user interrupt>";
5473 break;
5474 } else {
5475 const Process::ProcessEventData *event_data =
5476 Process::ProcessEventData::GetEventDataFromEvent(
5477 event_sp.get());
5478
5479 if (!event_data) {
5480 event_explanation = "<no event data>";
5481 break;
5482 }
5483
5484 Process *process = event_data->GetProcessSP().get();
5485
5486 if (!process) {
5487 event_explanation = "<no process>";
5488 break;
5489 }
5490
5491 ThreadList &thread_list = process->GetThreadList();
5492
5493 uint32_t num_threads = thread_list.GetSize();
5494 uint32_t thread_index;
5495
5496 ts.Printf("<%u threads> ", num_threads);
5497
5498 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5499 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5500
5501 if (!thread) {
5502 ts.Printf("<?> ");
5503 continue;
5504 }
5505
5506 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5507 RegisterContext *register_context =
5508 thread->GetRegisterContext().get();
5509
5510 if (register_context)
5511 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5512 else
5513 ts.Printf("[ip unknown] ");
5514
5515 // Show the private stop info here, the public stop info will be
5516 // from the last natural stop.
5517 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5518 if (stop_info_sp) {
5519 const char *stop_desc = stop_info_sp->GetDescription();
5520 if (stop_desc)
5521 ts.PutCString(stop_desc);
5522 }
5523 ts.Printf(">");
5524 }
5525
5526 event_explanation = ts.GetData();
5527 }
5528 } while (0);
5529
5530 if (event_explanation)
5531 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s",
5532 s.GetData(), event_explanation);
5533 else
5534 log->Printf("Process::RunThreadPlan(): execution interrupted: %s",
5535 s.GetData());
5536 }
5537
5538 if (should_unwind) {
5539 if (log)
5540 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - "
5541 "discarding thread plans up to %p.",
5542 static_cast<void *>(thread_plan_sp.get()));
5543 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5544 } else {
5545 if (log)
5546 log->Printf("Process::RunThreadPlan: ExecutionInterrupted - for "
5547 "plan: %p not discarding.",
5548 static_cast<void *>(thread_plan_sp.get()));
5549 }
5550 } else if (return_value == eExpressionSetupError) {
5551 if (log)
5552 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5553
5554 if (options.DoesUnwindOnError()) {
5555 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5556 }
5557 } else {
5558 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5559 if (log)
5560 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5561 return_value = eExpressionCompleted;
5562 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5563 if (log)
5564 log->PutCString(
5565 "Process::RunThreadPlan(): thread plan was discarded");
5566 return_value = eExpressionDiscarded;
5567 } else {
5568 if (log)
5569 log->PutCString(
5570 "Process::RunThreadPlan(): thread plan stopped in mid course");
5571 if (options.DoesUnwindOnError() && thread_plan_sp) {
5572 if (log)
5573 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5574 "'cause unwind_on_error is set.");
5575 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5576 }
5577 }
5578 }
5579
5580 // Thread we ran the function in may have gone away because we ran the
Adrian Prantl05097242018-04-30 16:49:04 +00005581 // target Check that it's still there, and if it is put it back in the
5582 // context. Also restore the frame in the context if it is still present.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005583 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5584 if (thread) {
5585 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5586 }
5587
5588 // Also restore the current process'es selected frame & thread, since this
Adrian Prantl05097242018-04-30 16:49:04 +00005589 // function calling may be done behind the user's back.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005590
5591 if (selected_tid != LLDB_INVALID_THREAD_ID) {
5592 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5593 selected_stack_id.IsValid()) {
5594 // We were able to restore the selected thread, now restore the frame:
5595 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5596 StackFrameSP old_frame_sp =
5597 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5598 selected_stack_id);
5599 if (old_frame_sp)
5600 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5601 old_frame_sp.get());
5602 }
5603 }
5604 }
5605
5606 // If the process exited during the run of the thread plan, notify everyone.
5607
5608 if (event_to_broadcast_sp) {
5609 if (log)
5610 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5611 BroadcastEvent(event_to_broadcast_sp);
5612 }
5613
5614 return return_value;
Jason Molendaef7d6412015-08-06 03:27:10 +00005615}
5616
Kate Stoneb9c1b512016-09-06 20:57:50 +00005617const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5618 const char *result_name;
5619
5620 switch (result) {
5621 case eExpressionCompleted:
5622 result_name = "eExpressionCompleted";
5623 break;
5624 case eExpressionDiscarded:
5625 result_name = "eExpressionDiscarded";
5626 break;
5627 case eExpressionInterrupted:
5628 result_name = "eExpressionInterrupted";
5629 break;
5630 case eExpressionHitBreakpoint:
5631 result_name = "eExpressionHitBreakpoint";
5632 break;
5633 case eExpressionSetupError:
5634 result_name = "eExpressionSetupError";
5635 break;
5636 case eExpressionParseError:
5637 result_name = "eExpressionParseError";
5638 break;
5639 case eExpressionResultUnavailable:
5640 result_name = "eExpressionResultUnavailable";
5641 break;
5642 case eExpressionTimedOut:
5643 result_name = "eExpressionTimedOut";
5644 break;
5645 case eExpressionStoppedForDebug:
5646 result_name = "eExpressionStoppedForDebug";
5647 break;
5648 }
5649 return result_name;
Jason Molenda484900b2015-08-10 07:55:25 +00005650}
5651
Kate Stoneb9c1b512016-09-06 20:57:50 +00005652void Process::GetStatus(Stream &strm) {
5653 const StateType state = GetState();
5654 if (StateIsStoppedState(state, false)) {
5655 if (state == eStateExited) {
5656 int exit_status = GetExitStatus();
5657 const char *exit_description = GetExitDescription();
5658 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5659 GetID(), exit_status, exit_status,
5660 exit_description ? exit_description : "");
5661 } else {
5662 if (state == eStateConnected)
5663 strm.Printf("Connected to remote target.\n");
5664 else
5665 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5666 }
5667 } else {
5668 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5669 }
Pavel Labatha933d512016-04-05 13:07:16 +00005670}
5671
Kate Stoneb9c1b512016-09-06 20:57:50 +00005672size_t Process::GetThreadStatus(Stream &strm,
5673 bool only_threads_with_stop_reason,
5674 uint32_t start_frame, uint32_t num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005675 uint32_t num_frames_with_source,
5676 bool stop_format) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005677 size_t num_thread_infos_dumped = 0;
Greg Clayton35ca64b2015-04-16 17:13:34 +00005678
Kate Stoneb9c1b512016-09-06 20:57:50 +00005679 // You can't hold the thread list lock while calling Thread::GetStatus. That
Adrian Prantl05097242018-04-30 16:49:04 +00005680 // very well might run code (e.g. if we need it to get return values or
5681 // arguments.) For that to work the process has to be able to acquire it.
5682 // So instead copy the thread ID's, and look them up one by one:
Kate Stoneb9c1b512016-09-06 20:57:50 +00005683
5684 uint32_t num_threads;
5685 std::vector<lldb::tid_t> thread_id_array;
5686 // Scope for thread list locker;
5687 {
5688 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5689 ThreadList &curr_thread_list = GetThreadList();
5690 num_threads = curr_thread_list.GetSize();
5691 uint32_t idx;
5692 thread_id_array.resize(num_threads);
5693 for (idx = 0; idx < num_threads; ++idx)
5694 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5695 }
5696
5697 for (uint32_t i = 0; i < num_threads; i++) {
5698 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5699 if (thread_sp) {
5700 if (only_threads_with_stop_reason) {
5701 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5702 if (!stop_info_sp || !stop_info_sp->IsValid())
5703 continue;
5704 }
5705 thread_sp->GetStatus(strm, start_frame, num_frames,
Jim Ingham6a9767c2016-11-08 20:36:40 +00005706 num_frames_with_source,
5707 stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005708 ++num_thread_infos_dumped;
5709 } else {
5710 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5711 if (log)
5712 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64
5713 " vanished while running Thread::GetStatus.");
Kuba Breckaa51ea382014-09-06 01:33:13 +00005714 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00005715 }
5716 return num_thread_infos_dumped;
5717}
5718
5719void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5720 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5721}
5722
5723bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5724 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5725 region.GetByteSize());
5726}
5727
5728void Process::AddPreResumeAction(PreResumeActionCallback callback,
5729 void *baton) {
5730 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5731}
5732
5733bool Process::RunPreResumeActions() {
5734 bool result = true;
5735 while (!m_pre_resume_actions.empty()) {
5736 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5737 m_pre_resume_actions.pop_back();
5738 bool this_result = action.callback(action.baton);
5739 if (result)
5740 result = this_result;
5741 }
5742 return result;
5743}
5744
5745void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5746
Jim Inghamffd91752016-10-20 22:50:00 +00005747void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5748{
5749 PreResumeCallbackAndBaton element(callback, baton);
5750 auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5751 if (found_iter != m_pre_resume_actions.end())
5752 {
5753 m_pre_resume_actions.erase(found_iter);
5754 }
5755}
5756
Kate Stoneb9c1b512016-09-06 20:57:50 +00005757ProcessRunLock &Process::GetRunLock() {
5758 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5759 return m_private_run_lock;
5760 else
5761 return m_public_run_lock;
5762}
5763
5764void Process::Flush() {
5765 m_thread_list.Flush();
5766 m_extended_thread_list.Flush();
5767 m_extended_thread_stop_id = 0;
5768 m_queue_list.Clear();
5769 m_queue_list_stop_id = 0;
5770}
5771
5772void Process::DidExec() {
5773 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5774 if (log)
5775 log->Printf("Process::%s()", __FUNCTION__);
5776
5777 Target &target = GetTarget();
5778 target.CleanupProcess();
5779 target.ClearModules(false);
5780 m_dynamic_checkers_ap.reset();
5781 m_abi_sp.reset();
5782 m_system_runtime_ap.reset();
5783 m_os_ap.reset();
5784 m_dyld_ap.reset();
5785 m_jit_loaders_ap.reset();
5786 m_image_tokens.clear();
5787 m_allocated_memory_cache.Clear();
5788 m_language_runtimes.clear();
5789 m_instrumentation_runtimes.clear();
5790 m_thread_list.DiscardThreadPlans();
5791 m_memory_cache.Clear(true);
Kate Stoneb9c1b512016-09-06 20:57:50 +00005792 DoDidExec();
5793 CompleteAttach();
5794 // Flush the process (threads and all stack frames) after running
Adrian Prantl05097242018-04-30 16:49:04 +00005795 // CompleteAttach() in case the dynamic loader loaded things in new
5796 // locations.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005797 Flush();
5798
Adrian Prantl05097242018-04-30 16:49:04 +00005799 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5800 // let the target know so it can do any cleanup it needs to.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005801 target.DidExec();
5802}
5803
Zachary Turner97206d52017-05-12 04:51:55 +00005804addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00005805 if (address == nullptr) {
5806 error.SetErrorString("Invalid address argument");
5807 return LLDB_INVALID_ADDRESS;
5808 }
5809
5810 addr_t function_addr = LLDB_INVALID_ADDRESS;
5811
5812 addr_t addr = address->GetLoadAddress(&GetTarget());
5813 std::map<addr_t, addr_t>::const_iterator iter =
5814 m_resolved_indirect_addresses.find(addr);
5815 if (iter != m_resolved_indirect_addresses.end()) {
5816 function_addr = (*iter).second;
5817 } else {
5818 if (!InferiorCall(this, address, function_addr)) {
5819 Symbol *symbol = address->CalculateSymbolContextSymbol();
5820 error.SetErrorStringWithFormat(
5821 "Unable to call resolver for indirect function %s",
5822 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5823 function_addr = LLDB_INVALID_ADDRESS;
5824 } else {
5825 m_resolved_indirect_addresses.insert(
5826 std::pair<addr_t, addr_t>(addr, function_addr));
5827 }
5828 }
5829 return function_addr;
5830}
5831
5832void Process::ModulesDidLoad(ModuleList &module_list) {
5833 SystemRuntime *sys_runtime = GetSystemRuntime();
5834 if (sys_runtime) {
5835 sys_runtime->ModulesDidLoad(module_list);
5836 }
5837
5838 GetJITLoaders().ModulesDidLoad(module_list);
5839
5840 // Give runtimes a chance to be created.
5841 InstrumentationRuntime::ModulesDidLoad(module_list, this,
5842 m_instrumentation_runtimes);
5843
5844 // Tell runtimes about new modules.
5845 for (auto pos = m_instrumentation_runtimes.begin();
5846 pos != m_instrumentation_runtimes.end(); ++pos) {
5847 InstrumentationRuntimeSP runtime = pos->second;
5848 runtime->ModulesDidLoad(module_list);
5849 }
5850
Adrian Prantl05097242018-04-30 16:49:04 +00005851 // Let any language runtimes we have already created know about the modules
5852 // that loaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005853
Adrian Prantl05097242018-04-30 16:49:04 +00005854 // Iterate over a copy of this language runtime list in case the language
Leonard Mosescu9ba51572018-08-07 18:00:30 +00005855 // runtime ModulesDidLoad somehow causes the language runtime to be
Adrian Prantl05097242018-04-30 16:49:04 +00005856 // unloaded.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005857 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5858 for (const auto &pair : language_runtimes) {
Adrian Prantl05097242018-04-30 16:49:04 +00005859 // We must check language_runtime_sp to make sure it is not nullptr as we
5860 // might cache the fact that we didn't have a language runtime for a
5861 // language.
Kate Stoneb9c1b512016-09-06 20:57:50 +00005862 LanguageRuntimeSP language_runtime_sp = pair.second;
5863 if (language_runtime_sp)
5864 language_runtime_sp->ModulesDidLoad(module_list);
5865 }
5866
5867 // If we don't have an operating system plug-in, try to load one since
5868 // loading shared libraries might cause a new one to try and load
5869 if (!m_os_ap)
5870 LoadOperatingSystemPlugin(false);
5871
5872 // Give structured-data plugins a chance to see the modified modules.
5873 for (auto pair : m_structured_data_plugin_map) {
5874 if (pair.second)
5875 pair.second->ModulesDidLoad(*this, module_list);
5876 }
5877}
5878
5879void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5880 const char *fmt, ...) {
5881 bool print_warning = true;
5882
5883 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5884 if (!stream_sp)
5885 return;
5886 if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5887 return;
5888 }
5889
5890 if (repeat_key != nullptr) {
5891 WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5892 if (it == m_warnings_issued.end()) {
5893 m_warnings_issued[warning_type] = WarningsPointerSet();
5894 m_warnings_issued[warning_type].insert(repeat_key);
5895 } else {
5896 if (it->second.find(repeat_key) != it->second.end()) {
5897 print_warning = false;
5898 } else {
5899 it->second.insert(repeat_key);
5900 }
5901 }
5902 }
5903
5904 if (print_warning) {
5905 va_list args;
5906 va_start(args, fmt);
5907 stream_sp->PrintfVarArg(fmt, args);
5908 va_end(args);
5909 }
5910}
5911
5912void Process::PrintWarningOptimization(const SymbolContext &sc) {
5913 if (GetWarningsOptimization() && sc.module_sp &&
5914 !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5915 sc.function->GetIsOptimized()) {
5916 PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5917 "%s was compiled with optimization - stepping may behave "
5918 "oddly; variables may not be available.\n",
5919 sc.module_sp->GetFileSpec().GetFilename().GetCString());
5920 }
5921}
5922
5923bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5924 info.Clear();
5925
5926 PlatformSP platform_sp = GetTarget().GetPlatform();
5927 if (!platform_sp)
5928 return false;
5929
5930 return platform_sp->GetProcessInfo(GetID(), info);
5931}
5932
5933ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5934 ThreadCollectionSP threads;
5935
5936 const MemoryHistorySP &memory_history =
5937 MemoryHistory::FindPlugin(shared_from_this());
5938
5939 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00005940 return threads;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005941 }
5942
5943 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
5944
5945 return threads;
Kuba Breckaa51ea382014-09-06 01:33:13 +00005946}
Kuba Brecka63927542014-10-11 01:59:32 +00005947
5948InstrumentationRuntimeSP
Kate Stoneb9c1b512016-09-06 20:57:50 +00005949Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5950 InstrumentationRuntimeCollection::iterator pos;
5951 pos = m_instrumentation_runtimes.find(type);
5952 if (pos == m_instrumentation_runtimes.end()) {
5953 return InstrumentationRuntimeSP();
5954 } else
5955 return (*pos).second;
Kuba Brecka63927542014-10-11 01:59:32 +00005956}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005957
Kate Stoneb9c1b512016-09-06 20:57:50 +00005958bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5959 const ArchSpec &arch, ModuleSpec &module_spec) {
5960 module_spec.Clear();
5961 return false;
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00005962}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005963
Kate Stoneb9c1b512016-09-06 20:57:50 +00005964size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5965 m_image_tokens.push_back(image_ptr);
5966 return m_image_tokens.size() - 1;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005967}
5968
Kate Stoneb9c1b512016-09-06 20:57:50 +00005969lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5970 if (token < m_image_tokens.size())
5971 return m_image_tokens[token];
5972 return LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00005973}
5974
Kate Stoneb9c1b512016-09-06 20:57:50 +00005975void Process::ResetImageToken(size_t token) {
5976 if (token < m_image_tokens.size())
5977 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00005978}
Jason Molendafd4cea52016-01-08 21:40:11 +00005979
5980Address
Kate Stoneb9c1b512016-09-06 20:57:50 +00005981Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5982 AddressRange range_bounds) {
5983 Target &target = GetTarget();
5984 DisassemblerSP disassembler_sp;
5985 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005986
Kate Stoneb9c1b512016-09-06 20:57:50 +00005987 Address retval = default_stop_addr;
Jason Molendafd4cea52016-01-08 21:40:11 +00005988
Kate Stoneb9c1b512016-09-06 20:57:50 +00005989 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00005990 return retval;
Kate Stoneb9c1b512016-09-06 20:57:50 +00005991 if (!default_stop_addr.IsValid())
5992 return retval;
5993
5994 ExecutionContext exe_ctx(this);
5995 const char *plugin_name = nullptr;
5996 const char *flavor = nullptr;
5997 const bool prefer_file_cache = true;
5998 disassembler_sp = Disassembler::DisassembleRange(
5999 target.GetArchitecture(), plugin_name, flavor, exe_ctx, range_bounds,
6000 prefer_file_cache);
6001 if (disassembler_sp)
6002 insn_list = &disassembler_sp->GetInstructionList();
6003
6004 if (insn_list == nullptr) {
6005 return retval;
6006 }
6007
6008 size_t insn_offset =
6009 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6010 if (insn_offset == UINT32_MAX) {
6011 return retval;
6012 }
6013
6014 uint32_t branch_index =
6015 insn_list->GetIndexOfNextBranchInstruction(insn_offset, target);
6016 if (branch_index == UINT32_MAX) {
6017 return retval;
6018 }
6019
6020 if (branch_index > insn_offset) {
6021 Address next_branch_insn_address =
6022 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6023 if (next_branch_insn_address.IsValid() &&
6024 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6025 retval = next_branch_insn_address;
6026 }
6027 }
6028
6029 return retval;
Jason Molendafd4cea52016-01-08 21:40:11 +00006030}
Howard Hellyerad007562016-07-07 08:21:28 +00006031
Zachary Turner97206d52017-05-12 04:51:55 +00006032Status
6033Process::GetMemoryRegions(std::vector<lldb::MemoryRegionInfoSP> &region_list) {
Howard Hellyerad007562016-07-07 08:21:28 +00006034
Zachary Turner97206d52017-05-12 04:51:55 +00006035 Status error;
Howard Hellyerad007562016-07-07 08:21:28 +00006036
Kate Stoneb9c1b512016-09-06 20:57:50 +00006037 lldb::addr_t range_end = 0;
Howard Hellyerad007562016-07-07 08:21:28 +00006038
Kate Stoneb9c1b512016-09-06 20:57:50 +00006039 region_list.clear();
6040 do {
6041 lldb::MemoryRegionInfoSP region_info(new lldb_private::MemoryRegionInfo());
6042 error = GetMemoryRegionInfo(range_end, *region_info);
6043 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6044 if (error.Fail()) {
6045 region_list.clear();
6046 break;
Todd Fiala75930012016-08-19 04:21:48 +00006047 }
6048
Kate Stoneb9c1b512016-09-06 20:57:50 +00006049 range_end = region_info->GetRange().GetRangeEnd();
6050 if (region_info->GetMapped() == MemoryRegionInfo::eYes) {
6051 region_list.push_back(region_info);
6052 }
6053 } while (range_end != LLDB_INVALID_ADDRESS);
Todd Fiala75930012016-08-19 04:21:48 +00006054
Kate Stoneb9c1b512016-09-06 20:57:50 +00006055 return error;
6056}
6057
Zachary Turner97206d52017-05-12 04:51:55 +00006058Status
6059Process::ConfigureStructuredData(const ConstString &type_name,
6060 const StructuredData::ObjectSP &config_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00006061 // If you get this, the Process-derived class needs to implement a method to
6062 // enable an already-reported asynchronous structured data feature. See
6063 // ProcessGDBRemote for an example implementation over gdb-remote.
Zachary Turner97206d52017-05-12 04:51:55 +00006064 return Status("unimplemented");
Kate Stoneb9c1b512016-09-06 20:57:50 +00006065}
6066
6067void Process::MapSupportedStructuredDataPlugins(
6068 const StructuredData::Array &supported_type_names) {
6069 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
6070
6071 // Bail out early if there are no type names to map.
6072 if (supported_type_names.GetSize() == 0) {
Todd Fiala75930012016-08-19 04:21:48 +00006073 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00006074 log->Printf("Process::%s(): no structured data types supported",
6075 __FUNCTION__);
6076 return;
6077 }
Todd Fiala75930012016-08-19 04:21:48 +00006078
Kate Stoneb9c1b512016-09-06 20:57:50 +00006079 // Convert StructuredData type names to ConstString instances.
6080 std::set<ConstString> const_type_names;
6081
6082 if (log)
6083 log->Printf("Process::%s(): the process supports the following async "
6084 "structured data types:",
6085 __FUNCTION__);
6086
6087 supported_type_names.ForEach(
6088 [&const_type_names, &log](StructuredData::Object *object) {
6089 if (!object) {
6090 // Invalid - shouldn't be null objects in the array.
6091 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006092 }
6093
6094 auto type_name = object->GetAsString();
Kate Stoneb9c1b512016-09-06 20:57:50 +00006095 if (!type_name) {
6096 // Invalid format - all type names should be strings.
6097 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006098 }
6099
6100 const_type_names.insert(ConstString(type_name->GetValue()));
Zachary Turner28333212017-05-12 05:49:54 +00006101 LLDB_LOG(log, "- {0}", type_name->GetValue());
Todd Fiala75930012016-08-19 04:21:48 +00006102 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00006103 });
Todd Fiala75930012016-08-19 04:21:48 +00006104
Adrian Prantl05097242018-04-30 16:49:04 +00006105 // For each StructuredDataPlugin, if the plugin handles any of the types in
6106 // the supported_type_names, map that type name to that plugin. Stop when
6107 // we've consumed all the type names.
Leonard Mosescu9ba51572018-08-07 18:00:30 +00006108 // FIXME: should we return an error if there are type names nobody
Jim Ingham93979f62018-04-27 01:57:40 +00006109 // supports?
6110 for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
6111 auto create_instance =
Kate Stoneb9c1b512016-09-06 20:57:50 +00006112 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6113 plugin_index);
Jim Ingham93979f62018-04-27 01:57:40 +00006114 if (!create_instance)
6115 break;
Leonard Mosescu9ba51572018-08-07 18:00:30 +00006116
Kate Stoneb9c1b512016-09-06 20:57:50 +00006117 // Create the plugin.
6118 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
6119 if (!plugin_sp) {
Adrian Prantl05097242018-04-30 16:49:04 +00006120 // This plugin doesn't think it can work with the process. Move on to the
6121 // next.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006122 continue;
Todd Fiala75930012016-08-19 04:21:48 +00006123 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00006124
Adrian Prantl05097242018-04-30 16:49:04 +00006125 // For any of the remaining type names, map any that this plugin supports.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006126 std::vector<ConstString> names_to_remove;
6127 for (auto &type_name : const_type_names) {
6128 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6129 m_structured_data_plugin_map.insert(
6130 std::make_pair(type_name, plugin_sp));
6131 names_to_remove.push_back(type_name);
6132 if (log)
6133 log->Printf("Process::%s(): using plugin %s for type name "
6134 "%s",
6135 __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
6136 type_name.GetCString());
6137 }
6138 }
6139
6140 // Remove the type names that were consumed by this plugin.
6141 for (auto &type_name : names_to_remove)
6142 const_type_names.erase(type_name);
6143 }
Todd Fiala75930012016-08-19 04:21:48 +00006144}
6145
Kate Stoneb9c1b512016-09-06 20:57:50 +00006146bool Process::RouteAsyncStructuredData(
6147 const StructuredData::ObjectSP object_sp) {
6148 // Nothing to do if there's no data.
6149 if (!object_sp)
6150 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006151
Adrian Prantl05097242018-04-30 16:49:04 +00006152 // The contract is this must be a dictionary, so we can look up the routing
6153 // key via the top-level 'type' string value within the dictionary.
Kate Stoneb9c1b512016-09-06 20:57:50 +00006154 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6155 if (!dictionary)
6156 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006157
Kate Stoneb9c1b512016-09-06 20:57:50 +00006158 // Grab the async structured type name (i.e. the feature/plugin name).
6159 ConstString type_name;
6160 if (!dictionary->GetValueForKeyAsString("type", type_name))
6161 return false;
Todd Fiala75930012016-08-19 04:21:48 +00006162
Kate Stoneb9c1b512016-09-06 20:57:50 +00006163 // Check if there's a plugin registered for this type name.
6164 auto find_it = m_structured_data_plugin_map.find(type_name);
6165 if (find_it == m_structured_data_plugin_map.end()) {
6166 // We don't have a mapping for this structured data type.
6167 return false;
6168 }
Todd Fiala75930012016-08-19 04:21:48 +00006169
Kate Stoneb9c1b512016-09-06 20:57:50 +00006170 // Route the structured data to the plugin.
6171 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6172 return true;
Howard Hellyerad007562016-07-07 08:21:28 +00006173}
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006174
Zachary Turner97206d52017-05-12 04:51:55 +00006175Status Process::UpdateAutomaticSignalFiltering() {
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006176 // Default implementation does nothign.
6177 // No automatic signal filtering to speak of.
Zachary Turner97206d52017-05-12 04:51:55 +00006178 return Status();
Eugene Zemtsov7993cc52017-03-07 21:34:40 +00006179}
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006180
Frederic Rissd10d3792018-05-11 18:21:11 +00006181UtilityFunction *Process::GetLoadImageUtilityFunction(
6182 Platform *platform,
6183 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006184 if (platform != GetTarget().GetPlatform().get())
6185 return nullptr;
Frederic Rissd10d3792018-05-11 18:21:11 +00006186 std::call_once(m_dlopen_utility_func_flag_once,
6187 [&] { m_dlopen_utility_func_up = factory(); });
Jim Ingham1ecb34f2018-04-17 20:44:47 +00006188 return m_dlopen_utility_func_up.get();
6189}