blob: e95c8ee7f254b95aa36d4bd3ef5c694ed72ad5bc [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eugene Zelenko8f30a652015-10-23 18:39:37 +000010// C Includes
11// C++ Includes
Greg Clayton5cc45e02016-02-26 19:41:49 +000012#include <atomic>
Greg Clayton04df8ee2016-02-26 19:38:18 +000013#include <mutex>
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +000014
Eugene Zelenko8f30a652015-10-23 18:39:37 +000015// Other libraries and framework includes
16// Project includes
Sean Callanan579e70c2016-03-19 00:03:59 +000017#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Breakpoint/BreakpointLocation.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000019#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000021#include "lldb/Core/Event.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +000024#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Core/PluginManager.h"
26#include "lldb/Core/State.h"
Greg Clayton44d93782014-01-27 23:43:24 +000027#include "lldb/Core/StreamFile.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000028#include "lldb/Expression/DiagnosticManager.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000029#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000030#include "lldb/Expression/UserExpression.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000031#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000032#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000034#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000035#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000036#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000037#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000038#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000039#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000040#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000041#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042#include "lldb/Target/ABI.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000043#include "lldb/Target/CPPLanguageRuntime.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000044#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000045#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000046#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000047#include "lldb/Target/JITLoaderList.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000048#include "lldb/Target/LanguageRuntime.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000049#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000050#include "lldb/Target/MemoryRegionInfo.h"
Jim Ingham22777012010-09-23 02:01:19 +000051#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000052#include "lldb/Target/OperatingSystem.h"
Greg Claytone996fd32011-03-08 22:40:15 +000053#include "lldb/Target/Platform.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000054#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000056#include "lldb/Target/StopInfo.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"
Zachary Turner50232572015-03-18 21:31:45 +000064#include "lldb/Utility/NameMatches.h"
Greg Claytonee1f5782016-08-10 22:43:48 +000065#include "lldb/Utility/SelectHelper.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066
67using namespace lldb;
68using namespace lldb_private;
69
Greg Clayton67cc0632012-08-22 17:17:09 +000070// Comment out line below to disable memory caching, overriding the process setting
71// target.process.disable-memory-cache
72#define ENABLE_MEMORY_CACHING
73
74#ifdef ENABLE_MEMORY_CACHING
75#define DISABLE_MEM_CACHE_DEFAULT false
76#else
77#define DISABLE_MEM_CACHE_DEFAULT true
78#endif
79
80class ProcessOptionValueProperties : public OptionValueProperties
81{
82public:
83 ProcessOptionValueProperties (const ConstString &name) :
84 OptionValueProperties (name)
85 {
86 }
87
88 // This constructor is used when creating ProcessOptionValueProperties when it
89 // is part of a new lldb_private::Process instance. It will copy all current
90 // global property values as needed
91 ProcessOptionValueProperties (ProcessProperties *global_properties) :
92 OptionValueProperties(*global_properties->GetValueProperties())
93 {
94 }
95
Eugene Zelenko8f30a652015-10-23 18:39:37 +000096 const Property *
97 GetPropertyAtIndex(const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const override
Greg Clayton67cc0632012-08-22 17:17:09 +000098 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000099 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +0000100 // try and grab the setting from the current process if there is one. Else we just
101 // use the one from this instance.
102 if (exe_ctx)
103 {
104 Process *process = exe_ctx->GetProcessPtr();
105 if (process)
106 {
107 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
108 if (this != instance_properties)
109 return instance_properties->ProtectedGetPropertyAtIndex (idx);
110 }
111 }
112 return ProtectedGetPropertyAtIndex (idx);
113 }
114};
115
116static PropertyDefinition
117g_properties[] =
118{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000119 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, nullptr, nullptr, "Disable reading and caching of memory in fixed-size units." },
120 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, nullptr, nullptr, "A list containing extra commands understood by the particular process plugin used. "
Jim Ingham8c3f2762012-11-29 00:41:12 +0000121 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000122 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, breakpoints will be ignored during expression evaluation." },
123 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
124 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, nullptr, nullptr, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
125 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, stop when a shared library is loaded or unloaded." },
126 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, detach will attempt to keep the process stopped." },
127 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, nullptr, nullptr, "The memory cache line size" },
128 { "optimization-warnings" , OptionValue::eTypeBoolean, false, true, nullptr, nullptr, "If true, warn when stopped in code that is optimized where stepping and variable availability may not behave as expected." },
129 { nullptr , OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr }
Greg Clayton67cc0632012-08-22 17:17:09 +0000130};
131
132enum {
133 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000134 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000135 ePropertyIgnoreBreakpointsInExpressions,
136 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000137 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000138 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54 +0000139 ePropertyDetachKeepsStopped,
Jason Molendaef7d6412015-08-06 03:27:10 +0000140 ePropertyMemCacheLineSize,
141 ePropertyWarningOptimization
Greg Clayton67cc0632012-08-22 17:17:09 +0000142};
143
Greg Clayton332e8b12015-01-13 21:13:08 +0000144ProcessProperties::ProcessProperties (lldb_private::Process *process) :
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000145 Properties(),
146 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000147{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000148 if (process == nullptr)
Greg Clayton67cc0632012-08-22 17:17:09 +0000149 {
Greg Clayton332e8b12015-01-13 21:13:08 +0000150 // Global process properties, set them up one time
Greg Clayton67cc0632012-08-22 17:17:09 +0000151 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
152 m_collection_sp->Initialize(g_properties);
153 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000154 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000155 true,
156 Thread::GetGlobalProperties()->GetValueProperties());
157 }
158 else
Greg Clayton332e8b12015-01-13 21:13:08 +0000159 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000160 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
Greg Clayton332e8b12015-01-13 21:13:08 +0000161 m_collection_sp->SetValueChangedCallback(ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this);
162 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000163}
164
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000165ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000166
Greg Clayton332e8b12015-01-13 21:13:08 +0000167void
168ProcessProperties::OptionValueChangedCallback (void *baton, OptionValue *option_value)
169{
170 ProcessProperties *properties = (ProcessProperties *)baton;
171 if (properties->m_process)
172 properties->m_process->LoadOperatingSystemPlugin(true);
173}
174
Greg Clayton67cc0632012-08-22 17:17:09 +0000175bool
176ProcessProperties::GetDisableMemoryCache() const
177{
178 const uint32_t idx = ePropertyDisableMemCache;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000179 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000180}
181
Jason Molendaf0340c92014-09-03 22:30:54 +0000182uint64_t
183ProcessProperties::GetMemoryCacheLineSize() const
184{
185 const uint32_t idx = ePropertyMemCacheLineSize;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000186 return m_collection_sp->GetPropertyAtIndexAsUInt64(nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000187}
188
Greg Clayton67cc0632012-08-22 17:17:09 +0000189Args
190ProcessProperties::GetExtraStartupCommands () const
191{
192 Args args;
193 const uint32_t idx = ePropertyExtraStartCommand;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000194 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000195 return args;
196}
197
198void
199ProcessProperties::SetExtraStartupCommands (const Args &args)
200{
201 const uint32_t idx = ePropertyExtraStartCommand;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000202 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000203}
204
Greg Claytonc9d645d2012-10-18 22:40:37 +0000205FileSpec
206ProcessProperties::GetPythonOSPluginPath () const
207{
208 const uint32_t idx = ePropertyPythonOSPluginPath;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000209 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000210}
211
212void
213ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
214{
215 const uint32_t idx = ePropertyPythonOSPluginPath;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000216 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000217}
218
Jim Ingham184e9812013-01-15 02:47:48 +0000219bool
220ProcessProperties::GetIgnoreBreakpointsInExpressions () const
221{
222 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000223 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000224}
225
226void
227ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
228{
229 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000230 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000231}
232
233bool
234ProcessProperties::GetUnwindOnErrorInExpressions () const
235{
236 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000237 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000238}
239
240void
241ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
242{
243 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000244 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000245}
246
Jim Ingham29950772013-01-26 02:19:28 +0000247bool
248ProcessProperties::GetStopOnSharedLibraryEvents () const
249{
250 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000251 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000252}
253
254void
255ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
256{
257 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000258 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
Jim Ingham29950772013-01-26 02:19:28 +0000259}
260
Jim Inghamacff8952013-05-02 00:27:30 +0000261bool
262ProcessProperties::GetDetachKeepsStopped () const
263{
264 const uint32_t idx = ePropertyDetachKeepsStopped;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000265 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghamacff8952013-05-02 00:27:30 +0000266}
267
268void
269ProcessProperties::SetDetachKeepsStopped (bool stop)
270{
271 const uint32_t idx = ePropertyDetachKeepsStopped;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000272 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
Jim Inghamacff8952013-05-02 00:27:30 +0000273}
274
Jason Molendaef7d6412015-08-06 03:27:10 +0000275bool
276ProcessProperties::GetWarningsOptimization () const
277{
278 const uint32_t idx = ePropertyWarningOptimization;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000279 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000280}
281
Greg Clayton32e0a752011-03-30 18:16:51 +0000282void
Greg Clayton8b82f082011-04-12 05:54:46 +0000283ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000284{
285 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000286 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000287 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000288
289 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000290 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000291
292 if (m_executable)
293 {
294 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
295 s.PutCString (" file = ");
296 m_executable.Dump(&s);
297 s.EOL();
298 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000299 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000300 if (argc > 0)
301 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000302 for (uint32_t i = 0; i < argc; i++)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000303 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000304 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000305 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000306 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000307 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000308 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000309 }
310 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000311
312 const uint32_t envc = m_environment.GetArgumentCount();
313 if (envc > 0)
314 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000315 for (uint32_t i = 0; i < envc; i++)
Greg Clayton8b82f082011-04-12 05:54:46 +0000316 {
317 const char *env = m_environment.GetArgumentAtIndex(i);
318 if (i < 10)
319 s.Printf (" env[%u] = %s\n", i, env);
320 else
321 s.Printf ("env[%u] = %s\n", i, env);
322 }
323 }
324
Todd Fiala7df337f2015-10-13 23:41:19 +0000325 if (m_arch.IsValid())
326 {
327 s.Printf (" arch = ");
328 m_arch.DumpTriple(s);
329 s.EOL();
330 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000331
Greg Clayton8b82f082011-04-12 05:54:46 +0000332 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000333 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000334 cstr = platform->GetUserName (m_uid);
335 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000336 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000337 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000338 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000339 cstr = platform->GetGroupName (m_gid);
340 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000341 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000342 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000343 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000344 cstr = platform->GetUserName (m_euid);
345 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000346 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000347 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000348 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000349 cstr = platform->GetGroupName (m_egid);
350 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000351 }
352}
353
354void
Greg Clayton8b82f082011-04-12 05:54:46 +0000355ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000356{
Greg Clayton8b82f082011-04-12 05:54:46 +0000357 const char *label;
358 if (show_args || verbose)
359 label = "ARGUMENTS";
360 else
361 label = "NAME";
362
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000363 if (verbose)
364 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000365 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000366 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
367 }
368 else
369 {
Jim Ingham368ac222014-08-15 17:05:27 +0000370 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
371 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000372 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000373}
374
375void
Greg Clayton8b82f082011-04-12 05:54:46 +0000376ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000377{
378 if (m_pid != LLDB_INVALID_PROCESS_ID)
379 {
380 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000381 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000382
Todd Fiala7df337f2015-10-13 23:41:19 +0000383 StreamString arch_strm;
384 if (m_arch.IsValid())
385 m_arch.DumpTriple(arch_strm);
386
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000387 if (verbose)
388 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000389 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000390 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
391 s.Printf ("%-10s ", cstr);
392 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000393 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000394
Greg Clayton8b82f082011-04-12 05:54:46 +0000395 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000396 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
397 s.Printf ("%-10s ", cstr);
398 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000399 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000400
Greg Clayton8b82f082011-04-12 05:54:46 +0000401 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000402 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
403 s.Printf ("%-10s ", cstr);
404 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000405 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000406
Greg Clayton8b82f082011-04-12 05:54:46 +0000407 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000408 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
409 s.Printf ("%-10s ", cstr);
410 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000411 s.Printf ("%-10u ", m_egid);
Todd Fiala7df337f2015-10-13 23:41:19 +0000412
413 s.Printf ("%-24s ", arch_strm.GetString().c_str());
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000414 }
415 else
416 {
Jim Ingham368ac222014-08-15 17:05:27 +0000417 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000418 platform->GetUserName (m_euid),
Todd Fiala7df337f2015-10-13 23:41:19 +0000419 arch_strm.GetString().c_str());
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000420 }
421
Greg Clayton8b82f082011-04-12 05:54:46 +0000422 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000423 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000424 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000425 if (argc > 0)
426 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000427 for (uint32_t i = 0; i < argc; i++)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000428 {
429 if (i > 0)
430 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000431 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000432 }
433 }
434 }
435 else
436 {
437 s.PutCString (GetName());
438 }
439
440 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000441 }
442}
443
Greg Clayton8b82f082011-04-12 05:54:46 +0000444Error
Todd Fialae1cfbc72016-08-11 23:51:28 +0000445ProcessLaunchCommandOptions::SetOptionValue(uint32_t option_idx,
446 const char *option_arg,
447 ExecutionContext *execution_context)
Greg Clayton8b82f082011-04-12 05:54:46 +0000448{
449 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000450 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000451
452 switch (short_option)
453 {
454 case 's': // Stop at program entry point
455 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
456 break;
457
Greg Clayton8b82f082011-04-12 05:54:46 +0000458 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000459 {
460 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000461 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000462 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000463 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000464 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000465
466 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000467 {
468 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000469 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000470 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000471 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000472 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000473
474 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000475 {
476 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000477 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000478 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000479 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000480 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000481
Greg Clayton8b82f082011-04-12 05:54:46 +0000482 case 'p': // Process plug-in name
483 launch_info.SetProcessPluginName (option_arg);
484 break;
485
486 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000487 {
488 FileAction action;
Zachary Turner4eff2d32015-10-14 21:37:36 +0000489 const FileSpec dev_null{FileSystem::DEV_NULL, false};
Chaoren Lind3173f32015-05-29 19:52:29 +0000490 if (action.Open(STDIN_FILENO, dev_null, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000491 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000492 if (action.Open(STDOUT_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000493 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000494 if (action.Open(STDERR_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000495 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000496 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000497 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000498
499 case 'w':
Chaoren Lind3173f32015-05-29 19:52:29 +0000500 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
Greg Clayton8b82f082011-04-12 05:54:46 +0000501 break;
502
503 case 't': // Open process in new terminal window
504 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
505 break;
506
507 case 'a':
Todd Fialae1cfbc72016-08-11 23:51:28 +0000508 {
509 TargetSP target_sp = execution_context ?
510 execution_context->GetTargetSP() : TargetSP();
511 PlatformSP platform_sp = target_sp ?
512 target_sp->GetPlatform() : PlatformSP();
513 if (!launch_info.GetArchitecture().SetTriple (option_arg, platform_sp.get()))
514 launch_info.GetArchitecture().SetTriple (option_arg);
515 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000516 break;
517
Todd Fiala51637922014-08-19 17:40:43 +0000518 case 'A': // Disable ASLR.
519 {
520 bool success;
521 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
522 if (success)
523 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
524 else
525 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000526 break;
Todd Fiala51637922014-08-19 17:40:43 +0000527 }
528
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000529 case 'X': // shell expand args.
Enrico Granatad7a83a92015-02-10 03:06:24 +0000530 {
531 bool success;
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000532 const bool expand_args = Args::StringToBoolean (option_arg, true, &success);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000533 if (success)
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000534 launch_info.SetShellExpandArguments(expand_args);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000535 else
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000536 error.SetErrorStringWithFormat ("Invalid boolean value for shell-expand-args option: '%s'", option_arg ? option_arg : "<null>");
Enrico Granatad7a83a92015-02-10 03:06:24 +0000537 break;
538 }
539
Todd Fiala51637922014-08-19 17:40:43 +0000540 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000541 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000542 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000543 else
Zachary Turner10687b02014-10-20 17:46:43 +0000544 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000545 break;
546
Greg Clayton8b82f082011-04-12 05:54:46 +0000547 case 'v':
548 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
549 break;
550
551 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000552 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000553 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000554 }
555 return error;
556}
557
558OptionDefinition
559ProcessLaunchCommandOptions::g_option_table[] =
560{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000561{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process." },
562{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Set whether to disable address space layout randomization when launching a process." },
563{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePlugin, "Name of the process plugin you want to use." },
564{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior." },
565{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous." },
566{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries." },
567{ LLDB_OPT_SET_1|LLDB_OPT_SET_2|LLDB_OPT_SET_3, false, "shell", 'c', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)." },
Greg Clayton8b82f082011-04-12 05:54:46 +0000568
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000569{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>." },
570{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>." },
571{ LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>." },
Greg Clayton8b82f082011-04-12 05:54:46 +0000572
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000573{ LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)." },
Greg Clayton8b82f082011-04-12 05:54:46 +0000574
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000575{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process." },
576{ LLDB_OPT_SET_4, false, "shell-expand-args", 'X', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Set whether to shell expand arguments to the process when launching." },
577{ 0 , false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
Greg Clayton8b82f082011-04-12 05:54:46 +0000578};
579
Greg Clayton8b82f082011-04-12 05:54:46 +0000580bool
581ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000582{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000583 if (m_name_match_type == eNameMatchIgnore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000584 return true;
585 const char *match_name = m_match_info.GetName();
586 if (!match_name)
587 return true;
588
589 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
590}
591
592bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000593ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000594{
595 if (!NameMatches (proc_info.GetName()))
596 return false;
597
598 if (m_match_info.ProcessIDIsValid() &&
599 m_match_info.GetProcessID() != proc_info.GetProcessID())
600 return false;
601
602 if (m_match_info.ParentProcessIDIsValid() &&
603 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
604 return false;
605
Greg Clayton8b82f082011-04-12 05:54:46 +0000606 if (m_match_info.UserIDIsValid () &&
607 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000608 return false;
609
Greg Clayton8b82f082011-04-12 05:54:46 +0000610 if (m_match_info.GroupIDIsValid () &&
611 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000612 return false;
613
614 if (m_match_info.EffectiveUserIDIsValid () &&
615 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
616 return false;
617
618 if (m_match_info.EffectiveGroupIDIsValid () &&
619 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
620 return false;
621
622 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000623 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000624 return false;
625 return true;
626}
627
628bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000629ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000630{
631 if (m_name_match_type != eNameMatchIgnore)
632 return false;
633
634 if (m_match_info.ProcessIDIsValid())
635 return false;
636
637 if (m_match_info.ParentProcessIDIsValid())
638 return false;
639
Greg Clayton8b82f082011-04-12 05:54:46 +0000640 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000641 return false;
642
Greg Clayton8b82f082011-04-12 05:54:46 +0000643 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000644 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;
Greg Clayton32e0a752011-03-30 18:16:51 +0000659}
660
661void
Greg Clayton8b82f082011-04-12 05:54:46 +0000662ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000663{
664 m_match_info.Clear();
665 m_name_match_type = eNameMatchIgnore;
666 m_match_all_users = false;
667}
Greg Clayton58be07b2011-01-07 06:08:19 +0000668
Greg Claytonc3776bf2012-02-09 06:16:32 +0000669ProcessSP
Jim Ingham583bbb12016-03-07 21:50:25 +0000670Process::FindPlugin (lldb::TargetSP target_sp, const char *plugin_name, ListenerSP listener_sp, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000671{
Greg Clayton949e8222013-01-16 17:29:04 +0000672 static uint32_t g_process_unique_id = 0;
673
Greg Claytonc3776bf2012-02-09 06:16:32 +0000674 ProcessSP process_sp;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000675 ProcessCreateInstance create_callback = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000676 if (plugin_name)
677 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000678 ConstString const_plugin_name(plugin_name);
679 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000680 if (create_callback)
681 {
Jim Ingham583bbb12016-03-07 21:50:25 +0000682 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
Greg Claytonc3776bf2012-02-09 06:16:32 +0000683 if (process_sp)
684 {
Zachary Turner7529df92015-09-01 20:02:29 +0000685 if (process_sp->CanDebug(target_sp, true))
Greg Clayton949e8222013-01-16 17:29:04 +0000686 {
687 process_sp->m_process_unique_id = ++g_process_unique_id;
688 }
689 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000690 process_sp.reset();
691 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000692 }
693 }
694 else
695 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000696 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000697 {
Jim Ingham583bbb12016-03-07 21:50:25 +0000698 process_sp = create_callback(target_sp, listener_sp, crash_file_path);
Greg Claytonc3776bf2012-02-09 06:16:32 +0000699 if (process_sp)
700 {
Zachary Turner7529df92015-09-01 20:02:29 +0000701 if (process_sp->CanDebug(target_sp, false))
Greg Clayton949e8222013-01-16 17:29:04 +0000702 {
703 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000704 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000705 }
706 else
707 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000708 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000709 }
710 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000711 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712}
713
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000714ConstString &
715Process::GetStaticBroadcasterClass ()
716{
717 static ConstString class_name ("lldb.process");
718 return class_name;
719}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000720
Jim Ingham583bbb12016-03-07 21:50:25 +0000721Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp) :
722 Process(target_sp, listener_sp, UnixSignals::Create(HostInfo::GetArchitecture()))
Todd Fiala4ceced32014-08-29 17:35:57 +0000723{
724 // This constructor just delegates to the full Process constructor,
725 // defaulting to using the Host's UnixSignals.
726}
727
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000728Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp, const UnixSignalsSP &unix_signals_sp)
729 : ProcessProperties(this),
730 UserID(LLDB_INVALID_PROCESS_ID),
731 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()), Process::GetStaticBroadcasterClass().AsCString()),
732 m_target_sp(target_sp),
733 m_public_state(eStateUnloaded),
734 m_private_state(eStateUnloaded),
735 m_private_state_broadcaster(nullptr, "lldb.process.internal_state_broadcaster"),
736 m_private_state_control_broadcaster(nullptr, "lldb.process.internal_state_control_broadcaster"),
737 m_private_state_listener_sp(Listener::MakeListener("lldb.process.internal_state_listener")),
738 m_mod_id(),
739 m_process_unique_id(0),
740 m_thread_index_id(0),
741 m_thread_id_to_index_id_map(),
742 m_exit_status(-1),
743 m_exit_string(),
744 m_exit_status_mutex(),
745 m_thread_mutex(),
746 m_thread_list_real(this),
747 m_thread_list(this),
748 m_extended_thread_list(this),
749 m_extended_thread_stop_id(0),
750 m_queue_list(this),
751 m_queue_list_stop_id(0),
752 m_notifications(),
753 m_image_tokens(),
754 m_listener_sp(listener_sp),
755 m_breakpoint_site_list(),
756 m_dynamic_checkers_ap(),
757 m_unix_signals_sp(unix_signals_sp),
758 m_abi_sp(),
759 m_process_input_reader(),
760 m_stdio_communication("process.stdio"),
761 m_stdio_communication_mutex(),
762 m_stdin_forward(false),
763 m_stdout_data(),
764 m_stderr_data(),
765 m_profile_data_comm_mutex(),
766 m_profile_data(),
767 m_iohandler_sync(0),
768 m_memory_cache(*this),
769 m_allocated_memory_cache(*this),
770 m_should_detach(false),
771 m_next_event_action_ap(),
772 m_public_run_lock(),
773 m_private_run_lock(),
774 m_stop_info_override_callback(nullptr),
775 m_finalizing(false),
776 m_finalize_called(false),
777 m_clear_thread_plans_on_stop(false),
778 m_force_next_event_delivery(false),
779 m_last_broadcast_state(eStateInvalid),
780 m_destroy_in_process(false),
781 m_can_interpret_function_calls(false),
782 m_warnings_issued(),
Jim Ingham3cc425832016-05-24 18:29:36 +0000783 m_run_thread_plan_lock(),
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000784 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000786 CheckInWithManager();
Caroline Tice1559a462010-09-27 00:30:10 +0000787
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000788 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000789 if (log)
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000790 log->Printf("%p Process::Process()", static_cast<void *>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791
Todd Fiala4ceced32014-08-29 17:35:57 +0000792 if (!m_unix_signals_sp)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000793 m_unix_signals_sp = std::make_shared<UnixSignals>();
Todd Fiala4ceced32014-08-29 17:35:57 +0000794
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000795 SetEventName(eBroadcastBitStateChanged, "state-changed");
796 SetEventName(eBroadcastBitInterrupt, "interrupt");
797 SetEventName(eBroadcastBitSTDOUT, "stdout-available");
798 SetEventName(eBroadcastBitSTDERR, "stderr-available");
799 SetEventName(eBroadcastBitProfileData, "profile-data-available");
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000800
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000801 m_private_state_control_broadcaster.SetEventName(eBroadcastInternalStateControlStop, "control-stop");
802 m_private_state_control_broadcaster.SetEventName(eBroadcastInternalStateControlPause, "control-pause");
803 m_private_state_control_broadcaster.SetEventName(eBroadcastInternalStateControlResume, "control-resume");
Greg Clayton35a4cc52012-10-29 20:52:08 +0000804
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000805 m_listener_sp->StartListeningForEvents(this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
806 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
807 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000808
Jim Ingham583bbb12016-03-07 21:50:25 +0000809 m_private_state_listener_sp->StartListeningForEvents(&m_private_state_broadcaster,
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000810 eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000811
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000812 m_private_state_listener_sp->StartListeningForEvents(
813 &m_private_state_control_broadcaster, eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
814 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000815 // We need something valid here, even if just the default UnixSignalsSP.
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000816 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Pavel Labathf2991482015-10-20 10:33:17 +0000817
818 // Allow the platform to override the default cache line size
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000819 OptionValueSP value_sp = m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)->GetValue();
Pavel Labathf2991482015-10-20 10:33:17 +0000820 uint32_t platform_cache_line_size = target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000821 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
Pavel Labathf2991482015-10-20 10:33:17 +0000822 value_sp->SetUInt64Value(platform_cache_line_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823}
824
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000825Process::~Process()
826{
Greg Clayton5160ce52013-03-27 23:08:40 +0000827 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000828 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000829 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000831
832 // ThreadList::Clear() will try to acquire this process's mutex, so
833 // explicitly clear the thread list here to ensure that the mutex
834 // is not destroyed before the thread list.
835 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000836}
837
Greg Clayton67cc0632012-08-22 17:17:09 +0000838const ProcessPropertiesSP &
839Process::GetGlobalProperties()
840{
Greg Claytoncc2e27f2016-02-26 23:20:08 +0000841 // NOTE: intentional leak so we don't crash if global destructor chain gets
842 // called as other threads still use the result of this function
843 static ProcessPropertiesSP *g_settings_sp_ptr = nullptr;
Greg Clayton04df8ee2016-02-26 19:38:18 +0000844 static std::once_flag g_once_flag;
845 std::call_once(g_once_flag, []() {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000846 g_settings_sp_ptr = new ProcessPropertiesSP(new ProcessProperties(nullptr));
Greg Clayton04df8ee2016-02-26 19:38:18 +0000847 });
Greg Claytoncc2e27f2016-02-26 23:20:08 +0000848 return *g_settings_sp_ptr;
Greg Clayton67cc0632012-08-22 17:17:09 +0000849}
850
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851void
852Process::Finalize()
853{
Greg Claytonc00ca312015-04-02 18:44:58 +0000854 m_finalizing = true;
855
Ilia Kc7efd562015-03-26 07:40:40 +0000856 // Destroy this process if needed
857 switch (GetPrivateState())
858 {
859 case eStateConnected:
860 case eStateAttaching:
861 case eStateLaunching:
862 case eStateStopped:
863 case eStateRunning:
864 case eStateStepping:
865 case eStateCrashed:
866 case eStateSuspended:
Jason Molendaede31932015-04-17 05:01:58 +0000867 Destroy(false);
Ilia Kc7efd562015-03-26 07:40:40 +0000868 break;
869
870 case eStateInvalid:
871 case eStateUnloaded:
872 case eStateDetached:
873 case eStateExited:
874 break;
875 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000876
Greg Clayton1ed54f52011-10-01 00:45:15 +0000877 // Clear our broadcaster before we proceed with destroying
878 Broadcaster::Clear();
879
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000880 // Do any cleanup needed prior to being destructed... Subclasses
881 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000882
883 // We need to destroy the loader before the derived Process class gets destroyed
884 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000885 m_dynamic_checkers_ap.reset();
886 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000887 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000888 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000889 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000890 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000891 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000892 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000893 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000894 m_queue_list.Clear();
895 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000896 std::vector<Notifications> empty_notifications;
897 m_notifications.swap(empty_notifications);
898 m_image_tokens.clear();
899 m_memory_cache.Clear();
900 m_allocated_memory_cache.Clear();
901 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000902 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000903 m_next_event_action_ap.reset();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000904 m_stop_info_override_callback = nullptr;
Greg Clayton08765fa2015-05-28 03:24:30 +0000905 // Clear the last natural stop ID since it has a strong
906 // reference to this process
907 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
Greg Clayton35a4cc52012-10-29 20:52:08 +0000908//#ifdef LLDB_CONFIGURATION_DEBUG
909// StreamFile s(stdout, false);
910// EventSP event_sp;
Jim Ingham583bbb12016-03-07 21:50:25 +0000911// while (m_private_state_listener_sp->GetNextEvent(event_sp))
Greg Clayton35a4cc52012-10-29 20:52:08 +0000912// {
913// event_sp->Dump (&s);
914// s.EOL();
915// }
916//#endif
917 // We have to be very careful here as the m_private_state_listener might
918 // contain events that have ProcessSP values in them which can keep this
919 // process around forever. These events need to be cleared out.
Jim Ingham583bbb12016-03-07 21:50:25 +0000920 m_private_state_listener_sp->Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000921 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
922 m_public_run_lock.SetStopped();
923 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
924 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000925 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000926}
927
928void
929Process::RegisterNotificationCallbacks (const Notifications& callbacks)
930{
931 m_notifications.push_back(callbacks);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000932 if (callbacks.initialize != nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000933 callbacks.initialize (callbacks.baton, this);
934}
935
936bool
937Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
938{
939 std::vector<Notifications>::iterator pos, end = m_notifications.end();
940 for (pos = m_notifications.begin(); pos != end; ++pos)
941 {
942 if (pos->baton == callbacks.baton &&
943 pos->initialize == callbacks.initialize &&
944 pos->process_state_changed == callbacks.process_state_changed)
945 {
946 m_notifications.erase(pos);
947 return true;
948 }
949 }
950 return false;
951}
952
953void
954Process::SynchronouslyNotifyStateChanged (StateType state)
955{
956 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
957 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
958 {
959 if (notification_pos->process_state_changed)
960 notification_pos->process_state_changed (notification_pos->baton, this, state);
961 }
962}
963
964// FIXME: We need to do some work on events before the general Listener sees them.
965// For instance if we are continuing from a breakpoint, we need to ensure that we do
966// the little "insert real insn, step & stop" trick. But we can't do that when the
967// event is delivered by the broadcaster - since that is done on the thread that is
968// waiting for new events, so if we needed more than one event for our handling, we would
969// stall. So instead we do it when we fetch the event off of the queue.
970//
971
972StateType
973Process::GetNextEvent (EventSP &event_sp)
974{
975 StateType state = eStateInvalid;
976
Jim Ingham583bbb12016-03-07 21:50:25 +0000977 if (m_listener_sp->GetNextEventForBroadcaster (this, event_sp) && event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000978 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
979
980 return state;
981}
982
Pavel Labath44464872015-05-27 12:40:32 +0000983void
984Process::SyncIOHandler (uint32_t iohandler_id, uint64_t timeout_msec)
Todd Fialaa3b89e22014-08-12 14:33:19 +0000985{
Todd Fialaa3b89e22014-08-12 14:33:19 +0000986 // don't sync (potentially context switch) in case where there is no process IO
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000987 if (!m_process_input_reader)
Pavel Labath44464872015-05-27 12:40:32 +0000988 return;
Todd Fialaa3b89e22014-08-12 14:33:19 +0000989
Pavel Labath44464872015-05-27 12:40:32 +0000990 uint32_t new_iohandler_id = 0;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000991 m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, new_iohandler_id, std::chrono::milliseconds(timeout_msec));
Todd Fialaa3b89e22014-08-12 14:33:19 +0000992
Pavel Labath44464872015-05-27 12:40:32 +0000993 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
994 if (log)
995 log->Printf("Process::%s waited for m_iohandler_sync to change from %u, new value is %u", __FUNCTION__, iohandler_id, new_iohandler_id);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000996}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997
998StateType
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000999Process::WaitForProcessToStop(const std::chrono::microseconds &timeout, EventSP *event_sp_ptr, bool wait_always,
1000 ListenerSP hijack_listener_sp, Stream *stream, bool use_run_lock)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001{
Jim Ingham4b536182011-08-09 02:12:22 +00001002 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1003 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1004 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001005 if (event_sp_ptr)
1006 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001007 StateType state = GetState();
1008 // If we are exited or detached, we won't ever get back to any
1009 // other valid state...
1010 if (state == eStateDetached || state == eStateExited)
1011 return state;
1012
Daniel Malea9e9919f2013-10-09 16:56:28 +00001013 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1014 if (log)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001015 log->Printf("Process::%s (timeout = %llu)", __FUNCTION__, static_cast<unsigned long long>(timeout.count()));
Daniel Malea9e9919f2013-10-09 16:56:28 +00001016
1017 if (!wait_always &&
1018 StateIsStoppedState(state, true) &&
Jim Ingham5b4c5eb2015-04-22 17:48:24 +00001019 StateIsStoppedState(GetPrivateState(), true))
1020 {
Daniel Malea9e9919f2013-10-09 16:56:28 +00001021 if (log)
1022 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1023 __FUNCTION__);
Pavel Labath78521ef2015-03-06 10:52:47 +00001024 // We need to toggle the run lock as this won't get done in
1025 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001026 if (hijack_listener_sp && use_run_lock)
Pavel Labath78521ef2015-03-06 10:52:47 +00001027 m_public_run_lock.SetStopped();
Daniel Malea9e9919f2013-10-09 16:56:28 +00001028 return state;
1029 }
1030
Jim Ingham4b536182011-08-09 02:12:22 +00001031 while (state != eStateInvalid)
1032 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001033 EventSP event_sp;
Pavel Labath12fc6752016-07-29 10:34:52 +00001034 state = WaitForStateChangedEvents(timeout, event_sp, hijack_listener_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001035 if (event_sp_ptr && event_sp)
1036 *event_sp_ptr = event_sp;
1037
Jim Ingham583bbb12016-03-07 21:50:25 +00001038 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
Greg Claytondc6224e2014-10-21 01:00:42 +00001039 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1040
Jim Ingham4b536182011-08-09 02:12:22 +00001041 switch (state)
1042 {
1043 case eStateCrashed:
1044 case eStateDetached:
1045 case eStateExited:
1046 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001047 // We need to toggle the run lock as this won't get done in
1048 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001049 if (hijack_listener_sp && use_run_lock)
Greg Clayton44d93782014-01-27 23:43:24 +00001050 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001051 return state;
1052 case eStateStopped:
1053 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1054 continue;
1055 else
Greg Clayton44d93782014-01-27 23:43:24 +00001056 {
1057 // We need to toggle the run lock as this won't get done in
1058 // SetPublicState() if the process is hijacked.
Jim Ingham583bbb12016-03-07 21:50:25 +00001059 if (hijack_listener_sp && use_run_lock)
Greg Clayton44d93782014-01-27 23:43:24 +00001060 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001061 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001062 }
Jim Ingham4b536182011-08-09 02:12:22 +00001063 default:
1064 continue;
1065 }
1066 }
1067 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001068}
1069
Greg Claytondc6224e2014-10-21 01:00:42 +00001070bool
1071Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1072 Stream *stream,
1073 bool &pop_process_io_handler)
1074{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001075 const bool handle_pop = pop_process_io_handler;
Greg Claytondc6224e2014-10-21 01:00:42 +00001076
1077 pop_process_io_handler = false;
1078 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1079
1080 if (!process_sp)
1081 return false;
1082
1083 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1084 if (event_state == eStateInvalid)
1085 return false;
1086
1087 switch (event_state)
1088 {
1089 case eStateInvalid:
1090 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:42 +00001091 case eStateAttaching:
1092 case eStateLaunching:
1093 case eStateStepping:
1094 case eStateDetached:
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001095 if (stream)
1096 stream->Printf("Process %" PRIu64 " %s\n",
1097 process_sp->GetID(),
1098 StateAsCString (event_state));
1099 if (event_state == eStateDetached)
1100 pop_process_io_handler = true;
Greg Claytondc6224e2014-10-21 01:00:42 +00001101 break;
1102
Stephane Sezerf2ef94e2014-12-13 05:23:51 +00001103 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:42 +00001104 case eStateRunning:
1105 // Don't be chatty when we run...
1106 break;
1107
1108 case eStateExited:
1109 if (stream)
1110 process_sp->GetStatus(*stream);
1111 pop_process_io_handler = true;
1112 break;
1113
1114 case eStateStopped:
1115 case eStateCrashed:
1116 case eStateSuspended:
1117 // Make sure the program hasn't been auto-restarted:
1118 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1119 {
1120 if (stream)
1121 {
1122 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1123 if (num_reasons > 0)
1124 {
1125 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1126 if (num_reasons == 1)
1127 {
1128 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1129 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1130 process_sp->GetID(),
1131 reason ? reason : "<UNKNOWN REASON>");
1132 }
1133 else
1134 {
1135 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1136 process_sp->GetID());
1137
1138
1139 for (size_t i = 0; i < num_reasons; i++)
1140 {
1141 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1142 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1143 }
1144 }
1145 }
1146 }
1147 }
1148 else
1149 {
1150 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1151 {
1152 ThreadList &thread_list = process_sp->GetThreadList();
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001153 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
Greg Claytondc6224e2014-10-21 01:00:42 +00001154
1155 ThreadSP curr_thread (thread_list.GetSelectedThread());
1156 ThreadSP thread;
1157 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1158 if (curr_thread)
1159 curr_thread_stop_reason = curr_thread->GetStopReason();
1160 if (!curr_thread ||
1161 !curr_thread->IsValid() ||
1162 curr_thread_stop_reason == eStopReasonInvalid ||
1163 curr_thread_stop_reason == eStopReasonNone)
1164 {
1165 // Prefer a thread that has just completed its plan over another thread as current thread.
1166 ThreadSP plan_thread;
1167 ThreadSP other_thread;
Jim Inghamce400d92015-07-08 00:06:30 +00001168
Greg Claytondc6224e2014-10-21 01:00:42 +00001169 const size_t num_threads = thread_list.GetSize();
1170 size_t i;
1171 for (i = 0; i < num_threads; ++i)
1172 {
1173 thread = thread_list.GetThreadAtIndex(i);
1174 StopReason thread_stop_reason = thread->GetStopReason();
1175 switch (thread_stop_reason)
1176 {
1177 case eStopReasonInvalid:
1178 case eStopReasonNone:
1179 break;
1180
Jim Inghamce400d92015-07-08 00:06:30 +00001181 case eStopReasonSignal:
1182 {
1183 // Don't select a signal thread if we weren't going to stop at that
1184 // signal. We have to have had another reason for stopping here, and
1185 // the user doesn't want to see this thread.
1186 uint64_t signo = thread->GetStopInfo()->GetValue();
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001187 if (process_sp->GetUnixSignals()->GetShouldStop(signo))
Jim Inghamce400d92015-07-08 00:06:30 +00001188 {
1189 if (!other_thread)
1190 other_thread = thread;
1191 }
1192 break;
1193 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001194 case eStopReasonTrace:
1195 case eStopReasonBreakpoint:
1196 case eStopReasonWatchpoint:
Greg Claytondc6224e2014-10-21 01:00:42 +00001197 case eStopReasonException:
1198 case eStopReasonExec:
1199 case eStopReasonThreadExiting:
1200 case eStopReasonInstrumentation:
1201 if (!other_thread)
1202 other_thread = thread;
1203 break;
1204 case eStopReasonPlanComplete:
1205 if (!plan_thread)
1206 plan_thread = thread;
1207 break;
1208 }
1209 }
1210 if (plan_thread)
1211 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1212 else if (other_thread)
1213 thread_list.SetSelectedThreadByID (other_thread->GetID());
1214 else
1215 {
1216 if (curr_thread && curr_thread->IsValid())
1217 thread = curr_thread;
1218 else
1219 thread = thread_list.GetThreadAtIndex(0);
1220
1221 if (thread)
1222 thread_list.SetSelectedThreadByID (thread->GetID());
1223 }
1224 }
1225 }
1226 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1227 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1228 // have a hard time restarting the process.
1229 if (stream)
1230 {
1231 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1232 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1233 {
1234 const bool only_threads_with_stop_reason = true;
1235 const uint32_t start_frame = 0;
1236 const uint32_t num_frames = 1;
1237 const uint32_t num_frames_with_source = 1;
1238 process_sp->GetStatus(*stream);
1239 process_sp->GetThreadStatus (*stream,
1240 only_threads_with_stop_reason,
1241 start_frame,
1242 num_frames,
1243 num_frames_with_source);
1244 }
1245 else
1246 {
1247 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1248 if (target_idx != UINT32_MAX)
1249 stream->Printf ("Target %d: (", target_idx);
1250 else
1251 stream->Printf ("Target <unknown index>: (");
1252 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1253 stream->Printf (") stopped.\n");
1254 }
1255 }
1256
1257 // Pop the process IO handler
1258 pop_process_io_handler = true;
1259 }
1260 break;
1261 }
1262
1263 if (handle_pop && pop_process_io_handler)
1264 process_sp->PopProcessIOHandler();
1265
1266 return true;
1267}
1268
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001269StateType
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001270Process::WaitForState(const std::chrono::microseconds &timeout, const StateType *match_states,
Eugene Zelenko8f30a652015-10-23 18:39:37 +00001271 const uint32_t num_match_states)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001272{
1273 EventSP event_sp;
Greg Clayton05faeb72010-10-07 04:19:01 +00001274 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001275 while (state != eStateInvalid)
1276 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001277 // If we are exited or detached, we won't ever get back to any
1278 // other valid state...
1279 if (state == eStateDetached || state == eStateExited)
1280 return state;
1281
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001282 state = WaitForStateChangedEvents(timeout, event_sp, nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001283
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001284 for (uint32_t i = 0; i < num_match_states; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001285 {
1286 if (match_states[i] == state)
1287 return state;
1288 }
1289 }
1290 return state;
1291}
1292
Jim Ingham30f9b212010-10-11 23:53:14 +00001293bool
Jim Ingham583bbb12016-03-07 21:50:25 +00001294Process::HijackProcessEvents (ListenerSP listener_sp)
Jim Ingham30f9b212010-10-11 23:53:14 +00001295{
Jim Ingham583bbb12016-03-07 21:50:25 +00001296 if (listener_sp)
Jim Ingham30f9b212010-10-11 23:53:14 +00001297 {
Jim Ingham583bbb12016-03-07 21:50:25 +00001298 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001299 }
1300 else
1301 return false;
1302}
1303
1304void
1305Process::RestoreProcessEvents ()
1306{
1307 RestoreBroadcaster();
1308}
1309
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001310StateType
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001311Process::WaitForStateChangedEvents(const std::chrono::microseconds &timeout, EventSP &event_sp,
1312 ListenerSP hijack_listener_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001313{
Greg Clayton5160ce52013-03-27 23:08:40 +00001314 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001315
1316 if (log)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001317 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1318 static_cast<unsigned long long>(timeout.count()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001319
Jim Ingham583bbb12016-03-07 21:50:25 +00001320 ListenerSP listener_sp = hijack_listener_sp;
1321 if (!listener_sp)
1322 listener_sp = m_listener_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001323
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001324 StateType state = eStateInvalid;
Jim Ingham583bbb12016-03-07 21:50:25 +00001325 if (listener_sp->WaitForEventForBroadcasterWithType (timeout,
1326 this,
1327 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1328 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001329 {
1330 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1331 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1332 else if (log)
1333 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1334 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001335
1336 if (log)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001337 log->Printf("Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1338 static_cast<unsigned long long>(timeout.count()), StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001339 return state;
1340}
1341
1342Event *
1343Process::PeekAtStateChangedEvents ()
1344{
Greg Clayton5160ce52013-03-27 23:08:40 +00001345 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346
1347 if (log)
1348 log->Printf ("Process::%s...", __FUNCTION__);
1349
1350 Event *event_ptr;
Jim Ingham583bbb12016-03-07 21:50:25 +00001351 event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType (this,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001352 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353 if (log)
1354 {
1355 if (event_ptr)
1356 {
1357 log->Printf ("Process::%s (event_ptr) => %s",
1358 __FUNCTION__,
1359 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1360 }
1361 else
1362 {
1363 log->Printf ("Process::%s no events found",
1364 __FUNCTION__);
1365 }
1366 }
1367 return event_ptr;
1368}
1369
1370StateType
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001371Process::WaitForStateChangedEventsPrivate(const std::chrono::microseconds &timeout, EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372{
Greg Clayton5160ce52013-03-27 23:08:40 +00001373 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374
1375 if (log)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001376 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1377 static_cast<unsigned long long>(timeout.count()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001378
1379 StateType state = eStateInvalid;
Jim Ingham583bbb12016-03-07 21:50:25 +00001380 if (m_private_state_listener_sp->WaitForEventForBroadcasterWithType (timeout,
Greg Clayton6779606a2011-01-22 23:43:18 +00001381 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001382 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001383 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001384 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1385 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001386
1387 // This is a bit of a hack, but when we wait here we could very well return
1388 // to the command-line, and that could disable the log, which would render the
1389 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001390 if (log)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001391 log->Printf("Process::%s (timeout = %llu, event_sp) => %s", __FUNCTION__,
1392 static_cast<unsigned long long>(timeout.count()),
1393 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001394 return state;
1395}
1396
1397bool
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001398Process::WaitForEventsPrivate(const std::chrono::microseconds &timeout, EventSP &event_sp, bool control_only)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001399{
Greg Clayton5160ce52013-03-27 23:08:40 +00001400 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401
1402 if (log)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001403 log->Printf("Process::%s (timeout = %llu, event_sp)...", __FUNCTION__,
1404 static_cast<unsigned long long>(timeout.count()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405
1406 if (control_only)
Jim Ingham583bbb12016-03-07 21:50:25 +00001407 return m_private_state_listener_sp->WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001408 else
Jim Ingham583bbb12016-03-07 21:50:25 +00001409 return m_private_state_listener_sp->WaitForEvent(timeout, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001410}
1411
1412bool
1413Process::IsRunning () const
1414{
1415 return StateIsRunningState (m_public_state.GetValue());
1416}
1417
1418int
1419Process::GetExitStatus ()
1420{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001421 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
Todd Fiala7b0917a2014-09-15 20:07:33 +00001422
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423 if (m_public_state.GetValue() == eStateExited)
1424 return m_exit_status;
1425 return -1;
1426}
1427
1428const char *
1429Process::GetExitDescription ()
1430{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001431 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
Todd Fiala7b0917a2014-09-15 20:07:33 +00001432
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001433 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1434 return m_exit_string.c_str();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001435 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001436}
1437
Greg Clayton6779606a2011-01-22 23:43:18 +00001438bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001439Process::SetExitStatus (int status, const char *cstr)
1440{
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001441 // Use a mutex to protect setting the exit status.
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001442 std::lock_guard<std::mutex> guard(m_exit_status_mutex);
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001443
Greg Clayton5160ce52013-03-27 23:08:40 +00001444 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001445 if (log)
1446 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1447 status, status,
1448 cstr ? "\"" : "",
1449 cstr ? cstr : "NULL",
1450 cstr ? "\"" : "");
1451
Greg Clayton6779606a2011-01-22 23:43:18 +00001452 // We were already in the exited state
1453 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001454 {
Greg Clayton385d6032011-01-26 23:47:29 +00001455 if (log)
1456 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001457 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001458 }
Todd Fiala7b0917a2014-09-15 20:07:33 +00001459
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001460 m_exit_status = status;
1461 if (cstr)
1462 m_exit_string = cstr;
1463 else
1464 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001465
Greg Clayton08765fa2015-05-28 03:24:30 +00001466 // Clear the last natural stop ID since it has a strong
1467 // reference to this process
1468 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1469
Greg Clayton6779606a2011-01-22 23:43:18 +00001470 SetPrivateState (eStateExited);
Greg Clayton5df78fa2015-05-23 03:54:53 +00001471
1472 // Allow subclasses to do some cleanup
1473 DidExit ();
1474
Greg Clayton6779606a2011-01-22 23:43:18 +00001475 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001476}
1477
Jason Molendaa814f702015-11-05 23:03:44 +00001478bool
1479Process::IsAlive ()
1480{
1481 switch (m_private_state.GetValue())
1482 {
Jason Molendaa814f702015-11-05 23:03:44 +00001483 case eStateConnected:
1484 case eStateAttaching:
1485 case eStateLaunching:
1486 case eStateStopped:
1487 case eStateRunning:
1488 case eStateStepping:
1489 case eStateCrashed:
1490 case eStateSuspended:
1491 return true;
Davide Italiano13fe2a92016-01-19 22:47:51 +00001492 default:
1493 return false;
Jason Molendaa814f702015-11-05 23:03:44 +00001494 }
1495}
1496
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001497// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001498// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001499// found in the global target list (we want to be completely sure that the
1500// lldb_private::Process doesn't go away before we can deliver the signal.
1501bool
Pavel Labath998bdc52016-05-11 16:59:04 +00001502Process::SetProcessExitStatus(lldb::pid_t pid, bool exited,
1503 int signo, // Zero for no signal
1504 int exit_status // Exit value of process if signal is zero
1505 )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001506{
Greg Clayton5160ce52013-03-27 23:08:40 +00001507 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001508 if (log)
Pavel Labath998bdc52016-05-11 16:59:04 +00001509 log->Printf("Process::SetProcessExitStatus (pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n", pid,
1510 exited, signo, exit_status);
Greg Claytone4e45922011-11-16 05:37:56 +00001511
1512 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001513 {
Greg Clayton66111032010-06-23 01:19:29 +00001514 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001515 if (target_sp)
1516 {
1517 ProcessSP process_sp (target_sp->GetProcessSP());
1518 if (process_sp)
1519 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001520 const char *signal_cstr = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001521 if (signo)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001522 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001523
1524 process_sp->SetExitStatus (exit_status, signal_cstr);
1525 }
1526 }
1527 return true;
1528 }
1529 return false;
1530}
1531
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001532void
1533Process::UpdateThreadListIfNeeded ()
1534{
1535 const uint32_t stop_id = GetStopID();
1536 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1537 {
Greg Clayton2637f822011-11-17 01:23:07 +00001538 const StateType state = GetPrivateState();
1539 if (StateIsStoppedState (state, true))
1540 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001541 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001542 // m_thread_list does have its own mutex, but we need to
1543 // hold onto the mutex between the call to UpdateThreadList(...)
1544 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001545 ThreadList &old_thread_list = m_thread_list;
1546 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001547 ThreadList new_thread_list(this);
1548 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001549 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001550 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001551 {
Jim Ingham09437922013-03-01 20:04:25 +00001552 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1553 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1554 // shutting us down, causing a deadlock.
Pavel Labath862432c2015-11-03 16:05:18 +00001555 OperatingSystem *os = GetOperatingSystem ();
1556 if (os && !m_destroy_in_process)
Jim Ingham09437922013-03-01 20:04:25 +00001557 {
Pavel Labath862432c2015-11-03 16:05:18 +00001558 // Clear any old backing threads where memory threads might have been
1559 // backed by actual threads from the lldb_private::Process subclass
1560 size_t num_old_threads = old_thread_list.GetSize(false);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001561 for (size_t i = 0; i < num_old_threads; ++i)
Pavel Labath862432c2015-11-03 16:05:18 +00001562 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001563
Pavel Labath862432c2015-11-03 16:05:18 +00001564 // Turn off dynamic types to ensure we don't run any expressions. Objective C
1565 // can run an expression to determine if a SBValue is a dynamic type or not
1566 // and we need to avoid this. OperatingSystem plug-ins can't run expressions
1567 // that require running code...
Greg Clayton15484402015-05-15 18:40:24 +00001568
Pavel Labath862432c2015-11-03 16:05:18 +00001569 Target &target = GetTarget();
1570 const lldb::DynamicValueType saved_prefer_dynamic = target.GetPreferDynamicValue ();
1571 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1572 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
Greg Clayton15484402015-05-15 18:40:24 +00001573
Pavel Labath862432c2015-11-03 16:05:18 +00001574 // Now let the OperatingSystem plug-in update the thread list
Greg Clayton15484402015-05-15 18:40:24 +00001575
Pavel Labath862432c2015-11-03 16:05:18 +00001576 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1577 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1578 new_thread_list); // The new thread list that we will show to the user that gets filled in
Greg Clayton15484402015-05-15 18:40:24 +00001579
Pavel Labath862432c2015-11-03 16:05:18 +00001580 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1581 target.SetPreferDynamicValue(saved_prefer_dynamic);
1582 }
1583 else
1584 {
1585 // No OS plug-in, the new thread list is the same as the real thread list
1586 new_thread_list = real_thread_list;
Jim Ingham09437922013-03-01 20:04:25 +00001587 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001588
1589 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001590 m_thread_list.Update (new_thread_list);
1591 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001592
Jason Molenda4ff13262013-11-20 00:31:38 +00001593 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1594 {
1595 // Clear any extended threads that we may have accumulated previously
1596 m_extended_thread_list.Clear();
1597 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001598
1599 m_queue_list.Clear();
1600 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001601 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001602 }
Greg Clayton2637f822011-11-17 01:23:07 +00001603 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001604 }
1605}
1606
Jason Molenda5e8dce42013-12-13 00:29:16 +00001607void
1608Process::UpdateQueueListIfNeeded ()
1609{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001610 if (m_system_runtime_ap)
Jason Molenda5e8dce42013-12-13 00:29:16 +00001611 {
1612 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1613 {
1614 const StateType state = GetPrivateState();
1615 if (StateIsStoppedState (state, true))
1616 {
1617 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1618 m_queue_list_stop_id = GetLastNaturalStopID();
1619 }
1620 }
1621 }
1622}
1623
Greg Claytona4d87472013-01-18 23:41:08 +00001624ThreadSP
1625Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1626{
1627 OperatingSystem *os = GetOperatingSystem ();
1628 if (os)
1629 return os->CreateThread(tid, context);
1630 return ThreadSP();
1631}
1632
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001633uint32_t
1634Process::GetNextThreadIndexID (uint64_t thread_id)
1635{
1636 return AssignIndexIDToThread(thread_id);
1637}
1638
1639bool
1640Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1641{
Eugene Zelenko8f30a652015-10-23 18:39:37 +00001642 return (m_thread_id_to_index_id_map.find(thread_id) != m_thread_id_to_index_id_map.end());
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001643}
1644
1645uint32_t
1646Process::AssignIndexIDToThread(uint64_t thread_id)
1647{
1648 uint32_t result = 0;
1649 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1650 if (iterator == m_thread_id_to_index_id_map.end())
1651 {
1652 result = ++m_thread_index_id;
1653 m_thread_id_to_index_id_map[thread_id] = result;
1654 }
1655 else
1656 {
1657 result = iterator->second;
1658 }
1659
1660 return result;
1661}
1662
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001663StateType
1664Process::GetState()
1665{
1666 // If any other threads access this we will need a mutex for it
1667 return m_public_state.GetValue ();
1668}
1669
Greg Claytondc6224e2014-10-21 01:00:42 +00001670bool
1671Process::StateChangedIsExternallyHijacked()
1672{
1673 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1674 {
Jim Ingham583bbb12016-03-07 21:50:25 +00001675 const char *hijacking_name = GetHijackingListenerName();
1676 if (hijacking_name && strcmp(hijacking_name, "lldb.Process.ResumeSynchronous.hijack"))
Greg Claytondc6224e2014-10-21 01:00:42 +00001677 return true;
1678 }
1679 return false;
1680}
1681
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001682void
Jim Ingham221d51c2013-05-08 00:35:16 +00001683Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001684{
Greg Clayton5160ce52013-03-27 23:08:40 +00001685 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001686 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001687 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001688 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001689 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001690
1691 // On the transition from Run to Stopped, we unlock the writer end of the
1692 // run lock. The lock gets locked in Resume, which is the public API
1693 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001694 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001695 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001696 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001697 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001698 if (log)
1699 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001700 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001701 }
1702 else
1703 {
1704 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1705 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001706 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001707 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001708 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001709 {
1710 if (log)
1711 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001712 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001713 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001714 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001715 }
1716 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001717}
1718
Jim Ingham3b8285d2012-04-19 01:40:33 +00001719Error
1720Process::Resume ()
1721{
Greg Clayton5160ce52013-03-27 23:08:40 +00001722 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001723 if (log)
1724 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001725 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001726 {
1727 Error error("Resume request failed - process still running.");
1728 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001729 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001730 return error;
1731 }
1732 return PrivateResume();
1733}
1734
Greg Claytondc6224e2014-10-21 01:00:42 +00001735Error
1736Process::ResumeSynchronous (Stream *stream)
1737{
1738 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1739 if (log)
1740 log->Printf("Process::ResumeSynchronous -- locking run lock");
1741 if (!m_public_run_lock.TrySetRunning())
1742 {
1743 Error error("Resume request failed - process still running.");
1744 if (log)
1745 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1746 return error;
1747 }
1748
Jim Ingham583bbb12016-03-07 21:50:25 +00001749 ListenerSP listener_sp (Listener::MakeListener("lldb.Process.ResumeSynchronous.hijack"));
1750 HijackProcessEvents(listener_sp);
Greg Claytondc6224e2014-10-21 01:00:42 +00001751
1752 Error error = PrivateResume();
Ilia Kd8c14752015-04-30 13:10:32 +00001753 if (error.Success())
1754 {
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001755 StateType state = WaitForProcessToStop(std::chrono::microseconds(0), NULL, true, listener_sp, stream);
Ilia Kd8c14752015-04-30 13:10:32 +00001756 const bool must_be_alive = false; // eStateExited is ok, so this must be false
1757 if (!StateIsStoppedState(state, must_be_alive))
1758 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1759 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001760
1761 // Undo the hijacking of process events...
1762 RestoreProcessEvents();
1763
Greg Claytondc6224e2014-10-21 01:00:42 +00001764 return error;
1765}
1766
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001767StateType
1768Process::GetPrivateState ()
1769{
1770 return m_private_state.GetValue();
1771}
1772
1773void
1774Process::SetPrivateState (StateType new_state)
1775{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001776 if (m_finalize_called)
1777 return;
1778
Greg Clayton5160ce52013-03-27 23:08:40 +00001779 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001780 bool state_changed = false;
1781
1782 if (log)
1783 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1784
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00001785 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +00001786 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001787
1788 const StateType old_state = m_private_state.GetValueNoLock ();
1789 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001790
Greg Claytonaa49c832013-05-03 22:25:56 +00001791 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1792 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1793 if (old_state_is_stopped != new_state_is_stopped)
1794 {
1795 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001796 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001797 else
Ed Maste64fad602013-07-29 20:58:06 +00001798 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001799 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001800
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001801 if (state_changed)
1802 {
1803 m_private_state.SetValueNoLock (new_state);
Ilia K38810f42015-05-20 10:15:47 +00001804 EventSP event_sp (new Event (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)));
Greg Clayton2637f822011-11-17 01:23:07 +00001805 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001807 // Note, this currently assumes that all threads in the list
1808 // stop when the process stops. In the future we will want to
1809 // support a debugging model where some threads continue to run
1810 // while others are stopped. When that happens we will either need
1811 // a way for the thread list to identify which threads are stopping
1812 // or create a special thread list containing only threads which
1813 // actually stopped.
1814 //
1815 // The process plugin is responsible for managing the actual
1816 // behavior of the threads and should have stopped any threads
1817 // that are going to stop before we get here.
1818 m_thread_list.DidStop();
1819
Jim Ingham4b536182011-08-09 02:12:22 +00001820 m_mod_id.BumpStopID();
Ilia K38810f42015-05-20 10:15:47 +00001821 if (!m_mod_id.IsLastResumeForUserExpression())
1822 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
Greg Clayton58be07b2011-01-07 06:08:19 +00001823 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001824 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001825 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001826 }
Ilia K38810f42015-05-20 10:15:47 +00001827
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001828 // Use our target to get a shared pointer to ourselves...
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001829 if (m_finalize_called && !PrivateStateThreadIsValid())
Ilia K38810f42015-05-20 10:15:47 +00001830 BroadcastEvent (event_sp);
Greg Clayton35a4cc52012-10-29 20:52:08 +00001831 else
Ilia K38810f42015-05-20 10:15:47 +00001832 m_private_state_broadcaster.BroadcastEvent (event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001833 }
1834 else
1835 {
1836 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001837 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001838 }
1839}
1840
Jim Ingham0faa43f2011-11-08 03:00:11 +00001841void
1842Process::SetRunningUserExpression (bool on)
1843{
1844 m_mod_id.SetRunningUserExpression (on);
1845}
1846
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001847addr_t
1848Process::GetImageInfoAddress()
1849{
1850 return LLDB_INVALID_ADDRESS;
1851}
1852
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001853const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001854Process::GetABI()
1855{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001856 if (!m_abi_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00001857 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001858 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001859}
1860
Jim Ingham22777012010-09-23 02:01:19 +00001861LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001862Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001863{
Greg Claytonc00ca312015-04-02 18:44:58 +00001864 if (m_finalizing)
1865 return nullptr;
1866
Jim Ingham22777012010-09-23 02:01:19 +00001867 LanguageRuntimeCollection::iterator pos;
1868 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001869 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001870 {
Jim Inghamab175242012-03-10 00:22:19 +00001871 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001872
Jim Inghamab175242012-03-10 00:22:19 +00001873 m_language_runtimes[language] = runtime_sp;
1874 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001875 }
1876 else
1877 return (*pos).second.get();
1878}
1879
1880CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001881Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001882{
Jim Inghamab175242012-03-10 00:22:19 +00001883 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001884 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
Jim Ingham22777012010-09-23 02:01:19 +00001885 return static_cast<CPPLanguageRuntime *> (runtime);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001886 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001887}
1888
1889ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001890Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001891{
Jim Inghamab175242012-03-10 00:22:19 +00001892 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001893 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
Jim Ingham22777012010-09-23 02:01:19 +00001894 return static_cast<ObjCLanguageRuntime *> (runtime);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001895 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001896}
1897
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001898bool
1899Process::IsPossibleDynamicValue (ValueObject& in_value)
1900{
Greg Claytonc00ca312015-04-02 18:44:58 +00001901 if (m_finalizing)
1902 return false;
1903
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001904 if (in_value.IsDynamic())
1905 return false;
1906 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1907
1908 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1909 {
1910 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1911 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1912 }
1913
1914 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1915 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1916 return true;
1917
1918 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1919 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1920}
1921
Zachary Turner93749ab2015-03-03 21:51:25 +00001922void
1923Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
1924{
1925 m_dynamic_checkers_ap.reset(dynamic_checkers);
1926}
1927
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001928BreakpointSiteList &
1929Process::GetBreakpointSiteList()
1930{
1931 return m_breakpoint_site_list;
1932}
1933
1934const BreakpointSiteList &
1935Process::GetBreakpointSiteList() const
1936{
1937 return m_breakpoint_site_list;
1938}
1939
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001940void
1941Process::DisableAllBreakpointSites ()
1942{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001943 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1944// bp_site->SetEnabled(true);
1945 DisableBreakpointSite(bp_site);
1946 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001947}
1948
1949Error
1950Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1951{
1952 Error error (DisableBreakpointSiteByID (break_id));
1953
1954 if (error.Success())
1955 m_breakpoint_site_list.Remove(break_id);
1956
1957 return error;
1958}
1959
1960Error
1961Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1962{
1963 Error error;
1964 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1965 if (bp_site_sp)
1966 {
1967 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001968 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001969 }
1970 else
1971 {
Daniel Malead01b2952012-11-29 21:49:15 +00001972 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001973 }
1974
1975 return error;
1976}
1977
1978Error
1979Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1980{
1981 Error error;
1982 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1983 if (bp_site_sp)
1984 {
1985 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001986 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001987 }
1988 else
1989 {
Daniel Malead01b2952012-11-29 21:49:15 +00001990 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001991 }
1992 return error;
1993}
1994
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001995lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001996Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001997{
Jim Ingham1460e4b2014-01-10 23:46:59 +00001998 addr_t load_addr = LLDB_INVALID_ADDRESS;
1999
2000 bool show_error = true;
2001 switch (GetState())
2002 {
2003 case eStateInvalid:
2004 case eStateUnloaded:
2005 case eStateConnected:
2006 case eStateAttaching:
2007 case eStateLaunching:
2008 case eStateDetached:
2009 case eStateExited:
2010 show_error = false;
2011 break;
2012
2013 case eStateStopped:
2014 case eStateRunning:
2015 case eStateStepping:
2016 case eStateCrashed:
2017 case eStateSuspended:
2018 show_error = IsAlive();
2019 break;
2020 }
2021
2022 // Reset the IsIndirect flag here, in case the location changes from
2023 // pointing to a indirect symbol to a regular symbol.
2024 owner->SetIsIndirect (false);
2025
2026 if (owner->ShouldResolveIndirectFunctions())
2027 {
2028 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2029 if (symbol && symbol->IsIndirect())
2030 {
2031 Error error;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002032 Address symbol_address = symbol->GetAddress();
2033 load_addr = ResolveIndirectFunction (&symbol_address, error);
Jim Ingham1460e4b2014-01-10 23:46:59 +00002034 if (!error.Success() && show_error)
2035 {
Zachary Turner7529df92015-09-01 20:02:29 +00002036 GetTarget().GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2037 symbol->GetLoadAddress(&GetTarget()),
2038 owner->GetBreakpoint().GetID(),
2039 owner->GetID(),
2040 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002041 return LLDB_INVALID_BREAK_ID;
2042 }
2043 Address resolved_address(load_addr);
Zachary Turner7529df92015-09-01 20:02:29 +00002044 load_addr = resolved_address.GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002045 owner->SetIsIndirect(true);
2046 }
2047 else
Zachary Turner7529df92015-09-01 20:02:29 +00002048 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002049 }
2050 else
Zachary Turner7529df92015-09-01 20:02:29 +00002051 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002052
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002053 if (load_addr != LLDB_INVALID_ADDRESS)
2054 {
2055 BreakpointSiteSP bp_site_sp;
2056
2057 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2058 // create a new breakpoint site and add it.
2059
2060 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2061
2062 if (bp_site_sp)
2063 {
2064 bp_site_sp->AddOwner (owner);
2065 owner->SetBreakpointSite (bp_site_sp);
2066 return bp_site_sp->GetID();
2067 }
2068 else
2069 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002070 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002071 if (bp_site_sp)
2072 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002073 Error error = EnableBreakpointSite (bp_site_sp.get());
2074 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002075 {
2076 owner->SetBreakpointSite (bp_site_sp);
2077 return m_breakpoint_site_list.Add (bp_site_sp);
2078 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002079 else
2080 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002081 if (show_error)
2082 {
2083 // Report error for setting breakpoint...
Zachary Turner7529df92015-09-01 20:02:29 +00002084 GetTarget().GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2085 load_addr,
2086 owner->GetBreakpoint().GetID(),
2087 owner->GetID(),
2088 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002089 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002090 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002091 }
2092 }
2093 }
2094 // We failed to enable the breakpoint
2095 return LLDB_INVALID_BREAK_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002096}
2097
2098void
2099Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2100{
2101 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2102 if (num_owners == 0)
2103 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002104 // Don't try to disable the site if we don't have a live process anymore.
2105 if (IsAlive())
2106 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002107 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2108 }
2109}
2110
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111size_t
2112Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2113{
2114 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002115 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002116
Jim Ingham20c77192011-06-29 19:42:28 +00002117 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002118 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002119 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2120 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002121 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002122 addr_t intersect_addr;
2123 size_t intersect_size;
2124 size_t opcode_offset;
2125 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002126 {
2127 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2128 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002129 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002130 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002131 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002132 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002133 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002134 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002135 }
2136 return bytes_removed;
2137}
2138
Greg Claytonded470d2011-03-19 01:12:21 +00002139size_t
2140Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2141{
Zachary Turner7529df92015-09-01 20:02:29 +00002142 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Claytonded470d2011-03-19 01:12:21 +00002143 if (platform_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00002144 return platform_sp->GetSoftwareBreakpointTrapOpcode (GetTarget(), bp_site);
Greg Claytonded470d2011-03-19 01:12:21 +00002145 return 0;
2146}
2147
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002148Error
2149Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2150{
2151 Error error;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002152 assert(bp_site != nullptr);
Greg Clayton5160ce52013-03-27 23:08:40 +00002153 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002154 const addr_t bp_addr = bp_site->GetLoadAddress();
2155 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002156 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002157 if (bp_site->IsEnabled())
2158 {
2159 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002160 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002161 return error;
2162 }
2163
2164 if (bp_addr == LLDB_INVALID_ADDRESS)
2165 {
2166 error.SetErrorString("BreakpointSite contains an invalid load address.");
2167 return error;
2168 }
2169 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2170 // trap for the breakpoint site
2171 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2172
2173 if (bp_opcode_size == 0)
2174 {
Daniel Malead01b2952012-11-29 21:49:15 +00002175 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002176 }
2177 else
2178 {
2179 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2180
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002181 if (bp_opcode_bytes == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002182 {
2183 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2184 return error;
2185 }
2186
2187 // Save the original opcode by reading it
2188 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2189 {
2190 // Write a software breakpoint in place of the original opcode
2191 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2192 {
2193 uint8_t verify_bp_opcode_bytes[64];
2194 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2195 {
2196 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2197 {
2198 bp_site->SetEnabled(true);
2199 bp_site->SetType (BreakpointSite::eSoftware);
2200 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002201 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002202 bp_site->GetID(),
2203 (uint64_t)bp_addr);
2204 }
2205 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002206 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002207 }
2208 else
2209 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2210 }
2211 else
2212 error.SetErrorString("Unable to write breakpoint trap to memory.");
2213 }
2214 else
2215 error.SetErrorString("Unable to read memory at breakpoint address.");
2216 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002217 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002218 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002219 bp_site->GetID(),
2220 (uint64_t)bp_addr,
2221 error.AsCString());
2222 return error;
2223}
2224
2225Error
2226Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2227{
2228 Error error;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002229 assert(bp_site != nullptr);
Greg Clayton5160ce52013-03-27 23:08:40 +00002230 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002231 addr_t bp_addr = bp_site->GetLoadAddress();
2232 lldb::user_id_t breakID = bp_site->GetID();
2233 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002234 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002235
2236 if (bp_site->IsHardware())
2237 {
2238 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2239 }
2240 else if (bp_site->IsEnabled())
2241 {
2242 const size_t break_op_size = bp_site->GetByteSize();
2243 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2244 if (break_op_size > 0)
2245 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002246 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002247 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002248 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002249 bool break_op_found = false;
2250
2251 // Read the breakpoint opcode
2252 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2253 {
2254 bool verify = false;
Bruce Mitchener58ef3912015-06-18 05:27:05 +00002255 // Make sure the breakpoint opcode exists at this address
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002256 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2257 {
2258 break_op_found = true;
2259 // We found a valid breakpoint opcode at this address, now restore
2260 // the saved opcode.
2261 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2262 {
2263 verify = true;
2264 }
2265 else
2266 error.SetErrorString("Memory write failed when restoring original opcode.");
2267 }
2268 else
2269 {
2270 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2271 // Set verify to true and so we can check if the original opcode has already been restored
2272 verify = true;
2273 }
2274
2275 if (verify)
2276 {
Greg Claytonc982c762010-07-09 20:39:50 +00002277 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002278 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002279 // Verify that our original opcode made it back to the inferior
2280 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2281 {
2282 // compare the memory we just read with the original opcode
2283 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2284 {
2285 // SUCCESS
2286 bp_site->SetEnabled(false);
2287 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002288 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002289 return error;
2290 }
2291 else
2292 {
2293 if (break_op_found)
2294 error.SetErrorString("Failed to restore original opcode.");
2295 }
2296 }
2297 else
2298 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2299 }
2300 }
2301 else
2302 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2303 }
2304 }
2305 else
2306 {
2307 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002308 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002309 return error;
2310 }
2311
2312 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002313 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002314 bp_site->GetID(),
2315 (uint64_t)bp_addr,
2316 error.AsCString());
2317 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002318}
2319
Greg Clayton58be07b2011-01-07 06:08:19 +00002320// Uncomment to verify memory caching works after making changes to caching code
2321//#define VERIFY_MEMORY_READS
2322
Sean Callanan64c0cf22012-06-07 22:26:42 +00002323size_t
2324Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2325{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002326 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002327 if (!GetDisableMemoryCache())
2328 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002329#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002330 // Memory caching is enabled, with debug verification
2331
2332 if (buf && size)
2333 {
2334 // Uncomment the line below to make sure memory caching is working.
2335 // I ran this through the test suite and got no assertions, so I am
2336 // pretty confident this is working well. If any changes are made to
2337 // memory caching, uncomment the line below and test your changes!
2338
2339 // Verify all memory reads by using the cache first, then redundantly
2340 // reading the same memory from the inferior and comparing to make sure
2341 // everything is exactly the same.
2342 std::string verify_buf (size, '\0');
2343 assert (verify_buf.size() == size);
2344 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2345 Error verify_error;
2346 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2347 assert (cache_bytes_read == verify_bytes_read);
2348 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2349 assert (verify_error.Success() == error.Success());
2350 return cache_bytes_read;
2351 }
2352 return 0;
2353#else // !defined(VERIFY_MEMORY_READS)
2354 // Memory caching is enabled, without debug verification
2355
2356 return m_memory_cache.Read (addr, buf, size, error);
2357#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002358 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002359 else
2360 {
2361 // Memory caching is disabled
2362
2363 return ReadMemoryFromInferior (addr, buf, size, error);
2364 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002365}
Greg Clayton58be07b2011-01-07 06:08:19 +00002366
Greg Clayton4c82d422012-05-18 23:20:01 +00002367size_t
2368Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2369{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002370 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002371 out_str.clear();
2372 addr_t curr_addr = addr;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002373 while (true)
Greg Clayton4c82d422012-05-18 23:20:01 +00002374 {
2375 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2376 if (length == 0)
2377 break;
2378 out_str.append(buf, length);
2379 // If we got "length - 1" bytes, we didn't get the whole C string, we
2380 // need to read some more characters
2381 if (length == sizeof(buf) - 1)
2382 curr_addr += length;
2383 else
2384 break;
2385 }
2386 return out_str.size();
2387}
2388
Greg Clayton58be07b2011-01-07 06:08:19 +00002389size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002390Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2391 size_t type_width)
2392{
2393 size_t total_bytes_read = 0;
2394 if (dst && max_bytes && type_width && max_bytes >= type_width)
2395 {
2396 // Ensure a null terminator independent of the number of bytes that is read.
2397 memset (dst, 0, max_bytes);
2398 size_t bytes_left = max_bytes - type_width;
2399
2400 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2401 assert(sizeof(terminator) >= type_width &&
2402 "Attempting to validate a string with more than 4 bytes per character!");
2403
2404 addr_t curr_addr = addr;
2405 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2406 char *curr_dst = dst;
2407
2408 error.Clear();
2409 while (bytes_left > 0 && error.Success())
2410 {
2411 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2412 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2413 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2414
2415 if (bytes_read == 0)
2416 break;
2417
2418 // Search for a null terminator of correct size and alignment in bytes_read
2419 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2420 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
Ulrich Weigand0501eeb2016-04-14 14:33:47 +00002421 if (::memcmp(&dst[i], terminator, type_width) == 0)
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002422 {
2423 error.Clear();
2424 return i;
2425 }
2426
2427 total_bytes_read += bytes_read;
2428 curr_dst += bytes_read;
2429 curr_addr += bytes_read;
2430 bytes_left -= bytes_read;
2431 }
2432 }
2433 else
2434 {
2435 if (max_bytes)
2436 error.SetErrorString("invalid arguments");
2437 }
2438 return total_bytes_read;
2439}
2440
2441// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2442// null terminators.
2443size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002444Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002445{
2446 size_t total_cstr_len = 0;
2447 if (dst && dst_max_len)
2448 {
Greg Claytone91b7952011-12-15 03:14:23 +00002449 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002450 // NULL out everything just to be safe
2451 memset (dst, 0, dst_max_len);
2452 Error error;
2453 addr_t curr_addr = addr;
2454 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2455 size_t bytes_left = dst_max_len - 1;
2456 char *curr_dst = dst;
2457
2458 while (bytes_left > 0)
2459 {
2460 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2461 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2462 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2463
2464 if (bytes_read == 0)
2465 {
Greg Claytone91b7952011-12-15 03:14:23 +00002466 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002467 dst[total_cstr_len] = '\0';
2468 break;
2469 }
2470 const size_t len = strlen(curr_dst);
2471
2472 total_cstr_len += len;
2473
2474 if (len < bytes_to_read)
2475 break;
2476
2477 curr_dst += bytes_read;
2478 curr_addr += bytes_read;
2479 bytes_left -= bytes_read;
2480 }
2481 }
Greg Claytone91b7952011-12-15 03:14:23 +00002482 else
2483 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002484 if (dst == nullptr)
Greg Claytone91b7952011-12-15 03:14:23 +00002485 result_error.SetErrorString("invalid arguments");
2486 else
2487 result_error.Clear();
2488 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002489 return total_cstr_len;
2490}
2491
2492size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002493Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2494{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002495 if (buf == nullptr || size == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002496 return 0;
2497
2498 size_t bytes_read = 0;
2499 uint8_t *bytes = (uint8_t *)buf;
2500
2501 while (bytes_read < size)
2502 {
2503 const size_t curr_size = size - bytes_read;
2504 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2505 bytes + bytes_read,
2506 curr_size,
2507 error);
2508 bytes_read += curr_bytes_read;
2509 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2510 break;
2511 }
2512
2513 // Replace any software breakpoint opcodes that fall into this range back
2514 // into "buf" before we return
2515 if (bytes_read > 0)
2516 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2517 return bytes_read;
2518}
2519
Greg Clayton58a4c462010-12-16 20:01:20 +00002520uint64_t
Greg Claytonc2267782016-05-23 20:37:24 +00002521Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value,
2522 Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002523{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002524 Scalar scalar;
2525 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2526 return scalar.ULongLong(fail_value);
2527 return fail_value;
2528}
2529
Greg Claytonc2267782016-05-23 20:37:24 +00002530int64_t
2531Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr, size_t integer_byte_size, int64_t fail_value, Error &error)
2532{
2533 Scalar scalar;
2534 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar, error))
2535 return scalar.SLongLong(fail_value);
2536 return fail_value;
2537}
2538
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002539addr_t
2540Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2541{
2542 Scalar scalar;
2543 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2544 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2545 return LLDB_INVALID_ADDRESS;
2546}
2547
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002548bool
2549Process::WritePointerToMemory (lldb::addr_t vm_addr,
2550 lldb::addr_t ptr_value,
2551 Error &error)
2552{
2553 Scalar scalar;
2554 const uint32_t addr_byte_size = GetAddressByteSize();
2555 if (addr_byte_size <= 4)
2556 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002557 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002558 scalar = ptr_value;
2559 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002560}
2561
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002562size_t
2563Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2564{
2565 size_t bytes_written = 0;
2566 const uint8_t *bytes = (const uint8_t *)buf;
2567
2568 while (bytes_written < size)
2569 {
2570 const size_t curr_size = size - bytes_written;
2571 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2572 bytes + bytes_written,
2573 curr_size,
2574 error);
2575 bytes_written += curr_bytes_written;
2576 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2577 break;
2578 }
2579 return bytes_written;
2580}
2581
2582size_t
2583Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2584{
Greg Clayton58be07b2011-01-07 06:08:19 +00002585#if defined (ENABLE_MEMORY_CACHING)
2586 m_memory_cache.Flush (addr, size);
2587#endif
2588
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002589 if (buf == nullptr || size == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002590 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002591
Jim Ingham4b536182011-08-09 02:12:22 +00002592 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002593
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002594 // We need to write any data that would go where any current software traps
2595 // (enabled software breakpoints) any software traps (breakpoints) that we
2596 // may have placed in our tasks memory.
2597
Greg Claytond8cf1a12013-06-12 00:46:38 +00002598 BreakpointSiteList bp_sites_in_range;
2599
2600 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002601 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002602 // No breakpoint sites overlap
2603 if (bp_sites_in_range.IsEmpty())
2604 return WriteMemoryPrivate (addr, buf, size, error);
2605 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002606 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002607 const uint8_t *ubuf = (const uint8_t *)buf;
2608 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002609
Greg Claytond8cf1a12013-06-12 00:46:38 +00002610 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2611
2612 if (error.Success())
2613 {
2614 addr_t intersect_addr;
2615 size_t intersect_size;
2616 size_t opcode_offset;
2617 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
Bruce Mitchener8a67bf72015-07-24 00:23:29 +00002618 UNUSED_IF_ASSERT_DISABLED(intersects);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002619 assert(intersects);
2620 assert(addr <= intersect_addr && intersect_addr < addr + size);
2621 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2622 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2623
2624 // Check for bytes before this breakpoint
2625 const addr_t curr_addr = addr + bytes_written;
2626 if (intersect_addr > curr_addr)
2627 {
2628 // There are some bytes before this breakpoint that we need to
2629 // just write to memory
2630 size_t curr_size = intersect_addr - curr_addr;
2631 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2632 ubuf + bytes_written,
2633 curr_size,
2634 error);
2635 bytes_written += curr_bytes_written;
2636 if (curr_bytes_written != curr_size)
2637 {
2638 // We weren't able to write all of the requested bytes, we
2639 // are done looping and will return the number of bytes that
2640 // we have written so far.
2641 if (error.Success())
2642 error.SetErrorToGenericError();
2643 }
2644 }
2645 // Now write any bytes that would cover up any software breakpoints
2646 // directly into the breakpoint opcode buffer
2647 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2648 bytes_written += intersect_size;
2649 }
2650 });
2651
2652 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002653 WriteMemoryPrivate (addr + bytes_written,
2654 ubuf + bytes_written,
2655 size - bytes_written,
2656 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002657 }
2658 }
2659 else
2660 {
2661 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002662 }
2663
2664 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002665 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002666}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002667
2668size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002669Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002670{
2671 if (byte_size == UINT32_MAX)
2672 byte_size = scalar.GetByteSize();
2673 if (byte_size > 0)
2674 {
2675 uint8_t buf[32];
2676 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2677 if (mem_size > 0)
2678 return WriteMemory(addr, buf, mem_size, error);
2679 else
2680 error.SetErrorString ("failed to get scalar as memory data");
2681 }
2682 else
2683 {
2684 error.SetErrorString ("invalid scalar value");
2685 }
2686 return 0;
2687}
2688
2689size_t
2690Process::ReadScalarIntegerFromMemory (addr_t addr,
2691 uint32_t byte_size,
2692 bool is_signed,
2693 Scalar &scalar,
2694 Error &error)
2695{
Greg Clayton7060f892013-05-01 23:41:30 +00002696 uint64_t uval = 0;
2697 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002698 {
Greg Clayton7060f892013-05-01 23:41:30 +00002699 error.SetErrorString ("byte size is zero");
2700 }
2701 else if (byte_size & (byte_size - 1))
2702 {
2703 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2704 }
2705 else if (byte_size <= sizeof(uval))
2706 {
2707 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002708 if (bytes_read == byte_size)
2709 {
2710 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002711 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002712 if (byte_size <= 4)
2713 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002714 else
Greg Clayton7060f892013-05-01 23:41:30 +00002715 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002716 if (is_signed)
2717 scalar.SignExtend(byte_size * 8);
2718 return bytes_read;
2719 }
2720 }
2721 else
2722 {
2723 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2724 }
2725 return 0;
2726}
2727
Greg Claytond495c532011-05-17 03:37:42 +00002728#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002729addr_t
2730Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2731{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002732 if (GetPrivateState() != eStateStopped)
2733 return LLDB_INVALID_ADDRESS;
2734
Greg Claytond495c532011-05-17 03:37:42 +00002735#if defined (USE_ALLOCATE_MEMORY_CACHE)
2736 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2737#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002738 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002739 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002740 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002741 log->Printf("Process::AllocateMemory(size=%" PRIu64 ", permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
Deepak Panickald66b50c2013-10-22 12:27:43 +00002742 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002743 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002744 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002745 m_mod_id.GetStopID(),
2746 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002747 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002748#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749}
2750
Jim Ingham2c381412015-11-04 20:32:27 +00002751addr_t
2752Process::CallocateMemory(size_t size, uint32_t permissions, Error &error)
2753{
2754 addr_t return_addr = AllocateMemory(size, permissions, error);
2755 if (error.Success())
2756 {
2757 std::string buffer(size, 0);
2758 WriteMemory(return_addr, buffer.c_str(), size, error);
2759 }
2760 return return_addr;
2761}
2762
Sean Callanan90539452011-09-20 23:01:51 +00002763bool
2764Process::CanJIT ()
2765{
Sean Callanana7b443a2012-02-14 22:50:38 +00002766 if (m_can_jit == eCanJITDontKnow)
2767 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002768 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002769 Error err;
2770
2771 uint64_t allocated_memory = AllocateMemory(8,
2772 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2773 err);
2774
2775 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002776 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002777 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002778 if (log)
2779 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2780 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002781 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002782 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002783 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002784 if (log)
2785 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2786 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002787
2788 DeallocateMemory (allocated_memory);
2789 }
2790
Sean Callanan90539452011-09-20 23:01:51 +00002791 return m_can_jit == eCanJITYes;
2792}
2793
2794void
2795Process::SetCanJIT (bool can_jit)
2796{
2797 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2798}
2799
Ewan Crawford90ff7912015-07-14 10:56:58 +00002800void
2801Process::SetCanRunCode (bool can_run_code)
2802{
2803 SetCanJIT(can_run_code);
2804 m_can_interpret_function_calls = can_run_code;
2805}
2806
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002807Error
2808Process::DeallocateMemory (addr_t ptr)
2809{
Greg Claytond495c532011-05-17 03:37:42 +00002810 Error error;
2811#if defined (USE_ALLOCATE_MEMORY_CACHE)
2812 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2813 {
Daniel Malead01b2952012-11-29 21:49:15 +00002814 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002815 }
2816#else
2817 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002818
Greg Clayton5160ce52013-03-27 23:08:40 +00002819 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002820 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002821 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002822 ptr,
2823 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002824 m_mod_id.GetStopID(),
2825 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002826#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002827 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002828}
2829
Greg Claytonc9660542012-02-05 02:38:54 +00002830ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002831Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002832 lldb::addr_t header_addr,
2833 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002834{
Jason Molenda08a32582015-07-25 02:39:42 +00002835 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2836 if (log)
2837 {
2838 log->Printf ("Process::ReadModuleFromMemory reading %s binary from memory", file_spec.GetPath().c_str());
2839 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002840 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002841 if (module_sp)
2842 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002843 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002844 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002845 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002846 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002847 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002848 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002849}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002850
Zachary Turner93749ab2015-03-03 21:51:25 +00002851bool
2852Process::GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
2853{
2854 MemoryRegionInfo range_info;
2855 permissions = 0;
2856 Error error (GetMemoryRegionInfo (load_addr, range_info));
2857 if (!error.Success())
2858 return false;
2859 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
2860 || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
2861 || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
2862 {
2863 return false;
2864 }
2865
2866 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2867 permissions |= lldb::ePermissionsReadable;
2868
2869 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2870 permissions |= lldb::ePermissionsWritable;
2871
2872 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2873 permissions |= lldb::ePermissionsExecutable;
2874
2875 return true;
2876}
2877
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002878Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002879Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880{
2881 Error error;
2882 error.SetErrorString("watchpoints are not supported");
2883 return error;
2884}
2885
2886Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002887Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002888{
2889 Error error;
2890 error.SetErrorString("watchpoints are not supported");
2891 return error;
2892}
2893
2894StateType
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002895Process::WaitForProcessStopPrivate(const std::chrono::microseconds &timeout, EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002896{
2897 StateType state;
2898 // Now wait for the process to launch and return control to us, and then
2899 // call DidLaunch:
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002900 while (true)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002901 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002902 event_sp.reset();
2903 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2904
Greg Clayton2637f822011-11-17 01:23:07 +00002905 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002906 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002907
2908 // If state is invalid, then we timed out
2909 if (state == eStateInvalid)
2910 break;
2911
2912 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002913 HandlePrivateEvent (event_sp);
2914 }
2915 return state;
2916}
2917
Greg Clayton332e8b12015-01-13 21:13:08 +00002918void
2919Process::LoadOperatingSystemPlugin(bool flush)
2920{
2921 if (flush)
2922 m_thread_list.Clear();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002923 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
Greg Clayton332e8b12015-01-13 21:13:08 +00002924 if (flush)
2925 Flush();
2926}
2927
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002928Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002929Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002930{
2931 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002932 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002933 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002934 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002935 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002936 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002937 m_process_input_reader.reset();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002938 m_stop_info_override_callback = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002939
Zachary Turner7529df92015-09-01 20:02:29 +00002940 Module *exe_module = GetTarget().GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002941 if (exe_module)
2942 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002943 char local_exec_file_path[PATH_MAX];
2944 char platform_exec_file_path[PATH_MAX];
2945 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2946 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002947 if (exe_module->GetFileSpec().Exists())
2948 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002949 // Install anything that might need to be installed prior to launching.
2950 // For host systems, this will do nothing, but if we are connected to a
2951 // remote platform it will install any needed binaries
2952 error = GetTarget().Install(&launch_info);
2953 if (error.Fail())
2954 return error;
2955
Greg Clayton71337622011-02-24 22:24:29 +00002956 if (PrivateStateThreadIsValid ())
2957 PausePrivateStateThread ();
2958
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002959 error = WillLaunch (exe_module);
2960 if (error.Success())
2961 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002962 const bool restarted = false;
2963 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002964 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002965
Ed Maste64fad602013-07-29 20:58:06 +00002966 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002967 {
2968 // Now launch using these arguments.
2969 error = DoLaunch (exe_module, launch_info);
2970 }
2971 else
2972 {
2973 // This shouldn't happen
2974 error.SetErrorString("failed to acquire process run lock");
2975 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002976
2977 if (error.Fail())
2978 {
2979 if (GetID() != LLDB_INVALID_PROCESS_ID)
2980 {
2981 SetID (LLDB_INVALID_PROCESS_ID);
2982 const char *error_string = error.AsCString();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002983 if (error_string == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002984 error_string = "launch failed";
2985 SetExitStatus (-1, error_string);
2986 }
2987 }
2988 else
2989 {
2990 EventSP event_sp;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00002991 StateType state = WaitForProcessStopPrivate(std::chrono::seconds(10), event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002992
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002993 if (state == eStateInvalid || !event_sp)
Greg Clayton1a38ea72011-06-22 01:42:17 +00002994 {
2995 // We were able to launch the process, but we failed to
2996 // catch the initial stop.
Tamas Berghammer04e63142015-02-23 10:59:54 +00002997 error.SetErrorString ("failed to catch stop after launch");
Greg Clayton1a38ea72011-06-22 01:42:17 +00002998 SetExitStatus (0, "failed to catch stop after launch");
Jason Molendaede31932015-04-17 05:01:58 +00002999 Destroy(false);
Greg Clayton1a38ea72011-06-22 01:42:17 +00003000 }
3001 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003002 {
3003 DidLaunch ();
3004
Greg Claytonc859e2d2012-02-13 23:10:39 +00003005 DynamicLoader *dyld = GetDynamicLoader ();
3006 if (dyld)
3007 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003008
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003009 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003010
Jason Molendaeef51062013-11-05 03:57:19 +00003011 SystemRuntime *system_runtime = GetSystemRuntime ();
3012 if (system_runtime)
3013 system_runtime->DidLaunch();
3014
Greg Clayton332e8b12015-01-13 21:13:08 +00003015 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:21 +00003016
3017 // Note, the stop event was consumed above, but not handled. This was done
3018 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3019 // Directly set the state. This is done to prevent a stop message with a bunch
3020 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3021 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003022
3023 if (PrivateStateThreadIsValid ())
3024 ResumePrivateStateThread ();
3025 else
3026 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003027
3028 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Ilia K6af632f2015-02-06 18:15:05 +00003029
3030 // Target was stopped at entry as was intended. Need to notify the listeners
3031 // about it.
Ilia K333fc182015-02-11 11:24:20 +00003032 if (state == eStateStopped && launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Ilia K6af632f2015-02-06 18:15:05 +00003033 HandlePrivateEvent(event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003034 }
3035 else if (state == eStateExited)
3036 {
3037 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3038 // not likely to work, and return an invalid pid.
3039 HandlePrivateEvent (event_sp);
3040 }
3041 }
3042 }
3043 }
3044 else
3045 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003046 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003047 }
3048 }
3049 return error;
3050}
3051
Greg Claytonc3776bf2012-02-09 06:16:32 +00003052Error
3053Process::LoadCore ()
3054{
3055 Error error = DoLoadCore();
3056 if (error.Success())
3057 {
Jim Ingham583bbb12016-03-07 21:50:25 +00003058 ListenerSP listener_sp (Listener::MakeListener("lldb.process.load_core_listener"));
3059 HijackProcessEvents(listener_sp);
Greg Clayton35824e32015-02-20 20:59:47 +00003060
Greg Claytonc3776bf2012-02-09 06:16:32 +00003061 if (PrivateStateThreadIsValid ())
3062 ResumePrivateStateThread ();
3063 else
3064 StartPrivateStateThread ();
3065
Greg Claytonc859e2d2012-02-13 23:10:39 +00003066 DynamicLoader *dyld = GetDynamicLoader ();
3067 if (dyld)
3068 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003069
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003070 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003071
Jason Molendaeef51062013-11-05 03:57:19 +00003072 SystemRuntime *system_runtime = GetSystemRuntime ();
3073 if (system_runtime)
3074 system_runtime->DidAttach();
3075
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003076 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003077 // We successfully loaded a core file, now pretend we stopped so we can
3078 // show all of the threads in the core file and explore the crashed
3079 // state.
3080 SetPrivateState (eStateStopped);
Greg Clayton35824e32015-02-20 20:59:47 +00003081
3082 // Wait indefinitely for a stopped event since we just posted one above...
3083 lldb::EventSP event_sp;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003084 listener_sp->WaitForEvent(std::chrono::microseconds(0), event_sp);
Greg Clayton35824e32015-02-20 20:59:47 +00003085 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3086
3087 if (!StateIsStoppedState (state, false))
3088 {
3089 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3090 if (log)
3091 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3092 error.SetErrorString ("Did not get stopped event after loading the core file.");
3093 }
Greg Clayton338d0bd2015-02-20 21:51:06 +00003094 RestoreProcessEvents ();
Greg Claytonc3776bf2012-02-09 06:16:32 +00003095 }
3096 return error;
3097}
3098
Greg Claytonc859e2d2012-02-13 23:10:39 +00003099DynamicLoader *
3100Process::GetDynamicLoader ()
3101{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003102 if (!m_dyld_ap)
3103 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
Greg Claytonc859e2d2012-02-13 23:10:39 +00003104 return m_dyld_ap.get();
3105}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003106
Todd Fialaaf245d12014-06-30 21:05:18 +00003107const lldb::DataBufferSP
3108Process::GetAuxvData()
3109{
3110 return DataBufferSP ();
3111}
3112
Andrew MacPherson17220c12014-03-05 10:12:43 +00003113JITLoaderList &
3114Process::GetJITLoaders ()
3115{
3116 if (!m_jit_loaders_ap)
3117 {
3118 m_jit_loaders_ap.reset(new JITLoaderList());
3119 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3120 }
3121 return *m_jit_loaders_ap;
3122}
3123
Jason Molendaeef51062013-11-05 03:57:19 +00003124SystemRuntime *
3125Process::GetSystemRuntime ()
3126{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003127 if (!m_system_runtime_ap)
3128 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
Jason Molendaeef51062013-11-05 03:57:19 +00003129 return m_system_runtime_ap.get();
3130}
3131
Todd Fiala76e0fc92014-08-27 22:58:26 +00003132Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3133 NextEventAction (process),
3134 m_exec_count (exec_count)
3135{
3136 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3137 if (log)
3138 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3139}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003140
Jim Inghambb3a2832011-01-29 01:49:25 +00003141Process::NextEventAction::EventActionResult
3142Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003143{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003144 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3145
Jim Inghambb3a2832011-01-29 01:49:25 +00003146 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003147 if (log)
3148 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3149
3150 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003151 {
Zachary Turnerc62733b2015-05-20 18:31:17 +00003152 case eStateAttaching:
3153 return eEventActionSuccess;
3154
Greg Clayton513c26c2011-01-29 07:10:55 +00003155 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003156 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003157 return eEventActionRetry;
3158
3159 case eStateStopped:
3160 case eStateCrashed:
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003161 // During attach, prior to sending the eStateStopped event,
3162 // lldb_private::Process subclasses must set the new process ID.
3163 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
3164 // We don't want these events to be reported, so go set the ShouldReportStop here:
3165 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3166
3167 if (m_exec_count > 0)
Greg Claytonc9ed4782011-11-12 02:10:56 +00003168 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003169 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003170
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003171 if (log)
3172 log->Printf ("Process::AttachCompletionHandler::%s state %s: reduced remaining exec count to %" PRIu32 ", requesting resume", __FUNCTION__, StateAsCString(state), m_exec_count);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003173
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003174 RequestResume();
3175 return eEventActionRetry;
3176 }
3177 else
3178 {
3179 if (log)
3180 log->Printf ("Process::AttachCompletionHandler::%s state %s: no more execs expected to start, continuing with attach", __FUNCTION__, StateAsCString(state));
Todd Fiala76e0fc92014-08-27 22:58:26 +00003181
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003182 m_process->CompleteAttach ();
3183 return eEventActionSuccess;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003184 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003185 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003186
Greg Clayton513c26c2011-01-29 07:10:55 +00003187 default:
3188 case eStateExited:
3189 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003190 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003191 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003192
3193 m_exit_string.assign ("No valid Process");
3194 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003195}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003196
Jim Inghambb3a2832011-01-29 01:49:25 +00003197Process::NextEventAction::EventActionResult
3198Process::AttachCompletionHandler::HandleBeingInterrupted()
3199{
3200 return eEventActionSuccess;
3201}
3202
3203const char *
3204Process::AttachCompletionHandler::GetExitString ()
3205{
3206 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003207}
3208
Jim Ingham583bbb12016-03-07 21:50:25 +00003209ListenerSP
Greg Clayton8012cad2014-11-17 19:39:20 +00003210ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3211{
Jim Ingham583bbb12016-03-07 21:50:25 +00003212 if (m_listener_sp)
3213 return m_listener_sp;
3214 else
3215 return debugger.GetListener();
Greg Clayton8012cad2014-11-17 19:39:20 +00003216}
3217
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003218Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003219Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003220{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003221 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003222 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003223 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003224 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003225 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003226 m_os_ap.reset();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003227 m_stop_info_override_callback = nullptr;
Jim Ingham5aee1622010-08-09 23:31:02 +00003228
Greg Clayton144f3a92011-11-15 03:53:30 +00003229 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003230 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003231 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003232 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003233 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003234
Greg Clayton144f3a92011-11-15 03:53:30 +00003235 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003236 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003237 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3238
3239 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003240 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003241 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3242 if (error.Success())
3243 {
Ed Maste64fad602013-07-29 20:58:06 +00003244 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003245 {
3246 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003247 const bool restarted = false;
3248 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003249 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003250 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003251 }
3252 else
3253 {
3254 // This shouldn't happen
3255 error.SetErrorString("failed to acquire process run lock");
3256 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003257
Greg Clayton144f3a92011-11-15 03:53:30 +00003258 if (error.Fail())
3259 {
3260 if (GetID() != LLDB_INVALID_PROCESS_ID)
3261 {
3262 SetID (LLDB_INVALID_PROCESS_ID);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003263 if (error.AsCString() == nullptr)
Greg Clayton144f3a92011-11-15 03:53:30 +00003264 error.SetErrorString("attach failed");
3265
3266 SetExitStatus(-1, error.AsCString());
3267 }
3268 }
3269 else
3270 {
3271 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3272 StartPrivateStateThread();
3273 }
3274 return error;
3275 }
Greg Claytone996fd32011-03-08 22:40:15 +00003276 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003277 else
Greg Claytone996fd32011-03-08 22:40:15 +00003278 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003279 ProcessInstanceInfoList process_infos;
Zachary Turner7529df92015-09-01 20:02:29 +00003280 PlatformSP platform_sp (GetTarget().GetPlatform ());
Greg Clayton144f3a92011-11-15 03:53:30 +00003281
3282 if (platform_sp)
3283 {
3284 ProcessInstanceInfoMatch match_info;
3285 match_info.GetProcessInfo() = attach_info;
3286 match_info.SetNameMatchType (eNameMatchEquals);
3287 platform_sp->FindProcesses (match_info, process_infos);
3288 const uint32_t num_matches = process_infos.GetSize();
3289 if (num_matches == 1)
3290 {
3291 attach_pid = process_infos.GetProcessIDAtIndex(0);
3292 // Fall through and attach using the above process ID
3293 }
3294 else
3295 {
3296 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3297 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003298 {
3299 StreamString s;
3300 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3301 for (size_t i = 0; i < num_matches; i++)
3302 {
3303 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3304 }
3305 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3306 process_name,
3307 s.GetData());
3308 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003309 else
3310 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3311 }
3312 }
3313 else
3314 {
3315 error.SetErrorString ("invalid platform, can't find processes by name");
3316 return error;
3317 }
Greg Claytone996fd32011-03-08 22:40:15 +00003318 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003319 }
3320 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003321 {
3322 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003323 }
3324 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003325
3326 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003327 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003328 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003329 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003330 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003331
Ed Maste64fad602013-07-29 20:58:06 +00003332 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003333 {
3334 // Now attach using these arguments.
3335 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003336 const bool restarted = false;
3337 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003338 error = DoAttachToProcessWithID (attach_pid, attach_info);
3339 }
3340 else
3341 {
3342 // This shouldn't happen
3343 error.SetErrorString("failed to acquire process run lock");
3344 }
3345
Greg Clayton144f3a92011-11-15 03:53:30 +00003346 if (error.Success())
3347 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003348 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3349 StartPrivateStateThread();
3350 }
3351 else
Greg Claytone996fd32011-03-08 22:40:15 +00003352 {
3353 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003354 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003355
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003356 const char *error_string = error.AsCString();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003357 if (error_string == nullptr)
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003358 error_string = "attach failed";
3359
3360 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003361 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003362 }
3363 }
3364 return error;
3365}
3366
Greg Clayton93d3c8332011-02-16 04:46:07 +00003367void
3368Process::CompleteAttach ()
3369{
Jason Molenda7d002762016-04-07 22:00:55 +00003370 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_TARGET));
Todd Fiala76e0fc92014-08-27 22:58:26 +00003371 if (log)
3372 log->Printf ("Process::%s()", __FUNCTION__);
3373
Greg Clayton93d3c8332011-02-16 04:46:07 +00003374 // Let the process subclass figure out at much as it can about the process
3375 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003376 ArchSpec process_arch;
3377 DidAttach(process_arch);
3378
3379 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003380 {
Zachary Turner7529df92015-09-01 20:02:29 +00003381 GetTarget().SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003382 if (log)
3383 {
3384 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3385 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3386 __FUNCTION__,
3387 triple_str ? triple_str : "<null>");
3388 }
3389 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003390
Jim Ingham4299fdb2011-09-15 01:10:17 +00003391 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3392 // the same as the one we've already set, switch architectures.
Zachary Turner7529df92015-09-01 20:02:29 +00003393 PlatformSP platform_sp (GetTarget().GetPlatform ());
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003394 assert(platform_sp);
Jim Ingham4299fdb2011-09-15 01:10:17 +00003395 if (platform_sp)
3396 {
Zachary Turner7529df92015-09-01 20:02:29 +00003397 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003398 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr))
Greg Clayton70512312012-05-08 01:45:38 +00003399 {
3400 ArchSpec platform_arch;
3401 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3402 if (platform_sp)
3403 {
Zachary Turner7529df92015-09-01 20:02:29 +00003404 GetTarget().SetPlatform (platform_sp);
3405 GetTarget().SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003406 if (log)
3407 log->Printf ("Process::%s switching platform to %s and architecture to %s based on info from attach", __FUNCTION__, platform_sp->GetName().AsCString (""), platform_arch.GetTriple().getTriple().c_str ());
Greg Clayton70512312012-05-08 01:45:38 +00003408 }
3409 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003410 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003411 {
3412 ProcessInstanceInfo process_info;
Pavel Labatha933d512016-04-05 13:07:16 +00003413 GetProcessInfo(process_info);
Greg Clayton70512312012-05-08 01:45:38 +00003414 const ArchSpec &process_arch = process_info.GetArchitecture();
Zachary Turner7529df92015-09-01 20:02:29 +00003415 if (process_arch.IsValid() && !GetTarget().GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003416 {
Zachary Turner7529df92015-09-01 20:02:29 +00003417 GetTarget().SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003418 if (log)
3419 log->Printf ("Process::%s switching architecture to %s based on info the platform retrieved for pid %" PRIu64, __FUNCTION__, process_arch.GetTriple().getTriple().c_str (), GetID ());
3420 }
Greg Clayton70512312012-05-08 01:45:38 +00003421 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003422 }
3423
3424 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003425 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003426 DynamicLoader *dyld = GetDynamicLoader ();
3427 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003428 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003429 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003430 if (log)
3431 {
Zachary Turner7529df92015-09-01 20:02:29 +00003432 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003433 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3434 __FUNCTION__,
3435 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3436 dyld->GetPluginName().AsCString ("<unnamed>"));
3437 }
3438 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003439
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003440 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003441
Jason Molendaeef51062013-11-05 03:57:19 +00003442 SystemRuntime *system_runtime = GetSystemRuntime ();
3443 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003444 {
Jason Molendaeef51062013-11-05 03:57:19 +00003445 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003446 if (log)
3447 {
Zachary Turner7529df92015-09-01 20:02:29 +00003448 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003449 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3450 __FUNCTION__,
3451 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3452 system_runtime->GetPluginName().AsCString("<unnamed>"));
3453 }
3454 }
Jason Molendaeef51062013-11-05 03:57:19 +00003455
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003456 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003457 // Figure out which one is the executable, and set that in our target:
Zachary Turner7529df92015-09-01 20:02:29 +00003458 const ModuleList &target_modules = GetTarget().GetImages();
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00003459 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003460 size_t num_modules = target_modules.GetSize();
3461 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003462
Andy Gibbsa297a972013-06-19 19:04:53 +00003463 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003464 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003465 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003466 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003467 {
Zachary Turner7529df92015-09-01 20:02:29 +00003468 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003469 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003470 break;
3471 }
3472 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003473 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003474 {
Zachary Turner7529df92015-09-01 20:02:29 +00003475 GetTarget().SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003476 if (log)
3477 {
Zachary Turner7529df92015-09-01 20:02:29 +00003478 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003479 log->Printf ("Process::%s after looping through modules, target executable is %s",
3480 __FUNCTION__,
3481 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3482 }
3483 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003484
3485 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003486}
3487
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003488Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003489Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003490{
Greg Claytonb766a732011-02-04 01:58:07 +00003491 m_abi_sp.reset();
3492 m_process_input_reader.reset();
3493
3494 // Find the process and its architecture. Make sure it matches the architecture
3495 // of the current Target, and if not adjust it.
3496
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003497 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003498 if (error.Success())
3499 {
Greg Clayton71337622011-02-24 22:24:29 +00003500 if (GetID() != LLDB_INVALID_PROCESS_ID)
3501 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003502 EventSP event_sp;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003503 StateType state = WaitForProcessStopPrivate(std::chrono::microseconds(0), event_sp);
3504
Greg Clayton32e0a752011-03-30 18:16:51 +00003505 if (state == eStateStopped || state == eStateCrashed)
3506 {
3507 // If we attached and actually have a process on the other end, then
3508 // this ended up being the equivalent of an attach.
3509 CompleteAttach ();
3510
3511 // This delays passing the stopped event to listeners till
3512 // CompleteAttach gets a chance to complete...
3513 HandlePrivateEvent (event_sp);
Greg Clayton32e0a752011-03-30 18:16:51 +00003514 }
Greg Clayton71337622011-02-24 22:24:29 +00003515 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003516
3517 if (PrivateStateThreadIsValid ())
3518 ResumePrivateStateThread ();
3519 else
3520 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003521 }
3522 return error;
3523}
3524
Greg Claytonb766a732011-02-04 01:58:07 +00003525Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003526Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003527{
Greg Clayton5160ce52013-03-27 23:08:40 +00003528 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003529 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003530 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003531 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003532 StateAsCString(m_public_state.GetValue()),
3533 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003534
3535 Error error (WillResume());
3536 // Tell the process it is about to resume before the thread list
3537 if (error.Success())
3538 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003539 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003540 // can let all of our threads know that they are about to be
3541 // resumed. Threads will each be called with
3542 // Thread::WillResume(StateType) where StateType contains the state
3543 // that they are supposed to have when the process is resumed
3544 // (suspended/running/stepping). Threads should also check
3545 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003546 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003547 if (m_thread_list.WillResume())
3548 {
Jim Ingham372787f2012-04-07 00:00:41 +00003549 // Last thing, do the PreResumeActions.
3550 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003551 {
Jim Ingham0161b492013-02-09 01:29:05 +00003552 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003553 }
3554 else
3555 {
3556 m_mod_id.BumpResumeID();
3557 error = DoResume();
3558 if (error.Success())
3559 {
3560 DidResume();
3561 m_thread_list.DidResume();
3562 if (log)
3563 log->Printf ("Process thinks the process has resumed.");
3564 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003565 }
3566 }
3567 else
3568 {
Jim Inghamd5ac1ab2015-01-19 23:51:51 +00003569 // Somebody wanted to run without running (e.g. we were faking a step from one frame of a set of inlined
3570 // frames that share the same PC to another.) So generate a continue & a stopped event,
Jim Ingham513c6bb2012-09-01 01:02:41 +00003571 // and let the world handle them.
3572 if (log)
3573 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3574
3575 SetPrivateState(eStateRunning);
3576 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003577 }
3578 }
Jim Ingham444586b2011-01-24 06:34:17 +00003579 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003580 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003581 return error;
3582}
3583
3584Error
Pavel Labath19da1f12015-12-07 12:36:52 +00003585Process::Halt (bool clear_thread_plans, bool use_run_lock)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003586{
Pavel Labath19da1f12015-12-07 12:36:52 +00003587 if (! StateIsRunningState(m_public_state.GetValue()))
3588 return Error("Process is not running.");
3589
Greg Claytonf9b57b92013-05-10 23:48:10 +00003590 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3591 // in case it was already set and some thread plan logic calls halt on its
3592 // own.
3593 m_clear_thread_plans_on_stop |= clear_thread_plans;
3594
Jim Ingham583bbb12016-03-07 21:50:25 +00003595 ListenerSP halt_listener_sp (Listener::MakeListener("lldb.process.halt_listener"));
3596 HijackProcessEvents(halt_listener_sp);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003597
Jim Inghambb3a2832011-01-29 01:49:25 +00003598 EventSP event_sp;
Jim Inghambb3a2832011-01-29 01:49:25 +00003599
Pavel Labath19da1f12015-12-07 12:36:52 +00003600 SendAsyncInterrupt();
3601
3602 if (m_public_state.GetValue() == eStateAttaching)
Jim Inghambb3a2832011-01-29 01:49:25 +00003603 {
Pavel Labath19da1f12015-12-07 12:36:52 +00003604 // Don't hijack and eat the eStateExited as the code that was doing
3605 // the attach will be waiting for this event...
3606 RestoreProcessEvents();
3607 SetExitStatus(SIGKILL, "Cancelled async attach.");
3608 Destroy (false);
3609 return Error();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003610 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003611
Pavel Labath19da1f12015-12-07 12:36:52 +00003612 // Wait for 10 second for the process to stop.
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003613 StateType state =
3614 WaitForProcessToStop(std::chrono::seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
Pavel Labath19da1f12015-12-07 12:36:52 +00003615 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003616
Pavel Labath19da1f12015-12-07 12:36:52 +00003617 if (state == eStateInvalid || ! event_sp)
3618 {
3619 // We timed out and didn't get a stop event...
3620 return Error("Halt timed out. State = %s", StateAsCString(GetState()));
3621 }
3622
3623 BroadcastEvent(event_sp);
3624
3625 return Error();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626}
3627
3628Error
Pavel Labathfcc7f662015-10-07 15:11:11 +00003629Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp)
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003630{
3631 Error error;
Jim Ingham0f5f7652016-07-26 19:47:45 +00003632
3633 // Check both the public & private states here. If we're hung evaluating an expression, for instance, then
3634 // the public state will be stopped, but we still need to interrupt.
3635 if (m_public_state.GetValue() == eStateRunning || m_private_state.GetValue() == eStateRunning)
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003636 {
3637 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3638 if (log)
Pavel Labathfcc7f662015-10-07 15:11:11 +00003639 log->Printf("Process::%s() About to stop.", __FUNCTION__);
3640
Jim Ingham583bbb12016-03-07 21:50:25 +00003641 ListenerSP listener_sp (Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3642 HijackProcessEvents(listener_sp);
Pavel Labathfcc7f662015-10-07 15:11:11 +00003643
3644 SendAsyncInterrupt();
3645
3646 // Consume the interrupt event.
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00003647 StateType state = WaitForProcessToStop(std::chrono::seconds(10), &exit_event_sp, true, listener_sp);
Pavel Labathfcc7f662015-10-07 15:11:11 +00003648
3649 RestoreProcessEvents();
3650
3651 // If the process exited while we were waiting for it to stop, put the exited event into
3652 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3653 // they don't have a process anymore...
3654
3655 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
Pavel Labathc8c77d42015-09-28 09:37:51 +00003656 {
3657 if (log)
Pavel Labathfcc7f662015-10-07 15:11:11 +00003658 log->Printf("Process::%s() Process exited while waiting to stop.", __FUNCTION__);
3659 return error;
3660 }
3661 else
3662 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3663
3664 if (state != eStateStopped)
3665 {
3666 if (log)
3667 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__, StateAsCString(state));
3668 // If we really couldn't stop the process then we should just error out here, but if the
3669 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3670 StateType private_state = m_private_state.GetValue();
3671 if (private_state != eStateStopped)
3672 {
Jim Ingham1d107722016-06-28 16:35:58 +00003673 return Error("Attempt to stop the target in order to detach timed out. State = %s", StateAsCString(GetState()));
Pavel Labathfcc7f662015-10-07 15:11:11 +00003674 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003675 }
3676 }
3677 return error;
3678}
3679
3680Error
Jim Inghamacff8952013-05-02 00:27:30 +00003681Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003682{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003683 EventSP exit_event_sp;
3684 Error error;
3685 m_destroy_in_process = true;
3686
3687 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003688
3689 if (error.Success())
3690 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003691 if (DetachRequiresHalt())
3692 {
Pavel Labathfcc7f662015-10-07 15:11:11 +00003693 error = StopForDestroyOrDetach (exit_event_sp);
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003694 if (!error.Success())
3695 {
3696 m_destroy_in_process = false;
3697 return error;
3698 }
3699 else if (exit_event_sp)
3700 {
3701 // We shouldn't need to do anything else here. There's no process left to detach from...
3702 StopPrivateStateThread();
3703 m_destroy_in_process = false;
3704 return error;
3705 }
3706 }
3707
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003708 m_thread_list.DiscardThreadPlans();
3709 DisableAllBreakpointSites();
3710
Jim Inghamacff8952013-05-02 00:27:30 +00003711 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003712 if (error.Success())
3713 {
3714 DidDetach();
3715 StopPrivateStateThread();
3716 }
Jim Inghamacff8952013-05-02 00:27:30 +00003717 else
3718 {
3719 return error;
3720 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003721 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003722 m_destroy_in_process = false;
3723
3724 // If we exited when we were waiting for a process to stop, then
3725 // forward the event here so we don't lose the event
3726 if (exit_event_sp)
3727 {
3728 // Directly broadcast our exited event because we shut down our
3729 // private state thread above
3730 BroadcastEvent(exit_event_sp);
3731 }
3732
3733 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3734 // the last events through the event system, in which case we might strand the write lock. Unlock
3735 // it here so when we do to tear down the process we don't get an error destroying the lock.
3736
Ed Maste64fad602013-07-29 20:58:06 +00003737 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003738 return error;
3739}
3740
3741Error
Jason Molendaede31932015-04-17 05:01:58 +00003742Process::Destroy (bool force_kill)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003743{
Pavel Labath19da1f12015-12-07 12:36:52 +00003744
Jim Ingham09437922013-03-01 20:04:25 +00003745 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3746 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3747 // failed and the process stays around for some reason it won't be in a confused state.
Jason Molendaede31932015-04-17 05:01:58 +00003748
3749 if (force_kill)
3750 m_should_detach = false;
Jim Ingham09437922013-03-01 20:04:25 +00003751
Ilia Kfcc89a02015-03-26 07:08:47 +00003752 if (GetShouldDetach())
3753 {
3754 // FIXME: This will have to be a process setting:
3755 bool keep_stopped = false;
3756 Detach(keep_stopped);
3757 }
3758
Jim Ingham09437922013-03-01 20:04:25 +00003759 m_destroy_in_process = true;
3760
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003761 Error error (WillDestroy());
3762 if (error.Success())
3763 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003764 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003765 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003766 {
Pavel Labathfcc7f662015-10-07 15:11:11 +00003767 error = StopForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003768 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003769
Jim Inghamaacc3182012-06-06 00:29:30 +00003770 if (m_public_state.GetValue() != eStateRunning)
3771 {
3772 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3773 // kill it, we don't want it hitting a breakpoint...
3774 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3775 // we're not going to have much luck doing this now.
3776 m_thread_list.DiscardThreadPlans();
3777 DisableAllBreakpointSites();
3778 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003779
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003780 error = DoDestroy();
3781 if (error.Success())
3782 {
3783 DidDestroy();
3784 StopPrivateStateThread();
3785 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003786 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:01 +00003787 m_stdio_communication.StopReadThread();
Vince Harrondf3f00f2015-02-10 21:09:04 +00003788 m_stdin_forward = false;
Greg Claytonb4874f12014-02-28 18:22:24 +00003789
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003790 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003791 {
3792 m_process_input_reader->SetIsDone(true);
3793 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003794 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003795 }
3796
Greg Clayton85fb1b92012-09-11 02:33:37 +00003797 // If we exited when we were waiting for a process to stop, then
3798 // forward the event here so we don't lose the event
3799 if (exit_event_sp)
3800 {
3801 // Directly broadcast our exited event because we shut down our
3802 // private state thread above
3803 BroadcastEvent(exit_event_sp);
3804 }
3805
Jim Inghamb1e2e842012-04-12 18:49:31 +00003806 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3807 // the last events through the event system, in which case we might strand the write lock. Unlock
3808 // it here so when we do to tear down the process we don't get an error destroying the lock.
Ed Maste64fad602013-07-29 20:58:06 +00003809 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003810 }
Jim Ingham09437922013-03-01 20:04:25 +00003811
3812 m_destroy_in_process = false;
3813
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003814 return error;
3815}
3816
3817Error
3818Process::Signal (int signal)
3819{
3820 Error error (WillSignal());
3821 if (error.Success())
3822 {
3823 error = DoSignal(signal);
3824 if (error.Success())
3825 DidSignal();
3826 }
3827 return error;
3828}
3829
Zachary Turner93749ab2015-03-03 21:51:25 +00003830void
Chaoren Linc963a222015-09-01 16:58:45 +00003831Process::SetUnixSignals(UnixSignalsSP &&signals_sp)
Zachary Turner93749ab2015-03-03 21:51:25 +00003832{
3833 assert (signals_sp && "null signals_sp");
3834 m_unix_signals_sp = signals_sp;
3835}
3836
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003837const lldb::UnixSignalsSP &
Zachary Turner93749ab2015-03-03 21:51:25 +00003838Process::GetUnixSignals ()
3839{
3840 assert (m_unix_signals_sp && "null m_unix_signals_sp");
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003841 return m_unix_signals_sp;
Zachary Turner93749ab2015-03-03 21:51:25 +00003842}
3843
Greg Clayton514487e2011-02-15 21:59:32 +00003844lldb::ByteOrder
3845Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003846{
Zachary Turner7529df92015-09-01 20:02:29 +00003847 return GetTarget().GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003848}
3849
3850uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003851Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003852{
Zachary Turner7529df92015-09-01 20:02:29 +00003853 return GetTarget().GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003854}
3855
3856bool
3857Process::ShouldBroadcastEvent (Event *event_ptr)
3858{
3859 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3860 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003861 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003862
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003863 switch (state)
3864 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003865 case eStateDetached:
3866 case eStateExited:
3867 case eStateUnloaded:
Pavel Labath3f5df532015-03-12 10:12:41 +00003868 m_stdio_communication.SynchronizeWithReadThread();
Pavel Labatha9a43372015-09-03 09:30:17 +00003869 m_stdio_communication.Disconnect();
3870 m_stdio_communication.StopReadThread();
3871 m_stdin_forward = false;
3872
Jason Molenda62e06812016-02-16 04:14:33 +00003873 LLVM_FALLTHROUGH;
Pavel Labath3f5df532015-03-12 10:12:41 +00003874 case eStateConnected:
3875 case eStateAttaching:
3876 case eStateLaunching:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003877 // These events indicate changes in the state of the debugging session, always report them.
3878 return_value = true;
3879 break;
3880 case eStateInvalid:
3881 // We stopped for no apparent reason, don't report it.
3882 return_value = false;
3883 break;
3884 case eStateRunning:
3885 case eStateStepping:
3886 // If we've started the target running, we handle the cases where we
3887 // are already running and where there is a transition from stopped to
3888 // running differently.
3889 // running -> running: Automatically suppress extra running events
3890 // stopped -> running: Report except when there is one or more no votes
3891 // and no yes votes.
3892 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003893 if (m_force_next_event_delivery)
3894 return_value = true;
3895 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003896 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003897 switch (m_last_broadcast_state)
3898 {
3899 case eStateRunning:
3900 case eStateStepping:
3901 // We always suppress multiple runnings with no PUBLIC stop in between.
3902 return_value = false;
3903 break;
3904 default:
3905 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003906 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003907 // events. If I run the lldb/test/thread/a.out file and
3908 // break at main.cpp:58, run and hit the breakpoints on
3909 // multiple threads, then somehow during the stepping over
3910 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003911
Jim Ingham1460e4b2014-01-10 23:46:59 +00003912 // This is a transition from stop to run.
3913 switch (m_thread_list.ShouldReportRun (event_ptr))
3914 {
3915 case eVoteYes:
3916 case eVoteNoOpinion:
3917 return_value = true;
3918 break;
3919 case eVoteNo:
3920 return_value = false;
3921 break;
3922 }
3923 break;
3924 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003925 }
3926 break;
3927 case eStateStopped:
3928 case eStateCrashed:
3929 case eStateSuspended:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003930 // We've stopped. First see if we're going to restart the target.
3931 // If we are going to stop, then we always broadcast the event.
3932 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00003933 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003934
Pavel Labath3f5df532015-03-12 10:12:41 +00003935 m_stdio_communication.SynchronizeWithReadThread();
Jim Inghamcb4ca112012-05-16 01:32:14 +00003936 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003937 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003938 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003939 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003940 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003941 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003942 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003943 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3944 // so they can properly set their state.
3945 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003946 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003947 }
3948 else
3949 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003950 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3951 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003952
Jim Ingham0161b492013-02-09 01:29:05 +00003953 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3954 // Asking the thread list is also not likely to go well, since we are running again.
3955 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003956
Jim Ingham0161b492013-02-09 01:29:05 +00003957 if (!was_restarted)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003958 should_resume = !m_thread_list.ShouldStop(event_ptr);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003959
Jim Ingham221d51c2013-05-08 00:35:16 +00003960 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003961 {
Jim Ingham0161b492013-02-09 01:29:05 +00003962 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3963 if (log)
Pavel Labath2acc4882016-01-05 17:55:32 +00003964 log->Printf ("Process::ShouldBroadcastEvent: should_resume: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003965 should_resume, StateAsCString(state),
3966 was_restarted, stop_vote);
3967
Jim Ingham0161b492013-02-09 01:29:05 +00003968 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003969 {
3970 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003971 return_value = true;
3972 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003973 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003974 case eVoteNo:
3975 return_value = false;
3976 break;
3977 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003978
Jim Inghamcb95f342012-09-05 21:13:56 +00003979 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003980 {
3981 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003982 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3983 static_cast<void*>(event_ptr),
3984 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003985 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003986 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003987 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003988 }
3989 else
3990 {
3991 return_value = true;
3992 SynchronouslyNotifyStateChanged (state);
3993 }
3994 }
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003995 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003996 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003997
Jim Ingham1460e4b2014-01-10 23:46:59 +00003998 // Forcing the next event delivery is a one shot deal. So reset it here.
3999 m_force_next_event_delivery = false;
4000
Jim Ingham0161b492013-02-09 01:29:05 +00004001 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4002 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4003 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4004 // because the PublicState reflects the last event pulled off the queue, and there may be several
4005 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4006 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004007
Jim Ingham0161b492013-02-09 01:29:05 +00004008 if (return_value)
4009 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004010
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004011 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004012 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004013 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004014 StateAsCString(m_last_broadcast_state),
4015 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004016 return return_value;
4017}
4018
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004019bool
Jim Ingham60c915e2015-06-23 21:02:45 +00004020Process::StartPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004021{
Greg Clayton5160ce52013-03-27 23:08:40 +00004022 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004023
Greg Clayton8b82f082011-04-12 05:54:46 +00004024 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004025 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004026 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4027
Jim Ingham60c915e2015-06-23 21:02:45 +00004028 if (!is_secondary_thread && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004029 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004030
4031 // Create a thread that watches our internal state and controls which
4032 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004033 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004034
Zachary Turner39de3112014-09-09 20:54:56 +00004035 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004036 {
Zachary Turner39de3112014-09-09 20:54:56 +00004037 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4038 if (already_running)
4039 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4040 else
4041 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004042 }
Jim Ingham372787f2012-04-07 00:00:41 +00004043 else
Todd Fiala17096d72014-07-16 19:03:16 +00004044 {
4045 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004046 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004047 else
Zachary Turner39de3112014-09-09 20:54:56 +00004048 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004049 }
4050
Jim Ingham076b3042012-04-10 01:21:57 +00004051 // Create the private state thread, and start it running.
Jim Inghama1ca8142016-02-04 01:34:33 +00004052 PrivateStateThreadArgs *args_ptr = new PrivateStateThreadArgs(this, is_secondary_thread);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004053 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, (void *) args_ptr, nullptr, 8 * 1024 * 1024);
Zachary Turneracee96a2014-09-23 18:32:09 +00004054 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004055 {
4056 ResumePrivateStateThread();
4057 return true;
4058 }
4059 else
4060 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004061}
4062
4063void
4064Process::PausePrivateStateThread ()
4065{
4066 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4067}
4068
4069void
4070Process::ResumePrivateStateThread ()
4071{
4072 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4073}
4074
4075void
4076Process::StopPrivateStateThread ()
4077{
Cameron Desrochers2c00fc42016-06-14 16:22:45 +00004078 if (m_private_state_thread.IsJoinable ())
Greg Clayton8b82f082011-04-12 05:54:46 +00004079 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004080 else
4081 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004082 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004083 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004084 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004085 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004086}
4087
4088void
4089Process::ControlPrivateStateThread (uint32_t signal)
4090{
Greg Clayton5160ce52013-03-27 23:08:40 +00004091 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004092
4093 assert (signal == eBroadcastInternalStateControlStop ||
4094 signal == eBroadcastInternalStateControlPause ||
4095 signal == eBroadcastInternalStateControlResume);
4096
4097 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004098 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004099
Cameron Desrochers2c00fc42016-06-14 16:22:45 +00004100 // Signal the private state thread
4101 if (m_private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004102 {
Cameron Desrochers2c00fc42016-06-14 16:22:45 +00004103 // Broadcast the event.
4104 // It is important to do this outside of the if below, because
4105 // it's possible that the thread state is invalid but that the
4106 // thread is waiting on a control event instead of simply being
4107 // on its way out (this should not happen, but it apparently can).
4108 if (log)
4109 log->Printf ("Sending control event of type: %d.", signal);
4110 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
4111 m_private_state_control_broadcaster.BroadcastEvent(signal, event_receipt_sp);
Greg Clayton1e20f022016-05-12 22:58:52 +00004112
Cameron Desrochers2c00fc42016-06-14 16:22:45 +00004113 // Wait for the event receipt or for the private state thread to exit
4114 bool receipt_received = false;
4115 if (PrivateStateThreadIsValid())
4116 {
Greg Clayton1e20f022016-05-12 22:58:52 +00004117 while (!receipt_received)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004118 {
Greg Clayton1e20f022016-05-12 22:58:52 +00004119 bool timed_out = false;
Greg Clayton1e20f022016-05-12 22:58:52 +00004120 // Check for a receipt for 2 seconds and then check if the private state
4121 // thread is still around.
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00004122 receipt_received = event_receipt_sp->WaitForEventReceived(std::chrono::seconds(2), &timed_out);
Greg Clayton1e20f022016-05-12 22:58:52 +00004123 if (!receipt_received)
4124 {
4125 // Check if the private state thread is still around. If it isn't then we are done waiting
Cameron Desrochers2c00fc42016-06-14 16:22:45 +00004126 if (!PrivateStateThreadIsValid())
4127 break; // Private state thread exited or is exiting, we are done
Greg Clayton1e20f022016-05-12 22:58:52 +00004128 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004129 }
Cameron Desrochers2c00fc42016-06-14 16:22:45 +00004130 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004131
Cameron Desrochers2c00fc42016-06-14 16:22:45 +00004132 if (signal == eBroadcastInternalStateControlStop)
Greg Clayton1e20f022016-05-12 22:58:52 +00004133 {
Cameron Desrochers2c00fc42016-06-14 16:22:45 +00004134 thread_result_t result = NULL;
4135 m_private_state_thread.Join(&result);
4136 m_private_state_thread.Reset();
Greg Clayton1e20f022016-05-12 22:58:52 +00004137 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004138 }
Cameron Desrochers2c00fc42016-06-14 16:22:45 +00004139 else
4140 {
4141 if (log)
4142 log->Printf("Private state thread already dead, no need to signal it to stop.");
4143 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004144}
4145
4146void
Jim Inghamcfc09352012-07-27 23:57:19 +00004147Process::SendAsyncInterrupt ()
4148{
4149 if (PrivateStateThreadIsValid())
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004150 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
Jim Inghamcfc09352012-07-27 23:57:19 +00004151 else
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004152 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
Jim Inghamcfc09352012-07-27 23:57:19 +00004153}
4154
4155void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004156Process::HandlePrivateEvent (EventSP &event_sp)
4157{
Greg Clayton5160ce52013-03-27 23:08:40 +00004158 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004159 m_resume_requested = false;
4160
Greg Clayton414f5d32011-01-25 02:58:48 +00004161 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004162
4163 // First check to see if anybody wants a shot at this event:
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004164 if (m_next_event_action_ap)
Jim Inghambb3a2832011-01-29 01:49:25 +00004165 {
Jim Ingham754ab982011-01-29 04:05:41 +00004166 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004167 if (log)
4168 log->Printf ("Ran next event action, result was %d.", action_result);
4169
Jim Inghambb3a2832011-01-29 01:49:25 +00004170 switch (action_result)
4171 {
4172 case NextEventAction::eEventActionSuccess:
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004173 SetNextEventAction(nullptr);
Jim Inghambb3a2832011-01-29 01:49:25 +00004174 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004175
Jim Inghambb3a2832011-01-29 01:49:25 +00004176 case NextEventAction::eEventActionRetry:
4177 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004178
Jim Inghambb3a2832011-01-29 01:49:25 +00004179 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004180 // Handle Exiting Here. If we already got an exited event,
4181 // we should just propagate it. Otherwise, swallow this event,
4182 // and set our state to exit so the next event will kill us.
4183 if (new_state != eStateExited)
4184 {
4185 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004186 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004187 SetNextEventAction(nullptr);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004188 return;
4189 }
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004190 SetNextEventAction(nullptr);
Jim Inghambb3a2832011-01-29 01:49:25 +00004191 break;
4192 }
4193 }
4194
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004195 // See if we should broadcast this state to external clients?
4196 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004197
4198 if (should_broadcast)
4199 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004200 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004201 if (log)
4202 {
Daniel Malead01b2952012-11-29 21:49:15 +00004203 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004204 __FUNCTION__,
4205 GetID(),
4206 StateAsCString(new_state),
4207 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004208 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004209 }
Jim Ingham9575d842011-03-11 03:53:59 +00004210 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004211 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004212 {
4213 // Only push the input handler if we aren't fowarding events,
4214 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004215 // Or don't push it if we are launching since it will come up stopped.
Zachary Turnerc62733b2015-05-20 18:31:17 +00004216 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching &&
4217 new_state != eStateAttaching)
Pavel Labath44464872015-05-27 12:40:32 +00004218 {
Greg Clayton44d93782014-01-27 23:43:24 +00004219 PushProcessIOHandler ();
Pavel Labath44464872015-05-27 12:40:32 +00004220 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue()+1, eBroadcastAlways);
4221 if (log)
4222 log->Printf("Process::%s updated m_iohandler_sync to %d", __FUNCTION__, m_iohandler_sync.GetValue());
4223 }
Greg Clayton44d93782014-01-27 23:43:24 +00004224 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004225 else if (StateIsStoppedState(new_state, false))
4226 {
4227 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4228 {
4229 // If the lldb_private::Debugger is handling the events, we don't
4230 // want to pop the process IOHandler here, we want to do it when
4231 // we receive the stopped event so we can carefully control when
4232 // the process IOHandler is popped because when we stop we want to
4233 // display some text stating how and why we stopped, then maybe some
4234 // process/thread/frame info, and then we want the "(lldb) " prompt
4235 // to show up. If we pop the process IOHandler here, then we will
4236 // cause the command interpreter to become the top IOHandler after
4237 // the process pops off and it will update its prompt right away...
4238 // See the Debugger.cpp file where it calls the function as
4239 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4240 // Otherwise we end up getting overlapping "(lldb) " prompts and
4241 // garbled output.
4242 //
4243 // If we aren't handling the events in the debugger (which is indicated
4244 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4245 // are hijacked, then we always pop the process IO handler manually.
4246 // Hijacking happens when the internal process state thread is running
4247 // thread plans, or when commands want to run in synchronous mode
4248 // and they call "process->WaitForProcessToStop()". An example of something
4249 // that will hijack the events is a simple expression:
4250 //
4251 // (lldb) expr (int)puts("hello")
4252 //
4253 // This will cause the internal process state thread to resume and halt
4254 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4255 // events) and we do need the IO handler to be pushed and popped
4256 // correctly.
4257
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004258 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
Greg Claytonb4874f12014-02-28 18:22:24 +00004259 PopProcessIOHandler ();
4260 }
4261 }
Jim Ingham9575d842011-03-11 03:53:59 +00004262
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004263 BroadcastEvent (event_sp);
4264 }
4265 else
4266 {
4267 if (log)
4268 {
Daniel Malead01b2952012-11-29 21:49:15 +00004269 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004270 __FUNCTION__,
4271 GetID(),
4272 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004273 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004274 }
4275 }
Pavel Labath19da1f12015-12-07 12:36:52 +00004276}
4277
4278Error
4279Process::HaltPrivate()
4280{
4281 EventSP event_sp;
4282 Error error (WillHalt());
4283 if (error.Fail())
4284 return error;
4285
4286 // Ask the process subclass to actually halt our process
4287 bool caused_stop;
4288 error = DoHalt(caused_stop);
4289
4290 DidHalt();
4291 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004292}
4293
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004294thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004295Process::PrivateStateThread (void *arg)
4296{
Jim Inghama1ca8142016-02-04 01:34:33 +00004297 PrivateStateThreadArgs real_args = *static_cast<PrivateStateThreadArgs *> (arg);
4298 free (arg);
4299 thread_result_t result = real_args.process->RunPrivateStateThread(real_args.is_secondary_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004300 return result;
4301}
4302
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004303thread_result_t
Jim Ingham60c915e2015-06-23 21:02:45 +00004304Process::RunPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004305{
Jim Ingham076b3042012-04-10 01:21:57 +00004306 bool control_only = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004307
Greg Clayton5160ce52013-03-27 23:08:40 +00004308 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004309 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004310 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4311 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004312
4313 bool exit_now = false;
Pavel Labath19da1f12015-12-07 12:36:52 +00004314 bool interrupt_requested = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004315 while (!exit_now)
4316 {
4317 EventSP event_sp;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00004318 WaitForEventsPrivate(std::chrono::microseconds(0), event_sp, control_only);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004319 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4320 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004321 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004322 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4323 __FUNCTION__, static_cast<void*>(this), GetID(),
4324 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004325
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004326 switch (event_sp->GetType())
4327 {
4328 case eBroadcastInternalStateControlStop:
4329 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004330 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004331
4332 case eBroadcastInternalStateControlPause:
4333 control_only = true;
4334 break;
4335
4336 case eBroadcastInternalStateControlResume:
4337 control_only = false;
4338 break;
4339 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004340
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004341 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004342 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004343 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4344 {
4345 if (m_public_state.GetValue() == eStateAttaching)
4346 {
4347 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004348 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4349 __FUNCTION__, static_cast<void*>(this),
4350 GetID());
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004351 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
Jim Inghamcfc09352012-07-27 23:57:19 +00004352 }
Pavel Labath19da1f12015-12-07 12:36:52 +00004353 else if(StateIsRunningState(m_last_broadcast_state))
Jim Inghamcfc09352012-07-27 23:57:19 +00004354 {
4355 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004356 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4357 __FUNCTION__, static_cast<void*>(this),
4358 GetID());
Pavel Labath19da1f12015-12-07 12:36:52 +00004359 Error error = HaltPrivate();
4360 if (error.Fail() && log)
4361 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") failed to halt the process: %s",
4362 __FUNCTION__, static_cast<void*>(this),
4363 GetID(), error.AsCString());
4364 // Halt should generate a stopped event. Make a note of the fact that we were
4365 // doing the interrupt, so we can set the interrupted flag after we receive the
4366 // event. We deliberately set this to true even if HaltPrivate failed, so that we
4367 // can interrupt on the next natural stop.
4368 interrupt_requested = true;
4369 }
4370 else
4371 {
4372 // This can happen when someone (e.g. Process::Halt) sees that we are running and
4373 // sends an interrupt request, but the process actually stops before we receive
4374 // it. In that case, we can just ignore the request. We use
4375 // m_last_broadcast_state, because the Stopped event may not have been popped of
4376 // the event queue yet, which is when the public state gets updated.
4377 if (log)
4378 log->Printf("Process::%s ignoring interrupt as we have already stopped.", __FUNCTION__);
Jim Inghamcfc09352012-07-27 23:57:19 +00004379 }
4380 continue;
4381 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004382
4383 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4384
4385 if (internal_state != eStateInvalid)
4386 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004387 if (m_clear_thread_plans_on_stop &&
4388 StateIsStoppedState(internal_state, true))
4389 {
4390 m_clear_thread_plans_on_stop = false;
4391 m_thread_list.DiscardThreadPlans();
4392 }
Pavel Labath19da1f12015-12-07 12:36:52 +00004393
4394 if (interrupt_requested)
4395 {
4396 if (StateIsStoppedState (internal_state, true))
4397 {
4398 // We requested the interrupt, so mark this as such in the stop event so
4399 // clients can tell an interrupted process from a natural stop
4400 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
4401 interrupt_requested = false;
4402 }
4403 else if (log)
4404 {
4405 log->Printf("Process::%s interrupt_requested, but a non-stopped state '%s' received.",
4406 __FUNCTION__, StateAsCString(internal_state));
4407 }
4408 }
4409
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004410 HandlePrivateEvent (event_sp);
4411 }
4412
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004413 if (internal_state == eStateInvalid ||
4414 internal_state == eStateExited ||
4415 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004416 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004417 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004418 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4419 __FUNCTION__, static_cast<void*>(this), GetID(),
4420 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004421
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004422 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004423 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004424 }
4425
Caroline Tice20ad3c42010-10-29 21:48:37 +00004426 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004427 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004428 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4429 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004430
Jim Ingham60c915e2015-06-23 21:02:45 +00004431 // If we are a secondary thread, then the primary thread we are working for will have already
4432 // acquired the public_run_lock, and isn't done with what it was doing yet, so don't
4433 // try to change it on the way out.
4434 if (!is_secondary_thread)
4435 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004436 return NULL;
4437}
4438
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004439//------------------------------------------------------------------
4440// Process Event Data
4441//------------------------------------------------------------------
4442
4443Process::ProcessEventData::ProcessEventData () :
4444 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004445 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004446 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004447 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004448 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004449 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004450{
4451}
4452
4453Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4454 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004455 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004456 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004457 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004458 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004459 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004460{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004461 if (process_sp)
4462 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004463}
4464
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004465Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004466
4467const ConstString &
4468Process::ProcessEventData::GetFlavorString ()
4469{
4470 static ConstString g_flavor ("Process::ProcessEventData");
4471 return g_flavor;
4472}
4473
4474const ConstString &
4475Process::ProcessEventData::GetFlavor () const
4476{
4477 return ProcessEventData::GetFlavorString ();
4478}
4479
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004480void
4481Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4482{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004483 ProcessSP process_sp(m_process_wp.lock());
4484
4485 if (!process_sp)
4486 return;
4487
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004488 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004489 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4490 // the public event queue, then other times when we're pretending that this is where we stopped at the
4491 // end of expression evaluation. m_update_state is used to distinguish these
4492 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004493 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004494 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004495 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004496
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004497 process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004498
4499 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4500 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4501 // end up restarting the process.
4502 if (m_interrupted)
4503 return;
4504
4505 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004506 if (m_state == eStateStopped && ! m_restarted)
Greg Clayton2e309072015-07-17 23:42:28 +00004507 {
4508 // Let process subclasses know we are about to do a public stop and
4509 // do anything they might need to in order to speed up register and
4510 // memory accesses.
4511 process_sp->WillPublicStop();
4512
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004513 ThreadList &curr_thread_list = process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004514 uint32_t num_threads = curr_thread_list.GetSize();
4515 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004516
Jim Ingham4b536182011-08-09 02:12:22 +00004517 // The actions might change one of the thread's stop_info's opinions about whether we should
4518 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004519
4520 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4521 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4522 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4523 // to also know if it has changed at all, so we make up a vector of the thread ID's and check what we get back
4524 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004525 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004526 for (idx = 0; idx < num_threads; ++idx)
4527 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4528
Jim Inghamc7078c22012-12-13 22:24:15 +00004529 // Use this to track whether we should continue from here. We will only continue the target running if
4530 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4531 // then it doesn't matter what the other threads say...
4532
4533 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004534
Jim Ingham0ad7e052013-04-25 02:04:59 +00004535 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4536 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4537 // thing to do is, and it's better to let the user decide than continue behind their backs.
4538
4539 bool does_anybody_have_an_opinion = false;
4540
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004541 for (idx = 0; idx < num_threads; ++idx)
4542 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004543 curr_thread_list = process_sp->GetThreadList();
Jim Ingham0faa43f2011-11-08 03:00:11 +00004544 if (curr_thread_list.GetSize() != num_threads)
4545 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004546 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004547 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004548 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004549 break;
4550 }
4551
4552 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4553
4554 if (thread_sp->GetIndexID() != thread_index_array[idx])
4555 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004556 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004557 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004558 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004559 idx,
4560 thread_index_array[idx],
4561 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004562 break;
4563 }
4564
Jim Inghamb15bfc72010-10-20 00:39:53 +00004565 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004566 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004567 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004568 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004569 bool this_thread_wants_to_stop;
4570 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004571 {
Jim Ingham0161b492013-02-09 01:29:05 +00004572 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4573 }
4574 else
4575 {
4576 stop_info_sp->PerformAction(event_ptr);
4577 // The stop action might restart the target. If it does, then we want to mark that in the
4578 // event so that whoever is receiving it will know to wait for the running event and reflect
4579 // that state appropriately.
4580 // We also need to stop processing actions, since they aren't expecting the target to be running.
4581
4582 // FIXME: we might have run.
4583 if (stop_info_sp->HasTargetRunSinceMe())
4584 {
4585 SetRestarted (true);
4586 break;
4587 }
4588
4589 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004590 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004591
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004592 if (!still_should_stop)
Jim Inghamc7078c22012-12-13 22:24:15 +00004593 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004594 }
4595 }
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004596
Jim Inghama8ca6e22013-05-03 23:04:37 +00004597 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004598 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004599 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004600 {
4601 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004602 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004603 // Use the public resume method here, since this is just
4604 // extending a public resume.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004605 process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004606 }
4607 else
4608 {
4609 // If we didn't restart, run the Stop Hooks here:
4610 // They might also restart the target, so watch for that.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004611 process_sp->GetTarget().RunStopHooks();
4612 if (process_sp->GetPrivateState() == eStateRunning)
Jim Ingham4b536182011-08-09 02:12:22 +00004613 SetRestarted(true);
4614 }
Jim Ingham9575d842011-03-11 03:53:59 +00004615 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004616 }
4617}
4618
4619void
4620Process::ProcessEventData::Dump (Stream *s) const
4621{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004622 ProcessSP process_sp(m_process_wp.lock());
4623
4624 if (process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004625 s->Printf(" process = %p (pid = %" PRIu64 "), ",
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004626 static_cast<void*>(process_sp.get()), process_sp->GetID());
4627 else
4628 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004629
Greg Clayton8b82f082011-04-12 05:54:46 +00004630 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004631}
4632
4633const Process::ProcessEventData *
4634Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4635{
4636 if (event_ptr)
4637 {
4638 const EventData *event_data = event_ptr->GetData();
4639 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4640 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4641 }
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004642 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004643}
4644
4645ProcessSP
4646Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4647{
4648 ProcessSP process_sp;
4649 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4650 if (data)
4651 process_sp = data->GetProcessSP();
4652 return process_sp;
4653}
4654
4655StateType
4656Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4657{
4658 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004659 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004660 return eStateInvalid;
4661 else
4662 return data->GetState();
4663}
4664
4665bool
4666Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4667{
4668 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004669 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004670 return false;
4671 else
4672 return data->GetRestarted();
4673}
4674
4675void
4676Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4677{
4678 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004679 if (data != nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004680 data->SetRestarted(new_value);
4681}
4682
Jim Ingham0161b492013-02-09 01:29:05 +00004683size_t
4684Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4685{
4686 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004687 if (data != nullptr)
Jim Ingham0161b492013-02-09 01:29:05 +00004688 return data->GetNumRestartedReasons();
4689 else
4690 return 0;
4691}
4692
4693const char *
4694Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4695{
4696 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004697 if (data != nullptr)
Jim Ingham0161b492013-02-09 01:29:05 +00004698 return data->GetRestartedReasonAtIndex(idx);
4699 else
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004700 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004701}
4702
4703void
4704Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4705{
4706 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004707 if (data != nullptr)
Jim Ingham0161b492013-02-09 01:29:05 +00004708 data->AddRestartedReason(reason);
4709}
4710
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004711bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004712Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4713{
4714 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004715 if (data == nullptr)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004716 return false;
4717 else
4718 return data->GetInterrupted ();
4719}
4720
4721void
4722Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4723{
4724 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004725 if (data != nullptr)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004726 data->SetInterrupted(new_value);
4727}
4728
4729bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004730Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4731{
4732 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4733 if (data)
4734 {
4735 data->SetUpdateStateOnRemoval();
4736 return true;
4737 }
4738 return false;
4739}
4740
Greg Claytond9e416c2012-02-18 05:35:26 +00004741lldb::TargetSP
4742Process::CalculateTarget ()
4743{
Zachary Turner7529df92015-09-01 20:02:29 +00004744 return m_target_sp.lock();
Greg Claytond9e416c2012-02-18 05:35:26 +00004745}
4746
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004747void
Greg Clayton0603aa92010-10-04 01:05:56 +00004748Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004749{
Zachary Turner7529df92015-09-01 20:02:29 +00004750 exe_ctx.SetTargetPtr (&GetTarget());
Greg Claytonc14ee322011-09-22 04:58:26 +00004751 exe_ctx.SetProcessPtr (this);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004752 exe_ctx.SetThreadPtr(nullptr);
4753 exe_ctx.SetFramePtr(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004754}
4755
Greg Claytone996fd32011-03-08 22:40:15 +00004756//uint32_t
4757//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4758//{
4759// return 0;
4760//}
4761//
4762//ArchSpec
4763//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4764//{
4765// return Host::GetArchSpecForExistingProcess (pid);
4766//}
4767//
4768//ArchSpec
4769//Process::GetArchSpecForExistingProcess (const char *process_name)
4770//{
4771// return Host::GetArchSpecForExistingProcess (process_name);
4772//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004773
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004774void
4775Process::AppendSTDOUT (const char * s, size_t len)
4776{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00004777 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004778 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004779 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004780}
4781
4782void
Greg Clayton93e86192011-11-13 04:45:22 +00004783Process::AppendSTDERR (const char * s, size_t len)
4784{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00004785 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
Greg Clayton93e86192011-11-13 04:45:22 +00004786 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004787 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004788}
4789
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004790void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004791Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004792{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00004793 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004794 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004795 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4796}
4797
4798size_t
4799Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4800{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00004801 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004802 if (m_profile_data.empty())
4803 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004804
4805 std::string &one_profile_data = m_profile_data.front();
4806 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004807 if (bytes_available > 0)
4808 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004809 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004810 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004811 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4812 static_cast<void*>(buf),
4813 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004814 if (bytes_available > buf_size)
4815 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004816 memcpy(buf, one_profile_data.c_str(), buf_size);
4817 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004818 bytes_available = buf_size;
4819 }
4820 else
4821 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004822 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004823 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004824 }
4825 }
4826 return bytes_available;
4827}
4828
Greg Clayton93e86192011-11-13 04:45:22 +00004829//------------------------------------------------------------------
4830// Process STDIO
4831//------------------------------------------------------------------
4832
4833size_t
4834Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4835{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00004836 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
Greg Clayton93e86192011-11-13 04:45:22 +00004837 size_t bytes_available = m_stdout_data.size();
4838 if (bytes_available > 0)
4839 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004840 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004841 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004842 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4843 static_cast<void*>(buf),
4844 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004845 if (bytes_available > buf_size)
4846 {
4847 memcpy(buf, m_stdout_data.c_str(), buf_size);
4848 m_stdout_data.erase(0, buf_size);
4849 bytes_available = buf_size;
4850 }
4851 else
4852 {
4853 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4854 m_stdout_data.clear();
4855 }
4856 }
4857 return bytes_available;
4858}
4859
Greg Clayton93e86192011-11-13 04:45:22 +00004860size_t
4861Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4862{
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00004863 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
Greg Clayton93e86192011-11-13 04:45:22 +00004864 size_t bytes_available = m_stderr_data.size();
4865 if (bytes_available > 0)
4866 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004867 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004868 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004869 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4870 static_cast<void*>(buf),
4871 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004872 if (bytes_available > buf_size)
4873 {
4874 memcpy(buf, m_stderr_data.c_str(), buf_size);
4875 m_stderr_data.erase(0, buf_size);
4876 bytes_available = buf_size;
4877 }
4878 else
4879 {
4880 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4881 m_stderr_data.clear();
4882 }
4883 }
4884 return bytes_available;
4885}
4886
4887void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004888Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4889{
4890 Process *process = (Process *) baton;
4891 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4892}
4893
Greg Clayton44d93782014-01-27 23:43:24 +00004894class IOHandlerProcessSTDIO :
4895 public IOHandler
4896{
4897public:
4898 IOHandlerProcessSTDIO (Process *process,
4899 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00004900 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00004901 m_process (process),
4902 m_read_file (),
4903 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004904 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004905 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004906 m_pipe.CreateNew(false);
Greg Clayton44d93782014-01-27 23:43:24 +00004907 m_read_file.SetDescriptor(GetInputFD(), false);
4908 }
4909
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004910 ~IOHandlerProcessSTDIO() override = default;
4911
Greg Clayton44d93782014-01-27 23:43:24 +00004912 // Each IOHandler gets to run until it is done. It should read data
4913 // from the "in" and place output into "out" and "err and return
4914 // when done.
Pavel Labath44464872015-05-27 12:40:32 +00004915 void
4916 Run () override
Greg Clayton44d93782014-01-27 23:43:24 +00004917 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004918 if (!m_read_file.IsValid() || !m_write_file.IsValid() || !m_pipe.CanRead() || !m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00004919 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004920 SetIsDone(true);
4921 return;
4922 }
4923
4924 SetIsDone(false);
4925 const int read_fd = m_read_file.GetDescriptor();
4926 TerminalState terminal_state;
4927 terminal_state.Save (read_fd, false);
4928 Terminal terminal(read_fd);
4929 terminal.SetCanonical(false);
4930 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004931// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004932#ifndef _WIN32
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004933 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton860582f2016-02-26 17:36:44 +00004934 m_is_running = true;
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004935 while (!GetIsDone())
4936 {
Greg Claytonee1f5782016-08-10 22:43:48 +00004937 SelectHelper select_helper;
4938 select_helper.FDSetRead(read_fd);
4939 select_helper.FDSetRead(pipe_read_fd);
4940 Error error = select_helper.Select();
Greg Clayton860582f2016-02-26 17:36:44 +00004941
Greg Claytonee1f5782016-08-10 22:43:48 +00004942 if (error.Fail())
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004943 {
Greg Claytonee1f5782016-08-10 22:43:48 +00004944 SetIsDone(true);
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004945 }
Greg Claytonee1f5782016-08-10 22:43:48 +00004946 else
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004947 {
4948 char ch = 0;
4949 size_t n;
Greg Claytonee1f5782016-08-10 22:43:48 +00004950 if (select_helper.FDIsSetRead(read_fd))
Greg Clayton44d93782014-01-27 23:43:24 +00004951 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004952 n = 1;
4953 if (m_read_file.Read(&ch, n).Success() && n == 1)
Greg Clayton44d93782014-01-27 23:43:24 +00004954 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004955 if (m_write_file.Write(&ch, n).Fail() || n != 1)
Greg Clayton44d93782014-01-27 23:43:24 +00004956 SetIsDone(true);
4957 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004958 else
4959 SetIsDone(true);
4960 }
Greg Claytonee1f5782016-08-10 22:43:48 +00004961 if (select_helper.FDIsSetRead(pipe_read_fd))
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004962 {
4963 size_t bytes_read;
4964 // Consume the interrupt byte
4965 Error error = m_pipe.Read(&ch, 1, bytes_read);
4966 if (error.Success())
Greg Clayton44d93782014-01-27 23:43:24 +00004967 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004968 switch (ch)
Greg Clayton44d93782014-01-27 23:43:24 +00004969 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004970 case 'q':
Greg Clayton44d93782014-01-27 23:43:24 +00004971 SetIsDone(true);
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004972 break;
4973 case 'i':
4974 if (StateIsRunningState(m_process->GetState()))
Pavel Labathfcc7f662015-10-07 15:11:11 +00004975 m_process->SendAsyncInterrupt();
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004976 break;
Greg Clayton44d93782014-01-27 23:43:24 +00004977 }
4978 }
4979 }
Greg Clayton44d93782014-01-27 23:43:24 +00004980 }
Greg Clayton44d93782014-01-27 23:43:24 +00004981 }
Greg Clayton860582f2016-02-26 17:36:44 +00004982 m_is_running = false;
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004983#endif
4984 terminal_state.Restore();
Greg Clayton44d93782014-01-27 23:43:24 +00004985 }
4986
Pavel Labath44464872015-05-27 12:40:32 +00004987 void
4988 Cancel () override
Greg Clayton44d93782014-01-27 23:43:24 +00004989 {
Greg Clayton860582f2016-02-26 17:36:44 +00004990 SetIsDone(true);
4991 // Only write to our pipe to cancel if we are in IOHandlerProcessSTDIO::Run().
4992 // We can end up with a python command that is being run from the command
4993 // interpreter:
4994 //
4995 // (lldb) step_process_thousands_of_times
4996 //
4997 // In this case the command interpreter will be in the middle of handling
4998 // the command and if the process pushes and pops the IOHandler thousands
4999 // of times, we can end up writing to m_pipe without ever consuming the
5000 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
5001 // deadlocking when the pipe gets fed up and blocks until data is consumed.
5002 if (m_is_running)
5003 {
5004 char ch = 'q'; // Send 'q' for quit
5005 size_t bytes_written = 0;
5006 m_pipe.Write(&ch, 1, bytes_written);
5007 }
Greg Clayton44d93782014-01-27 23:43:24 +00005008 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005009
Pavel Labath44464872015-05-27 12:40:32 +00005010 bool
5011 Interrupt () override
Greg Claytone68f5d62014-02-24 22:50:57 +00005012 {
Greg Clayton19e11352014-02-26 22:47:33 +00005013 // Do only things that are safe to do in an interrupt context (like in
5014 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5015 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
Pavel Labathfcc7f662015-10-07 15:11:11 +00005016 // that was written to the pipe and then call m_process->SendAsyncInterrupt()
5017 // from a much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005018 if (m_active)
5019 {
5020 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005021 size_t bytes_written = 0;
5022 Error result = m_pipe.Write(&ch, 1, bytes_written);
5023 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005024 }
5025 else
5026 {
5027 // This IOHandler might be pushed on the stack, but not being run currently
5028 // so do the right thing if we aren't actively watching for STDIN by sending
5029 // the interrupt to the process. Otherwise the write to the pipe above would
5030 // do nothing. This can happen when the command interpreter is running and
5031 // gets a "expression ...". It will be on the IOHandler thread and sending
5032 // the input is complete to the delegate which will cause the expression to
5033 // run, which will push the process IO handler, but not run it.
5034
5035 if (StateIsRunningState(m_process->GetState()))
5036 {
5037 m_process->SendAsyncInterrupt();
5038 return true;
5039 }
5040 }
5041 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005042 }
Greg Clayton44d93782014-01-27 23:43:24 +00005043
Pavel Labath44464872015-05-27 12:40:32 +00005044 void
5045 GotEOF() override
Greg Clayton44d93782014-01-27 23:43:24 +00005046 {
Greg Clayton44d93782014-01-27 23:43:24 +00005047 }
5048
5049protected:
5050 Process *m_process;
5051 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5052 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005053 Pipe m_pipe;
Greg Clayton860582f2016-02-26 17:36:44 +00005054 std::atomic<bool> m_is_running;
Greg Clayton44d93782014-01-27 23:43:24 +00005055};
5056
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005057void
Greg Clayton44d93782014-01-27 23:43:24 +00005058Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005059{
5060 // First set up the Read Thread for reading/handling process I/O
5061
Greg Clayton44d93782014-01-27 23:43:24 +00005062 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005063
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005064 if (conn_ap)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005065 {
5066 m_stdio_communication.SetConnection (conn_ap.release());
5067 if (m_stdio_communication.IsConnected())
5068 {
5069 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5070 m_stdio_communication.StartReadThread();
5071
5072 // Now read thread is set up, set up input reader.
5073
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005074 if (!m_process_input_reader)
Greg Clayton44d93782014-01-27 23:43:24 +00005075 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005076 }
5077 }
5078}
5079
Greg Claytonb4874f12014-02-28 18:22:24 +00005080bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005081Process::ProcessIOHandlerIsActive ()
5082{
5083 IOHandlerSP io_handler_sp (m_process_input_reader);
5084 if (io_handler_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00005085 return GetTarget().GetDebugger().IsTopIOHandler (io_handler_sp);
Greg Clayton6fea17e2014-03-03 19:15:20 +00005086 return false;
5087}
5088bool
Greg Clayton44d93782014-01-27 23:43:24 +00005089Process::PushProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005090{
Greg Clayton44d93782014-01-27 23:43:24 +00005091 IOHandlerSP io_handler_sp (m_process_input_reader);
5092 if (io_handler_sp)
5093 {
Pavel Labath44464872015-05-27 12:40:32 +00005094 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5095 if (log)
5096 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
5097
Greg Clayton44d93782014-01-27 23:43:24 +00005098 io_handler_sp->SetIsDone(false);
Zachary Turner7529df92015-09-01 20:02:29 +00005099 GetTarget().GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005100 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005101 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005102 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005103}
5104
Greg Claytonb4874f12014-02-28 18:22:24 +00005105bool
Greg Clayton44d93782014-01-27 23:43:24 +00005106Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005107{
Greg Clayton44d93782014-01-27 23:43:24 +00005108 IOHandlerSP io_handler_sp (m_process_input_reader);
5109 if (io_handler_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00005110 return GetTarget().GetDebugger().PopIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005111 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005112}
5113
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005114// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005115void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005116Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005117{
Greg Clayton6920b522012-08-22 18:39:03 +00005118 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005119}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005120
Greg Clayton99d0faf2010-11-18 23:32:35 +00005121void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005122Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005123{
Greg Clayton6920b522012-08-22 18:39:03 +00005124 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005125}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005126
Jim Inghamc60963c2015-10-12 19:11:03 +00005127namespace
5128{
5129 // RestorePlanState is used to record the "is private", "is master" and "okay to discard" fields of
5130 // the plan we are running, and reset it on Clean or on destruction.
5131 // It will only reset the state once, so you can call Clean and then monkey with the state and it
5132 // won't get reset on you again.
5133
5134 class RestorePlanState
5135 {
5136 public:
5137 RestorePlanState (lldb::ThreadPlanSP thread_plan_sp) :
5138 m_thread_plan_sp(thread_plan_sp),
5139 m_already_reset(false)
5140 {
5141 if (m_thread_plan_sp)
5142 {
5143 m_private = m_thread_plan_sp->GetPrivate();
5144 m_is_master = m_thread_plan_sp->IsMasterPlan();
5145 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
5146 }
5147 }
5148
5149 ~RestorePlanState()
5150 {
5151 Clean();
5152 }
5153
5154 void
5155 Clean ()
5156 {
5157 if (!m_already_reset && m_thread_plan_sp)
5158 {
5159 m_already_reset = true;
5160 m_thread_plan_sp->SetPrivate(m_private);
5161 m_thread_plan_sp->SetIsMasterPlan (m_is_master);
5162 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
5163 }
5164 }
Eugene Zelenko8f30a652015-10-23 18:39:37 +00005165
Jim Inghamc60963c2015-10-12 19:11:03 +00005166 private:
5167 lldb::ThreadPlanSP m_thread_plan_sp;
5168 bool m_already_reset;
5169 bool m_private;
5170 bool m_is_master;
5171 bool m_okay_to_discard;
5172 };
Eugene Zelenko8f30a652015-10-23 18:39:37 +00005173} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00005174
Jim Ingham1624a2d2014-05-05 02:26:40 +00005175ExpressionResults
Sean Callanan579e70c2016-03-19 00:03:59 +00005176Process::RunThreadPlan(ExecutionContext &exe_ctx, lldb::ThreadPlanSP &thread_plan_sp,
5177 const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager)
Jim Inghamf48169b2010-11-30 02:22:11 +00005178{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005179 ExpressionResults return_value = eExpressionSetupError;
Jim Ingham3cc425832016-05-24 18:29:36 +00005180
5181 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005182
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005183 if (!thread_plan_sp)
Jim Ingham77787032011-01-20 02:03:18 +00005184 {
Sean Callanan579e70c2016-03-19 00:03:59 +00005185 diagnostic_manager.PutCString(eDiagnosticSeverityError, "RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005186 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005187 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005188
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005189 if (!thread_plan_sp->ValidatePlan(nullptr))
Jim Ingham7d7931d2013-03-28 00:05:34 +00005190 {
Sean Callanan579e70c2016-03-19 00:03:59 +00005191 diagnostic_manager.PutCString(eDiagnosticSeverityError, "RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005192 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005193 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005194
Greg Claytonc14ee322011-09-22 04:58:26 +00005195 if (exe_ctx.GetProcessPtr() != this)
5196 {
Sean Callanan579e70c2016-03-19 00:03:59 +00005197 diagnostic_manager.PutCString(eDiagnosticSeverityError, "RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005198 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005199 }
5200
5201 Thread *thread = exe_ctx.GetThreadPtr();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005202 if (thread == nullptr)
Greg Claytonc14ee322011-09-22 04:58:26 +00005203 {
Sean Callanan579e70c2016-03-19 00:03:59 +00005204 diagnostic_manager.PutCString(eDiagnosticSeverityError, "RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005205 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005206 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005207
Jim Inghamc60963c2015-10-12 19:11:03 +00005208 // We need to change some of the thread plan attributes for the thread plan runner. This will restore them
5209 // when we are done:
Jim Ingham3cc425832016-05-24 18:29:36 +00005210
Jim Inghamc60963c2015-10-12 19:11:03 +00005211 RestorePlanState thread_plan_restorer(thread_plan_sp);
5212
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005213 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5214 // For that to be true the plan can't be private - since private plans suppress themselves in the
5215 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005216
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005217 thread_plan_sp->SetPrivate(false);
Jim Inghamc60963c2015-10-12 19:11:03 +00005218
5219 // The plans run with RunThreadPlan also need to be terminal master plans or when they are done we will end
5220 // up asking the plan above us whether we should stop, which may give the wrong answer.
5221
5222 thread_plan_sp->SetIsMasterPlan (true);
5223 thread_plan_sp->SetOkayToDiscard(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005224
Jim Ingham444586b2011-01-24 06:34:17 +00005225 if (m_private_state.GetValue() != eStateStopped)
5226 {
Sean Callanan579e70c2016-03-19 00:03:59 +00005227 diagnostic_manager.PutCString(eDiagnosticSeverityError,
5228 "RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005229 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005230 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005231
Jim Ingham66243842011-08-13 00:56:10 +00005232 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005233 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005234 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005235 if (!selected_frame_sp)
5236 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005237 thread->SetSelectedFrame(nullptr);
Jim Ingham11b0e052013-02-19 23:22:45 +00005238 selected_frame_sp = thread->GetSelectedFrame();
5239 if (!selected_frame_sp)
5240 {
Sean Callanan579e70c2016-03-19 00:03:59 +00005241 diagnostic_manager.Printf(eDiagnosticSeverityError,
5242 "RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005243 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005244 }
5245 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005246
Jim Ingham11b0e052013-02-19 23:22:45 +00005247 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005248
5249 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5250 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005251
Greg Claytonc14ee322011-09-22 04:58:26 +00005252 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005253
Jim Ingham66243842011-08-13 00:56:10 +00005254 uint32_t selected_tid;
5255 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005256 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005257 {
5258 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005259 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005260 }
5261 else
5262 {
5263 selected_tid = LLDB_INVALID_THREAD_ID;
5264 }
5265
Zachary Turner39de3112014-09-09 20:54:56 +00005266 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005267 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005268 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005269
Greg Clayton5160ce52013-03-27 23:08:40 +00005270 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005271 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005272 {
Jim Ingham076b3042012-04-10 01:21:57 +00005273 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5274 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005275 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Ingham076b3042012-04-10 01:21:57 +00005276 // we are fielding public events here.
5277 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005278 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
Jim Ingham076b3042012-04-10 01:21:57 +00005279
Jim Ingham372787f2012-04-07 00:00:41 +00005280 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005281
5282 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5283 // returning control here.
5284 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5285 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5286 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5287 // do just what we want.
5288 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5289 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5290 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5291 old_state = m_public_state.GetValue();
5292 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005293
Jim Ingham076b3042012-04-10 01:21:57 +00005294 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005295 StartPrivateStateThread(true);
5296 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005297
Jim Ingham372787f2012-04-07 00:00:41 +00005298 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005299
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005300 if (options.GetDebug())
5301 {
5302 // In this case, we aren't actually going to run, we just want to stop right away.
5303 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5304 // FIXME: To make this prettier we should invent some stop reason for this, but that
5305 // is only cosmetic, and this functionality is only of use to lldb developers who can
5306 // live with not pretty...
5307 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005308 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005309 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005310
Jim Ingham583bbb12016-03-07 21:50:25 +00005311 ListenerSP listener_sp(Listener::MakeListener("lldb.process.listener.run-thread-plan"));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005312
Sean Callanana46ec452012-07-11 21:31:24 +00005313 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005314
Jim Ingham77787032011-01-20 02:03:18 +00005315 {
Sean Callanana46ec452012-07-11 21:31:24 +00005316 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5317 // restored on exit to the function.
5318 //
5319 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5320 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005321
Jim Ingham583bbb12016-03-07 21:50:25 +00005322 ProcessEventHijacker run_thread_plan_hijacker (*this, listener_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005323
Jim Inghamf48169b2010-11-30 02:22:11 +00005324 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005325 {
5326 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005327 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005328 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005329 thread->GetIndexID(),
5330 thread->GetID(),
5331 s.GetData());
5332 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005333
Sean Callanana46ec452012-07-11 21:31:24 +00005334 bool got_event;
5335 lldb::EventSP event_sp;
5336 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005337
Jim Ingham0161b492013-02-09 01:29:05 +00005338 bool before_first_timeout = true; // This is set to false the first time that we have to halt the target.
Sean Callanana46ec452012-07-11 21:31:24 +00005339 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005340 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005341 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005342
Jim Ingham0161b492013-02-09 01:29:05 +00005343 // This is just for accounting:
5344 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005345
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005346 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005347 uint32_t one_thread_timeout_usec;
5348 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005349
5350 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5351 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5352 // first timeout already.
5353
5354 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005355 {
5356 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005357 one_thread_timeout_usec = 0;
5358 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005359 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005360 else
Jim Ingham0161b492013-02-09 01:29:05 +00005361 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005362 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005363
Jim Ingham914f4e72014-03-28 21:58:28 +00005364 // If the overall wait is forever, then we only need to set the one thread timeout:
5365 if (timeout_usec == 0)
5366 {
Ed Maste801335c2014-03-31 19:28:14 +00005367 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005368 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005369 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005370 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005371 }
Jim Ingham0161b492013-02-09 01:29:05 +00005372 else
5373 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005374 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5375 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5376 uint64_t computed_one_thread_timeout;
5377 if (option_one_thread_timeout != 0)
5378 {
5379 if (timeout_usec < option_one_thread_timeout)
5380 {
Sean Callanan579e70c2016-03-19 00:03:59 +00005381 diagnostic_manager.PutCString(
5382 eDiagnosticSeverityError,
5383 "RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005384 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005385 }
5386 computed_one_thread_timeout = option_one_thread_timeout;
5387 }
5388 else
5389 {
5390 computed_one_thread_timeout = timeout_usec / 2;
5391 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5392 computed_one_thread_timeout = default_one_thread_timeout_usec;
5393 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005394 one_thread_timeout_usec = computed_one_thread_timeout;
5395 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
Jim Ingham0161b492013-02-09 01:29:05 +00005396 }
Jim Ingham0161b492013-02-09 01:29:05 +00005397 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005398
5399 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005400 log->Printf ("Stop others: %u, try all: %u, before_first: %u, one thread: %" PRIu32 " - all threads: %" PRIu32 ".\n",
Jim Inghamfe1c3422014-04-16 02:24:48 +00005401 options.GetStopOthers(),
5402 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005403 before_first_timeout,
5404 one_thread_timeout_usec,
5405 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005406
Jim Ingham1460e4b2014-01-10 23:46:59 +00005407 // This isn't going to work if there are unfetched events on the queue.
5408 // Are there cases where we might want to run the remaining events here, and then try to
5409 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005410
Jim Ingham583bbb12016-03-07 21:50:25 +00005411 Event *other_events = listener_sp->PeekAtNextEvent();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005412 if (other_events != nullptr)
Jim Ingham1460e4b2014-01-10 23:46:59 +00005413 {
Sean Callanan579e70c2016-03-19 00:03:59 +00005414 diagnostic_manager.PutCString(eDiagnosticSeverityError,
5415 "RunThreadPlan called with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005416 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005417 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005418
Jim Ingham1460e4b2014-01-10 23:46:59 +00005419 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5420 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5421 // event coalescing to cause us to lose OUR running event...
5422 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005423
Jim Ingham8559a352012-11-26 23:52:18 +00005424 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5425 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005426
5427#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5428 // It's pretty much impossible to write test cases for things like:
5429 // One thread timeout expires, I go to halt, but the process already stopped
5430 // on the function call stop breakpoint. Turning on this define will make us not
5431 // fetch the first event till after the halt. So if you run a quick function, it will have
5432 // completed, and the completion event will be waiting, when you interrupt for halt.
5433 // The expression evaluation should still succeed.
5434 bool miss_first_event = true;
5435#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005436 TimeValue one_thread_timeout;
5437 TimeValue final_timeout;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00005438 std::chrono::microseconds timeout = std::chrono::microseconds(0);
Eugene Zelenko8f30a652015-10-23 18:39:37 +00005439
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005440 while (true)
Sean Callanana46ec452012-07-11 21:31:24 +00005441 {
5442 // We usually want to resume the process if we get to the top of the loop.
5443 // The only exception is if we get two running events with no intervening
5444 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005445 if (log)
5446 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5447 do_resume,
5448 handle_running_event,
5449 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005450
Jim Ingham184e9812013-01-15 02:47:48 +00005451 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005452 {
5453 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005454
Jim Ingham184e9812013-01-15 02:47:48 +00005455 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005456 {
Jim Ingham0161b492013-02-09 01:29:05 +00005457 num_resumes++;
Sean Callanan579e70c2016-03-19 00:03:59 +00005458 Error resume_error = PrivateResume();
Jim Ingham184e9812013-01-15 02:47:48 +00005459 if (!resume_error.Success())
5460 {
Sean Callanan579e70c2016-03-19 00:03:59 +00005461 diagnostic_manager.Printf(eDiagnosticSeverityError,
5462 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5463 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005464 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005465 break;
5466 }
Sean Callanana46ec452012-07-11 21:31:24 +00005467 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005468
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00005469 got_event = listener_sp->WaitForEvent(std::chrono::microseconds(500000), event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005470 if (!got_event)
5471 {
5472 if (log)
Sean Callanan579e70c2016-03-19 00:03:59 +00005473 log->Printf("Process::RunThreadPlan(): didn't get any event after resume %" PRIu32 ", exiting.",
5474 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005475
Sean Callanan579e70c2016-03-19 00:03:59 +00005476 diagnostic_manager.Printf(eDiagnosticSeverityError,
5477 "didn't get any event after resume %" PRIu32 ", exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005478 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005479 break;
5480 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005481
Sean Callanana46ec452012-07-11 21:31:24 +00005482 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005483
Sean Callanana46ec452012-07-11 21:31:24 +00005484 if (stop_state != eStateRunning)
5485 {
Jim Ingham0161b492013-02-09 01:29:05 +00005486 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005487
Jim Ingham0161b492013-02-09 01:29:05 +00005488 if (stop_state == eStateStopped)
5489 {
5490 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5491 if (log)
5492 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5493 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5494 num_resumes,
5495 StateAsCString(stop_state),
5496 restarted,
5497 do_resume,
5498 handle_running_event);
5499 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005500
Jim Ingham0161b492013-02-09 01:29:05 +00005501 if (restarted)
5502 {
5503 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5504 // event here. But if I do, the best thing is to Halt and then get out of here.
Pavel Labath19da1f12015-12-07 12:36:52 +00005505 const bool clear_thread_plans = false;
5506 const bool use_run_lock = false;
5507 Halt(clear_thread_plans, use_run_lock);
Jim Ingham0161b492013-02-09 01:29:05 +00005508 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005509
Sean Callanan579e70c2016-03-19 00:03:59 +00005510 diagnostic_manager.Printf(eDiagnosticSeverityError,
5511 "didn't get running event after initial resume, got %s instead.",
5512 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005513 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005514 break;
5515 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005516
Sean Callanana46ec452012-07-11 21:31:24 +00005517 if (log)
5518 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5519 // We need to call the function synchronously, so spin waiting for it to return.
5520 // If we get interrupted while executing, we're going to lose our context, and
5521 // won't be able to gather the result at this point.
5522 // We set the timeout AFTER the resume, since the resume takes some time and we
5523 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005524 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005525 else
5526 {
Sean Callanana46ec452012-07-11 21:31:24 +00005527 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005528 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005529 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005530
Jim Ingham0161b492013-02-09 01:29:05 +00005531 if (before_first_timeout)
5532 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005533 if (options.GetTryAllThreads())
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00005534 timeout = std::chrono::microseconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005535 else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00005536 timeout = std::chrono::microseconds(timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005537 }
5538 else
5539 {
5540 if (timeout_usec == 0)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00005541 timeout = std::chrono::microseconds(0);
Jim Ingham0161b492013-02-09 01:29:05 +00005542 else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00005543 timeout = std::chrono::microseconds(all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005544 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005545
Jim Ingham0161b492013-02-09 01:29:05 +00005546 do_resume = true;
5547 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005548
Sean Callanana46ec452012-07-11 21:31:24 +00005549 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005550 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005551
Jim Ingham0f16e732011-02-08 05:20:59 +00005552 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005553 {
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00005554 if (timeout.count())
Sean Callanana46ec452012-07-11 21:31:24 +00005555 {
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00005556 log->Printf(
5557 "Process::RunThreadPlan(): about to wait - now is %llu - endpoint is %llu",
5558 static_cast<unsigned long long>(std::chrono::system_clock::now().time_since_epoch().count()),
5559 static_cast<unsigned long long>(
5560 std::chrono::time_point<std::chrono::system_clock, std::chrono::microseconds>(timeout)
5561 .time_since_epoch()
5562 .count()));
Sean Callanana46ec452012-07-11 21:31:24 +00005563 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005564 else
Sean Callanana46ec452012-07-11 21:31:24 +00005565 {
5566 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5567 }
5568 }
Jim Ingham35878c42014-04-08 21:33:21 +00005569
5570#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5571 // See comment above...
5572 if (miss_first_event)
5573 {
5574 usleep(1000);
5575 miss_first_event = false;
5576 got_event = false;
5577 }
5578 else
5579#endif
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00005580 got_event = listener_sp->WaitForEvent(timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005581
Sean Callanana46ec452012-07-11 21:31:24 +00005582 if (got_event)
5583 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005584 if (event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005585 {
5586 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005587 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005588 {
Pavel Labath19da1f12015-12-07 12:36:52 +00005589 const bool clear_thread_plans = false;
5590 const bool use_run_lock = false;
5591 Halt(clear_thread_plans, use_run_lock);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005592 return_value = eExpressionInterrupted;
Sean Callanan579e70c2016-03-19 00:03:59 +00005593 diagnostic_manager.PutCString(eDiagnosticSeverityRemark, "execution halted by user interrupt.");
Jim Inghamcfc09352012-07-27 23:57:19 +00005594 if (log)
Sean Callanan579e70c2016-03-19 00:03:59 +00005595 log->Printf(
5596 "Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005597 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005598 }
5599 else
5600 {
5601 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5602 if (log)
5603 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005604
Jim Inghamcfc09352012-07-27 23:57:19 +00005605 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005606 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005607 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005608 {
Jim Ingham0161b492013-02-09 01:29:05 +00005609 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005610 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5611 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005612 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005613 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005614 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005615 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005616 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005617 }
5618 else
5619 {
Jim Ingham0161b492013-02-09 01:29:05 +00005620 // If we were restarted, we just need to go back up to fetch another event.
5621 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005622 {
5623 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005624 {
5625 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5626 }
5627 keep_going = true;
5628 do_resume = false;
5629 handle_running_event = true;
Jim Inghamcfc09352012-07-27 23:57:19 +00005630 }
5631 else
5632 {
Jim Ingham0161b492013-02-09 01:29:05 +00005633 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5634 StopReason stop_reason = eStopReasonInvalid;
5635 if (stop_info_sp)
5636 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005637
Jim Ingham0161b492013-02-09 01:29:05 +00005638 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5639 // it is OUR plan that is complete?
5640 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005641 {
5642 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005643 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
Jim Inghamc60963c2015-10-12 19:11:03 +00005644
5645 // Restore the plan state so it will get reported as intended when we are done.
5646 thread_plan_restorer.Clean();
5647
Jim Ingham8646d3c2014-05-05 02:47:44 +00005648 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005649 }
5650 else
5651 {
Jim Ingham0161b492013-02-09 01:29:05 +00005652 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005653 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005654 {
5655 if (log)
5656 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005657 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005658 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005659 {
Jim Inghamc60963c2015-10-12 19:11:03 +00005660 // Restore the plan state and then force Private to false. We are
5661 // going to stop because of this plan so we need it to become a public
5662 // plan or it won't report correctly when we continue to its termination
5663 // later on.
5664 thread_plan_restorer.Clean();
5665 if (thread_plan_sp)
5666 thread_plan_sp->SetPrivate(false);
Sean Callanan4b388c92013-07-30 19:54:09 +00005667 event_to_broadcast_sp = event_sp;
5668 }
Jim Ingham0161b492013-02-09 01:29:05 +00005669 }
Jim Ingham184e9812013-01-15 02:47:48 +00005670 else
Jim Ingham0161b492013-02-09 01:29:05 +00005671 {
5672 if (log)
5673 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005674 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005675 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005676 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005677 }
Jim Ingham184e9812013-01-15 02:47:48 +00005678 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005679 }
Sean Callanana46ec452012-07-11 21:31:24 +00005680 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005681 }
5682 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005683
Jim Inghamcfc09352012-07-27 23:57:19 +00005684 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005685 // This shouldn't really happen, but sometimes we do get two running events without an
5686 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005687 do_resume = false;
5688 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005689 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005690 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005691
Jim Inghamcfc09352012-07-27 23:57:19 +00005692 default:
5693 if (log)
5694 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005695
Jim Inghamcfc09352012-07-27 23:57:19 +00005696 if (stop_state == eStateExited)
5697 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005698
Sean Callanan579e70c2016-03-19 00:03:59 +00005699 diagnostic_manager.PutCString(eDiagnosticSeverityError,
5700 "execution stopped with unexpected state.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005701 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005702 break;
5703 }
Sean Callanana46ec452012-07-11 21:31:24 +00005704 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005705
Sean Callanana46ec452012-07-11 21:31:24 +00005706 if (keep_going)
5707 continue;
5708 else
5709 break;
5710 }
5711 else
5712 {
5713 if (log)
5714 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005715 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005716 break;
5717 }
5718 }
5719 else
5720 {
5721 // If we didn't get an event that means we've timed out...
5722 // We will interrupt the process here. Depending on what we were asked to do we will
5723 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005724
Sean Callanana46ec452012-07-11 21:31:24 +00005725 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005726 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005727 {
Jim Ingham0161b492013-02-09 01:29:05 +00005728 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005729 {
5730 if (timeout_usec != 0)
5731 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005732 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005733 "running for %" PRIu32 " usec with all threads enabled.",
5734 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005735 }
5736 else
5737 {
5738 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005739 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005740 }
5741 }
Sean Callanana46ec452012-07-11 21:31:24 +00005742 else
5743 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005744 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005745 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005746 }
5747 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005748 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005749 "abandoning execution.",
5750 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005751 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005752
Jim Ingham0161b492013-02-09 01:29:05 +00005753 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5754 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5755 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5756 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5757 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005758
Jim Ingham0161b492013-02-09 01:29:05 +00005759 bool back_to_top = true;
5760 uint32_t try_halt_again = 0;
5761 bool do_halt = true;
5762 const uint32_t num_retries = 5;
5763 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005764 {
Jim Ingham0161b492013-02-09 01:29:05 +00005765 Error halt_error;
5766 if (do_halt)
5767 {
5768 if (log)
5769 log->Printf ("Process::RunThreadPlan(): Running Halt.");
Pavel Labath19da1f12015-12-07 12:36:52 +00005770 const bool clear_thread_plans = false;
5771 const bool use_run_lock = false;
5772 Halt(clear_thread_plans, use_run_lock);
Jim Ingham0161b492013-02-09 01:29:05 +00005773 }
5774 if (halt_error.Success())
5775 {
5776 if (log)
5777 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005778
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00005779 got_event = listener_sp->WaitForEvent(std::chrono::microseconds(500000), event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005780
Jim Ingham0161b492013-02-09 01:29:05 +00005781 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005782 {
Jim Ingham0161b492013-02-09 01:29:05 +00005783 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5784 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005785 {
Jim Ingham0161b492013-02-09 01:29:05 +00005786 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5787 if (stop_state == lldb::eStateStopped
5788 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5789 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005790 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005791
Jim Ingham0161b492013-02-09 01:29:05 +00005792 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005793 {
Jim Ingham0161b492013-02-09 01:29:05 +00005794 // Between the time we initiated the Halt and the time we delivered it, the process could have
5795 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005796
Jim Ingham0161b492013-02-09 01:29:05 +00005797 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5798 {
5799 if (log)
5800 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5801 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005802 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005803 back_to_top = false;
5804 break;
5805 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005806
Jim Ingham0161b492013-02-09 01:29:05 +00005807 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5808 {
5809 if (log)
5810 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5811 "Exiting wait loop.");
5812 try_halt_again++;
5813 do_halt = false;
5814 continue;
5815 }
Sean Callanana46ec452012-07-11 21:31:24 +00005816
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005817 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005818 {
5819 if (log)
5820 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005821 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005822 back_to_top = false;
5823 break;
5824 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005825
Jim Ingham0161b492013-02-09 01:29:05 +00005826 if (before_first_timeout)
5827 {
5828 // Set all the other threads to run, and return to the top of the loop, which will continue;
5829 before_first_timeout = false;
5830 thread_plan_sp->SetStopOthers (false);
5831 if (log)
5832 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005833
Jim Ingham0161b492013-02-09 01:29:05 +00005834 back_to_top = true;
5835 break;
5836 }
5837 else
5838 {
5839 // Running all threads failed, so return Interrupted.
5840 if (log)
5841 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005842 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005843 back_to_top = false;
5844 break;
5845 }
Sean Callanana46ec452012-07-11 21:31:24 +00005846 }
5847 }
5848 else
Jim Ingham0161b492013-02-09 01:29:05 +00005849 { if (log)
5850 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5851 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005852 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005853 back_to_top = false;
5854 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005855 }
5856 }
Jim Ingham0161b492013-02-09 01:29:05 +00005857 else
5858 {
5859 try_halt_again++;
5860 continue;
5861 }
Sean Callanana46ec452012-07-11 21:31:24 +00005862 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005863
Jim Ingham0161b492013-02-09 01:29:05 +00005864 if (!back_to_top || try_halt_again > num_retries)
5865 break;
5866 else
5867 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005868 }
Sean Callanana46ec452012-07-11 21:31:24 +00005869 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005870
Sean Callanana46ec452012-07-11 21:31:24 +00005871 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
Zachary Turneracee96a2014-09-23 18:32:09 +00005872 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00005873 {
5874 StopPrivateStateThread();
5875 Error error;
5876 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005877 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005878 {
5879 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5880 }
Jason Molenda76513fd2014-10-15 23:39:31 +00005881 if (old_state != eStateInvalid)
5882 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00005883 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005884
Jim Inghamc60963c2015-10-12 19:11:03 +00005885 if (return_value != eExpressionCompleted && log)
5886 {
5887 // Print a backtrace into the log so we can figure out where we are:
5888 StreamString s;
5889 s.PutCString("Thread state after unsuccessful completion: \n");
5890 thread->GetStackFrameStatus (s,
5891 0,
5892 UINT32_MAX,
5893 true,
5894 UINT32_MAX);
5895 log->PutCString(s.GetData());
5896
5897 }
Jim Ingham184e9812013-01-15 02:47:48 +00005898 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5899 // could happen:
5900 // 1) The execution successfully completed
5901 // 2) We hit a breakpoint, and ignore_breakpoints was true
5902 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005903 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5904 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005905
Jim Ingham8646d3c2014-05-05 02:47:44 +00005906 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005907 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005908 {
5909 thread_plan_sp->RestoreThreadState();
5910 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005911
Sean Callanana46ec452012-07-11 21:31:24 +00005912 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005913 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005914 {
5915 if (log)
5916 {
5917 StreamString s;
5918 if (event_sp)
5919 event_sp->Dump (&s);
5920 else
5921 {
5922 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5923 }
5924
5925 StreamString ts;
5926
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005927 const char *event_explanation = nullptr;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005928
Sean Callanana46ec452012-07-11 21:31:24 +00005929 do
5930 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005931 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005932 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005933 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005934 break;
5935 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005936 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005937 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005938 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005939 break;
5940 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005941 else
Sean Callanana46ec452012-07-11 21:31:24 +00005942 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005943 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5944
5945 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005946 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005947 event_explanation = "<no event data>";
5948 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005949 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005950
Jim Inghamcfc09352012-07-27 23:57:19 +00005951 Process *process = event_data->GetProcessSP().get();
5952
5953 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005954 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005955 event_explanation = "<no process>";
5956 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005957 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005958
Jim Inghamcfc09352012-07-27 23:57:19 +00005959 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005960
Jim Inghamcfc09352012-07-27 23:57:19 +00005961 uint32_t num_threads = thread_list.GetSize();
5962 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005963
Jim Inghamcfc09352012-07-27 23:57:19 +00005964 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005965
Jim Inghamcfc09352012-07-27 23:57:19 +00005966 for (thread_index = 0;
5967 thread_index < num_threads;
5968 ++thread_index)
5969 {
5970 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005971
Jim Inghamcfc09352012-07-27 23:57:19 +00005972 if (!thread)
5973 {
5974 ts.Printf("<?> ");
5975 continue;
5976 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005977
Daniel Malead01b2952012-11-29 21:49:15 +00005978 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005979 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005980
Jim Inghamcfc09352012-07-27 23:57:19 +00005981 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005982 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005983 else
5984 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005985
Jim Inghamc60963c2015-10-12 19:11:03 +00005986 // Show the private stop info here, the public stop info will be from the last natural stop.
5987 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
Jim Inghamcfc09352012-07-27 23:57:19 +00005988 if (stop_info_sp)
5989 {
5990 const char *stop_desc = stop_info_sp->GetDescription();
5991 if (stop_desc)
5992 ts.PutCString (stop_desc);
5993 }
5994 ts.Printf(">");
5995 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005996
Jim Inghamcfc09352012-07-27 23:57:19 +00005997 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005998 }
Sean Callanana46ec452012-07-11 21:31:24 +00005999 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006000
Jim Inghamcfc09352012-07-27 23:57:19 +00006001 if (event_explanation)
6002 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00006003 else
Jim Inghamcfc09352012-07-27 23:57:19 +00006004 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6005 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006006
Jim Inghame4483cf2013-09-27 01:13:01 +00006007 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00006008 {
6009 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006010 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6011 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006012 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Inghamcfc09352012-07-27 23:57:19 +00006013 }
6014 else
6015 {
6016 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006017 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6018 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006019 }
6020 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006021 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006022 {
6023 if (log)
6024 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006025
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006026 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006027 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006028 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham0f16e732011-02-08 05:20:59 +00006029 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006030 }
6031 else
6032 {
Sean Callanana46ec452012-07-11 21:31:24 +00006033 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006034 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006035 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006036 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006037 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006038 }
6039 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6040 {
6041 if (log)
6042 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006043 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006044 }
6045 else
6046 {
6047 if (log)
6048 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006049 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006050 {
6051 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006052 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006053 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00006054 }
6055 }
6056 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006057
Sean Callanana46ec452012-07-11 21:31:24 +00006058 // Thread we ran the function in may have gone away because we ran the target
6059 // Check that it's still there, and if it is put it back in the context. Also restore the
6060 // frame in the context if it is still present.
6061 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6062 if (thread)
6063 {
6064 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6065 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006066
Sean Callanana46ec452012-07-11 21:31:24 +00006067 // Also restore the current process'es selected frame & thread, since this function calling may
6068 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006069
Sean Callanana46ec452012-07-11 21:31:24 +00006070 if (selected_tid != LLDB_INVALID_THREAD_ID)
6071 {
6072 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6073 {
6074 // We were able to restore the selected thread, now restore the frame:
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00006075 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006076 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006077 if (old_frame_sp)
6078 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006079 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006080 }
6081 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006082
Sean Callanana46ec452012-07-11 21:31:24 +00006083 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006084
Sean Callanana46ec452012-07-11 21:31:24 +00006085 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006086 {
Sean Callanana46ec452012-07-11 21:31:24 +00006087 if (log)
6088 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6089 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006090 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006091
Jim Inghamf48169b2010-11-30 02:22:11 +00006092 return return_value;
6093}
6094
6095const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006096Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006097{
6098 const char *result_name;
6099
6100 switch (result)
6101 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006102 case eExpressionCompleted:
6103 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006104 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006105 case eExpressionDiscarded:
6106 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006107 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006108 case eExpressionInterrupted:
6109 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006110 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006111 case eExpressionHitBreakpoint:
6112 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006113 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006114 case eExpressionSetupError:
6115 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006116 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006117 case eExpressionParseError:
6118 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006119 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006120 case eExpressionResultUnavailable:
6121 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006122 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006123 case eExpressionTimedOut:
6124 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006125 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006126 case eExpressionStoppedForDebug:
6127 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006128 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006129 }
6130 return result_name;
6131}
6132
Greg Clayton7260f622011-04-18 08:33:37 +00006133void
6134Process::GetStatus (Stream &strm)
6135{
6136 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006137 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006138 {
6139 if (state == eStateExited)
6140 {
6141 int exit_status = GetExitStatus();
6142 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006143 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006144 GetID(),
6145 exit_status,
6146 exit_status,
6147 exit_description ? exit_description : "");
6148 }
6149 else
6150 {
6151 if (state == eStateConnected)
6152 strm.Printf ("Connected to remote target.\n");
6153 else
Daniel Malead01b2952012-11-29 21:49:15 +00006154 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006155 }
6156 }
6157 else
6158 {
Daniel Malead01b2952012-11-29 21:49:15 +00006159 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006160 }
6161}
6162
6163size_t
6164Process::GetThreadStatus (Stream &strm,
6165 bool only_threads_with_stop_reason,
6166 uint32_t start_frame,
6167 uint32_t num_frames,
6168 uint32_t num_frames_with_source)
6169{
6170 size_t num_thread_infos_dumped = 0;
6171
Jim Ingham4a65fb12014-03-07 11:20:03 +00006172 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6173 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6174 // ID's, and look them up one by one:
6175
6176 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006177 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006178 //Scope for thread list locker;
6179 {
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +00006180 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
Jim Ingham4a65fb12014-03-07 11:20:03 +00006181 ThreadList &curr_thread_list = GetThreadList();
6182 num_threads = curr_thread_list.GetSize();
6183 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006184 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006185 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006186 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006187 }
6188
Greg Clayton7260f622011-04-18 08:33:37 +00006189 for (uint32_t i = 0; i < num_threads; i++)
6190 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006191 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006192 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006193 {
6194 if (only_threads_with_stop_reason)
6195 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006196 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006197 if (!stop_info_sp || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006198 continue;
6199 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006200 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006201 start_frame,
6202 num_frames,
6203 num_frames_with_source);
6204 ++num_thread_infos_dumped;
6205 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006206 else
6207 {
6208 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6209 if (log)
6210 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
Jim Ingham4a65fb12014-03-07 11:20:03 +00006211 }
Greg Clayton7260f622011-04-18 08:33:37 +00006212 }
6213 return num_thread_infos_dumped;
6214}
6215
Greg Claytona9f40ad2012-02-22 04:37:26 +00006216void
6217Process::AddInvalidMemoryRegion (const LoadRange &region)
6218{
6219 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6220}
6221
6222bool
6223Process::RemoveInvalidMemoryRange (const LoadRange &region)
6224{
6225 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6226}
6227
Jim Ingham372787f2012-04-07 00:00:41 +00006228void
6229Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6230{
6231 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6232}
6233
6234bool
6235Process::RunPreResumeActions ()
6236{
6237 bool result = true;
6238 while (!m_pre_resume_actions.empty())
6239 {
6240 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6241 m_pre_resume_actions.pop_back();
6242 bool this_result = action.callback (action.baton);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006243 if (result)
Jason Molenda55710932014-11-17 20:10:15 +00006244 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006245 }
6246 return result;
6247}
6248
6249void
6250Process::ClearPreResumeActions ()
6251{
6252 m_pre_resume_actions.clear();
6253}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006254
Zachary Turner93749ab2015-03-03 21:51:25 +00006255ProcessRunLock &
6256Process::GetRunLock()
6257{
6258 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
6259 return m_private_run_lock;
6260 else
6261 return m_public_run_lock;
6262}
6263
Greg Claytonfa559e52012-05-18 02:38:05 +00006264void
6265Process::Flush ()
6266{
6267 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006268 m_extended_thread_list.Flush();
6269 m_extended_thread_stop_id = 0;
6270 m_queue_list.Clear();
6271 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006272}
Greg Clayton90ba8112012-12-05 00:16:59 +00006273
6274void
6275Process::DidExec ()
6276{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006277 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6278 if (log)
6279 log->Printf ("Process::%s()", __FUNCTION__);
6280
Greg Clayton90ba8112012-12-05 00:16:59 +00006281 Target &target = GetTarget();
6282 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006283 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006284 m_dynamic_checkers_ap.reset();
6285 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006286 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006287 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006288 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006289 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006290 m_image_tokens.clear();
6291 m_allocated_memory_cache.Clear();
6292 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006293 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006294 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006295 m_memory_cache.Clear(true);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006296 m_stop_info_override_callback = nullptr;
Greg Clayton90ba8112012-12-05 00:16:59 +00006297 DoDidExec();
6298 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006299 // Flush the process (threads and all stack frames) after running CompleteAttach()
6300 // in case the dynamic loader loaded things in new locations.
6301 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006302
6303 // After we figure out what was loaded/unloaded in CompleteAttach,
6304 // we need to let the target know so it can do any cleanup it needs to.
6305 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006306}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006307
Jim Ingham1460e4b2014-01-10 23:46:59 +00006308addr_t
6309Process::ResolveIndirectFunction(const Address *address, Error &error)
6310{
6311 if (address == nullptr)
6312 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006313 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006314 return LLDB_INVALID_ADDRESS;
6315 }
6316
6317 addr_t function_addr = LLDB_INVALID_ADDRESS;
6318
6319 addr_t addr = address->GetLoadAddress(&GetTarget());
6320 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6321 if (iter != m_resolved_indirect_addresses.end())
6322 {
6323 function_addr = (*iter).second;
6324 }
6325 else
6326 {
6327 if (!InferiorCall(this, address, function_addr))
6328 {
6329 Symbol *symbol = address->CalculateSymbolContextSymbol();
6330 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6331 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6332 function_addr = LLDB_INVALID_ADDRESS;
6333 }
6334 else
6335 {
6336 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6337 }
6338 }
6339 return function_addr;
6340}
6341
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006342void
6343Process::ModulesDidLoad (ModuleList &module_list)
6344{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006345 SystemRuntime *sys_runtime = GetSystemRuntime();
6346 if (sys_runtime)
6347 {
6348 sys_runtime->ModulesDidLoad (module_list);
6349 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006350
Kuba Breckaafdf8422014-10-10 23:43:03 +00006351 GetJITLoaders().ModulesDidLoad (module_list);
6352
6353 // Give runtimes a chance to be created.
6354 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6355
6356 // Tell runtimes about new modules.
6357 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6358 {
6359 InstrumentationRuntimeSP runtime = pos->second;
6360 runtime->ModulesDidLoad(module_list);
6361 }
6362
Greg Clayton35ca64b2015-04-16 17:13:34 +00006363 // Let any language runtimes we have already created know
6364 // about the modules that loaded.
6365
6366 // Iterate over a copy of this language runtime list in case
6367 // the language runtime ModulesDidLoad somehow causes the language
6368 // riuntime to be unloaded.
6369 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
6370 for (const auto &pair: language_runtimes)
6371 {
6372 // We must check language_runtime_sp to make sure it is not
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006373 // nullptr as we might cache the fact that we didn't have a
Greg Clayton35ca64b2015-04-16 17:13:34 +00006374 // language runtime for a language.
6375 LanguageRuntimeSP language_runtime_sp = pair.second;
6376 if (language_runtime_sp)
6377 language_runtime_sp->ModulesDidLoad(module_list);
6378 }
Ryan Brown65d4d5c2015-09-16 21:20:44 +00006379
Greg Clayton2591fe12016-03-15 22:44:07 +00006380 // If we don't have an operating system plug-in, try to load one since
6381 // loading shared libraries might cause a new one to try and load
6382 if (!m_os_ap)
6383 LoadOperatingSystemPlugin(false);
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006384}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006385
Jason Molendaef7d6412015-08-06 03:27:10 +00006386void
Sean Callanan77decf52015-12-09 01:25:01 +00006387Process::PrintWarning (uint64_t warning_type, const void *repeat_key, const char *fmt, ...)
Jason Molendaef7d6412015-08-06 03:27:10 +00006388{
6389 bool print_warning = true;
6390
6391 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006392 if (!stream_sp)
Jason Molendaef7d6412015-08-06 03:27:10 +00006393 return;
6394 if (warning_type == eWarningsOptimization
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006395 && !GetWarningsOptimization())
Jason Molendaef7d6412015-08-06 03:27:10 +00006396 {
6397 return;
6398 }
6399
6400 if (repeat_key != nullptr)
6401 {
6402 WarningsCollection::iterator it = m_warnings_issued.find (warning_type);
6403 if (it == m_warnings_issued.end())
6404 {
6405 m_warnings_issued[warning_type] = WarningsPointerSet();
6406 m_warnings_issued[warning_type].insert (repeat_key);
6407 }
6408 else
6409 {
6410 if (it->second.find (repeat_key) != it->second.end())
6411 {
6412 print_warning = false;
6413 }
6414 else
6415 {
6416 it->second.insert (repeat_key);
6417 }
6418 }
6419 }
6420
6421 if (print_warning)
6422 {
6423 va_list args;
6424 va_start (args, fmt);
6425 stream_sp->PrintfVarArg (fmt, args);
6426 va_end (args);
6427 }
6428}
6429
Jason Molenda484900b2015-08-10 07:55:25 +00006430void
6431Process::PrintWarningOptimization (const SymbolContext &sc)
6432{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006433 if (GetWarningsOptimization()
6434 && sc.module_sp
6435 && !sc.module_sp->GetFileSpec().GetFilename().IsEmpty()
Jason Molenda484900b2015-08-10 07:55:25 +00006436 && sc.function
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006437 && sc.function->GetIsOptimized())
Jason Molenda484900b2015-08-10 07:55:25 +00006438 {
6439 PrintWarning (Process::Warnings::eWarningsOptimization, sc.module_sp.get(), "%s was compiled with optimization - stepping may behave oddly; variables may not be available.\n", sc.module_sp->GetFileSpec().GetFilename().GetCString());
6440 }
6441}
6442
Pavel Labatha933d512016-04-05 13:07:16 +00006443bool
6444Process::GetProcessInfo(ProcessInstanceInfo &info)
6445{
6446 info.Clear();
6447
6448 PlatformSP platform_sp = GetTarget().GetPlatform();
6449 if (! platform_sp)
6450 return false;
6451
6452 return platform_sp->GetProcessInfo(GetID(), info);
6453}
6454
Kuba Breckaa51ea382014-09-06 01:33:13 +00006455ThreadCollectionSP
6456Process::GetHistoryThreads(lldb::addr_t addr)
6457{
6458 ThreadCollectionSP threads;
Greg Clayton35ca64b2015-04-16 17:13:34 +00006459
Kuba Breckaa51ea382014-09-06 01:33:13 +00006460 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6461
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006462 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00006463 return threads;
6464 }
6465
6466 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6467
6468 return threads;
6469}
Kuba Brecka63927542014-10-11 01:59:32 +00006470
6471InstrumentationRuntimeSP
6472Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6473{
6474 InstrumentationRuntimeCollection::iterator pos;
6475 pos = m_instrumentation_runtimes.find (type);
6476 if (pos == m_instrumentation_runtimes.end())
6477 {
6478 return InstrumentationRuntimeSP();
6479 }
6480 else
6481 return (*pos).second;
6482}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006483
6484bool
6485Process::GetModuleSpec(const FileSpec& module_file_spec,
6486 const ArchSpec& arch,
6487 ModuleSpec& module_spec)
6488{
6489 module_spec.Clear();
6490 return false;
6491}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006492
6493size_t
6494Process::AddImageToken(lldb::addr_t image_ptr)
6495{
6496 m_image_tokens.push_back(image_ptr);
6497 return m_image_tokens.size() - 1;
6498}
6499
6500lldb::addr_t
6501Process::GetImagePtrFromToken(size_t token) const
6502{
6503 if (token < m_image_tokens.size())
6504 return m_image_tokens[token];
6505 return LLDB_INVALID_IMAGE_TOKEN;
6506}
6507
6508void
6509Process::ResetImageToken(size_t token)
6510{
6511 if (token < m_image_tokens.size())
6512 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00006513}
Jason Molendafd4cea52016-01-08 21:40:11 +00006514
6515Address
6516Process::AdvanceAddressToNextBranchInstruction (Address default_stop_addr, AddressRange range_bounds)
6517{
6518 Target &target = GetTarget();
6519 DisassemblerSP disassembler_sp;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006520 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006521
6522 Address retval = default_stop_addr;
6523
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006524 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00006525 return retval;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006526 if (!default_stop_addr.IsValid())
Jason Molendafd4cea52016-01-08 21:40:11 +00006527 return retval;
6528
6529 ExecutionContext exe_ctx (this);
6530 const char *plugin_name = nullptr;
6531 const char *flavor = nullptr;
6532 const bool prefer_file_cache = true;
6533 disassembler_sp = Disassembler::DisassembleRange(target.GetArchitecture(),
6534 plugin_name,
6535 flavor,
6536 exe_ctx,
6537 range_bounds,
6538 prefer_file_cache);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006539 if (disassembler_sp)
Jason Molendafd4cea52016-01-08 21:40:11 +00006540 insn_list = &disassembler_sp->GetInstructionList();
6541
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006542 if (insn_list == nullptr)
Jason Molendafd4cea52016-01-08 21:40:11 +00006543 {
6544 return retval;
6545 }
6546
6547 size_t insn_offset = insn_list->GetIndexOfInstructionAtAddress (default_stop_addr);
6548 if (insn_offset == UINT32_MAX)
6549 {
6550 return retval;
6551 }
6552
6553 uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction (insn_offset, target);
6554 if (branch_index == UINT32_MAX)
6555 {
6556 return retval;
6557 }
6558
6559 if (branch_index > insn_offset)
6560 {
6561 Address next_branch_insn_address = insn_list->GetInstructionAtIndex (branch_index)->GetAddress();
6562 if (next_branch_insn_address.IsValid() && range_bounds.ContainsFileAddress (next_branch_insn_address))
6563 {
6564 retval = next_branch_insn_address;
6565 }
6566 }
6567
Jason Molendafd4cea52016-01-08 21:40:11 +00006568 return retval;
6569}
Howard Hellyerad007562016-07-07 08:21:28 +00006570
6571Error
6572Process::GetMemoryRegions (std::vector<lldb::MemoryRegionInfoSP>& region_list)
6573{
6574
6575 Error error;
6576
6577 lldb::addr_t range_base = 0;
6578 lldb::addr_t range_end = 0;
6579
6580 region_list.clear();
6581 do
6582 {
6583 lldb::MemoryRegionInfoSP region_info( new lldb_private::MemoryRegionInfo() );
6584 error = GetMemoryRegionInfo (range_end, *region_info);
6585 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6586 if (error.Fail())
6587 {
6588 region_list.clear();
6589 break;
6590 }
6591
6592 range_base = region_info->GetRange().GetRangeBase();
6593 range_end = region_info->GetRange().GetRangeEnd();
6594 if( region_info->GetMapped() == MemoryRegionInfo::eYes )
6595 {
6596 region_list.push_back(region_info);
6597 }
6598 } while (range_end != LLDB_INVALID_ADDRESS);
6599
6600 return error;
6601
6602}