blob: ced4c92d1f7ce938546e879da46f0e37b9b14e26 [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
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Breakpoint/StoppointCallbackContext.h"
19#include "lldb/Breakpoint/BreakpointLocation.h"
20#include "lldb/Core/Event.h"
21#include "lldb/Core/Debugger.h"
22#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"
Jim Ingham151c0322015-09-15 21:13:50 +000028#include "lldb/Expression/UserExpression.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000029#include "lldb/Expression/IRDynamicChecks.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000030#include "lldb/Host/ConnectionFileDescriptor.h"
Zachary Turner4eff2d32015-10-14 21:37:36 +000031#include "lldb/Host/FileSystem.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Host/Host.h"
Zachary Turner39de3112014-09-09 20:54:56 +000033#include "lldb/Host/HostInfo.h"
Greg Clayton100eb932014-07-02 21:10:39 +000034#include "lldb/Host/Pipe.h"
Greg Clayton44d93782014-01-27 23:43:24 +000035#include "lldb/Host/Terminal.h"
Zachary Turner39de3112014-09-09 20:54:56 +000036#include "lldb/Host/ThreadLauncher.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000037#include "lldb/Interpreter/CommandInterpreter.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000038#include "lldb/Interpreter/OptionValueProperties.h"
Jason Molenda484900b2015-08-10 07:55:25 +000039#include "lldb/Symbol/Function.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000040#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000042#include "lldb/Target/DynamicLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000043#include "lldb/Target/InstrumentationRuntime.h"
Andrew MacPherson17220c12014-03-05 10:12:43 +000044#include "lldb/Target/JITLoader.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000045#include "lldb/Target/JITLoaderList.h"
Kuba Breckaa51ea382014-09-06 01:33:13 +000046#include "lldb/Target/MemoryHistory.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000047#include "lldb/Target/MemoryRegionInfo.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000048#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000049#include "lldb/Target/LanguageRuntime.h"
50#include "lldb/Target/CPPLanguageRuntime.h"
51#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000052#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000054#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000055#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056#include "lldb/Target/Target.h"
57#include "lldb/Target/TargetList.h"
58#include "lldb/Target/Thread.h"
59#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000060#include "lldb/Target/ThreadPlanBase.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000061#include "lldb/Target/UnixSignals.h"
Zachary Turner50232572015-03-18 21:31:45 +000062#include "lldb/Utility/NameMatches.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000063#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000064
65using namespace lldb;
66using namespace lldb_private;
67
Greg Clayton67cc0632012-08-22 17:17:09 +000068// Comment out line below to disable memory caching, overriding the process setting
69// target.process.disable-memory-cache
70#define ENABLE_MEMORY_CACHING
71
72#ifdef ENABLE_MEMORY_CACHING
73#define DISABLE_MEM_CACHE_DEFAULT false
74#else
75#define DISABLE_MEM_CACHE_DEFAULT true
76#endif
77
78class ProcessOptionValueProperties : public OptionValueProperties
79{
80public:
81 ProcessOptionValueProperties (const ConstString &name) :
82 OptionValueProperties (name)
83 {
84 }
85
86 // This constructor is used when creating ProcessOptionValueProperties when it
87 // is part of a new lldb_private::Process instance. It will copy all current
88 // global property values as needed
89 ProcessOptionValueProperties (ProcessProperties *global_properties) :
90 OptionValueProperties(*global_properties->GetValueProperties())
91 {
92 }
93
Eugene Zelenko8f30a652015-10-23 18:39:37 +000094 const Property *
95 GetPropertyAtIndex(const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const override
Greg Clayton67cc0632012-08-22 17:17:09 +000096 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +000097 // When getting the value for a key from the process options, we will always
Greg Clayton67cc0632012-08-22 17:17:09 +000098 // try and grab the setting from the current process if there is one. Else we just
99 // use the one from this instance.
100 if (exe_ctx)
101 {
102 Process *process = exe_ctx->GetProcessPtr();
103 if (process)
104 {
105 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
106 if (this != instance_properties)
107 return instance_properties->ProtectedGetPropertyAtIndex (idx);
108 }
109 }
110 return ProtectedGetPropertyAtIndex (idx);
111 }
112};
113
114static PropertyDefinition
115g_properties[] =
116{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000117 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, nullptr, nullptr, "Disable reading and caching of memory in fixed-size units." },
118 { "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 +0000119 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000120 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, breakpoints will be ignored during expression evaluation." },
121 { "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." },
122 { "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." },
123 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, stop when a shared library is loaded or unloaded." },
124 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, detach will attempt to keep the process stopped." },
125 { "memory-cache-line-size" , OptionValue::eTypeUInt64, false, 512, nullptr, nullptr, "The memory cache line size" },
126 { "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." },
127 { nullptr , OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr }
Greg Clayton67cc0632012-08-22 17:17:09 +0000128};
129
130enum {
131 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000132 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000133 ePropertyIgnoreBreakpointsInExpressions,
134 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000135 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000136 ePropertyStopOnSharedLibraryEvents,
Jason Molendaf0340c92014-09-03 22:30:54 +0000137 ePropertyDetachKeepsStopped,
Jason Molendaef7d6412015-08-06 03:27:10 +0000138 ePropertyMemCacheLineSize,
139 ePropertyWarningOptimization
Greg Clayton67cc0632012-08-22 17:17:09 +0000140};
141
Greg Clayton332e8b12015-01-13 21:13:08 +0000142ProcessProperties::ProcessProperties (lldb_private::Process *process) :
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000143 Properties(),
144 m_process(process) // Can be nullptr for global ProcessProperties
Greg Clayton67cc0632012-08-22 17:17:09 +0000145{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000146 if (process == nullptr)
Greg Clayton67cc0632012-08-22 17:17:09 +0000147 {
Greg Clayton332e8b12015-01-13 21:13:08 +0000148 // Global process properties, set them up one time
Greg Clayton67cc0632012-08-22 17:17:09 +0000149 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
150 m_collection_sp->Initialize(g_properties);
151 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000152 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000153 true,
154 Thread::GetGlobalProperties()->GetValueProperties());
155 }
156 else
Greg Clayton332e8b12015-01-13 21:13:08 +0000157 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000158 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
Greg Clayton332e8b12015-01-13 21:13:08 +0000159 m_collection_sp->SetValueChangedCallback(ePropertyPythonOSPluginPath, ProcessProperties::OptionValueChangedCallback, this);
160 }
Greg Clayton67cc0632012-08-22 17:17:09 +0000161}
162
Eugene Zelenko8f30a652015-10-23 18:39:37 +0000163ProcessProperties::~ProcessProperties() = default;
Greg Clayton67cc0632012-08-22 17:17:09 +0000164
Greg Clayton332e8b12015-01-13 21:13:08 +0000165void
166ProcessProperties::OptionValueChangedCallback (void *baton, OptionValue *option_value)
167{
168 ProcessProperties *properties = (ProcessProperties *)baton;
169 if (properties->m_process)
170 properties->m_process->LoadOperatingSystemPlugin(true);
171}
172
Greg Clayton67cc0632012-08-22 17:17:09 +0000173bool
174ProcessProperties::GetDisableMemoryCache() const
175{
176 const uint32_t idx = ePropertyDisableMemCache;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000177 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton67cc0632012-08-22 17:17:09 +0000178}
179
Jason Molendaf0340c92014-09-03 22:30:54 +0000180uint64_t
181ProcessProperties::GetMemoryCacheLineSize() const
182{
183 const uint32_t idx = ePropertyMemCacheLineSize;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000184 return m_collection_sp->GetPropertyAtIndexAsUInt64(nullptr, idx, g_properties[idx].default_uint_value);
Jason Molendaf0340c92014-09-03 22:30:54 +0000185}
186
Greg Clayton67cc0632012-08-22 17:17:09 +0000187Args
188ProcessProperties::GetExtraStartupCommands () const
189{
190 Args args;
191 const uint32_t idx = ePropertyExtraStartCommand;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000192 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000193 return args;
194}
195
196void
197ProcessProperties::SetExtraStartupCommands (const Args &args)
198{
199 const uint32_t idx = ePropertyExtraStartCommand;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000200 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
Greg Clayton67cc0632012-08-22 17:17:09 +0000201}
202
Greg Claytonc9d645d2012-10-18 22:40:37 +0000203FileSpec
204ProcessProperties::GetPythonOSPluginPath () const
205{
206 const uint32_t idx = ePropertyPythonOSPluginPath;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000207 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000208}
209
210void
211ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
212{
213 const uint32_t idx = ePropertyPythonOSPluginPath;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000214 m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
Greg Claytonc9d645d2012-10-18 22:40:37 +0000215}
216
Jim Ingham184e9812013-01-15 02:47:48 +0000217bool
218ProcessProperties::GetIgnoreBreakpointsInExpressions () const
219{
220 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000221 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000222}
223
224void
225ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
226{
227 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000228 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000229}
230
231bool
232ProcessProperties::GetUnwindOnErrorInExpressions () const
233{
234 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000235 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham184e9812013-01-15 02:47:48 +0000236}
237
238void
239ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
240{
241 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000242 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
Jim Ingham184e9812013-01-15 02:47:48 +0000243}
244
Jim Ingham29950772013-01-26 02:19:28 +0000245bool
246ProcessProperties::GetStopOnSharedLibraryEvents () const
247{
248 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000249 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Ingham29950772013-01-26 02:19:28 +0000250}
251
252void
253ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
254{
255 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000256 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
Jim Ingham29950772013-01-26 02:19:28 +0000257}
258
Jim Inghamacff8952013-05-02 00:27:30 +0000259bool
260ProcessProperties::GetDetachKeepsStopped () const
261{
262 const uint32_t idx = ePropertyDetachKeepsStopped;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000263 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Jim Inghamacff8952013-05-02 00:27:30 +0000264}
265
266void
267ProcessProperties::SetDetachKeepsStopped (bool stop)
268{
269 const uint32_t idx = ePropertyDetachKeepsStopped;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000270 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
Jim Inghamacff8952013-05-02 00:27:30 +0000271}
272
Jason Molendaef7d6412015-08-06 03:27:10 +0000273bool
274ProcessProperties::GetWarningsOptimization () const
275{
276 const uint32_t idx = ePropertyWarningOptimization;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000277 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
Jason Molendaef7d6412015-08-06 03:27:10 +0000278}
279
Greg Clayton32e0a752011-03-30 18:16:51 +0000280void
Greg Clayton8b82f082011-04-12 05:54:46 +0000281ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000282{
283 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000284 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000285 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000286
287 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000288 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000289
290 if (m_executable)
291 {
292 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
293 s.PutCString (" file = ");
294 m_executable.Dump(&s);
295 s.EOL();
296 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000297 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000298 if (argc > 0)
299 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000300 for (uint32_t i = 0; i < argc; i++)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000301 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000302 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000303 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000304 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000305 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000306 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000307 }
308 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000309
310 const uint32_t envc = m_environment.GetArgumentCount();
311 if (envc > 0)
312 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000313 for (uint32_t i = 0; i < envc; i++)
Greg Clayton8b82f082011-04-12 05:54:46 +0000314 {
315 const char *env = m_environment.GetArgumentAtIndex(i);
316 if (i < 10)
317 s.Printf (" env[%u] = %s\n", i, env);
318 else
319 s.Printf ("env[%u] = %s\n", i, env);
320 }
321 }
322
Todd Fiala7df337f2015-10-13 23:41:19 +0000323 if (m_arch.IsValid())
324 {
325 s.Printf (" arch = ");
326 m_arch.DumpTriple(s);
327 s.EOL();
328 }
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000329
Greg Clayton8b82f082011-04-12 05:54:46 +0000330 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000331 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000332 cstr = platform->GetUserName (m_uid);
333 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000334 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000335 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000336 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000337 cstr = platform->GetGroupName (m_gid);
338 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000339 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000340 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000341 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000342 cstr = platform->GetUserName (m_euid);
343 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000344 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000345 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000346 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000347 cstr = platform->GetGroupName (m_egid);
348 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000349 }
350}
351
352void
Greg Clayton8b82f082011-04-12 05:54:46 +0000353ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000354{
Greg Clayton8b82f082011-04-12 05:54:46 +0000355 const char *label;
356 if (show_args || verbose)
357 label = "ARGUMENTS";
358 else
359 label = "NAME";
360
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000361 if (verbose)
362 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000363 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000364 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
365 }
366 else
367 {
Jim Ingham368ac222014-08-15 17:05:27 +0000368 s.Printf ("PID PARENT USER TRIPLE %s\n", label);
369 s.PutCString ("====== ====== ========== ======================== ============================\n");
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000370 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000371}
372
373void
Greg Clayton8b82f082011-04-12 05:54:46 +0000374ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000375{
376 if (m_pid != LLDB_INVALID_PROCESS_ID)
377 {
378 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000379 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000380
Todd Fiala7df337f2015-10-13 23:41:19 +0000381 StreamString arch_strm;
382 if (m_arch.IsValid())
383 m_arch.DumpTriple(arch_strm);
384
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000385 if (verbose)
386 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000387 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000388 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
389 s.Printf ("%-10s ", cstr);
390 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000391 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000392
Greg Clayton8b82f082011-04-12 05:54:46 +0000393 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000394 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
395 s.Printf ("%-10s ", cstr);
396 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000397 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000398
Greg Clayton8b82f082011-04-12 05:54:46 +0000399 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000400 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
401 s.Printf ("%-10s ", cstr);
402 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000403 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000404
Greg Clayton8b82f082011-04-12 05:54:46 +0000405 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000406 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
407 s.Printf ("%-10s ", cstr);
408 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000409 s.Printf ("%-10u ", m_egid);
Todd Fiala7df337f2015-10-13 23:41:19 +0000410
411 s.Printf ("%-24s ", arch_strm.GetString().c_str());
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000412 }
413 else
414 {
Jim Ingham368ac222014-08-15 17:05:27 +0000415 s.Printf ("%-10s %-24s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000416 platform->GetUserName (m_euid),
Todd Fiala7df337f2015-10-13 23:41:19 +0000417 arch_strm.GetString().c_str());
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000418 }
419
Greg Clayton8b82f082011-04-12 05:54:46 +0000420 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000421 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000422 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000423 if (argc > 0)
424 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000425 for (uint32_t i = 0; i < argc; i++)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000426 {
427 if (i > 0)
428 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000429 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000430 }
431 }
432 }
433 else
434 {
435 s.PutCString (GetName());
436 }
437
438 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000439 }
440}
441
Greg Clayton8b82f082011-04-12 05:54:46 +0000442Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000443ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000444{
445 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000446 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000447
448 switch (short_option)
449 {
450 case 's': // Stop at program entry point
451 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
452 break;
453
Greg Clayton8b82f082011-04-12 05:54:46 +0000454 case 'i': // STDIN for read only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000455 {
456 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000457 if (action.Open(STDIN_FILENO, FileSpec{option_arg, false}, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000458 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000459 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000460 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000461
462 case 'o': // Open STDOUT for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000463 {
464 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000465 if (action.Open(STDOUT_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000466 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000467 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000468 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000469
470 case 'e': // STDERR for write only
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000471 {
472 FileAction action;
Chaoren Lind3173f32015-05-29 19:52:29 +0000473 if (action.Open(STDERR_FILENO, FileSpec{option_arg, false}, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000474 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000475 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000476 }
Greg Clayton9845a8d2012-03-06 04:01:04 +0000477
Greg Clayton8b82f082011-04-12 05:54:46 +0000478 case 'p': // Process plug-in name
479 launch_info.SetProcessPluginName (option_arg);
480 break;
481
482 case 'n': // Disable STDIO
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000483 {
484 FileAction action;
Zachary Turner4eff2d32015-10-14 21:37:36 +0000485 const FileSpec dev_null{FileSystem::DEV_NULL, false};
Chaoren Lind3173f32015-05-29 19:52:29 +0000486 if (action.Open(STDIN_FILENO, dev_null, true, false))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000487 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000488 if (action.Open(STDOUT_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000489 launch_info.AppendFileAction (action);
Chaoren Lind3173f32015-05-29 19:52:29 +0000490 if (action.Open(STDERR_FILENO, dev_null, false, true))
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000491 launch_info.AppendFileAction (action);
Greg Clayton8b82f082011-04-12 05:54:46 +0000492 break;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000493 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000494
495 case 'w':
Chaoren Lind3173f32015-05-29 19:52:29 +0000496 launch_info.SetWorkingDirectory(FileSpec{option_arg, false});
Greg Clayton8b82f082011-04-12 05:54:46 +0000497 break;
498
499 case 't': // Open process in new terminal window
500 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
501 break;
502
503 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000504 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
505 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000506 break;
507
Todd Fiala51637922014-08-19 17:40:43 +0000508 case 'A': // Disable ASLR.
509 {
510 bool success;
511 const bool disable_aslr_arg = Args::StringToBoolean (option_arg, true, &success);
512 if (success)
513 disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
514 else
515 error.SetErrorStringWithFormat ("Invalid boolean value for disable-aslr option: '%s'", option_arg ? option_arg : "<null>");
Greg Clayton8b82f082011-04-12 05:54:46 +0000516 break;
Todd Fiala51637922014-08-19 17:40:43 +0000517 }
518
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000519 case 'X': // shell expand args.
Enrico Granatad7a83a92015-02-10 03:06:24 +0000520 {
521 bool success;
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000522 const bool expand_args = Args::StringToBoolean (option_arg, true, &success);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000523 if (success)
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000524 launch_info.SetShellExpandArguments(expand_args);
Enrico Granatad7a83a92015-02-10 03:06:24 +0000525 else
Enrico Granatab38ef8c2015-02-20 22:20:30 +0000526 error.SetErrorStringWithFormat ("Invalid boolean value for shell-expand-args option: '%s'", option_arg ? option_arg : "<null>");
Enrico Granatad7a83a92015-02-10 03:06:24 +0000527 break;
528 }
529
Todd Fiala51637922014-08-19 17:40:43 +0000530 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000531 if (option_arg && option_arg[0])
Zachary Turner10687b02014-10-20 17:46:43 +0000532 launch_info.SetShell (FileSpec(option_arg, false));
Greg Clayton144f3a92011-11-15 03:53:30 +0000533 else
Zachary Turner10687b02014-10-20 17:46:43 +0000534 launch_info.SetShell (HostInfo::GetDefaultShell());
Greg Clayton982c9762011-11-03 21:22:33 +0000535 break;
536
Greg Clayton8b82f082011-04-12 05:54:46 +0000537 case 'v':
538 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
539 break;
540
541 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000542 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000543 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000544 }
545 return error;
546}
547
548OptionDefinition
549ProcessLaunchCommandOptions::g_option_table[] =
550{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000551{ 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." },
552{ 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." },
553{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePlugin, "Name of the process plugin you want to use." },
554{ 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." },
555{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous." },
556{ 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." },
557{ 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 +0000558
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000559{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>." },
560{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>." },
561{ 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 +0000562
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000563{ 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 +0000564
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000565{ 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." },
566{ 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." },
567{ 0 , false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
Greg Clayton8b82f082011-04-12 05:54:46 +0000568};
569
Greg Clayton8b82f082011-04-12 05:54:46 +0000570bool
571ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000572{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000573 if (m_name_match_type == eNameMatchIgnore || process_name == nullptr)
Greg Clayton32e0a752011-03-30 18:16:51 +0000574 return true;
575 const char *match_name = m_match_info.GetName();
576 if (!match_name)
577 return true;
578
579 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
580}
581
582bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000583ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000584{
585 if (!NameMatches (proc_info.GetName()))
586 return false;
587
588 if (m_match_info.ProcessIDIsValid() &&
589 m_match_info.GetProcessID() != proc_info.GetProcessID())
590 return false;
591
592 if (m_match_info.ParentProcessIDIsValid() &&
593 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
594 return false;
595
Greg Clayton8b82f082011-04-12 05:54:46 +0000596 if (m_match_info.UserIDIsValid () &&
597 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000598 return false;
599
Greg Clayton8b82f082011-04-12 05:54:46 +0000600 if (m_match_info.GroupIDIsValid () &&
601 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000602 return false;
603
604 if (m_match_info.EffectiveUserIDIsValid () &&
605 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
606 return false;
607
608 if (m_match_info.EffectiveGroupIDIsValid () &&
609 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
610 return false;
611
612 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000613 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000614 return false;
615 return true;
616}
617
618bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000619ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000620{
621 if (m_name_match_type != eNameMatchIgnore)
622 return false;
623
624 if (m_match_info.ProcessIDIsValid())
625 return false;
626
627 if (m_match_info.ParentProcessIDIsValid())
628 return false;
629
Greg Clayton8b82f082011-04-12 05:54:46 +0000630 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000631 return false;
632
Greg Clayton8b82f082011-04-12 05:54:46 +0000633 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000634 return false;
635
636 if (m_match_info.EffectiveUserIDIsValid ())
637 return false;
638
639 if (m_match_info.EffectiveGroupIDIsValid ())
640 return false;
641
642 if (m_match_info.GetArchitecture().IsValid())
643 return false;
644
645 if (m_match_all_users)
646 return false;
647
648 return true;
Greg Clayton32e0a752011-03-30 18:16:51 +0000649}
650
651void
Greg Clayton8b82f082011-04-12 05:54:46 +0000652ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000653{
654 m_match_info.Clear();
655 m_name_match_type = eNameMatchIgnore;
656 m_match_all_users = false;
657}
Greg Clayton58be07b2011-01-07 06:08:19 +0000658
Greg Claytonc3776bf2012-02-09 06:16:32 +0000659ProcessSP
Zachary Turner7529df92015-09-01 20:02:29 +0000660Process::FindPlugin (lldb::TargetSP target_sp, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000661{
Greg Clayton949e8222013-01-16 17:29:04 +0000662 static uint32_t g_process_unique_id = 0;
663
Greg Claytonc3776bf2012-02-09 06:16:32 +0000664 ProcessSP process_sp;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000665 ProcessCreateInstance create_callback = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000666 if (plugin_name)
667 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000668 ConstString const_plugin_name(plugin_name);
669 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000670 if (create_callback)
671 {
Zachary Turner7529df92015-09-01 20:02:29 +0000672 process_sp = create_callback(target_sp, listener, crash_file_path);
Greg Claytonc3776bf2012-02-09 06:16:32 +0000673 if (process_sp)
674 {
Zachary Turner7529df92015-09-01 20:02:29 +0000675 if (process_sp->CanDebug(target_sp, true))
Greg Clayton949e8222013-01-16 17:29:04 +0000676 {
677 process_sp->m_process_unique_id = ++g_process_unique_id;
678 }
679 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000680 process_sp.reset();
681 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000682 }
683 }
684 else
685 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000686 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000687 {
Zachary Turner7529df92015-09-01 20:02:29 +0000688 process_sp = create_callback(target_sp, listener, crash_file_path);
Greg Claytonc3776bf2012-02-09 06:16:32 +0000689 if (process_sp)
690 {
Zachary Turner7529df92015-09-01 20:02:29 +0000691 if (process_sp->CanDebug(target_sp, false))
Greg Clayton949e8222013-01-16 17:29:04 +0000692 {
693 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000694 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000695 }
696 else
697 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000698 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000699 }
700 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000701 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000702}
703
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000704ConstString &
705Process::GetStaticBroadcasterClass ()
706{
707 static ConstString class_name ("lldb.process");
708 return class_name;
709}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710
Zachary Turner7529df92015-09-01 20:02:29 +0000711Process::Process(lldb::TargetSP target_sp, Listener &listener) :
712 Process(target_sp, listener, UnixSignals::Create(HostInfo::GetArchitecture()))
Todd Fiala4ceced32014-08-29 17:35:57 +0000713{
714 // This constructor just delegates to the full Process constructor,
715 // defaulting to using the Host's UnixSignals.
716}
717
Zachary Turner7529df92015-09-01 20:02:29 +0000718Process::Process(lldb::TargetSP target_sp, Listener &listener, const UnixSignalsSP &unix_signals_sp) :
Greg Clayton332e8b12015-01-13 21:13:08 +0000719 ProcessProperties (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000720 UserID (LLDB_INVALID_PROCESS_ID),
Zachary Turner7529df92015-09-01 20:02:29 +0000721 Broadcaster (&(target_sp->GetDebugger()), Process::GetStaticBroadcasterClass().AsCString()),
722 m_target_sp (target_sp),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 m_public_state (eStateUnloaded),
724 m_private_state (eStateUnloaded),
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000725 m_private_state_broadcaster(nullptr, "lldb.process.internal_state_broadcaster"),
726 m_private_state_control_broadcaster(nullptr, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727 m_private_state_listener ("lldb.process.internal_state_listener"),
728 m_private_state_control_wait(),
Jim Ingham4b536182011-08-09 02:12:22 +0000729 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +0000730 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +0000732 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733 m_exit_status (-1),
734 m_exit_string (),
Todd Fiala7b0917a2014-09-15 20:07:33 +0000735 m_exit_status_mutex(),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000736 m_thread_mutex (Mutex::eMutexTypeRecursive),
737 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +0000739 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +0000740 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +0000741 m_queue_list (this),
742 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000744 m_image_tokens (),
745 m_listener (listener),
746 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000747 m_dynamic_checkers_ap (),
Todd Fiala4ceced32014-08-29 17:35:57 +0000748 m_unix_signals_sp (unix_signals_sp),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000749 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000750 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000751 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000752 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Vince Harrondf3f00f2015-02-10 21:09:04 +0000753 m_stdin_forward (false),
Greg Clayton58be07b2011-01-07 06:08:19 +0000754 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000755 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000756 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
757 m_profile_data (),
Pavel Labath44464872015-05-27 12:40:32 +0000758 m_iohandler_sync (0),
Greg Claytond495c532011-05-17 03:37:42 +0000759 m_memory_cache (*this),
760 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000761 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000762 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +0000763 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +0000764 m_private_run_lock (),
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000765 m_stop_info_override_callback(nullptr),
Greg Claytonc00ca312015-04-02 18:44:58 +0000766 m_finalizing (false),
767 m_finalize_called (false),
Greg Claytonf9b57b92013-05-10 23:48:10 +0000768 m_clear_thread_plans_on_stop (false),
Greg Claytonc00ca312015-04-02 18:44:58 +0000769 m_force_next_event_delivery (false),
Jim Ingham0161b492013-02-09 01:29:05 +0000770 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +0000771 m_destroy_in_process (false),
Ewan Crawford90ff7912015-07-14 10:56:58 +0000772 m_can_interpret_function_calls(false),
Jason Molendaef7d6412015-08-06 03:27:10 +0000773 m_warnings_issued (),
Jason Molenda69b6b632013-03-05 03:33:59 +0000774 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000776 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000777
Greg Clayton5160ce52013-03-27 23:08:40 +0000778 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000780 log->Printf ("%p Process::Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000781
Todd Fiala4ceced32014-08-29 17:35:57 +0000782 if (!m_unix_signals_sp)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000783 m_unix_signals_sp = std::make_shared<UnixSignals>();
Todd Fiala4ceced32014-08-29 17:35:57 +0000784
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000785 SetEventName (eBroadcastBitStateChanged, "state-changed");
786 SetEventName (eBroadcastBitInterrupt, "interrupt");
787 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
788 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000789 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Chaoren Lin98d0a4b2015-07-14 01:09:28 +0000790
Greg Clayton35a4cc52012-10-29 20:52:08 +0000791 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
792 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
793 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
794
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795 listener.StartListeningForEvents (this,
796 eBroadcastBitStateChanged |
797 eBroadcastBitInterrupt |
798 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000799 eBroadcastBitSTDERR |
800 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000801
802 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000803 eBroadcastBitStateChanged |
804 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000805
806 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
807 eBroadcastInternalStateControlStop |
808 eBroadcastInternalStateControlPause |
809 eBroadcastInternalStateControlResume);
Todd Fiala4ceced32014-08-29 17:35:57 +0000810 // We need something valid here, even if just the default UnixSignalsSP.
811 assert (m_unix_signals_sp && "null m_unix_signals_sp after initialization");
Pavel Labathf2991482015-10-20 10:33:17 +0000812
813 // Allow the platform to override the default cache line size
814 OptionValueSP value_sp =
815 m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)->GetValue();
816 uint32_t platform_cache_line_size = target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
817 if (! value_sp->OptionWasSet() && platform_cache_line_size != 0)
818 value_sp->SetUInt64Value(platform_cache_line_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000819}
820
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000821Process::~Process()
822{
Greg Clayton5160ce52013-03-27 23:08:40 +0000823 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000824 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000825 log->Printf ("%p Process::~Process()", static_cast<void*>(this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000826 StopPrivateStateThread();
Zachary Turner39de3112014-09-09 20:54:56 +0000827
828 // ThreadList::Clear() will try to acquire this process's mutex, so
829 // explicitly clear the thread list here to ensure that the mutex
830 // is not destroyed before the thread list.
831 m_thread_list.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000832}
833
Greg Clayton67cc0632012-08-22 17:17:09 +0000834const ProcessPropertiesSP &
835Process::GetGlobalProperties()
836{
Greg Claytoncc2e27f2016-02-26 23:20:08 +0000837 // NOTE: intentional leak so we don't crash if global destructor chain gets
838 // called as other threads still use the result of this function
839 static ProcessPropertiesSP *g_settings_sp_ptr = nullptr;
Greg Clayton04df8ee2016-02-26 19:38:18 +0000840 static std::once_flag g_once_flag;
841 std::call_once(g_once_flag, []() {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000842 g_settings_sp_ptr = new ProcessPropertiesSP(new ProcessProperties(nullptr));
Greg Clayton04df8ee2016-02-26 19:38:18 +0000843 });
Greg Claytoncc2e27f2016-02-26 23:20:08 +0000844 return *g_settings_sp_ptr;
Greg Clayton67cc0632012-08-22 17:17:09 +0000845}
846
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000847void
848Process::Finalize()
849{
Greg Claytonc00ca312015-04-02 18:44:58 +0000850 m_finalizing = true;
851
Ilia Kc7efd562015-03-26 07:40:40 +0000852 // Destroy this process if needed
853 switch (GetPrivateState())
854 {
855 case eStateConnected:
856 case eStateAttaching:
857 case eStateLaunching:
858 case eStateStopped:
859 case eStateRunning:
860 case eStateStepping:
861 case eStateCrashed:
862 case eStateSuspended:
Jason Molendaede31932015-04-17 05:01:58 +0000863 Destroy(false);
Ilia Kc7efd562015-03-26 07:40:40 +0000864 break;
865
866 case eStateInvalid:
867 case eStateUnloaded:
868 case eStateDetached:
869 case eStateExited:
870 break;
871 }
Greg Claytone24c4ac2011-11-17 04:46:02 +0000872
Greg Clayton1ed54f52011-10-01 00:45:15 +0000873 // Clear our broadcaster before we proceed with destroying
874 Broadcaster::Clear();
875
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000876 // Do any cleanup needed prior to being destructed... Subclasses
877 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000878
879 // We need to destroy the loader before the derived Process class gets destroyed
880 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000881 m_dynamic_checkers_ap.reset();
882 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000883 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +0000884 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000885 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +0000886 m_jit_loaders_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +0000887 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000888 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +0000889 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +0000890 m_queue_list.Clear();
891 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +0000892 std::vector<Notifications> empty_notifications;
893 m_notifications.swap(empty_notifications);
894 m_image_tokens.clear();
895 m_memory_cache.Clear();
896 m_allocated_memory_cache.Clear();
897 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +0000898 m_instrumentation_runtimes.clear();
Greg Clayton894f82f2012-01-20 23:08:34 +0000899 m_next_event_action_ap.reset();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000900 m_stop_info_override_callback = nullptr;
Greg Clayton08765fa2015-05-28 03:24:30 +0000901 // Clear the last natural stop ID since it has a strong
902 // reference to this process
903 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
Greg Clayton35a4cc52012-10-29 20:52:08 +0000904//#ifdef LLDB_CONFIGURATION_DEBUG
905// StreamFile s(stdout, false);
906// EventSP event_sp;
907// while (m_private_state_listener.GetNextEvent(event_sp))
908// {
909// event_sp->Dump (&s);
910// s.EOL();
911// }
912//#endif
913 // We have to be very careful here as the m_private_state_listener might
914 // contain events that have ProcessSP values in them which can keep this
915 // process around forever. These events need to be cleared out.
916 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +0000917 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
918 m_public_run_lock.SetStopped();
919 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
920 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000921 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000922}
923
924void
925Process::RegisterNotificationCallbacks (const Notifications& callbacks)
926{
927 m_notifications.push_back(callbacks);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000928 if (callbacks.initialize != nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000929 callbacks.initialize (callbacks.baton, this);
930}
931
932bool
933Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
934{
935 std::vector<Notifications>::iterator pos, end = m_notifications.end();
936 for (pos = m_notifications.begin(); pos != end; ++pos)
937 {
938 if (pos->baton == callbacks.baton &&
939 pos->initialize == callbacks.initialize &&
940 pos->process_state_changed == callbacks.process_state_changed)
941 {
942 m_notifications.erase(pos);
943 return true;
944 }
945 }
946 return false;
947}
948
949void
950Process::SynchronouslyNotifyStateChanged (StateType state)
951{
952 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
953 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
954 {
955 if (notification_pos->process_state_changed)
956 notification_pos->process_state_changed (notification_pos->baton, this, state);
957 }
958}
959
960// FIXME: We need to do some work on events before the general Listener sees them.
961// For instance if we are continuing from a breakpoint, we need to ensure that we do
962// the little "insert real insn, step & stop" trick. But we can't do that when the
963// event is delivered by the broadcaster - since that is done on the thread that is
964// waiting for new events, so if we needed more than one event for our handling, we would
965// stall. So instead we do it when we fetch the event off of the queue.
966//
967
968StateType
969Process::GetNextEvent (EventSP &event_sp)
970{
971 StateType state = eStateInvalid;
972
973 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
974 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
975
976 return state;
977}
978
Pavel Labath44464872015-05-27 12:40:32 +0000979void
980Process::SyncIOHandler (uint32_t iohandler_id, uint64_t timeout_msec)
Todd Fialaa3b89e22014-08-12 14:33:19 +0000981{
Todd Fialaa3b89e22014-08-12 14:33:19 +0000982 // don't sync (potentially context switch) in case where there is no process IO
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +0000983 if (!m_process_input_reader)
Pavel Labath44464872015-05-27 12:40:32 +0000984 return;
Todd Fialaa3b89e22014-08-12 14:33:19 +0000985
Pavel Labath44464872015-05-27 12:40:32 +0000986 TimeValue timeout = TimeValue::Now();
987 timeout.OffsetWithMicroSeconds(timeout_msec*1000);
988 uint32_t new_iohandler_id = 0;
989 m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, new_iohandler_id, &timeout);
Todd Fialaa3b89e22014-08-12 14:33:19 +0000990
Pavel Labath44464872015-05-27 12:40:32 +0000991 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
992 if (log)
993 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 +0000994}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000995
996StateType
Greg Claytondc6224e2014-10-21 01:00:42 +0000997Process::WaitForProcessToStop (const TimeValue *timeout,
998 EventSP *event_sp_ptr,
999 bool wait_always,
1000 Listener *hijack_listener,
Pavel Labath19da1f12015-12-07 12:36:52 +00001001 Stream *stream,
1002 bool use_run_lock)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001003{
Jim Ingham4b536182011-08-09 02:12:22 +00001004 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1005 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1006 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001007 if (event_sp_ptr)
1008 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001009 StateType state = GetState();
1010 // If we are exited or detached, we won't ever get back to any
1011 // other valid state...
1012 if (state == eStateDetached || state == eStateExited)
1013 return state;
1014
Daniel Malea9e9919f2013-10-09 16:56:28 +00001015 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1016 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001017 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__,
1018 static_cast<const void*>(timeout));
Daniel Malea9e9919f2013-10-09 16:56:28 +00001019
1020 if (!wait_always &&
1021 StateIsStoppedState(state, true) &&
Jim Ingham5b4c5eb2015-04-22 17:48:24 +00001022 StateIsStoppedState(GetPrivateState(), true))
1023 {
Daniel Malea9e9919f2013-10-09 16:56:28 +00001024 if (log)
1025 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1026 __FUNCTION__);
Pavel Labath78521ef2015-03-06 10:52:47 +00001027 // We need to toggle the run lock as this won't get done in
1028 // SetPublicState() if the process is hijacked.
Pavel Labath19da1f12015-12-07 12:36:52 +00001029 if (hijack_listener && use_run_lock)
Pavel Labath78521ef2015-03-06 10:52:47 +00001030 m_public_run_lock.SetStopped();
Daniel Malea9e9919f2013-10-09 16:56:28 +00001031 return state;
1032 }
1033
Jim Ingham4b536182011-08-09 02:12:22 +00001034 while (state != eStateInvalid)
1035 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001036 EventSP event_sp;
Greg Clayton44d93782014-01-27 23:43:24 +00001037 state = WaitForStateChangedEvents (timeout, event_sp, hijack_listener);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001038 if (event_sp_ptr && event_sp)
1039 *event_sp_ptr = event_sp;
1040
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001041 bool pop_process_io_handler = hijack_listener != nullptr;
Greg Claytondc6224e2014-10-21 01:00:42 +00001042 Process::HandleProcessStateChangedEvent (event_sp, stream, pop_process_io_handler);
1043
Jim Ingham4b536182011-08-09 02:12:22 +00001044 switch (state)
1045 {
1046 case eStateCrashed:
1047 case eStateDetached:
1048 case eStateExited:
1049 case eStateUnloaded:
Greg Clayton44d93782014-01-27 23:43:24 +00001050 // We need to toggle the run lock as this won't get done in
1051 // SetPublicState() if the process is hijacked.
Pavel Labath19da1f12015-12-07 12:36:52 +00001052 if (hijack_listener && use_run_lock)
Greg Clayton44d93782014-01-27 23:43:24 +00001053 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001054 return state;
1055 case eStateStopped:
1056 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1057 continue;
1058 else
Greg Clayton44d93782014-01-27 23:43:24 +00001059 {
1060 // We need to toggle the run lock as this won't get done in
1061 // SetPublicState() if the process is hijacked.
Pavel Labath19da1f12015-12-07 12:36:52 +00001062 if (hijack_listener && use_run_lock)
Greg Clayton44d93782014-01-27 23:43:24 +00001063 m_public_run_lock.SetStopped();
Jim Ingham4b536182011-08-09 02:12:22 +00001064 return state;
Greg Clayton44d93782014-01-27 23:43:24 +00001065 }
Jim Ingham4b536182011-08-09 02:12:22 +00001066 default:
1067 continue;
1068 }
1069 }
1070 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071}
1072
Greg Claytondc6224e2014-10-21 01:00:42 +00001073bool
1074Process::HandleProcessStateChangedEvent (const EventSP &event_sp,
1075 Stream *stream,
1076 bool &pop_process_io_handler)
1077{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001078 const bool handle_pop = pop_process_io_handler;
Greg Claytondc6224e2014-10-21 01:00:42 +00001079
1080 pop_process_io_handler = false;
1081 ProcessSP process_sp = Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1082
1083 if (!process_sp)
1084 return false;
1085
1086 StateType event_state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1087 if (event_state == eStateInvalid)
1088 return false;
1089
1090 switch (event_state)
1091 {
1092 case eStateInvalid:
1093 case eStateUnloaded:
Greg Claytondc6224e2014-10-21 01:00:42 +00001094 case eStateAttaching:
1095 case eStateLaunching:
1096 case eStateStepping:
1097 case eStateDetached:
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001098 if (stream)
1099 stream->Printf("Process %" PRIu64 " %s\n",
1100 process_sp->GetID(),
1101 StateAsCString (event_state));
1102 if (event_state == eStateDetached)
1103 pop_process_io_handler = true;
Greg Claytondc6224e2014-10-21 01:00:42 +00001104 break;
1105
Stephane Sezerf2ef94e2014-12-13 05:23:51 +00001106 case eStateConnected:
Greg Claytondc6224e2014-10-21 01:00:42 +00001107 case eStateRunning:
1108 // Don't be chatty when we run...
1109 break;
1110
1111 case eStateExited:
1112 if (stream)
1113 process_sp->GetStatus(*stream);
1114 pop_process_io_handler = true;
1115 break;
1116
1117 case eStateStopped:
1118 case eStateCrashed:
1119 case eStateSuspended:
1120 // Make sure the program hasn't been auto-restarted:
1121 if (Process::ProcessEventData::GetRestartedFromEvent (event_sp.get()))
1122 {
1123 if (stream)
1124 {
1125 size_t num_reasons = Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
1126 if (num_reasons > 0)
1127 {
1128 // FIXME: Do we want to report this, or would that just be annoyingly chatty?
1129 if (num_reasons == 1)
1130 {
1131 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), 0);
1132 stream->Printf ("Process %" PRIu64 " stopped and restarted: %s\n",
1133 process_sp->GetID(),
1134 reason ? reason : "<UNKNOWN REASON>");
1135 }
1136 else
1137 {
1138 stream->Printf ("Process %" PRIu64 " stopped and restarted, reasons:\n",
1139 process_sp->GetID());
1140
1141
1142 for (size_t i = 0; i < num_reasons; i++)
1143 {
1144 const char *reason = Process::ProcessEventData::GetRestartedReasonAtIndex (event_sp.get(), i);
1145 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
1146 }
1147 }
1148 }
1149 }
1150 }
1151 else
1152 {
1153 // Lock the thread list so it doesn't change on us, this is the scope for the locker:
1154 {
1155 ThreadList &thread_list = process_sp->GetThreadList();
1156 Mutex::Locker locker (thread_list.GetMutex());
1157
1158 ThreadSP curr_thread (thread_list.GetSelectedThread());
1159 ThreadSP thread;
1160 StopReason curr_thread_stop_reason = eStopReasonInvalid;
1161 if (curr_thread)
1162 curr_thread_stop_reason = curr_thread->GetStopReason();
1163 if (!curr_thread ||
1164 !curr_thread->IsValid() ||
1165 curr_thread_stop_reason == eStopReasonInvalid ||
1166 curr_thread_stop_reason == eStopReasonNone)
1167 {
1168 // Prefer a thread that has just completed its plan over another thread as current thread.
1169 ThreadSP plan_thread;
1170 ThreadSP other_thread;
Jim Inghamce400d92015-07-08 00:06:30 +00001171
Greg Claytondc6224e2014-10-21 01:00:42 +00001172 const size_t num_threads = thread_list.GetSize();
1173 size_t i;
1174 for (i = 0; i < num_threads; ++i)
1175 {
1176 thread = thread_list.GetThreadAtIndex(i);
1177 StopReason thread_stop_reason = thread->GetStopReason();
1178 switch (thread_stop_reason)
1179 {
1180 case eStopReasonInvalid:
1181 case eStopReasonNone:
1182 break;
1183
Jim Inghamce400d92015-07-08 00:06:30 +00001184 case eStopReasonSignal:
1185 {
1186 // Don't select a signal thread if we weren't going to stop at that
1187 // signal. We have to have had another reason for stopping here, and
1188 // the user doesn't want to see this thread.
1189 uint64_t signo = thread->GetStopInfo()->GetValue();
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001190 if (process_sp->GetUnixSignals()->GetShouldStop(signo))
Jim Inghamce400d92015-07-08 00:06:30 +00001191 {
1192 if (!other_thread)
1193 other_thread = thread;
1194 }
1195 break;
1196 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001197 case eStopReasonTrace:
1198 case eStopReasonBreakpoint:
1199 case eStopReasonWatchpoint:
Greg Claytondc6224e2014-10-21 01:00:42 +00001200 case eStopReasonException:
1201 case eStopReasonExec:
1202 case eStopReasonThreadExiting:
1203 case eStopReasonInstrumentation:
1204 if (!other_thread)
1205 other_thread = thread;
1206 break;
1207 case eStopReasonPlanComplete:
1208 if (!plan_thread)
1209 plan_thread = thread;
1210 break;
1211 }
1212 }
1213 if (plan_thread)
1214 thread_list.SetSelectedThreadByID (plan_thread->GetID());
1215 else if (other_thread)
1216 thread_list.SetSelectedThreadByID (other_thread->GetID());
1217 else
1218 {
1219 if (curr_thread && curr_thread->IsValid())
1220 thread = curr_thread;
1221 else
1222 thread = thread_list.GetThreadAtIndex(0);
1223
1224 if (thread)
1225 thread_list.SetSelectedThreadByID (thread->GetID());
1226 }
1227 }
1228 }
1229 // Drop the ThreadList mutex by here, since GetThreadStatus below might have to run code,
1230 // e.g. for Data formatters, and if we hold the ThreadList mutex, then the process is going to
1231 // have a hard time restarting the process.
1232 if (stream)
1233 {
1234 Debugger &debugger = process_sp->GetTarget().GetDebugger();
1235 if (debugger.GetTargetList().GetSelectedTarget().get() == &process_sp->GetTarget())
1236 {
1237 const bool only_threads_with_stop_reason = true;
1238 const uint32_t start_frame = 0;
1239 const uint32_t num_frames = 1;
1240 const uint32_t num_frames_with_source = 1;
1241 process_sp->GetStatus(*stream);
1242 process_sp->GetThreadStatus (*stream,
1243 only_threads_with_stop_reason,
1244 start_frame,
1245 num_frames,
1246 num_frames_with_source);
1247 }
1248 else
1249 {
1250 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(process_sp->GetTarget().shared_from_this());
1251 if (target_idx != UINT32_MAX)
1252 stream->Printf ("Target %d: (", target_idx);
1253 else
1254 stream->Printf ("Target <unknown index>: (");
1255 process_sp->GetTarget().Dump (stream, eDescriptionLevelBrief);
1256 stream->Printf (") stopped.\n");
1257 }
1258 }
1259
1260 // Pop the process IO handler
1261 pop_process_io_handler = true;
1262 }
1263 break;
1264 }
1265
1266 if (handle_pop && pop_process_io_handler)
1267 process_sp->PopProcessIOHandler();
1268
1269 return true;
1270}
1271
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001272StateType
Eugene Zelenko8f30a652015-10-23 18:39:37 +00001273Process::WaitForState(const TimeValue *timeout,
1274 const StateType *match_states,
1275 const uint32_t num_match_states)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001276{
1277 EventSP event_sp;
Greg Clayton05faeb72010-10-07 04:19:01 +00001278 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001279 while (state != eStateInvalid)
1280 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001281 // If we are exited or detached, we won't ever get back to any
1282 // other valid state...
1283 if (state == eStateDetached || state == eStateExited)
1284 return state;
1285
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001286 state = WaitForStateChangedEvents(timeout, event_sp, nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001287
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001288 for (uint32_t i = 0; i < num_match_states; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001289 {
1290 if (match_states[i] == state)
1291 return state;
1292 }
1293 }
1294 return state;
1295}
1296
Jim Ingham30f9b212010-10-11 23:53:14 +00001297bool
1298Process::HijackProcessEvents (Listener *listener)
1299{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001300 if (listener != nullptr)
Jim Ingham30f9b212010-10-11 23:53:14 +00001301 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001302 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001303 }
1304 else
1305 return false;
1306}
1307
1308void
1309Process::RestoreProcessEvents ()
1310{
1311 RestoreBroadcaster();
1312}
1313
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001314StateType
Greg Clayton44d93782014-01-27 23:43:24 +00001315Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp, Listener *hijack_listener)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001316{
Greg Clayton5160ce52013-03-27 23:08:40 +00001317 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001318
1319 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001320 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1321 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001322
Greg Clayton44d93782014-01-27 23:43:24 +00001323 Listener *listener = hijack_listener;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001324 if (listener == nullptr)
Greg Clayton44d93782014-01-27 23:43:24 +00001325 listener = &m_listener;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001326
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001327 StateType state = eStateInvalid;
Greg Clayton44d93782014-01-27 23:43:24 +00001328 if (listener->WaitForEventForBroadcasterWithType (timeout,
1329 this,
1330 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
1331 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001332 {
1333 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1334 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1335 else if (log)
1336 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1337 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001338
1339 if (log)
1340 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001341 __FUNCTION__, static_cast<const void*>(timeout),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001342 StateAsCString(state));
1343 return state;
1344}
1345
1346Event *
1347Process::PeekAtStateChangedEvents ()
1348{
Greg Clayton5160ce52013-03-27 23:08:40 +00001349 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001350
1351 if (log)
1352 log->Printf ("Process::%s...", __FUNCTION__);
1353
1354 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001355 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1356 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001357 if (log)
1358 {
1359 if (event_ptr)
1360 {
1361 log->Printf ("Process::%s (event_ptr) => %s",
1362 __FUNCTION__,
1363 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1364 }
1365 else
1366 {
1367 log->Printf ("Process::%s no events found",
1368 __FUNCTION__);
1369 }
1370 }
1371 return event_ptr;
1372}
1373
1374StateType
1375Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1376{
Greg Clayton5160ce52013-03-27 23:08:40 +00001377 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001378
1379 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001380 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1381 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001382
1383 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001384 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1385 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001386 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001387 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001388 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1389 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001390
1391 // This is a bit of a hack, but when we wait here we could very well return
1392 // to the command-line, and that could disable the log, which would render the
1393 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001394 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001395 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1396 __FUNCTION__, static_cast<const void *>(timeout),
1397 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001398 return state;
1399}
1400
1401bool
1402Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1403{
Greg Clayton5160ce52013-03-27 23:08:40 +00001404 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405
1406 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001407 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__,
1408 static_cast<const void*>(timeout));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001409
1410 if (control_only)
1411 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1412 else
1413 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1414}
1415
1416bool
1417Process::IsRunning () const
1418{
1419 return StateIsRunningState (m_public_state.GetValue());
1420}
1421
1422int
1423Process::GetExitStatus ()
1424{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001425 Mutex::Locker locker (m_exit_status_mutex);
1426
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001427 if (m_public_state.GetValue() == eStateExited)
1428 return m_exit_status;
1429 return -1;
1430}
1431
1432const char *
1433Process::GetExitDescription ()
1434{
Todd Fiala7b0917a2014-09-15 20:07:33 +00001435 Mutex::Locker locker (m_exit_status_mutex);
1436
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1438 return m_exit_string.c_str();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001439 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001440}
1441
Greg Clayton6779606a2011-01-22 23:43:18 +00001442bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001443Process::SetExitStatus (int status, const char *cstr)
1444{
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001445 // Use a mutex to protect setting the exit status.
1446 Mutex::Locker locker (m_exit_status_mutex);
1447
Greg Clayton5160ce52013-03-27 23:08:40 +00001448 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001449 if (log)
1450 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1451 status, status,
1452 cstr ? "\"" : "",
1453 cstr ? cstr : "NULL",
1454 cstr ? "\"" : "");
1455
Greg Clayton6779606a2011-01-22 23:43:18 +00001456 // We were already in the exited state
1457 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001458 {
Greg Clayton385d6032011-01-26 23:47:29 +00001459 if (log)
1460 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001461 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001462 }
Todd Fiala7b0917a2014-09-15 20:07:33 +00001463
Greg Clayton81e2b6b2015-06-01 23:14:09 +00001464 m_exit_status = status;
1465 if (cstr)
1466 m_exit_string = cstr;
1467 else
1468 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001469
Pavel Labatha9a43372015-09-03 09:30:17 +00001470 // When we exit, we don't need the input reader anymore
Greg Clayton5df78fa2015-05-23 03:54:53 +00001471 if (m_process_input_reader)
1472 {
1473 m_process_input_reader->SetIsDone(true);
1474 m_process_input_reader->Cancel();
1475 m_process_input_reader.reset();
1476 }
Greg Clayton10177aa2010-12-08 05:08:21 +00001477
Greg Clayton08765fa2015-05-28 03:24:30 +00001478 // Clear the last natural stop ID since it has a strong
1479 // reference to this process
1480 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1481
Greg Clayton6779606a2011-01-22 23:43:18 +00001482 SetPrivateState (eStateExited);
Greg Clayton5df78fa2015-05-23 03:54:53 +00001483
1484 // Allow subclasses to do some cleanup
1485 DidExit ();
1486
Greg Clayton6779606a2011-01-22 23:43:18 +00001487 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001488}
1489
Jason Molendaa814f702015-11-05 23:03:44 +00001490bool
1491Process::IsAlive ()
1492{
1493 switch (m_private_state.GetValue())
1494 {
Jason Molendaa814f702015-11-05 23:03:44 +00001495 case eStateConnected:
1496 case eStateAttaching:
1497 case eStateLaunching:
1498 case eStateStopped:
1499 case eStateRunning:
1500 case eStateStepping:
1501 case eStateCrashed:
1502 case eStateSuspended:
1503 return true;
Davide Italiano13fe2a92016-01-19 22:47:51 +00001504 default:
1505 return false;
Jason Molendaa814f702015-11-05 23:03:44 +00001506 }
1507}
1508
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001509// This static callback can be used to watch for local child processes on
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001510// the current host. The child process exits, the process will be
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001511// found in the global target list (we want to be completely sure that the
1512// lldb_private::Process doesn't go away before we can deliver the signal.
1513bool
Greg Claytone4e45922011-11-16 05:37:56 +00001514Process::SetProcessExitStatus (void *callback_baton,
1515 lldb::pid_t pid,
1516 bool exited,
1517 int signo, // Zero for no signal
1518 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001519)
1520{
Greg Clayton5160ce52013-03-27 23:08:40 +00001521 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001522 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001523 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001524 callback_baton,
1525 pid,
1526 exited,
1527 signo,
1528 exit_status);
1529
1530 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001531 {
Greg Clayton66111032010-06-23 01:19:29 +00001532 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001533 if (target_sp)
1534 {
1535 ProcessSP process_sp (target_sp->GetProcessSP());
1536 if (process_sp)
1537 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001538 const char *signal_cstr = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001539 if (signo)
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001540 signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001541
1542 process_sp->SetExitStatus (exit_status, signal_cstr);
1543 }
1544 }
1545 return true;
1546 }
1547 return false;
1548}
1549
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001550void
1551Process::UpdateThreadListIfNeeded ()
1552{
1553 const uint32_t stop_id = GetStopID();
1554 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1555 {
Greg Clayton2637f822011-11-17 01:23:07 +00001556 const StateType state = GetPrivateState();
1557 if (StateIsStoppedState (state, true))
1558 {
1559 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001560 // m_thread_list does have its own mutex, but we need to
1561 // hold onto the mutex between the call to UpdateThreadList(...)
1562 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001563 ThreadList &old_thread_list = m_thread_list;
1564 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001565 ThreadList new_thread_list(this);
1566 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001567 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001568 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001569 {
Jim Ingham09437922013-03-01 20:04:25 +00001570 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1571 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1572 // shutting us down, causing a deadlock.
Pavel Labath862432c2015-11-03 16:05:18 +00001573 OperatingSystem *os = GetOperatingSystem ();
1574 if (os && !m_destroy_in_process)
Jim Ingham09437922013-03-01 20:04:25 +00001575 {
Pavel Labath862432c2015-11-03 16:05:18 +00001576 // Clear any old backing threads where memory threads might have been
1577 // backed by actual threads from the lldb_private::Process subclass
1578 size_t num_old_threads = old_thread_list.GetSize(false);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001579 for (size_t i = 0; i < num_old_threads; ++i)
Pavel Labath862432c2015-11-03 16:05:18 +00001580 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001581
Pavel Labath862432c2015-11-03 16:05:18 +00001582 // Turn off dynamic types to ensure we don't run any expressions. Objective C
1583 // can run an expression to determine if a SBValue is a dynamic type or not
1584 // and we need to avoid this. OperatingSystem plug-ins can't run expressions
1585 // that require running code...
Greg Clayton15484402015-05-15 18:40:24 +00001586
Pavel Labath862432c2015-11-03 16:05:18 +00001587 Target &target = GetTarget();
1588 const lldb::DynamicValueType saved_prefer_dynamic = target.GetPreferDynamicValue ();
1589 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1590 target.SetPreferDynamicValue(lldb::eNoDynamicValues);
Greg Clayton15484402015-05-15 18:40:24 +00001591
Pavel Labath862432c2015-11-03 16:05:18 +00001592 // Now let the OperatingSystem plug-in update the thread list
Greg Clayton15484402015-05-15 18:40:24 +00001593
Pavel Labath862432c2015-11-03 16:05:18 +00001594 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1595 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1596 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 +00001597
Pavel Labath862432c2015-11-03 16:05:18 +00001598 if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1599 target.SetPreferDynamicValue(saved_prefer_dynamic);
1600 }
1601 else
1602 {
1603 // No OS plug-in, the new thread list is the same as the real thread list
1604 new_thread_list = real_thread_list;
Jim Ingham09437922013-03-01 20:04:25 +00001605 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001606
1607 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001608 m_thread_list.Update (new_thread_list);
1609 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001610
Jason Molenda4ff13262013-11-20 00:31:38 +00001611 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1612 {
1613 // Clear any extended threads that we may have accumulated previously
1614 m_extended_thread_list.Clear();
1615 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001616
1617 m_queue_list.Clear();
1618 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001619 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001620 }
Greg Clayton2637f822011-11-17 01:23:07 +00001621 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001622 }
1623}
1624
Jason Molenda5e8dce42013-12-13 00:29:16 +00001625void
1626Process::UpdateQueueListIfNeeded ()
1627{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001628 if (m_system_runtime_ap)
Jason Molenda5e8dce42013-12-13 00:29:16 +00001629 {
1630 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1631 {
1632 const StateType state = GetPrivateState();
1633 if (StateIsStoppedState (state, true))
1634 {
1635 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1636 m_queue_list_stop_id = GetLastNaturalStopID();
1637 }
1638 }
1639 }
1640}
1641
Greg Claytona4d87472013-01-18 23:41:08 +00001642ThreadSP
1643Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1644{
1645 OperatingSystem *os = GetOperatingSystem ();
1646 if (os)
1647 return os->CreateThread(tid, context);
1648 return ThreadSP();
1649}
1650
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001651uint32_t
1652Process::GetNextThreadIndexID (uint64_t thread_id)
1653{
1654 return AssignIndexIDToThread(thread_id);
1655}
1656
1657bool
1658Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1659{
Eugene Zelenko8f30a652015-10-23 18:39:37 +00001660 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 +00001661}
1662
1663uint32_t
1664Process::AssignIndexIDToThread(uint64_t thread_id)
1665{
1666 uint32_t result = 0;
1667 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1668 if (iterator == m_thread_id_to_index_id_map.end())
1669 {
1670 result = ++m_thread_index_id;
1671 m_thread_id_to_index_id_map[thread_id] = result;
1672 }
1673 else
1674 {
1675 result = iterator->second;
1676 }
1677
1678 return result;
1679}
1680
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001681StateType
1682Process::GetState()
1683{
1684 // If any other threads access this we will need a mutex for it
1685 return m_public_state.GetValue ();
1686}
1687
Greg Claytondc6224e2014-10-21 01:00:42 +00001688bool
1689Process::StateChangedIsExternallyHijacked()
1690{
1691 if (IsHijackedForEvent(eBroadcastBitStateChanged))
1692 {
1693 if (strcmp(m_hijacking_listeners.back()->GetName(), "lldb.Process.ResumeSynchronous.hijack"))
1694 return true;
1695 }
1696 return false;
1697}
1698
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001699void
Jim Ingham221d51c2013-05-08 00:35:16 +00001700Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001701{
Greg Clayton5160ce52013-03-27 23:08:40 +00001702 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001703 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001704 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001705 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001706 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001707
1708 // On the transition from Run to Stopped, we unlock the writer end of the
1709 // run lock. The lock gets locked in Resume, which is the public API
1710 // to tell the program to run.
Greg Claytondc6224e2014-10-21 01:00:42 +00001711 if (!StateChangedIsExternallyHijacked())
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001712 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001713 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001714 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001715 if (log)
1716 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001717 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001718 }
1719 else
1720 {
1721 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1722 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001723 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001724 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001725 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001726 {
1727 if (log)
1728 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001729 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001730 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001731 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001732 }
1733 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001734}
1735
Jim Ingham3b8285d2012-04-19 01:40:33 +00001736Error
1737Process::Resume ()
1738{
Greg Clayton5160ce52013-03-27 23:08:40 +00001739 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001740 if (log)
1741 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001742 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001743 {
1744 Error error("Resume request failed - process still running.");
1745 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001746 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001747 return error;
1748 }
1749 return PrivateResume();
1750}
1751
Greg Claytondc6224e2014-10-21 01:00:42 +00001752Error
1753Process::ResumeSynchronous (Stream *stream)
1754{
1755 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1756 if (log)
1757 log->Printf("Process::ResumeSynchronous -- locking run lock");
1758 if (!m_public_run_lock.TrySetRunning())
1759 {
1760 Error error("Resume request failed - process still running.");
1761 if (log)
1762 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
1763 return error;
1764 }
1765
1766 ListenerSP listener_sp (new Listener("lldb.Process.ResumeSynchronous.hijack"));
1767 HijackProcessEvents(listener_sp.get());
1768
1769 Error error = PrivateResume();
Ilia Kd8c14752015-04-30 13:10:32 +00001770 if (error.Success())
1771 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001772 StateType state = WaitForProcessToStop(nullptr, nullptr, true, listener_sp.get(), stream);
Ilia Kd8c14752015-04-30 13:10:32 +00001773 const bool must_be_alive = false; // eStateExited is ok, so this must be false
1774 if (!StateIsStoppedState(state, must_be_alive))
1775 error.SetErrorStringWithFormat("process not in stopped state after synchronous resume: %s", StateAsCString(state));
1776 }
Greg Claytondc6224e2014-10-21 01:00:42 +00001777
1778 // Undo the hijacking of process events...
1779 RestoreProcessEvents();
1780
Greg Claytondc6224e2014-10-21 01:00:42 +00001781 return error;
1782}
1783
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001784StateType
1785Process::GetPrivateState ()
1786{
1787 return m_private_state.GetValue();
1788}
1789
1790void
1791Process::SetPrivateState (StateType new_state)
1792{
Greg Claytonfb8b37a2014-07-14 23:09:29 +00001793 if (m_finalize_called)
1794 return;
1795
Greg Clayton5160ce52013-03-27 23:08:40 +00001796 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001797 bool state_changed = false;
1798
1799 if (log)
1800 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1801
Andrew Kaylor29d65742013-05-10 17:19:04 +00001802 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803 Mutex::Locker locker(m_private_state.GetMutex());
1804
1805 const StateType old_state = m_private_state.GetValueNoLock ();
1806 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001807
Greg Claytonaa49c832013-05-03 22:25:56 +00001808 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1809 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1810 if (old_state_is_stopped != new_state_is_stopped)
1811 {
1812 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001813 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001814 else
Ed Maste64fad602013-07-29 20:58:06 +00001815 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001816 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001817
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001818 if (state_changed)
1819 {
1820 m_private_state.SetValueNoLock (new_state);
Ilia K38810f42015-05-20 10:15:47 +00001821 EventSP event_sp (new Event (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state)));
Greg Clayton2637f822011-11-17 01:23:07 +00001822 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001823 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001824 // Note, this currently assumes that all threads in the list
1825 // stop when the process stops. In the future we will want to
1826 // support a debugging model where some threads continue to run
1827 // while others are stopped. When that happens we will either need
1828 // a way for the thread list to identify which threads are stopping
1829 // or create a special thread list containing only threads which
1830 // actually stopped.
1831 //
1832 // The process plugin is responsible for managing the actual
1833 // behavior of the threads and should have stopped any threads
1834 // that are going to stop before we get here.
1835 m_thread_list.DidStop();
1836
Jim Ingham4b536182011-08-09 02:12:22 +00001837 m_mod_id.BumpStopID();
Ilia K38810f42015-05-20 10:15:47 +00001838 if (!m_mod_id.IsLastResumeForUserExpression())
1839 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
Greg Clayton58be07b2011-01-07 06:08:19 +00001840 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001841 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001842 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001843 }
Ilia K38810f42015-05-20 10:15:47 +00001844
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001845 // Use our target to get a shared pointer to ourselves...
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001846 if (m_finalize_called && !PrivateStateThreadIsValid())
Ilia K38810f42015-05-20 10:15:47 +00001847 BroadcastEvent (event_sp);
Greg Clayton35a4cc52012-10-29 20:52:08 +00001848 else
Ilia K38810f42015-05-20 10:15:47 +00001849 m_private_state_broadcaster.BroadcastEvent (event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001850 }
1851 else
1852 {
1853 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001854 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001855 }
1856}
1857
Jim Ingham0faa43f2011-11-08 03:00:11 +00001858void
1859Process::SetRunningUserExpression (bool on)
1860{
1861 m_mod_id.SetRunningUserExpression (on);
1862}
1863
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864addr_t
1865Process::GetImageInfoAddress()
1866{
1867 return LLDB_INVALID_ADDRESS;
1868}
1869
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001870const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001871Process::GetABI()
1872{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001873 if (!m_abi_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00001874 m_abi_sp = ABI::FindPlugin(GetTarget().GetArchitecture());
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001875 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001876}
1877
Jim Ingham22777012010-09-23 02:01:19 +00001878LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001879Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001880{
Greg Claytonc00ca312015-04-02 18:44:58 +00001881 if (m_finalizing)
1882 return nullptr;
1883
Jim Ingham22777012010-09-23 02:01:19 +00001884 LanguageRuntimeCollection::iterator pos;
1885 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001886 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001887 {
Jim Inghamab175242012-03-10 00:22:19 +00001888 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001889
Jim Inghamab175242012-03-10 00:22:19 +00001890 m_language_runtimes[language] = runtime_sp;
1891 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001892 }
1893 else
1894 return (*pos).second.get();
1895}
1896
1897CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001898Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001899{
Jim Inghamab175242012-03-10 00:22:19 +00001900 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001901 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
Jim Ingham22777012010-09-23 02:01:19 +00001902 return static_cast<CPPLanguageRuntime *> (runtime);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001903 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001904}
1905
1906ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001907Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001908{
Jim Inghamab175242012-03-10 00:22:19 +00001909 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001910 if (runtime != nullptr && runtime->GetLanguageType() == eLanguageTypeObjC)
Jim Ingham22777012010-09-23 02:01:19 +00001911 return static_cast<ObjCLanguageRuntime *> (runtime);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00001912 return nullptr;
Jim Ingham22777012010-09-23 02:01:19 +00001913}
1914
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001915bool
1916Process::IsPossibleDynamicValue (ValueObject& in_value)
1917{
Greg Claytonc00ca312015-04-02 18:44:58 +00001918 if (m_finalizing)
1919 return false;
1920
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001921 if (in_value.IsDynamic())
1922 return false;
1923 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1924
1925 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1926 {
1927 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1928 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1929 }
1930
1931 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1932 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1933 return true;
1934
1935 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1936 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1937}
1938
Zachary Turner93749ab2015-03-03 21:51:25 +00001939void
1940Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
1941{
1942 m_dynamic_checkers_ap.reset(dynamic_checkers);
1943}
1944
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001945BreakpointSiteList &
1946Process::GetBreakpointSiteList()
1947{
1948 return m_breakpoint_site_list;
1949}
1950
1951const BreakpointSiteList &
1952Process::GetBreakpointSiteList() const
1953{
1954 return m_breakpoint_site_list;
1955}
1956
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001957void
1958Process::DisableAllBreakpointSites ()
1959{
Greg Claytond8cf1a12013-06-12 00:46:38 +00001960 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1961// bp_site->SetEnabled(true);
1962 DisableBreakpointSite(bp_site);
1963 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001964}
1965
1966Error
1967Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1968{
1969 Error error (DisableBreakpointSiteByID (break_id));
1970
1971 if (error.Success())
1972 m_breakpoint_site_list.Remove(break_id);
1973
1974 return error;
1975}
1976
1977Error
1978Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1979{
1980 Error error;
1981 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1982 if (bp_site_sp)
1983 {
1984 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00001985 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001986 }
1987 else
1988 {
Daniel Malead01b2952012-11-29 21:49:15 +00001989 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001990 }
1991
1992 return error;
1993}
1994
1995Error
1996Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1997{
1998 Error error;
1999 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2000 if (bp_site_sp)
2001 {
2002 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002003 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002004 }
2005 else
2006 {
Daniel Malead01b2952012-11-29 21:49:15 +00002007 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002008 }
2009 return error;
2010}
2011
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002012lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002013Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002015 addr_t load_addr = LLDB_INVALID_ADDRESS;
2016
2017 bool show_error = true;
2018 switch (GetState())
2019 {
2020 case eStateInvalid:
2021 case eStateUnloaded:
2022 case eStateConnected:
2023 case eStateAttaching:
2024 case eStateLaunching:
2025 case eStateDetached:
2026 case eStateExited:
2027 show_error = false;
2028 break;
2029
2030 case eStateStopped:
2031 case eStateRunning:
2032 case eStateStepping:
2033 case eStateCrashed:
2034 case eStateSuspended:
2035 show_error = IsAlive();
2036 break;
2037 }
2038
2039 // Reset the IsIndirect flag here, in case the location changes from
2040 // pointing to a indirect symbol to a regular symbol.
2041 owner->SetIsIndirect (false);
2042
2043 if (owner->ShouldResolveIndirectFunctions())
2044 {
2045 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2046 if (symbol && symbol->IsIndirect())
2047 {
2048 Error error;
Greg Clayton358cf1e2015-06-25 21:46:34 +00002049 Address symbol_address = symbol->GetAddress();
2050 load_addr = ResolveIndirectFunction (&symbol_address, error);
Jim Ingham1460e4b2014-01-10 23:46:59 +00002051 if (!error.Success() && show_error)
2052 {
Zachary Turner7529df92015-09-01 20:02:29 +00002053 GetTarget().GetDebugger().GetErrorFile()->Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2054 symbol->GetLoadAddress(&GetTarget()),
2055 owner->GetBreakpoint().GetID(),
2056 owner->GetID(),
2057 error.AsCString() ? error.AsCString() : "unknown error");
Jim Ingham1460e4b2014-01-10 23:46:59 +00002058 return LLDB_INVALID_BREAK_ID;
2059 }
2060 Address resolved_address(load_addr);
Zachary Turner7529df92015-09-01 20:02:29 +00002061 load_addr = resolved_address.GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002062 owner->SetIsIndirect(true);
2063 }
2064 else
Zachary Turner7529df92015-09-01 20:02:29 +00002065 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002066 }
2067 else
Zachary Turner7529df92015-09-01 20:02:29 +00002068 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&GetTarget());
Jim Ingham1460e4b2014-01-10 23:46:59 +00002069
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002070 if (load_addr != LLDB_INVALID_ADDRESS)
2071 {
2072 BreakpointSiteSP bp_site_sp;
2073
2074 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2075 // create a new breakpoint site and add it.
2076
2077 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2078
2079 if (bp_site_sp)
2080 {
2081 bp_site_sp->AddOwner (owner);
2082 owner->SetBreakpointSite (bp_site_sp);
2083 return bp_site_sp->GetID();
2084 }
2085 else
2086 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002087 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002088 if (bp_site_sp)
2089 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002090 Error error = EnableBreakpointSite (bp_site_sp.get());
2091 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002092 {
2093 owner->SetBreakpointSite (bp_site_sp);
2094 return m_breakpoint_site_list.Add (bp_site_sp);
2095 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002096 else
2097 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002098 if (show_error)
2099 {
2100 // Report error for setting breakpoint...
Zachary Turner7529df92015-09-01 20:02:29 +00002101 GetTarget().GetDebugger().GetErrorFile()->Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2102 load_addr,
2103 owner->GetBreakpoint().GetID(),
2104 owner->GetID(),
2105 error.AsCString() ? error.AsCString() : "unknown error");
Greg Claytonfbb76342013-11-20 21:07:01 +00002106 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002107 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108 }
2109 }
2110 }
2111 // We failed to enable the breakpoint
2112 return LLDB_INVALID_BREAK_ID;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002113}
2114
2115void
2116Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2117{
2118 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2119 if (num_owners == 0)
2120 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002121 // Don't try to disable the site if we don't have a live process anymore.
2122 if (IsAlive())
2123 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002124 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2125 }
2126}
2127
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002128size_t
2129Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2130{
2131 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002132 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002133
Jim Ingham20c77192011-06-29 19:42:28 +00002134 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002135 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002136 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2137 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002139 addr_t intersect_addr;
2140 size_t intersect_size;
2141 size_t opcode_offset;
2142 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002143 {
2144 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2145 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002146 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002147 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002148 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002149 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002150 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002151 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002152 }
2153 return bytes_removed;
2154}
2155
Greg Claytonded470d2011-03-19 01:12:21 +00002156size_t
2157Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2158{
Zachary Turner7529df92015-09-01 20:02:29 +00002159 PlatformSP platform_sp (GetTarget().GetPlatform());
Greg Claytonded470d2011-03-19 01:12:21 +00002160 if (platform_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00002161 return platform_sp->GetSoftwareBreakpointTrapOpcode (GetTarget(), bp_site);
Greg Claytonded470d2011-03-19 01:12:21 +00002162 return 0;
2163}
2164
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002165Error
2166Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2167{
2168 Error error;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002169 assert(bp_site != nullptr);
Greg Clayton5160ce52013-03-27 23:08:40 +00002170 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002171 const addr_t bp_addr = bp_site->GetLoadAddress();
2172 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002173 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002174 if (bp_site->IsEnabled())
2175 {
2176 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002177 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 +00002178 return error;
2179 }
2180
2181 if (bp_addr == LLDB_INVALID_ADDRESS)
2182 {
2183 error.SetErrorString("BreakpointSite contains an invalid load address.");
2184 return error;
2185 }
2186 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2187 // trap for the breakpoint site
2188 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2189
2190 if (bp_opcode_size == 0)
2191 {
Daniel Malead01b2952012-11-29 21:49:15 +00002192 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002193 }
2194 else
2195 {
2196 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2197
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002198 if (bp_opcode_bytes == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002199 {
2200 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2201 return error;
2202 }
2203
2204 // Save the original opcode by reading it
2205 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2206 {
2207 // Write a software breakpoint in place of the original opcode
2208 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2209 {
2210 uint8_t verify_bp_opcode_bytes[64];
2211 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2212 {
2213 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2214 {
2215 bp_site->SetEnabled(true);
2216 bp_site->SetType (BreakpointSite::eSoftware);
2217 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002218 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002219 bp_site->GetID(),
2220 (uint64_t)bp_addr);
2221 }
2222 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002223 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002224 }
2225 else
2226 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2227 }
2228 else
2229 error.SetErrorString("Unable to write breakpoint trap to memory.");
2230 }
2231 else
2232 error.SetErrorString("Unable to read memory at breakpoint address.");
2233 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002234 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002235 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002236 bp_site->GetID(),
2237 (uint64_t)bp_addr,
2238 error.AsCString());
2239 return error;
2240}
2241
2242Error
2243Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2244{
2245 Error error;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002246 assert(bp_site != nullptr);
Greg Clayton5160ce52013-03-27 23:08:40 +00002247 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002248 addr_t bp_addr = bp_site->GetLoadAddress();
2249 lldb::user_id_t breakID = bp_site->GetID();
2250 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002251 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002252
2253 if (bp_site->IsHardware())
2254 {
2255 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2256 }
2257 else if (bp_site->IsEnabled())
2258 {
2259 const size_t break_op_size = bp_site->GetByteSize();
2260 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2261 if (break_op_size > 0)
2262 {
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00002263 // Clear a software breakpoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002264 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002265 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266 bool break_op_found = false;
2267
2268 // Read the breakpoint opcode
2269 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2270 {
2271 bool verify = false;
Bruce Mitchener58ef3912015-06-18 05:27:05 +00002272 // Make sure the breakpoint opcode exists at this address
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002273 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2274 {
2275 break_op_found = true;
2276 // We found a valid breakpoint opcode at this address, now restore
2277 // the saved opcode.
2278 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2279 {
2280 verify = true;
2281 }
2282 else
2283 error.SetErrorString("Memory write failed when restoring original opcode.");
2284 }
2285 else
2286 {
2287 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2288 // Set verify to true and so we can check if the original opcode has already been restored
2289 verify = true;
2290 }
2291
2292 if (verify)
2293 {
Greg Claytonc982c762010-07-09 20:39:50 +00002294 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002295 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002296 // Verify that our original opcode made it back to the inferior
2297 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2298 {
2299 // compare the memory we just read with the original opcode
2300 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2301 {
2302 // SUCCESS
2303 bp_site->SetEnabled(false);
2304 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002305 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 +00002306 return error;
2307 }
2308 else
2309 {
2310 if (break_op_found)
2311 error.SetErrorString("Failed to restore original opcode.");
2312 }
2313 }
2314 else
2315 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2316 }
2317 }
2318 else
2319 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2320 }
2321 }
2322 else
2323 {
2324 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002325 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 +00002326 return error;
2327 }
2328
2329 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002330 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002331 bp_site->GetID(),
2332 (uint64_t)bp_addr,
2333 error.AsCString());
2334 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002335}
2336
Greg Clayton58be07b2011-01-07 06:08:19 +00002337// Uncomment to verify memory caching works after making changes to caching code
2338//#define VERIFY_MEMORY_READS
2339
Sean Callanan64c0cf22012-06-07 22:26:42 +00002340size_t
2341Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2342{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002343 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002344 if (!GetDisableMemoryCache())
2345 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002346#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002347 // Memory caching is enabled, with debug verification
2348
2349 if (buf && size)
2350 {
2351 // Uncomment the line below to make sure memory caching is working.
2352 // I ran this through the test suite and got no assertions, so I am
2353 // pretty confident this is working well. If any changes are made to
2354 // memory caching, uncomment the line below and test your changes!
2355
2356 // Verify all memory reads by using the cache first, then redundantly
2357 // reading the same memory from the inferior and comparing to make sure
2358 // everything is exactly the same.
2359 std::string verify_buf (size, '\0');
2360 assert (verify_buf.size() == size);
2361 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2362 Error verify_error;
2363 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2364 assert (cache_bytes_read == verify_bytes_read);
2365 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2366 assert (verify_error.Success() == error.Success());
2367 return cache_bytes_read;
2368 }
2369 return 0;
2370#else // !defined(VERIFY_MEMORY_READS)
2371 // Memory caching is enabled, without debug verification
2372
2373 return m_memory_cache.Read (addr, buf, size, error);
2374#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002375 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002376 else
2377 {
2378 // Memory caching is disabled
2379
2380 return ReadMemoryFromInferior (addr, buf, size, error);
2381 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002382}
Greg Clayton58be07b2011-01-07 06:08:19 +00002383
Greg Clayton4c82d422012-05-18 23:20:01 +00002384size_t
2385Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2386{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002387 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002388 out_str.clear();
2389 addr_t curr_addr = addr;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002390 while (true)
Greg Clayton4c82d422012-05-18 23:20:01 +00002391 {
2392 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2393 if (length == 0)
2394 break;
2395 out_str.append(buf, length);
2396 // If we got "length - 1" bytes, we didn't get the whole C string, we
2397 // need to read some more characters
2398 if (length == sizeof(buf) - 1)
2399 curr_addr += length;
2400 else
2401 break;
2402 }
2403 return out_str.size();
2404}
2405
Greg Clayton58be07b2011-01-07 06:08:19 +00002406size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002407Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2408 size_t type_width)
2409{
2410 size_t total_bytes_read = 0;
2411 if (dst && max_bytes && type_width && max_bytes >= type_width)
2412 {
2413 // Ensure a null terminator independent of the number of bytes that is read.
2414 memset (dst, 0, max_bytes);
2415 size_t bytes_left = max_bytes - type_width;
2416
2417 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2418 assert(sizeof(terminator) >= type_width &&
2419 "Attempting to validate a string with more than 4 bytes per character!");
2420
2421 addr_t curr_addr = addr;
2422 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2423 char *curr_dst = dst;
2424
2425 error.Clear();
2426 while (bytes_left > 0 && error.Success())
2427 {
2428 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2429 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2430 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2431
2432 if (bytes_read == 0)
2433 break;
2434
2435 // Search for a null terminator of correct size and alignment in bytes_read
2436 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2437 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2438 if (::strncmp(&dst[i], terminator, type_width) == 0)
2439 {
2440 error.Clear();
2441 return i;
2442 }
2443
2444 total_bytes_read += bytes_read;
2445 curr_dst += bytes_read;
2446 curr_addr += bytes_read;
2447 bytes_left -= bytes_read;
2448 }
2449 }
2450 else
2451 {
2452 if (max_bytes)
2453 error.SetErrorString("invalid arguments");
2454 }
2455 return total_bytes_read;
2456}
2457
2458// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2459// null terminators.
2460size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002461Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002462{
2463 size_t total_cstr_len = 0;
2464 if (dst && dst_max_len)
2465 {
Greg Claytone91b7952011-12-15 03:14:23 +00002466 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002467 // NULL out everything just to be safe
2468 memset (dst, 0, dst_max_len);
2469 Error error;
2470 addr_t curr_addr = addr;
2471 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2472 size_t bytes_left = dst_max_len - 1;
2473 char *curr_dst = dst;
2474
2475 while (bytes_left > 0)
2476 {
2477 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2478 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2479 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2480
2481 if (bytes_read == 0)
2482 {
Greg Claytone91b7952011-12-15 03:14:23 +00002483 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002484 dst[total_cstr_len] = '\0';
2485 break;
2486 }
2487 const size_t len = strlen(curr_dst);
2488
2489 total_cstr_len += len;
2490
2491 if (len < bytes_to_read)
2492 break;
2493
2494 curr_dst += bytes_read;
2495 curr_addr += bytes_read;
2496 bytes_left -= bytes_read;
2497 }
2498 }
Greg Claytone91b7952011-12-15 03:14:23 +00002499 else
2500 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002501 if (dst == nullptr)
Greg Claytone91b7952011-12-15 03:14:23 +00002502 result_error.SetErrorString("invalid arguments");
2503 else
2504 result_error.Clear();
2505 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002506 return total_cstr_len;
2507}
2508
2509size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002510Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2511{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002512 if (buf == nullptr || size == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002513 return 0;
2514
2515 size_t bytes_read = 0;
2516 uint8_t *bytes = (uint8_t *)buf;
2517
2518 while (bytes_read < size)
2519 {
2520 const size_t curr_size = size - bytes_read;
2521 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2522 bytes + bytes_read,
2523 curr_size,
2524 error);
2525 bytes_read += curr_bytes_read;
2526 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2527 break;
2528 }
2529
2530 // Replace any software breakpoint opcodes that fall into this range back
2531 // into "buf" before we return
2532 if (bytes_read > 0)
2533 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2534 return bytes_read;
2535}
2536
Greg Clayton58a4c462010-12-16 20:01:20 +00002537uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002538Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002539{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002540 Scalar scalar;
2541 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2542 return scalar.ULongLong(fail_value);
2543 return fail_value;
2544}
2545
2546addr_t
2547Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2548{
2549 Scalar scalar;
2550 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2551 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2552 return LLDB_INVALID_ADDRESS;
2553}
2554
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002555bool
2556Process::WritePointerToMemory (lldb::addr_t vm_addr,
2557 lldb::addr_t ptr_value,
2558 Error &error)
2559{
2560 Scalar scalar;
2561 const uint32_t addr_byte_size = GetAddressByteSize();
2562 if (addr_byte_size <= 4)
2563 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002564 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002565 scalar = ptr_value;
2566 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002567}
2568
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002569size_t
2570Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2571{
2572 size_t bytes_written = 0;
2573 const uint8_t *bytes = (const uint8_t *)buf;
2574
2575 while (bytes_written < size)
2576 {
2577 const size_t curr_size = size - bytes_written;
2578 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2579 bytes + bytes_written,
2580 curr_size,
2581 error);
2582 bytes_written += curr_bytes_written;
2583 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2584 break;
2585 }
2586 return bytes_written;
2587}
2588
2589size_t
2590Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2591{
Greg Clayton58be07b2011-01-07 06:08:19 +00002592#if defined (ENABLE_MEMORY_CACHING)
2593 m_memory_cache.Flush (addr, size);
2594#endif
2595
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002596 if (buf == nullptr || size == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002597 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002598
Jim Ingham4b536182011-08-09 02:12:22 +00002599 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002600
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002601 // We need to write any data that would go where any current software traps
2602 // (enabled software breakpoints) any software traps (breakpoints) that we
2603 // may have placed in our tasks memory.
2604
Greg Claytond8cf1a12013-06-12 00:46:38 +00002605 BreakpointSiteList bp_sites_in_range;
2606
2607 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002608 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002609 // No breakpoint sites overlap
2610 if (bp_sites_in_range.IsEmpty())
2611 return WriteMemoryPrivate (addr, buf, size, error);
2612 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002613 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002614 const uint8_t *ubuf = (const uint8_t *)buf;
2615 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002616
Greg Claytond8cf1a12013-06-12 00:46:38 +00002617 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2618
2619 if (error.Success())
2620 {
2621 addr_t intersect_addr;
2622 size_t intersect_size;
2623 size_t opcode_offset;
2624 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
Bruce Mitchener8a67bf72015-07-24 00:23:29 +00002625 UNUSED_IF_ASSERT_DISABLED(intersects);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002626 assert(intersects);
2627 assert(addr <= intersect_addr && intersect_addr < addr + size);
2628 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2629 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2630
2631 // Check for bytes before this breakpoint
2632 const addr_t curr_addr = addr + bytes_written;
2633 if (intersect_addr > curr_addr)
2634 {
2635 // There are some bytes before this breakpoint that we need to
2636 // just write to memory
2637 size_t curr_size = intersect_addr - curr_addr;
2638 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2639 ubuf + bytes_written,
2640 curr_size,
2641 error);
2642 bytes_written += curr_bytes_written;
2643 if (curr_bytes_written != curr_size)
2644 {
2645 // We weren't able to write all of the requested bytes, we
2646 // are done looping and will return the number of bytes that
2647 // we have written so far.
2648 if (error.Success())
2649 error.SetErrorToGenericError();
2650 }
2651 }
2652 // Now write any bytes that would cover up any software breakpoints
2653 // directly into the breakpoint opcode buffer
2654 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2655 bytes_written += intersect_size;
2656 }
2657 });
2658
2659 if (bytes_written < size)
Jason Molenda8b5f2cf2014-10-16 07:49:27 +00002660 WriteMemoryPrivate (addr + bytes_written,
2661 ubuf + bytes_written,
2662 size - bytes_written,
2663 error);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002664 }
2665 }
2666 else
2667 {
2668 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002669 }
2670
2671 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002672 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002673}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002674
2675size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002676Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002677{
2678 if (byte_size == UINT32_MAX)
2679 byte_size = scalar.GetByteSize();
2680 if (byte_size > 0)
2681 {
2682 uint8_t buf[32];
2683 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2684 if (mem_size > 0)
2685 return WriteMemory(addr, buf, mem_size, error);
2686 else
2687 error.SetErrorString ("failed to get scalar as memory data");
2688 }
2689 else
2690 {
2691 error.SetErrorString ("invalid scalar value");
2692 }
2693 return 0;
2694}
2695
2696size_t
2697Process::ReadScalarIntegerFromMemory (addr_t addr,
2698 uint32_t byte_size,
2699 bool is_signed,
2700 Scalar &scalar,
2701 Error &error)
2702{
Greg Clayton7060f892013-05-01 23:41:30 +00002703 uint64_t uval = 0;
2704 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002705 {
Greg Clayton7060f892013-05-01 23:41:30 +00002706 error.SetErrorString ("byte size is zero");
2707 }
2708 else if (byte_size & (byte_size - 1))
2709 {
2710 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2711 }
2712 else if (byte_size <= sizeof(uval))
2713 {
2714 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002715 if (bytes_read == byte_size)
2716 {
2717 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002718 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002719 if (byte_size <= 4)
2720 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002721 else
Greg Clayton7060f892013-05-01 23:41:30 +00002722 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002723 if (is_signed)
2724 scalar.SignExtend(byte_size * 8);
2725 return bytes_read;
2726 }
2727 }
2728 else
2729 {
2730 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2731 }
2732 return 0;
2733}
2734
Greg Claytond495c532011-05-17 03:37:42 +00002735#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736addr_t
2737Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2738{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002739 if (GetPrivateState() != eStateStopped)
2740 return LLDB_INVALID_ADDRESS;
2741
Greg Claytond495c532011-05-17 03:37:42 +00002742#if defined (USE_ALLOCATE_MEMORY_CACHE)
2743 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2744#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002745 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002746 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002747 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002748 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 +00002749 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002750 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002751 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002752 m_mod_id.GetStopID(),
2753 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002754 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002755#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756}
2757
Jim Ingham2c381412015-11-04 20:32:27 +00002758addr_t
2759Process::CallocateMemory(size_t size, uint32_t permissions, Error &error)
2760{
2761 addr_t return_addr = AllocateMemory(size, permissions, error);
2762 if (error.Success())
2763 {
2764 std::string buffer(size, 0);
2765 WriteMemory(return_addr, buffer.c_str(), size, error);
2766 }
2767 return return_addr;
2768}
2769
Sean Callanan90539452011-09-20 23:01:51 +00002770bool
2771Process::CanJIT ()
2772{
Sean Callanana7b443a2012-02-14 22:50:38 +00002773 if (m_can_jit == eCanJITDontKnow)
2774 {
Todd Fialaaf245d12014-06-30 21:05:18 +00002775 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Sean Callanana7b443a2012-02-14 22:50:38 +00002776 Error err;
2777
2778 uint64_t allocated_memory = AllocateMemory(8,
2779 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2780 err);
2781
2782 if (err.Success())
Todd Fialaaf245d12014-06-30 21:05:18 +00002783 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002784 m_can_jit = eCanJITYes;
Todd Fialaaf245d12014-06-30 21:05:18 +00002785 if (log)
2786 log->Printf ("Process::%s pid %" PRIu64 " allocation test passed, CanJIT () is true", __FUNCTION__, GetID ());
2787 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002788 else
Todd Fialaaf245d12014-06-30 21:05:18 +00002789 {
Sean Callanana7b443a2012-02-14 22:50:38 +00002790 m_can_jit = eCanJITNo;
Todd Fialaaf245d12014-06-30 21:05:18 +00002791 if (log)
2792 log->Printf ("Process::%s pid %" PRIu64 " allocation test failed, CanJIT () is false: %s", __FUNCTION__, GetID (), err.AsCString ());
2793 }
Sean Callanana7b443a2012-02-14 22:50:38 +00002794
2795 DeallocateMemory (allocated_memory);
2796 }
2797
Sean Callanan90539452011-09-20 23:01:51 +00002798 return m_can_jit == eCanJITYes;
2799}
2800
2801void
2802Process::SetCanJIT (bool can_jit)
2803{
2804 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2805}
2806
Ewan Crawford90ff7912015-07-14 10:56:58 +00002807void
2808Process::SetCanRunCode (bool can_run_code)
2809{
2810 SetCanJIT(can_run_code);
2811 m_can_interpret_function_calls = can_run_code;
2812}
2813
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002814Error
2815Process::DeallocateMemory (addr_t ptr)
2816{
Greg Claytond495c532011-05-17 03:37:42 +00002817 Error error;
2818#if defined (USE_ALLOCATE_MEMORY_CACHE)
2819 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2820 {
Daniel Malead01b2952012-11-29 21:49:15 +00002821 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002822 }
2823#else
2824 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002825
Greg Clayton5160ce52013-03-27 23:08:40 +00002826 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002827 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002828 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 +00002829 ptr,
2830 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002831 m_mod_id.GetStopID(),
2832 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002833#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002834 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002835}
2836
Greg Claytonc9660542012-02-05 02:38:54 +00002837ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002838Process::ReadModuleFromMemory (const FileSpec& file_spec,
Andrew MacPherson17220c12014-03-05 10:12:43 +00002839 lldb::addr_t header_addr,
2840 size_t size_to_read)
Greg Claytonc9660542012-02-05 02:38:54 +00002841{
Jason Molenda08a32582015-07-25 02:39:42 +00002842 Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2843 if (log)
2844 {
2845 log->Printf ("Process::ReadModuleFromMemory reading %s binary from memory", file_spec.GetPath().c_str());
2846 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002847 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002848 if (module_sp)
2849 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002850 Error error;
Andrew MacPherson17220c12014-03-05 10:12:43 +00002851 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error, size_to_read);
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002852 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002853 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002854 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002855 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002856}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002857
Zachary Turner93749ab2015-03-03 21:51:25 +00002858bool
2859Process::GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions)
2860{
2861 MemoryRegionInfo range_info;
2862 permissions = 0;
2863 Error error (GetMemoryRegionInfo (load_addr, range_info));
2864 if (!error.Success())
2865 return false;
2866 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow
2867 || range_info.GetWritable() == MemoryRegionInfo::eDontKnow
2868 || range_info.GetExecutable() == MemoryRegionInfo::eDontKnow)
2869 {
2870 return false;
2871 }
2872
2873 if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2874 permissions |= lldb::ePermissionsReadable;
2875
2876 if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2877 permissions |= lldb::ePermissionsWritable;
2878
2879 if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2880 permissions |= lldb::ePermissionsExecutable;
2881
2882 return true;
2883}
2884
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002885Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002886Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002887{
2888 Error error;
2889 error.SetErrorString("watchpoints are not supported");
2890 return error;
2891}
2892
2893Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002894Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002895{
2896 Error error;
2897 error.SetErrorString("watchpoints are not supported");
2898 return error;
2899}
2900
2901StateType
2902Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2903{
2904 StateType state;
2905 // Now wait for the process to launch and return control to us, and then
2906 // call DidLaunch:
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002907 while (true)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002908 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002909 event_sp.reset();
2910 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2911
Greg Clayton2637f822011-11-17 01:23:07 +00002912 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002913 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002914
2915 // If state is invalid, then we timed out
2916 if (state == eStateInvalid)
2917 break;
2918
2919 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002920 HandlePrivateEvent (event_sp);
2921 }
2922 return state;
2923}
2924
Greg Clayton332e8b12015-01-13 21:13:08 +00002925void
2926Process::LoadOperatingSystemPlugin(bool flush)
2927{
2928 if (flush)
2929 m_thread_list.Clear();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002930 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
Greg Clayton332e8b12015-01-13 21:13:08 +00002931 if (flush)
2932 Flush();
2933}
2934
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002935Error
Greg Claytonfbb76342013-11-20 21:07:01 +00002936Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002937{
2938 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002939 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002940 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00002941 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00002942 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002943 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002944 m_process_input_reader.reset();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002945 m_stop_info_override_callback = nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946
Zachary Turner7529df92015-09-01 20:02:29 +00002947 Module *exe_module = GetTarget().GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948 if (exe_module)
2949 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002950 char local_exec_file_path[PATH_MAX];
2951 char platform_exec_file_path[PATH_MAX];
2952 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2953 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002954 if (exe_module->GetFileSpec().Exists())
2955 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002956 // Install anything that might need to be installed prior to launching.
2957 // For host systems, this will do nothing, but if we are connected to a
2958 // remote platform it will install any needed binaries
2959 error = GetTarget().Install(&launch_info);
2960 if (error.Fail())
2961 return error;
2962
Greg Clayton71337622011-02-24 22:24:29 +00002963 if (PrivateStateThreadIsValid ())
2964 PausePrivateStateThread ();
2965
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002966 error = WillLaunch (exe_module);
2967 if (error.Success())
2968 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002969 const bool restarted = false;
2970 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002971 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972
Ed Maste64fad602013-07-29 20:58:06 +00002973 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002974 {
2975 // Now launch using these arguments.
2976 error = DoLaunch (exe_module, launch_info);
2977 }
2978 else
2979 {
2980 // This shouldn't happen
2981 error.SetErrorString("failed to acquire process run lock");
2982 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002983
2984 if (error.Fail())
2985 {
2986 if (GetID() != LLDB_INVALID_PROCESS_ID)
2987 {
2988 SetID (LLDB_INVALID_PROCESS_ID);
2989 const char *error_string = error.AsCString();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00002990 if (error_string == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002991 error_string = "launch failed";
2992 SetExitStatus (-1, error_string);
2993 }
2994 }
2995 else
2996 {
2997 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002998 TimeValue timeout_time;
2999 timeout_time = TimeValue::Now();
3000 timeout_time.OffsetWithSeconds(10);
3001 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003002
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003003 if (state == eStateInvalid || !event_sp)
Greg Clayton1a38ea72011-06-22 01:42:17 +00003004 {
3005 // We were able to launch the process, but we failed to
3006 // catch the initial stop.
Tamas Berghammer04e63142015-02-23 10:59:54 +00003007 error.SetErrorString ("failed to catch stop after launch");
Greg Clayton1a38ea72011-06-22 01:42:17 +00003008 SetExitStatus (0, "failed to catch stop after launch");
Jason Molendaede31932015-04-17 05:01:58 +00003009 Destroy(false);
Greg Clayton1a38ea72011-06-22 01:42:17 +00003010 }
3011 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003012 {
3013 DidLaunch ();
3014
Greg Claytonc859e2d2012-02-13 23:10:39 +00003015 DynamicLoader *dyld = GetDynamicLoader ();
3016 if (dyld)
3017 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003018
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003019 GetJITLoaders().DidLaunch();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003020
Jason Molendaeef51062013-11-05 03:57:19 +00003021 SystemRuntime *system_runtime = GetSystemRuntime ();
3022 if (system_runtime)
3023 system_runtime->DidLaunch();
3024
Greg Clayton332e8b12015-01-13 21:13:08 +00003025 LoadOperatingSystemPlugin(false);
Todd Fialaf72fa672014-10-07 16:05:21 +00003026
3027 // Note, the stop event was consumed above, but not handled. This was done
3028 // to give DidLaunch a chance to run. The target is either stopped or crashed.
3029 // Directly set the state. This is done to prevent a stop message with a bunch
3030 // of spurious output on thread status, as well as not pop a ProcessIOHandler.
3031 SetPublicState(state, false);
Greg Clayton71337622011-02-24 22:24:29 +00003032
3033 if (PrivateStateThreadIsValid ())
3034 ResumePrivateStateThread ();
3035 else
3036 StartPrivateStateThread ();
Greg Claytona97c4d22014-12-09 23:31:02 +00003037
3038 m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
Ilia K6af632f2015-02-06 18:15:05 +00003039
3040 // Target was stopped at entry as was intended. Need to notify the listeners
3041 // about it.
Ilia K333fc182015-02-11 11:24:20 +00003042 if (state == eStateStopped && launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
Ilia K6af632f2015-02-06 18:15:05 +00003043 HandlePrivateEvent(event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003044 }
3045 else if (state == eStateExited)
3046 {
3047 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3048 // not likely to work, and return an invalid pid.
3049 HandlePrivateEvent (event_sp);
3050 }
3051 }
3052 }
3053 }
3054 else
3055 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003056 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003057 }
3058 }
3059 return error;
3060}
3061
Greg Claytonc3776bf2012-02-09 06:16:32 +00003062Error
3063Process::LoadCore ()
3064{
3065 Error error = DoLoadCore();
3066 if (error.Success())
3067 {
Greg Clayton35824e32015-02-20 20:59:47 +00003068 Listener listener ("lldb.process.load_core_listener");
Greg Clayton338d0bd2015-02-20 21:51:06 +00003069 HijackProcessEvents(&listener);
Greg Clayton35824e32015-02-20 20:59:47 +00003070
Greg Claytonc3776bf2012-02-09 06:16:32 +00003071 if (PrivateStateThreadIsValid ())
3072 ResumePrivateStateThread ();
3073 else
3074 StartPrivateStateThread ();
3075
Greg Claytonc859e2d2012-02-13 23:10:39 +00003076 DynamicLoader *dyld = GetDynamicLoader ();
3077 if (dyld)
3078 dyld->DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003079
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003080 GetJITLoaders().DidAttach();
Greg Claytonc859e2d2012-02-13 23:10:39 +00003081
Jason Molendaeef51062013-11-05 03:57:19 +00003082 SystemRuntime *system_runtime = GetSystemRuntime ();
3083 if (system_runtime)
3084 system_runtime->DidAttach();
3085
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003086 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003087 // We successfully loaded a core file, now pretend we stopped so we can
3088 // show all of the threads in the core file and explore the crashed
3089 // state.
3090 SetPrivateState (eStateStopped);
Greg Clayton35824e32015-02-20 20:59:47 +00003091
3092 // Wait indefinitely for a stopped event since we just posted one above...
3093 lldb::EventSP event_sp;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003094 listener.WaitForEvent(nullptr, event_sp);
Greg Clayton35824e32015-02-20 20:59:47 +00003095 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3096
3097 if (!StateIsStoppedState (state, false))
3098 {
3099 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3100 if (log)
3101 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3102 error.SetErrorString ("Did not get stopped event after loading the core file.");
3103 }
Greg Clayton338d0bd2015-02-20 21:51:06 +00003104 RestoreProcessEvents ();
Greg Claytonc3776bf2012-02-09 06:16:32 +00003105 }
3106 return error;
3107}
3108
Greg Claytonc859e2d2012-02-13 23:10:39 +00003109DynamicLoader *
3110Process::GetDynamicLoader ()
3111{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003112 if (!m_dyld_ap)
3113 m_dyld_ap.reset(DynamicLoader::FindPlugin(this, nullptr));
Greg Claytonc859e2d2012-02-13 23:10:39 +00003114 return m_dyld_ap.get();
3115}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003116
Todd Fialaaf245d12014-06-30 21:05:18 +00003117const lldb::DataBufferSP
3118Process::GetAuxvData()
3119{
3120 return DataBufferSP ();
3121}
3122
Andrew MacPherson17220c12014-03-05 10:12:43 +00003123JITLoaderList &
3124Process::GetJITLoaders ()
3125{
3126 if (!m_jit_loaders_ap)
3127 {
3128 m_jit_loaders_ap.reset(new JITLoaderList());
3129 JITLoader::LoadPlugins(this, *m_jit_loaders_ap);
3130 }
3131 return *m_jit_loaders_ap;
3132}
3133
Jason Molendaeef51062013-11-05 03:57:19 +00003134SystemRuntime *
3135Process::GetSystemRuntime ()
3136{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003137 if (!m_system_runtime_ap)
3138 m_system_runtime_ap.reset(SystemRuntime::FindPlugin(this));
Jason Molendaeef51062013-11-05 03:57:19 +00003139 return m_system_runtime_ap.get();
3140}
3141
Todd Fiala76e0fc92014-08-27 22:58:26 +00003142Process::AttachCompletionHandler::AttachCompletionHandler (Process *process, uint32_t exec_count) :
3143 NextEventAction (process),
3144 m_exec_count (exec_count)
3145{
3146 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3147 if (log)
3148 log->Printf ("Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, __FUNCTION__, static_cast<void*>(process), exec_count);
3149}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003150
Jim Inghambb3a2832011-01-29 01:49:25 +00003151Process::NextEventAction::EventActionResult
3152Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003153{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003154 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3155
Jim Inghambb3a2832011-01-29 01:49:25 +00003156 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
Todd Fiala76e0fc92014-08-27 22:58:26 +00003157 if (log)
3158 log->Printf ("Process::AttachCompletionHandler::%s called with state %s (%d)", __FUNCTION__, StateAsCString(state), static_cast<int> (state));
3159
3160 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003161 {
Zachary Turnerc62733b2015-05-20 18:31:17 +00003162 case eStateAttaching:
3163 return eEventActionSuccess;
3164
Greg Clayton513c26c2011-01-29 07:10:55 +00003165 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003166 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003167 return eEventActionRetry;
3168
3169 case eStateStopped:
3170 case eStateCrashed:
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003171 // During attach, prior to sending the eStateStopped event,
3172 // lldb_private::Process subclasses must set the new process ID.
3173 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
3174 // We don't want these events to be reported, so go set the ShouldReportStop here:
3175 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3176
3177 if (m_exec_count > 0)
Greg Claytonc9ed4782011-11-12 02:10:56 +00003178 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003179 --m_exec_count;
Todd Fiala76e0fc92014-08-27 22:58:26 +00003180
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003181 if (log)
3182 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 +00003183
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003184 RequestResume();
3185 return eEventActionRetry;
3186 }
3187 else
3188 {
3189 if (log)
3190 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 +00003191
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003192 m_process->CompleteAttach ();
3193 return eEventActionSuccess;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003194 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003195 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003196
Greg Clayton513c26c2011-01-29 07:10:55 +00003197 default:
3198 case eStateExited:
3199 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003200 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003201 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003202
3203 m_exit_string.assign ("No valid Process");
3204 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003205}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003206
Jim Inghambb3a2832011-01-29 01:49:25 +00003207Process::NextEventAction::EventActionResult
3208Process::AttachCompletionHandler::HandleBeingInterrupted()
3209{
3210 return eEventActionSuccess;
3211}
3212
3213const char *
3214Process::AttachCompletionHandler::GetExitString ()
3215{
3216 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003217}
3218
Greg Clayton8012cad2014-11-17 19:39:20 +00003219Listener &
3220ProcessAttachInfo::GetListenerForProcess (Debugger &debugger)
3221{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003222 return (m_listener_sp ? *m_listener_sp : debugger.GetListener());
Greg Clayton8012cad2014-11-17 19:39:20 +00003223}
3224
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003225Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003226Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003227{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003228 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003229 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003230 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003231 m_jit_loaders_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003232 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003233 m_os_ap.reset();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003234 m_stop_info_override_callback = nullptr;
Jim Ingham5aee1622010-08-09 23:31:02 +00003235
Greg Clayton144f3a92011-11-15 03:53:30 +00003236 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003237 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003238 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003239 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003240 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003241
Greg Clayton144f3a92011-11-15 03:53:30 +00003242 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003243 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003244 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3245
3246 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003247 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003248 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3249 if (error.Success())
3250 {
Ed Maste64fad602013-07-29 20:58:06 +00003251 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003252 {
3253 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003254 const bool restarted = false;
3255 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003256 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003257 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003258 }
3259 else
3260 {
3261 // This shouldn't happen
3262 error.SetErrorString("failed to acquire process run lock");
3263 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003264
Greg Clayton144f3a92011-11-15 03:53:30 +00003265 if (error.Fail())
3266 {
3267 if (GetID() != LLDB_INVALID_PROCESS_ID)
3268 {
3269 SetID (LLDB_INVALID_PROCESS_ID);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003270 if (error.AsCString() == nullptr)
Greg Clayton144f3a92011-11-15 03:53:30 +00003271 error.SetErrorString("attach failed");
3272
3273 SetExitStatus(-1, error.AsCString());
3274 }
3275 }
3276 else
3277 {
3278 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3279 StartPrivateStateThread();
3280 }
3281 return error;
3282 }
Greg Claytone996fd32011-03-08 22:40:15 +00003283 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003284 else
Greg Claytone996fd32011-03-08 22:40:15 +00003285 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003286 ProcessInstanceInfoList process_infos;
Zachary Turner7529df92015-09-01 20:02:29 +00003287 PlatformSP platform_sp (GetTarget().GetPlatform ());
Greg Clayton144f3a92011-11-15 03:53:30 +00003288
3289 if (platform_sp)
3290 {
3291 ProcessInstanceInfoMatch match_info;
3292 match_info.GetProcessInfo() = attach_info;
3293 match_info.SetNameMatchType (eNameMatchEquals);
3294 platform_sp->FindProcesses (match_info, process_infos);
3295 const uint32_t num_matches = process_infos.GetSize();
3296 if (num_matches == 1)
3297 {
3298 attach_pid = process_infos.GetProcessIDAtIndex(0);
3299 // Fall through and attach using the above process ID
3300 }
3301 else
3302 {
3303 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3304 if (num_matches > 1)
Jim Ingham368ac222014-08-15 17:05:27 +00003305 {
3306 StreamString s;
3307 ProcessInstanceInfo::DumpTableHeader (s, platform_sp.get(), true, false);
3308 for (size_t i = 0; i < num_matches; i++)
3309 {
3310 process_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(s, platform_sp.get(), true, false);
3311 }
3312 error.SetErrorStringWithFormat ("more than one process named %s:\n%s",
3313 process_name,
3314 s.GetData());
3315 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003316 else
3317 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3318 }
3319 }
3320 else
3321 {
3322 error.SetErrorString ("invalid platform, can't find processes by name");
3323 return error;
3324 }
Greg Claytone996fd32011-03-08 22:40:15 +00003325 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003326 }
3327 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003328 {
3329 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003330 }
3331 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003332
3333 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003334 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003335 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003336 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003337 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003338
Ed Maste64fad602013-07-29 20:58:06 +00003339 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003340 {
3341 // Now attach using these arguments.
3342 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003343 const bool restarted = false;
3344 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003345 error = DoAttachToProcessWithID (attach_pid, attach_info);
3346 }
3347 else
3348 {
3349 // This shouldn't happen
3350 error.SetErrorString("failed to acquire process run lock");
3351 }
3352
Greg Clayton144f3a92011-11-15 03:53:30 +00003353 if (error.Success())
3354 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003355 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3356 StartPrivateStateThread();
3357 }
3358 else
Greg Claytone996fd32011-03-08 22:40:15 +00003359 {
3360 if (GetID() != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003361 SetID (LLDB_INVALID_PROCESS_ID);
Greg Claytone996fd32011-03-08 22:40:15 +00003362
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003363 const char *error_string = error.AsCString();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003364 if (error_string == nullptr)
Oleksiy Vyalov5d064742014-11-19 18:27:45 +00003365 error_string = "attach failed";
3366
3367 SetExitStatus(-1, error_string);
Greg Claytone996fd32011-03-08 22:40:15 +00003368 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003369 }
3370 }
3371 return error;
3372}
3373
Greg Clayton93d3c8332011-02-16 04:46:07 +00003374void
3375Process::CompleteAttach ()
3376{
Todd Fiala76e0fc92014-08-27 22:58:26 +00003377 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3378 if (log)
3379 log->Printf ("Process::%s()", __FUNCTION__);
3380
Greg Clayton93d3c8332011-02-16 04:46:07 +00003381 // Let the process subclass figure out at much as it can about the process
3382 // before we go looking for a dynamic loader plug-in.
Jim Inghambb006ce2014-08-02 00:33:35 +00003383 ArchSpec process_arch;
3384 DidAttach(process_arch);
3385
3386 if (process_arch.IsValid())
Todd Fiala76e0fc92014-08-27 22:58:26 +00003387 {
Zachary Turner7529df92015-09-01 20:02:29 +00003388 GetTarget().SetArchitecture(process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003389 if (log)
3390 {
3391 const char *triple_str = process_arch.GetTriple().getTriple().c_str ();
3392 log->Printf ("Process::%s replacing process architecture with DidAttach() architecture: %s",
3393 __FUNCTION__,
3394 triple_str ? triple_str : "<null>");
3395 }
3396 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003397
Jim Ingham4299fdb2011-09-15 01:10:17 +00003398 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3399 // the same as the one we've already set, switch architectures.
Zachary Turner7529df92015-09-01 20:02:29 +00003400 PlatformSP platform_sp (GetTarget().GetPlatform ());
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003401 assert(platform_sp);
Jim Ingham4299fdb2011-09-15 01:10:17 +00003402 if (platform_sp)
3403 {
Zachary Turner7529df92015-09-01 20:02:29 +00003404 const ArchSpec &target_arch = GetTarget().GetArchitecture();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003405 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr))
Greg Clayton70512312012-05-08 01:45:38 +00003406 {
3407 ArchSpec platform_arch;
3408 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3409 if (platform_sp)
3410 {
Zachary Turner7529df92015-09-01 20:02:29 +00003411 GetTarget().SetPlatform (platform_sp);
3412 GetTarget().SetArchitecture(platform_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003413 if (log)
3414 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 +00003415 }
3416 }
Jim Inghambb006ce2014-08-02 00:33:35 +00003417 else if (!process_arch.IsValid())
Greg Clayton70512312012-05-08 01:45:38 +00003418 {
3419 ProcessInstanceInfo process_info;
3420 platform_sp->GetProcessInfo (GetID(), process_info);
3421 const ArchSpec &process_arch = process_info.GetArchitecture();
Zachary Turner7529df92015-09-01 20:02:29 +00003422 if (process_arch.IsValid() && !GetTarget().GetArchitecture().IsExactMatch(process_arch))
Todd Fiala76e0fc92014-08-27 22:58:26 +00003423 {
Zachary Turner7529df92015-09-01 20:02:29 +00003424 GetTarget().SetArchitecture (process_arch);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003425 if (log)
3426 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 ());
3427 }
Greg Clayton70512312012-05-08 01:45:38 +00003428 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003429 }
3430
3431 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003432 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003433 DynamicLoader *dyld = GetDynamicLoader ();
3434 if (dyld)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003435 {
Greg Claytonc859e2d2012-02-13 23:10:39 +00003436 dyld->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003437 if (log)
3438 {
Zachary Turner7529df92015-09-01 20:02:29 +00003439 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003440 log->Printf ("Process::%s after DynamicLoader::DidAttach(), target executable is %s (using %s plugin)",
3441 __FUNCTION__,
3442 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3443 dyld->GetPluginName().AsCString ("<unnamed>"));
3444 }
3445 }
Greg Clayton93d3c8332011-02-16 04:46:07 +00003446
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00003447 GetJITLoaders().DidAttach();
Andrew MacPherson17220c12014-03-05 10:12:43 +00003448
Jason Molendaeef51062013-11-05 03:57:19 +00003449 SystemRuntime *system_runtime = GetSystemRuntime ();
3450 if (system_runtime)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003451 {
Jason Molendaeef51062013-11-05 03:57:19 +00003452 system_runtime->DidAttach();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003453 if (log)
3454 {
Zachary Turner7529df92015-09-01 20:02:29 +00003455 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003456 log->Printf ("Process::%s after SystemRuntime::DidAttach(), target executable is %s (using %s plugin)",
3457 __FUNCTION__,
3458 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>",
3459 system_runtime->GetPluginName().AsCString("<unnamed>"));
3460 }
3461 }
Jason Molendaeef51062013-11-05 03:57:19 +00003462
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003463 m_os_ap.reset(OperatingSystem::FindPlugin(this, nullptr));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003464 // Figure out which one is the executable, and set that in our target:
Zachary Turner7529df92015-09-01 20:02:29 +00003465 const ModuleList &target_modules = GetTarget().GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003466 Mutex::Locker modules_locker(target_modules.GetMutex());
3467 size_t num_modules = target_modules.GetSize();
3468 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003469
Andy Gibbsa297a972013-06-19 19:04:53 +00003470 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003471 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003472 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003473 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003474 {
Zachary Turner7529df92015-09-01 20:02:29 +00003475 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003476 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003477 break;
3478 }
3479 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003480 if (new_executable_module_sp)
Todd Fiala76e0fc92014-08-27 22:58:26 +00003481 {
Zachary Turner7529df92015-09-01 20:02:29 +00003482 GetTarget().SetExecutableModule (new_executable_module_sp, false);
Todd Fiala76e0fc92014-08-27 22:58:26 +00003483 if (log)
3484 {
Zachary Turner7529df92015-09-01 20:02:29 +00003485 ModuleSP exe_module_sp = GetTarget().GetExecutableModule ();
Todd Fiala76e0fc92014-08-27 22:58:26 +00003486 log->Printf ("Process::%s after looping through modules, target executable is %s",
3487 __FUNCTION__,
3488 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
3489 }
3490 }
Greg Claytona97c4d22014-12-09 23:31:02 +00003491
3492 m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003493}
3494
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003495Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003496Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003497{
Greg Claytonb766a732011-02-04 01:58:07 +00003498 m_abi_sp.reset();
3499 m_process_input_reader.reset();
3500
3501 // Find the process and its architecture. Make sure it matches the architecture
3502 // of the current Target, and if not adjust it.
3503
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003504 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003505 if (error.Success())
3506 {
Greg Clayton71337622011-02-24 22:24:29 +00003507 if (GetID() != LLDB_INVALID_PROCESS_ID)
3508 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003509 EventSP event_sp;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003510 StateType state = WaitForProcessStopPrivate(nullptr, event_sp);
Greg Clayton32e0a752011-03-30 18:16:51 +00003511
3512 if (state == eStateStopped || state == eStateCrashed)
3513 {
3514 // If we attached and actually have a process on the other end, then
3515 // this ended up being the equivalent of an attach.
3516 CompleteAttach ();
3517
3518 // This delays passing the stopped event to listeners till
3519 // CompleteAttach gets a chance to complete...
3520 HandlePrivateEvent (event_sp);
Greg Clayton32e0a752011-03-30 18:16:51 +00003521 }
Greg Clayton71337622011-02-24 22:24:29 +00003522 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003523
3524 if (PrivateStateThreadIsValid ())
3525 ResumePrivateStateThread ();
3526 else
3527 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003528 }
3529 return error;
3530}
3531
Greg Claytonb766a732011-02-04 01:58:07 +00003532Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003533Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003534{
Greg Clayton5160ce52013-03-27 23:08:40 +00003535 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003536 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003537 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003538 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003539 StateAsCString(m_public_state.GetValue()),
3540 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003541
3542 Error error (WillResume());
3543 // Tell the process it is about to resume before the thread list
3544 if (error.Success())
3545 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003546 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003547 // can let all of our threads know that they are about to be
3548 // resumed. Threads will each be called with
3549 // Thread::WillResume(StateType) where StateType contains the state
3550 // that they are supposed to have when the process is resumed
3551 // (suspended/running/stepping). Threads should also check
3552 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003553 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003554 if (m_thread_list.WillResume())
3555 {
Jim Ingham372787f2012-04-07 00:00:41 +00003556 // Last thing, do the PreResumeActions.
3557 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003558 {
Jim Ingham0161b492013-02-09 01:29:05 +00003559 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003560 }
3561 else
3562 {
3563 m_mod_id.BumpResumeID();
3564 error = DoResume();
3565 if (error.Success())
3566 {
3567 DidResume();
3568 m_thread_list.DidResume();
3569 if (log)
3570 log->Printf ("Process thinks the process has resumed.");
3571 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003572 }
3573 }
3574 else
3575 {
Jim Inghamd5ac1ab2015-01-19 23:51:51 +00003576 // Somebody wanted to run without running (e.g. we were faking a step from one frame of a set of inlined
3577 // frames that share the same PC to another.) So generate a continue & a stopped event,
Jim Ingham513c6bb2012-09-01 01:02:41 +00003578 // and let the world handle them.
3579 if (log)
3580 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3581
3582 SetPrivateState(eStateRunning);
3583 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003584 }
3585 }
Jim Ingham444586b2011-01-24 06:34:17 +00003586 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003587 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003588 return error;
3589}
3590
3591Error
Pavel Labath19da1f12015-12-07 12:36:52 +00003592Process::Halt (bool clear_thread_plans, bool use_run_lock)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003593{
Pavel Labath19da1f12015-12-07 12:36:52 +00003594 if (! StateIsRunningState(m_public_state.GetValue()))
3595 return Error("Process is not running.");
3596
Greg Claytonf9b57b92013-05-10 23:48:10 +00003597 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3598 // in case it was already set and some thread plan logic calls halt on its
3599 // own.
3600 m_clear_thread_plans_on_stop |= clear_thread_plans;
3601
Jim Ingham0f16e732011-02-08 05:20:59 +00003602 Listener halt_listener ("lldb.process.halt_listener");
Pavel Labath19da1f12015-12-07 12:36:52 +00003603 HijackProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003604
Jim Inghambb3a2832011-01-29 01:49:25 +00003605 EventSP event_sp;
Jim Inghambb3a2832011-01-29 01:49:25 +00003606
Pavel Labath19da1f12015-12-07 12:36:52 +00003607 SendAsyncInterrupt();
3608
3609 if (m_public_state.GetValue() == eStateAttaching)
Jim Inghambb3a2832011-01-29 01:49:25 +00003610 {
Pavel Labath19da1f12015-12-07 12:36:52 +00003611 // Don't hijack and eat the eStateExited as the code that was doing
3612 // the attach will be waiting for this event...
3613 RestoreProcessEvents();
3614 SetExitStatus(SIGKILL, "Cancelled async attach.");
3615 Destroy (false);
3616 return Error();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003617 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003618
Pavel Labath19da1f12015-12-07 12:36:52 +00003619 // Wait for 10 second for the process to stop.
3620 TimeValue timeout_time;
3621 timeout_time = TimeValue::Now();
3622 timeout_time.OffsetWithSeconds(10);
3623 StateType state = WaitForProcessToStop(&timeout_time, &event_sp, true, &halt_listener,
3624 nullptr, use_run_lock);
3625 RestoreProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003626
Pavel Labath19da1f12015-12-07 12:36:52 +00003627 if (state == eStateInvalid || ! event_sp)
3628 {
3629 // We timed out and didn't get a stop event...
3630 return Error("Halt timed out. State = %s", StateAsCString(GetState()));
3631 }
3632
3633 BroadcastEvent(event_sp);
3634
3635 return Error();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003636}
3637
3638Error
Pavel Labathfcc7f662015-10-07 15:11:11 +00003639Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp)
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003640{
3641 Error error;
3642 if (m_public_state.GetValue() == eStateRunning)
3643 {
3644 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3645 if (log)
Pavel Labathfcc7f662015-10-07 15:11:11 +00003646 log->Printf("Process::%s() About to stop.", __FUNCTION__);
3647
3648 ListenerSP listener_sp (new Listener("lldb.Process.StopForDestroyOrDetach.hijack"));
3649 HijackProcessEvents(listener_sp.get());
3650
3651 SendAsyncInterrupt();
3652
3653 // Consume the interrupt event.
3654 TimeValue timeout (TimeValue::Now());
3655 timeout.OffsetWithSeconds(10);
3656
3657 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp, true, listener_sp.get());
3658
3659 RestoreProcessEvents();
3660
3661 // If the process exited while we were waiting for it to stop, put the exited event into
3662 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3663 // they don't have a process anymore...
3664
3665 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
Pavel Labathc8c77d42015-09-28 09:37:51 +00003666 {
3667 if (log)
Pavel Labathfcc7f662015-10-07 15:11:11 +00003668 log->Printf("Process::%s() Process exited while waiting to stop.", __FUNCTION__);
3669 return error;
3670 }
3671 else
3672 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3673
3674 if (state != eStateStopped)
3675 {
3676 if (log)
3677 log->Printf("Process::%s() failed to stop, state is: %s", __FUNCTION__, StateAsCString(state));
3678 // If we really couldn't stop the process then we should just error out here, but if the
3679 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3680 StateType private_state = m_private_state.GetValue();
3681 if (private_state != eStateStopped)
3682 {
3683 return error;
3684 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003685 }
3686 }
3687 return error;
3688}
3689
3690Error
Jim Inghamacff8952013-05-02 00:27:30 +00003691Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003692{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003693 EventSP exit_event_sp;
3694 Error error;
3695 m_destroy_in_process = true;
3696
3697 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003698
3699 if (error.Success())
3700 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003701 if (DetachRequiresHalt())
3702 {
Pavel Labathfcc7f662015-10-07 15:11:11 +00003703 error = StopForDestroyOrDetach (exit_event_sp);
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003704 if (!error.Success())
3705 {
3706 m_destroy_in_process = false;
3707 return error;
3708 }
3709 else if (exit_event_sp)
3710 {
3711 // We shouldn't need to do anything else here. There's no process left to detach from...
3712 StopPrivateStateThread();
3713 m_destroy_in_process = false;
3714 return error;
3715 }
3716 }
3717
Andrew MacPhersonc3826b52014-03-25 19:59:36 +00003718 m_thread_list.DiscardThreadPlans();
3719 DisableAllBreakpointSites();
3720
Jim Inghamacff8952013-05-02 00:27:30 +00003721 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003722 if (error.Success())
3723 {
3724 DidDetach();
3725 StopPrivateStateThread();
3726 }
Jim Inghamacff8952013-05-02 00:27:30 +00003727 else
3728 {
3729 return error;
3730 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003731 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003732 m_destroy_in_process = false;
3733
3734 // If we exited when we were waiting for a process to stop, then
3735 // forward the event here so we don't lose the event
3736 if (exit_event_sp)
3737 {
3738 // Directly broadcast our exited event because we shut down our
3739 // private state thread above
3740 BroadcastEvent(exit_event_sp);
3741 }
3742
3743 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3744 // the last events through the event system, in which case we might strand the write lock. Unlock
3745 // it here so when we do to tear down the process we don't get an error destroying the lock.
3746
Ed Maste64fad602013-07-29 20:58:06 +00003747 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003748 return error;
3749}
3750
3751Error
Jason Molendaede31932015-04-17 05:01:58 +00003752Process::Destroy (bool force_kill)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003753{
Pavel Labath19da1f12015-12-07 12:36:52 +00003754
Jim Ingham09437922013-03-01 20:04:25 +00003755 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3756 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3757 // failed and the process stays around for some reason it won't be in a confused state.
Jason Molendaede31932015-04-17 05:01:58 +00003758
3759 if (force_kill)
3760 m_should_detach = false;
Jim Ingham09437922013-03-01 20:04:25 +00003761
Ilia Kfcc89a02015-03-26 07:08:47 +00003762 if (GetShouldDetach())
3763 {
3764 // FIXME: This will have to be a process setting:
3765 bool keep_stopped = false;
3766 Detach(keep_stopped);
3767 }
3768
Jim Ingham09437922013-03-01 20:04:25 +00003769 m_destroy_in_process = true;
3770
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003771 Error error (WillDestroy());
3772 if (error.Success())
3773 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003774 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003775 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003776 {
Pavel Labathfcc7f662015-10-07 15:11:11 +00003777 error = StopForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003778 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003779
Jim Inghamaacc3182012-06-06 00:29:30 +00003780 if (m_public_state.GetValue() != eStateRunning)
3781 {
3782 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3783 // kill it, we don't want it hitting a breakpoint...
3784 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3785 // we're not going to have much luck doing this now.
3786 m_thread_list.DiscardThreadPlans();
3787 DisableAllBreakpointSites();
3788 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003789
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003790 error = DoDestroy();
3791 if (error.Success())
3792 {
3793 DidDestroy();
3794 StopPrivateStateThread();
3795 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003796 m_stdio_communication.Disconnect();
Greg Clayton23d54f42015-06-03 00:34:01 +00003797 m_stdio_communication.StopReadThread();
Vince Harrondf3f00f2015-02-10 21:09:04 +00003798 m_stdin_forward = false;
Greg Claytonb4874f12014-02-28 18:22:24 +00003799
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003800 if (m_process_input_reader)
Greg Claytonb4874f12014-02-28 18:22:24 +00003801 {
3802 m_process_input_reader->SetIsDone(true);
3803 m_process_input_reader->Cancel();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003804 m_process_input_reader.reset();
Greg Claytonb4874f12014-02-28 18:22:24 +00003805 }
3806
Greg Clayton85fb1b92012-09-11 02:33:37 +00003807 // If we exited when we were waiting for a process to stop, then
3808 // forward the event here so we don't lose the event
3809 if (exit_event_sp)
3810 {
3811 // Directly broadcast our exited event because we shut down our
3812 // private state thread above
3813 BroadcastEvent(exit_event_sp);
3814 }
3815
Jim Inghamb1e2e842012-04-12 18:49:31 +00003816 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3817 // the last events through the event system, in which case we might strand the write lock. Unlock
3818 // 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 +00003819 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003820 }
Jim Ingham09437922013-03-01 20:04:25 +00003821
3822 m_destroy_in_process = false;
3823
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003824 return error;
3825}
3826
3827Error
3828Process::Signal (int signal)
3829{
3830 Error error (WillSignal());
3831 if (error.Success())
3832 {
3833 error = DoSignal(signal);
3834 if (error.Success())
3835 DidSignal();
3836 }
3837 return error;
3838}
3839
Zachary Turner93749ab2015-03-03 21:51:25 +00003840void
Chaoren Linc963a222015-09-01 16:58:45 +00003841Process::SetUnixSignals(UnixSignalsSP &&signals_sp)
Zachary Turner93749ab2015-03-03 21:51:25 +00003842{
3843 assert (signals_sp && "null signals_sp");
3844 m_unix_signals_sp = signals_sp;
3845}
3846
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003847const lldb::UnixSignalsSP &
Zachary Turner93749ab2015-03-03 21:51:25 +00003848Process::GetUnixSignals ()
3849{
3850 assert (m_unix_signals_sp && "null m_unix_signals_sp");
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00003851 return m_unix_signals_sp;
Zachary Turner93749ab2015-03-03 21:51:25 +00003852}
3853
Greg Clayton514487e2011-02-15 21:59:32 +00003854lldb::ByteOrder
3855Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003856{
Zachary Turner7529df92015-09-01 20:02:29 +00003857 return GetTarget().GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003858}
3859
3860uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003861Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003862{
Zachary Turner7529df92015-09-01 20:02:29 +00003863 return GetTarget().GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003864}
3865
3866bool
3867Process::ShouldBroadcastEvent (Event *event_ptr)
3868{
3869 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3870 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003871 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003872
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003873 switch (state)
3874 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003875 case eStateDetached:
3876 case eStateExited:
3877 case eStateUnloaded:
Pavel Labath3f5df532015-03-12 10:12:41 +00003878 m_stdio_communication.SynchronizeWithReadThread();
Pavel Labatha9a43372015-09-03 09:30:17 +00003879 m_stdio_communication.Disconnect();
3880 m_stdio_communication.StopReadThread();
3881 m_stdin_forward = false;
3882
Jason Molenda62e06812016-02-16 04:14:33 +00003883 LLVM_FALLTHROUGH;
Pavel Labath3f5df532015-03-12 10:12:41 +00003884 case eStateConnected:
3885 case eStateAttaching:
3886 case eStateLaunching:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003887 // These events indicate changes in the state of the debugging session, always report them.
3888 return_value = true;
3889 break;
3890 case eStateInvalid:
3891 // We stopped for no apparent reason, don't report it.
3892 return_value = false;
3893 break;
3894 case eStateRunning:
3895 case eStateStepping:
3896 // If we've started the target running, we handle the cases where we
3897 // are already running and where there is a transition from stopped to
3898 // running differently.
3899 // running -> running: Automatically suppress extra running events
3900 // stopped -> running: Report except when there is one or more no votes
3901 // and no yes votes.
3902 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003903 if (m_force_next_event_delivery)
3904 return_value = true;
3905 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003906 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003907 switch (m_last_broadcast_state)
3908 {
3909 case eStateRunning:
3910 case eStateStepping:
3911 // We always suppress multiple runnings with no PUBLIC stop in between.
3912 return_value = false;
3913 break;
3914 default:
3915 // TODO: make this work correctly. For now always report
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00003916 // run if we aren't running so we don't miss any running
Jim Ingham1460e4b2014-01-10 23:46:59 +00003917 // events. If I run the lldb/test/thread/a.out file and
3918 // break at main.cpp:58, run and hit the breakpoints on
3919 // multiple threads, then somehow during the stepping over
3920 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003921
Jim Ingham1460e4b2014-01-10 23:46:59 +00003922 // This is a transition from stop to run.
3923 switch (m_thread_list.ShouldReportRun (event_ptr))
3924 {
3925 case eVoteYes:
3926 case eVoteNoOpinion:
3927 return_value = true;
3928 break;
3929 case eVoteNo:
3930 return_value = false;
3931 break;
3932 }
3933 break;
3934 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003935 }
3936 break;
3937 case eStateStopped:
3938 case eStateCrashed:
3939 case eStateSuspended:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003940 // We've stopped. First see if we're going to restart the target.
3941 // If we are going to stop, then we always broadcast the event.
3942 // 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 +00003943 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003944
Pavel Labath3f5df532015-03-12 10:12:41 +00003945 m_stdio_communication.SynchronizeWithReadThread();
Jim Inghamcb4ca112012-05-16 01:32:14 +00003946 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003947 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003948 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003949 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003950 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003951 static_cast<void*>(event_ptr),
Jim Ingham0161b492013-02-09 01:29:05 +00003952 StateAsCString(state));
Jim Ingham35878c42014-04-08 21:33:21 +00003953 // Even though we know we are going to stop, we should let the threads have a look at the stop,
3954 // so they can properly set their state.
3955 m_thread_list.ShouldStop (event_ptr);
Jim Ingham0161b492013-02-09 01:29:05 +00003956 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003957 }
3958 else
3959 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003960 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3961 bool should_resume = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003962
Jim Ingham0161b492013-02-09 01:29:05 +00003963 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3964 // Asking the thread list is also not likely to go well, since we are running again.
3965 // So in that case just report the event.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003966
Jim Ingham0161b492013-02-09 01:29:05 +00003967 if (!was_restarted)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00003968 should_resume = !m_thread_list.ShouldStop(event_ptr);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003969
Jim Ingham221d51c2013-05-08 00:35:16 +00003970 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003971 {
Jim Ingham0161b492013-02-09 01:29:05 +00003972 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3973 if (log)
Pavel Labath2acc4882016-01-05 17:55:32 +00003974 log->Printf ("Process::ShouldBroadcastEvent: should_resume: %i state: %s was_restarted: %i stop_vote: %d.",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003975 should_resume, StateAsCString(state),
3976 was_restarted, stop_vote);
3977
Jim Ingham0161b492013-02-09 01:29:05 +00003978 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003979 {
3980 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003981 return_value = true;
3982 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003983 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003984 case eVoteNo:
3985 return_value = false;
3986 break;
3987 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003988
Jim Inghamcb95f342012-09-05 21:13:56 +00003989 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003990 {
3991 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00003992 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s",
3993 static_cast<void*>(event_ptr),
3994 StateAsCString(state));
Jim Ingham0161b492013-02-09 01:29:05 +00003995 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003996 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003997 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003998 }
3999 else
4000 {
4001 return_value = true;
4002 SynchronouslyNotifyStateChanged (state);
4003 }
4004 }
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004005 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004006 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004007
Jim Ingham1460e4b2014-01-10 23:46:59 +00004008 // Forcing the next event delivery is a one shot deal. So reset it here.
4009 m_force_next_event_delivery = false;
4010
Jim Ingham0161b492013-02-09 01:29:05 +00004011 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
4012 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
4013 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
4014 // because the PublicState reflects the last event pulled off the queue, and there may be several
4015 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
4016 // yet. m_last_broadcast_state gets updated here.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004017
Jim Ingham0161b492013-02-09 01:29:05 +00004018 if (return_value)
4019 m_last_broadcast_state = state;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004020
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004021 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004022 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004023 static_cast<void*>(event_ptr), StateAsCString(state),
Jim Ingham0161b492013-02-09 01:29:05 +00004024 StateAsCString(m_last_broadcast_state),
4025 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004026 return return_value;
4027}
4028
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004029bool
Jim Ingham60c915e2015-06-23 21:02:45 +00004030Process::StartPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004031{
Greg Clayton5160ce52013-03-27 23:08:40 +00004032 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004033
Greg Clayton8b82f082011-04-12 05:54:46 +00004034 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004035 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00004036 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
4037
Jim Ingham60c915e2015-06-23 21:02:45 +00004038 if (!is_secondary_thread && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00004039 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004040
4041 // Create a thread that watches our internal state and controls which
4042 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00004043 char thread_name[1024];
Todd Fiala17096d72014-07-16 19:03:16 +00004044
Zachary Turner39de3112014-09-09 20:54:56 +00004045 if (HostInfo::GetMaxThreadNameLength() <= 30)
Todd Fiala17096d72014-07-16 19:03:16 +00004046 {
Zachary Turner39de3112014-09-09 20:54:56 +00004047 // On platforms with abbreviated thread name lengths, choose thread names that fit within the limit.
4048 if (already_running)
4049 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4050 else
4051 snprintf(thread_name, sizeof(thread_name), "intern-state");
Todd Fiala17096d72014-07-16 19:03:16 +00004052 }
Jim Ingham372787f2012-04-07 00:00:41 +00004053 else
Todd Fiala17096d72014-07-16 19:03:16 +00004054 {
4055 if (already_running)
Zachary Turner39de3112014-09-09 20:54:56 +00004056 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004057 else
Zachary Turner39de3112014-09-09 20:54:56 +00004058 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Todd Fiala17096d72014-07-16 19:03:16 +00004059 }
4060
Jim Ingham076b3042012-04-10 01:21:57 +00004061 // Create the private state thread, and start it running.
Jim Inghama1ca8142016-02-04 01:34:33 +00004062 PrivateStateThreadArgs *args_ptr = new PrivateStateThreadArgs(this, is_secondary_thread);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004063 m_private_state_thread = ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread, (void *) args_ptr, nullptr, 8 * 1024 * 1024);
Zachary Turneracee96a2014-09-23 18:32:09 +00004064 if (m_private_state_thread.IsJoinable())
Jim Ingham076b3042012-04-10 01:21:57 +00004065 {
4066 ResumePrivateStateThread();
4067 return true;
4068 }
4069 else
4070 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004071}
4072
4073void
4074Process::PausePrivateStateThread ()
4075{
4076 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4077}
4078
4079void
4080Process::ResumePrivateStateThread ()
4081{
4082 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4083}
4084
4085void
4086Process::StopPrivateStateThread ()
4087{
Greg Clayton8b82f082011-04-12 05:54:46 +00004088 if (PrivateStateThreadIsValid ())
4089 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004090 else
4091 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004092 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004093 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004094 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004095 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004096}
4097
4098void
4099Process::ControlPrivateStateThread (uint32_t signal)
4100{
Greg Clayton5160ce52013-03-27 23:08:40 +00004101 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004102
4103 assert (signal == eBroadcastInternalStateControlStop ||
4104 signal == eBroadcastInternalStateControlPause ||
4105 signal == eBroadcastInternalStateControlResume);
4106
4107 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004108 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004109
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004110 // Signal the private state thread. First we should copy this is case the
4111 // thread starts exiting since the private state thread will NULL this out
4112 // when it exits
Zachary Turner39de3112014-09-09 20:54:56 +00004113 HostThread private_state_thread(m_private_state_thread);
Zachary Turneracee96a2014-09-23 18:32:09 +00004114 if (private_state_thread.IsJoinable())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004115 {
4116 TimeValue timeout_time;
4117 bool timed_out;
4118
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004119 m_private_state_control_broadcaster.BroadcastEvent(signal, nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004120
4121 timeout_time = TimeValue::Now();
4122 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004123 if (log)
4124 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004125 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4126 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4127
4128 if (signal == eBroadcastInternalStateControlStop)
4129 {
4130 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004131 {
Zachary Turner39de3112014-09-09 20:54:56 +00004132 Error error = private_state_thread.Cancel();
Jim Inghamb1e2e842012-04-12 18:49:31 +00004133 if (log)
4134 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4135 }
4136 else
4137 {
4138 if (log)
4139 log->Printf ("The control event killed the private state thread without having to cancel.");
4140 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004141
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004142 thread_result_t result = nullptr;
Zachary Turner39de3112014-09-09 20:54:56 +00004143 private_state_thread.Join(&result);
4144 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004145 }
4146 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004147 else
4148 {
4149 if (log)
4150 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4151 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004152}
4153
4154void
Jim Inghamcfc09352012-07-27 23:57:19 +00004155Process::SendAsyncInterrupt ()
4156{
4157 if (PrivateStateThreadIsValid())
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004158 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
Jim Inghamcfc09352012-07-27 23:57:19 +00004159 else
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004160 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
Jim Inghamcfc09352012-07-27 23:57:19 +00004161}
4162
4163void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004164Process::HandlePrivateEvent (EventSP &event_sp)
4165{
Greg Clayton5160ce52013-03-27 23:08:40 +00004166 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004167 m_resume_requested = false;
4168
Greg Clayton414f5d32011-01-25 02:58:48 +00004169 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004170
4171 // First check to see if anybody wants a shot at this event:
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004172 if (m_next_event_action_ap)
Jim Inghambb3a2832011-01-29 01:49:25 +00004173 {
Jim Ingham754ab982011-01-29 04:05:41 +00004174 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004175 if (log)
4176 log->Printf ("Ran next event action, result was %d.", action_result);
4177
Jim Inghambb3a2832011-01-29 01:49:25 +00004178 switch (action_result)
4179 {
4180 case NextEventAction::eEventActionSuccess:
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004181 SetNextEventAction(nullptr);
Jim Inghambb3a2832011-01-29 01:49:25 +00004182 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004183
Jim Inghambb3a2832011-01-29 01:49:25 +00004184 case NextEventAction::eEventActionRetry:
4185 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004186
Jim Inghambb3a2832011-01-29 01:49:25 +00004187 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004188 // Handle Exiting Here. If we already got an exited event,
4189 // we should just propagate it. Otherwise, swallow this event,
4190 // and set our state to exit so the next event will kill us.
4191 if (new_state != eStateExited)
4192 {
4193 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004194 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004195 SetNextEventAction(nullptr);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004196 return;
4197 }
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004198 SetNextEventAction(nullptr);
Jim Inghambb3a2832011-01-29 01:49:25 +00004199 break;
4200 }
4201 }
4202
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004203 // See if we should broadcast this state to external clients?
4204 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004205
4206 if (should_broadcast)
4207 {
Greg Claytonb4874f12014-02-28 18:22:24 +00004208 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004209 if (log)
4210 {
Daniel Malead01b2952012-11-29 21:49:15 +00004211 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004212 __FUNCTION__,
4213 GetID(),
4214 StateAsCString(new_state),
4215 StateAsCString (GetState ()),
Greg Claytonb4874f12014-02-28 18:22:24 +00004216 is_hijacked ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004217 }
Jim Ingham9575d842011-03-11 03:53:59 +00004218 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004219 if (StateIsRunningState (new_state))
Greg Clayton44d93782014-01-27 23:43:24 +00004220 {
4221 // Only push the input handler if we aren't fowarding events,
4222 // as this means the curses GUI is in use...
Todd Fialaf72fa672014-10-07 16:05:21 +00004223 // Or don't push it if we are launching since it will come up stopped.
Zachary Turnerc62733b2015-05-20 18:31:17 +00004224 if (!GetTarget().GetDebugger().IsForwardingEvents() && new_state != eStateLaunching &&
4225 new_state != eStateAttaching)
Pavel Labath44464872015-05-27 12:40:32 +00004226 {
Greg Clayton44d93782014-01-27 23:43:24 +00004227 PushProcessIOHandler ();
Pavel Labath44464872015-05-27 12:40:32 +00004228 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue()+1, eBroadcastAlways);
4229 if (log)
4230 log->Printf("Process::%s updated m_iohandler_sync to %d", __FUNCTION__, m_iohandler_sync.GetValue());
4231 }
Greg Clayton44d93782014-01-27 23:43:24 +00004232 }
Greg Claytonb4874f12014-02-28 18:22:24 +00004233 else if (StateIsStoppedState(new_state, false))
4234 {
4235 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4236 {
4237 // If the lldb_private::Debugger is handling the events, we don't
4238 // want to pop the process IOHandler here, we want to do it when
4239 // we receive the stopped event so we can carefully control when
4240 // the process IOHandler is popped because when we stop we want to
4241 // display some text stating how and why we stopped, then maybe some
4242 // process/thread/frame info, and then we want the "(lldb) " prompt
4243 // to show up. If we pop the process IOHandler here, then we will
4244 // cause the command interpreter to become the top IOHandler after
4245 // the process pops off and it will update its prompt right away...
4246 // See the Debugger.cpp file where it calls the function as
4247 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4248 // Otherwise we end up getting overlapping "(lldb) " prompts and
4249 // garbled output.
4250 //
4251 // If we aren't handling the events in the debugger (which is indicated
4252 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or we
4253 // are hijacked, then we always pop the process IO handler manually.
4254 // Hijacking happens when the internal process state thread is running
4255 // thread plans, or when commands want to run in synchronous mode
4256 // and they call "process->WaitForProcessToStop()". An example of something
4257 // that will hijack the events is a simple expression:
4258 //
4259 // (lldb) expr (int)puts("hello")
4260 //
4261 // This will cause the internal process state thread to resume and halt
4262 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4263 // events) and we do need the IO handler to be pushed and popped
4264 // correctly.
4265
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004266 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
Greg Claytonb4874f12014-02-28 18:22:24 +00004267 PopProcessIOHandler ();
4268 }
4269 }
Jim Ingham9575d842011-03-11 03:53:59 +00004270
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004271 BroadcastEvent (event_sp);
4272 }
4273 else
4274 {
4275 if (log)
4276 {
Daniel Malead01b2952012-11-29 21:49:15 +00004277 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004278 __FUNCTION__,
4279 GetID(),
4280 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004281 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004282 }
4283 }
Pavel Labath19da1f12015-12-07 12:36:52 +00004284}
4285
4286Error
4287Process::HaltPrivate()
4288{
4289 EventSP event_sp;
4290 Error error (WillHalt());
4291 if (error.Fail())
4292 return error;
4293
4294 // Ask the process subclass to actually halt our process
4295 bool caused_stop;
4296 error = DoHalt(caused_stop);
4297
4298 DidHalt();
4299 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004300}
4301
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004302thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004303Process::PrivateStateThread (void *arg)
4304{
Jim Inghama1ca8142016-02-04 01:34:33 +00004305 PrivateStateThreadArgs real_args = *static_cast<PrivateStateThreadArgs *> (arg);
4306 free (arg);
4307 thread_result_t result = real_args.process->RunPrivateStateThread(real_args.is_secondary_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004308 return result;
4309}
4310
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004311thread_result_t
Jim Ingham60c915e2015-06-23 21:02:45 +00004312Process::RunPrivateStateThread (bool is_secondary_thread)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004313{
Jim Ingham076b3042012-04-10 01:21:57 +00004314 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004315 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004316
Greg Clayton5160ce52013-03-27 23:08:40 +00004317 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004318 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004319 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4320 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004321
4322 bool exit_now = false;
Pavel Labath19da1f12015-12-07 12:36:52 +00004323 bool interrupt_requested = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004324 while (!exit_now)
4325 {
4326 EventSP event_sp;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004327 WaitForEventsPrivate(nullptr, event_sp, control_only);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004328 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4329 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004330 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004331 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d",
4332 __FUNCTION__, static_cast<void*>(this), GetID(),
4333 event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004334
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004335 switch (event_sp->GetType())
4336 {
4337 case eBroadcastInternalStateControlStop:
4338 exit_now = true;
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00004339 break; // doing any internal state management below
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004340
4341 case eBroadcastInternalStateControlPause:
4342 control_only = true;
4343 break;
4344
4345 case eBroadcastInternalStateControlResume:
4346 control_only = false;
4347 break;
4348 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004349
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004350 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004351 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004352 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004353 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4354 {
4355 if (m_public_state.GetValue() == eStateAttaching)
4356 {
4357 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004358 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.",
4359 __FUNCTION__, static_cast<void*>(this),
4360 GetID());
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004361 BroadcastEvent(eBroadcastBitInterrupt, nullptr);
Jim Inghamcfc09352012-07-27 23:57:19 +00004362 }
Pavel Labath19da1f12015-12-07 12:36:52 +00004363 else if(StateIsRunningState(m_last_broadcast_state))
Jim Inghamcfc09352012-07-27 23:57:19 +00004364 {
4365 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004366 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.",
4367 __FUNCTION__, static_cast<void*>(this),
4368 GetID());
Pavel Labath19da1f12015-12-07 12:36:52 +00004369 Error error = HaltPrivate();
4370 if (error.Fail() && log)
4371 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") failed to halt the process: %s",
4372 __FUNCTION__, static_cast<void*>(this),
4373 GetID(), error.AsCString());
4374 // Halt should generate a stopped event. Make a note of the fact that we were
4375 // doing the interrupt, so we can set the interrupted flag after we receive the
4376 // event. We deliberately set this to true even if HaltPrivate failed, so that we
4377 // can interrupt on the next natural stop.
4378 interrupt_requested = true;
4379 }
4380 else
4381 {
4382 // This can happen when someone (e.g. Process::Halt) sees that we are running and
4383 // sends an interrupt request, but the process actually stops before we receive
4384 // it. In that case, we can just ignore the request. We use
4385 // m_last_broadcast_state, because the Stopped event may not have been popped of
4386 // the event queue yet, which is when the public state gets updated.
4387 if (log)
4388 log->Printf("Process::%s ignoring interrupt as we have already stopped.", __FUNCTION__);
Jim Inghamcfc09352012-07-27 23:57:19 +00004389 }
4390 continue;
4391 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004392
4393 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4394
4395 if (internal_state != eStateInvalid)
4396 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004397 if (m_clear_thread_plans_on_stop &&
4398 StateIsStoppedState(internal_state, true))
4399 {
4400 m_clear_thread_plans_on_stop = false;
4401 m_thread_list.DiscardThreadPlans();
4402 }
Pavel Labath19da1f12015-12-07 12:36:52 +00004403
4404 if (interrupt_requested)
4405 {
4406 if (StateIsStoppedState (internal_state, true))
4407 {
4408 // We requested the interrupt, so mark this as such in the stop event so
4409 // clients can tell an interrupted process from a natural stop
4410 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
4411 interrupt_requested = false;
4412 }
4413 else if (log)
4414 {
4415 log->Printf("Process::%s interrupt_requested, but a non-stopped state '%s' received.",
4416 __FUNCTION__, StateAsCString(internal_state));
4417 }
4418 }
4419
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004420 HandlePrivateEvent (event_sp);
4421 }
4422
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004423 if (internal_state == eStateInvalid ||
4424 internal_state == eStateExited ||
4425 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004426 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004427 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004428 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...",
4429 __FUNCTION__, static_cast<void*>(this), GetID(),
4430 StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004431
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004432 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004433 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004434 }
4435
Caroline Tice20ad3c42010-10-29 21:48:37 +00004436 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004437 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004438 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4439 __FUNCTION__, static_cast<void*>(this), GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004440
Jim Ingham60c915e2015-06-23 21:02:45 +00004441 // If we are a secondary thread, then the primary thread we are working for will have already
4442 // acquired the public_run_lock, and isn't done with what it was doing yet, so don't
4443 // try to change it on the way out.
4444 if (!is_secondary_thread)
4445 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004446 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Zachary Turner39de3112014-09-09 20:54:56 +00004447 m_private_state_thread.Reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004448 return NULL;
4449}
4450
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004451//------------------------------------------------------------------
4452// Process Event Data
4453//------------------------------------------------------------------
4454
4455Process::ProcessEventData::ProcessEventData () :
4456 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004457 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004458 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004459 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004460 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004461 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004462{
4463}
4464
4465Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4466 EventData (),
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004467 m_process_wp (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004468 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004469 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004470 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004471 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004472{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004473 if (process_sp)
4474 m_process_wp = process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004475}
4476
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004477Process::ProcessEventData::~ProcessEventData() = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004478
4479const ConstString &
4480Process::ProcessEventData::GetFlavorString ()
4481{
4482 static ConstString g_flavor ("Process::ProcessEventData");
4483 return g_flavor;
4484}
4485
4486const ConstString &
4487Process::ProcessEventData::GetFlavor () const
4488{
4489 return ProcessEventData::GetFlavorString ();
4490}
4491
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004492void
4493Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4494{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004495 ProcessSP process_sp(m_process_wp.lock());
4496
4497 if (!process_sp)
4498 return;
4499
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004500 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004501 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4502 // the public event queue, then other times when we're pretending that this is where we stopped at the
4503 // end of expression evaluation. m_update_state is used to distinguish these
4504 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004505 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004506 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004507 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004508
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004509 process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Jim Ingham35878c42014-04-08 21:33:21 +00004510
4511 // If this is a halt event, even if the halt stopped with some reason other than a plain interrupt (e.g. we had
4512 // already stopped for a breakpoint when the halt request came through) don't do the StopInfo actions, as they may
4513 // end up restarting the process.
4514 if (m_interrupted)
4515 return;
4516
4517 // If we're stopped and haven't restarted, then do the StopInfo actions here:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004518 if (m_state == eStateStopped && ! m_restarted)
Greg Clayton2e309072015-07-17 23:42:28 +00004519 {
4520 // Let process subclasses know we are about to do a public stop and
4521 // do anything they might need to in order to speed up register and
4522 // memory accesses.
4523 process_sp->WillPublicStop();
4524
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004525 ThreadList &curr_thread_list = process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004526 uint32_t num_threads = curr_thread_list.GetSize();
4527 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004528
Jim Ingham4b536182011-08-09 02:12:22 +00004529 // The actions might change one of the thread's stop_info's opinions about whether we should
4530 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004531
4532 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4533 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4534 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4535 // 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
4536 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004537 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004538 for (idx = 0; idx < num_threads; ++idx)
4539 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4540
Jim Inghamc7078c22012-12-13 22:24:15 +00004541 // Use this to track whether we should continue from here. We will only continue the target running if
4542 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4543 // then it doesn't matter what the other threads say...
4544
4545 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004546
Jim Ingham0ad7e052013-04-25 02:04:59 +00004547 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4548 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4549 // thing to do is, and it's better to let the user decide than continue behind their backs.
4550
4551 bool does_anybody_have_an_opinion = false;
4552
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004553 for (idx = 0; idx < num_threads; ++idx)
4554 {
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004555 curr_thread_list = process_sp->GetThreadList();
Jim Ingham0faa43f2011-11-08 03:00:11 +00004556 if (curr_thread_list.GetSize() != num_threads)
4557 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004558 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004559 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004560 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 +00004561 break;
4562 }
4563
4564 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4565
4566 if (thread_sp->GetIndexID() != thread_index_array[idx])
4567 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004568 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004569 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004570 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004571 idx,
4572 thread_index_array[idx],
4573 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004574 break;
4575 }
4576
Jim Inghamb15bfc72010-10-20 00:39:53 +00004577 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004578 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004579 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004580 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004581 bool this_thread_wants_to_stop;
4582 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004583 {
Jim Ingham0161b492013-02-09 01:29:05 +00004584 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4585 }
4586 else
4587 {
4588 stop_info_sp->PerformAction(event_ptr);
4589 // The stop action might restart the target. If it does, then we want to mark that in the
4590 // event so that whoever is receiving it will know to wait for the running event and reflect
4591 // that state appropriately.
4592 // We also need to stop processing actions, since they aren't expecting the target to be running.
4593
4594 // FIXME: we might have run.
4595 if (stop_info_sp->HasTargetRunSinceMe())
4596 {
4597 SetRestarted (true);
4598 break;
4599 }
4600
4601 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004602 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004603
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004604 if (!still_should_stop)
Jim Inghamc7078c22012-12-13 22:24:15 +00004605 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004606 }
4607 }
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004608
Jim Inghama8ca6e22013-05-03 23:04:37 +00004609 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004610 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004611 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004612 {
4613 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004614 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004615 // Use the public resume method here, since this is just
4616 // extending a public resume.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004617 process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004618 }
4619 else
4620 {
4621 // If we didn't restart, run the Stop Hooks here:
4622 // They might also restart the target, so watch for that.
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004623 process_sp->GetTarget().RunStopHooks();
4624 if (process_sp->GetPrivateState() == eStateRunning)
Jim Ingham4b536182011-08-09 02:12:22 +00004625 SetRestarted(true);
4626 }
Jim Ingham9575d842011-03-11 03:53:59 +00004627 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004628 }
4629}
4630
4631void
4632Process::ProcessEventData::Dump (Stream *s) const
4633{
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004634 ProcessSP process_sp(m_process_wp.lock());
4635
4636 if (process_sp)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004637 s->Printf(" process = %p (pid = %" PRIu64 "), ",
Greg Claytonaeb3b8b2015-05-29 03:20:37 +00004638 static_cast<void*>(process_sp.get()), process_sp->GetID());
4639 else
4640 s->PutCString(" process = NULL, ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004641
Greg Clayton8b82f082011-04-12 05:54:46 +00004642 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004643}
4644
4645const Process::ProcessEventData *
4646Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4647{
4648 if (event_ptr)
4649 {
4650 const EventData *event_data = event_ptr->GetData();
4651 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4652 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4653 }
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004654 return nullptr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004655}
4656
4657ProcessSP
4658Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4659{
4660 ProcessSP process_sp;
4661 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4662 if (data)
4663 process_sp = data->GetProcessSP();
4664 return process_sp;
4665}
4666
4667StateType
4668Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4669{
4670 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004671 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004672 return eStateInvalid;
4673 else
4674 return data->GetState();
4675}
4676
4677bool
4678Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4679{
4680 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004681 if (data == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004682 return false;
4683 else
4684 return data->GetRestarted();
4685}
4686
4687void
4688Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4689{
4690 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004691 if (data != nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004692 data->SetRestarted(new_value);
4693}
4694
Jim Ingham0161b492013-02-09 01:29:05 +00004695size_t
4696Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4697{
4698 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004699 if (data != nullptr)
Jim Ingham0161b492013-02-09 01:29:05 +00004700 return data->GetNumRestartedReasons();
4701 else
4702 return 0;
4703}
4704
4705const char *
4706Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4707{
4708 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004709 if (data != nullptr)
Jim Ingham0161b492013-02-09 01:29:05 +00004710 return data->GetRestartedReasonAtIndex(idx);
4711 else
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004712 return nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00004713}
4714
4715void
4716Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4717{
4718 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004719 if (data != nullptr)
Jim Ingham0161b492013-02-09 01:29:05 +00004720 data->AddRestartedReason(reason);
4721}
4722
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004723bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004724Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4725{
4726 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004727 if (data == nullptr)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004728 return false;
4729 else
4730 return data->GetInterrupted ();
4731}
4732
4733void
4734Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4735{
4736 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004737 if (data != nullptr)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004738 data->SetInterrupted(new_value);
4739}
4740
4741bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004742Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4743{
4744 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4745 if (data)
4746 {
4747 data->SetUpdateStateOnRemoval();
4748 return true;
4749 }
4750 return false;
4751}
4752
Greg Claytond9e416c2012-02-18 05:35:26 +00004753lldb::TargetSP
4754Process::CalculateTarget ()
4755{
Zachary Turner7529df92015-09-01 20:02:29 +00004756 return m_target_sp.lock();
Greg Claytond9e416c2012-02-18 05:35:26 +00004757}
4758
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004759void
Greg Clayton0603aa92010-10-04 01:05:56 +00004760Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004761{
Zachary Turner7529df92015-09-01 20:02:29 +00004762 exe_ctx.SetTargetPtr (&GetTarget());
Greg Claytonc14ee322011-09-22 04:58:26 +00004763 exe_ctx.SetProcessPtr (this);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004764 exe_ctx.SetThreadPtr(nullptr);
4765 exe_ctx.SetFramePtr(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004766}
4767
Greg Claytone996fd32011-03-08 22:40:15 +00004768//uint32_t
4769//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4770//{
4771// return 0;
4772//}
4773//
4774//ArchSpec
4775//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4776//{
4777// return Host::GetArchSpecForExistingProcess (pid);
4778//}
4779//
4780//ArchSpec
4781//Process::GetArchSpecForExistingProcess (const char *process_name)
4782//{
4783// return Host::GetArchSpecForExistingProcess (process_name);
4784//}
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004785
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004786void
4787Process::AppendSTDOUT (const char * s, size_t len)
4788{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004789 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004790 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004791 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004792}
4793
4794void
Greg Clayton93e86192011-11-13 04:45:22 +00004795Process::AppendSTDERR (const char * s, size_t len)
4796{
4797 Mutex::Locker locker (m_stdio_communication_mutex);
4798 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004799 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004800}
4801
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004802void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004803Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004804{
4805 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004806 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004807 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4808}
4809
4810size_t
4811Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4812{
4813 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004814 if (m_profile_data.empty())
4815 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004816
4817 std::string &one_profile_data = m_profile_data.front();
4818 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004819 if (bytes_available > 0)
4820 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004821 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004822 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004823 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4824 static_cast<void*>(buf),
4825 static_cast<uint64_t>(buf_size));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004826 if (bytes_available > buf_size)
4827 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004828 memcpy(buf, one_profile_data.c_str(), buf_size);
4829 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004830 bytes_available = buf_size;
4831 }
4832 else
4833 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004834 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004835 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004836 }
4837 }
4838 return bytes_available;
4839}
4840
Greg Clayton93e86192011-11-13 04:45:22 +00004841//------------------------------------------------------------------
4842// Process STDIO
4843//------------------------------------------------------------------
4844
4845size_t
4846Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4847{
4848 Mutex::Locker locker(m_stdio_communication_mutex);
4849 size_t bytes_available = m_stdout_data.size();
4850 if (bytes_available > 0)
4851 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004852 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004853 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004854 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4855 static_cast<void*>(buf),
4856 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004857 if (bytes_available > buf_size)
4858 {
4859 memcpy(buf, m_stdout_data.c_str(), buf_size);
4860 m_stdout_data.erase(0, buf_size);
4861 bytes_available = buf_size;
4862 }
4863 else
4864 {
4865 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4866 m_stdout_data.clear();
4867 }
4868 }
4869 return bytes_available;
4870}
4871
Greg Clayton93e86192011-11-13 04:45:22 +00004872size_t
4873Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4874{
4875 Mutex::Locker locker(m_stdio_communication_mutex);
4876 size_t bytes_available = m_stderr_data.size();
4877 if (bytes_available > 0)
4878 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004879 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004880 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00004881 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4882 static_cast<void*>(buf),
4883 static_cast<uint64_t>(buf_size));
Greg Clayton93e86192011-11-13 04:45:22 +00004884 if (bytes_available > buf_size)
4885 {
4886 memcpy(buf, m_stderr_data.c_str(), buf_size);
4887 m_stderr_data.erase(0, buf_size);
4888 bytes_available = buf_size;
4889 }
4890 else
4891 {
4892 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4893 m_stderr_data.clear();
4894 }
4895 }
4896 return bytes_available;
4897}
4898
4899void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004900Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4901{
4902 Process *process = (Process *) baton;
4903 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4904}
4905
Greg Clayton44d93782014-01-27 23:43:24 +00004906class IOHandlerProcessSTDIO :
4907 public IOHandler
4908{
4909public:
4910 IOHandlerProcessSTDIO (Process *process,
4911 int write_fd) :
Kate Stonee30f11d2014-11-17 19:06:59 +00004912 IOHandler(process->GetTarget().GetDebugger(), IOHandler::Type::ProcessIO),
Greg Clayton44d93782014-01-27 23:43:24 +00004913 m_process (process),
4914 m_read_file (),
4915 m_write_file (write_fd, false),
Greg Clayton100eb932014-07-02 21:10:39 +00004916 m_pipe ()
Greg Clayton44d93782014-01-27 23:43:24 +00004917 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004918 m_pipe.CreateNew(false);
Greg Clayton44d93782014-01-27 23:43:24 +00004919 m_read_file.SetDescriptor(GetInputFD(), false);
4920 }
4921
Eugene Zelenko8f30a652015-10-23 18:39:37 +00004922 ~IOHandlerProcessSTDIO() override = default;
4923
Greg Clayton44d93782014-01-27 23:43:24 +00004924 // Each IOHandler gets to run until it is done. It should read data
4925 // from the "in" and place output into "out" and "err and return
4926 // when done.
Pavel Labath44464872015-05-27 12:40:32 +00004927 void
4928 Run () override
Greg Clayton44d93782014-01-27 23:43:24 +00004929 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004930 if (!m_read_file.IsValid() || !m_write_file.IsValid() || !m_pipe.CanRead() || !m_pipe.CanWrite())
Greg Clayton44d93782014-01-27 23:43:24 +00004931 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004932 SetIsDone(true);
4933 return;
4934 }
4935
4936 SetIsDone(false);
4937 const int read_fd = m_read_file.GetDescriptor();
4938 TerminalState terminal_state;
4939 terminal_state.Save (read_fd, false);
4940 Terminal terminal(read_fd);
4941 terminal.SetCanonical(false);
4942 terminal.SetEcho(false);
Deepak Panickal914b8d92014-01-31 18:48:46 +00004943// FD_ZERO, FD_SET are not supported on windows
Hafiz Abid Qadeer6eff1012014-03-12 10:45:23 +00004944#ifndef _WIN32
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004945 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
Greg Clayton860582f2016-02-26 17:36:44 +00004946 m_is_running = true;
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004947 while (!GetIsDone())
4948 {
4949 fd_set read_fdset;
4950 FD_ZERO (&read_fdset);
4951 FD_SET (read_fd, &read_fdset);
4952 FD_SET (pipe_read_fd, &read_fdset);
4953 const int nfds = std::max<int>(read_fd, pipe_read_fd) + 1;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00004954 int num_set_fds = select(nfds, &read_fdset, nullptr, nullptr, nullptr);
Greg Clayton860582f2016-02-26 17:36:44 +00004955
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004956 if (num_set_fds < 0)
4957 {
4958 const int select_errno = errno;
4959
4960 if (select_errno != EINTR)
4961 SetIsDone(true);
4962 }
4963 else if (num_set_fds > 0)
4964 {
4965 char ch = 0;
4966 size_t n;
4967 if (FD_ISSET (read_fd, &read_fdset))
Greg Clayton44d93782014-01-27 23:43:24 +00004968 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004969 n = 1;
4970 if (m_read_file.Read(&ch, n).Success() && n == 1)
Greg Clayton44d93782014-01-27 23:43:24 +00004971 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004972 if (m_write_file.Write(&ch, n).Fail() || n != 1)
Greg Clayton44d93782014-01-27 23:43:24 +00004973 SetIsDone(true);
4974 }
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004975 else
4976 SetIsDone(true);
4977 }
4978 if (FD_ISSET (pipe_read_fd, &read_fdset))
4979 {
4980 size_t bytes_read;
4981 // Consume the interrupt byte
4982 Error error = m_pipe.Read(&ch, 1, bytes_read);
4983 if (error.Success())
Greg Clayton44d93782014-01-27 23:43:24 +00004984 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004985 switch (ch)
Greg Clayton44d93782014-01-27 23:43:24 +00004986 {
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004987 case 'q':
Greg Clayton44d93782014-01-27 23:43:24 +00004988 SetIsDone(true);
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004989 break;
4990 case 'i':
4991 if (StateIsRunningState(m_process->GetState()))
Pavel Labathfcc7f662015-10-07 15:11:11 +00004992 m_process->SendAsyncInterrupt();
Pavel Labathfb7d5b82015-05-28 13:41:08 +00004993 break;
Greg Clayton44d93782014-01-27 23:43:24 +00004994 }
4995 }
4996 }
Greg Clayton44d93782014-01-27 23:43:24 +00004997 }
Greg Clayton44d93782014-01-27 23:43:24 +00004998 }
Greg Clayton860582f2016-02-26 17:36:44 +00004999 m_is_running = false;
Pavel Labathfb7d5b82015-05-28 13:41:08 +00005000#endif
5001 terminal_state.Restore();
Greg Clayton44d93782014-01-27 23:43:24 +00005002 }
5003
Pavel Labath44464872015-05-27 12:40:32 +00005004 void
5005 Cancel () override
Greg Clayton44d93782014-01-27 23:43:24 +00005006 {
Greg Clayton860582f2016-02-26 17:36:44 +00005007 SetIsDone(true);
5008 // Only write to our pipe to cancel if we are in IOHandlerProcessSTDIO::Run().
5009 // We can end up with a python command that is being run from the command
5010 // interpreter:
5011 //
5012 // (lldb) step_process_thousands_of_times
5013 //
5014 // In this case the command interpreter will be in the middle of handling
5015 // the command and if the process pushes and pops the IOHandler thousands
5016 // of times, we can end up writing to m_pipe without ever consuming the
5017 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
5018 // deadlocking when the pipe gets fed up and blocks until data is consumed.
5019 if (m_is_running)
5020 {
5021 char ch = 'q'; // Send 'q' for quit
5022 size_t bytes_written = 0;
5023 m_pipe.Write(&ch, 1, bytes_written);
5024 }
Greg Clayton44d93782014-01-27 23:43:24 +00005025 }
Greg Claytone68f5d62014-02-24 22:50:57 +00005026
Pavel Labath44464872015-05-27 12:40:32 +00005027 bool
5028 Interrupt () override
Greg Claytone68f5d62014-02-24 22:50:57 +00005029 {
Greg Clayton19e11352014-02-26 22:47:33 +00005030 // Do only things that are safe to do in an interrupt context (like in
5031 // a SIGINT handler), like write 1 byte to a file descriptor. This will
5032 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
Pavel Labathfcc7f662015-10-07 15:11:11 +00005033 // that was written to the pipe and then call m_process->SendAsyncInterrupt()
5034 // from a much safer location in code.
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005035 if (m_active)
5036 {
5037 char ch = 'i'; // Send 'i' for interrupt
Zachary Turner0b9d3ee2014-12-17 18:02:19 +00005038 size_t bytes_written = 0;
5039 Error result = m_pipe.Write(&ch, 1, bytes_written);
5040 return result.Success();
Greg Clayton0fdd3ae2014-07-16 21:05:41 +00005041 }
5042 else
5043 {
5044 // This IOHandler might be pushed on the stack, but not being run currently
5045 // so do the right thing if we aren't actively watching for STDIN by sending
5046 // the interrupt to the process. Otherwise the write to the pipe above would
5047 // do nothing. This can happen when the command interpreter is running and
5048 // gets a "expression ...". It will be on the IOHandler thread and sending
5049 // the input is complete to the delegate which will cause the expression to
5050 // run, which will push the process IO handler, but not run it.
5051
5052 if (StateIsRunningState(m_process->GetState()))
5053 {
5054 m_process->SendAsyncInterrupt();
5055 return true;
5056 }
5057 }
5058 return false;
Greg Claytone68f5d62014-02-24 22:50:57 +00005059 }
Greg Clayton44d93782014-01-27 23:43:24 +00005060
Pavel Labath44464872015-05-27 12:40:32 +00005061 void
5062 GotEOF() override
Greg Clayton44d93782014-01-27 23:43:24 +00005063 {
Greg Clayton44d93782014-01-27 23:43:24 +00005064 }
5065
5066protected:
5067 Process *m_process;
5068 File m_read_file; // Read from this file (usually actual STDIN for LLDB
5069 File m_write_file; // Write to this file (usually the master pty for getting io to debuggee)
Greg Clayton100eb932014-07-02 21:10:39 +00005070 Pipe m_pipe;
Greg Clayton860582f2016-02-26 17:36:44 +00005071 std::atomic<bool> m_is_running;
Greg Clayton44d93782014-01-27 23:43:24 +00005072};
5073
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005074void
Greg Clayton44d93782014-01-27 23:43:24 +00005075Process::SetSTDIOFileDescriptor (int fd)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005076{
5077 // First set up the Read Thread for reading/handling process I/O
5078
Greg Clayton44d93782014-01-27 23:43:24 +00005079 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (fd, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005080
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005081 if (conn_ap)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005082 {
5083 m_stdio_communication.SetConnection (conn_ap.release());
5084 if (m_stdio_communication.IsConnected())
5085 {
5086 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
5087 m_stdio_communication.StartReadThread();
5088
5089 // Now read thread is set up, set up input reader.
5090
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005091 if (!m_process_input_reader)
Greg Clayton44d93782014-01-27 23:43:24 +00005092 m_process_input_reader.reset (new IOHandlerProcessSTDIO (this, fd));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005093 }
5094 }
5095}
5096
Greg Claytonb4874f12014-02-28 18:22:24 +00005097bool
Greg Clayton6fea17e2014-03-03 19:15:20 +00005098Process::ProcessIOHandlerIsActive ()
5099{
5100 IOHandlerSP io_handler_sp (m_process_input_reader);
5101 if (io_handler_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00005102 return GetTarget().GetDebugger().IsTopIOHandler (io_handler_sp);
Greg Clayton6fea17e2014-03-03 19:15:20 +00005103 return false;
5104}
5105bool
Greg Clayton44d93782014-01-27 23:43:24 +00005106Process::PushProcessIOHandler ()
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)
5110 {
Pavel Labath44464872015-05-27 12:40:32 +00005111 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
5112 if (log)
5113 log->Printf("Process::%s pushing IO handler", __FUNCTION__);
5114
Greg Clayton44d93782014-01-27 23:43:24 +00005115 io_handler_sp->SetIsDone(false);
Zachary Turner7529df92015-09-01 20:02:29 +00005116 GetTarget().GetDebugger().PushIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005117 return true;
Greg Clayton44d93782014-01-27 23:43:24 +00005118 }
Greg Claytonb4874f12014-02-28 18:22:24 +00005119 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005120}
5121
Greg Claytonb4874f12014-02-28 18:22:24 +00005122bool
Greg Clayton44d93782014-01-27 23:43:24 +00005123Process::PopProcessIOHandler ()
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005124{
Greg Clayton44d93782014-01-27 23:43:24 +00005125 IOHandlerSP io_handler_sp (m_process_input_reader);
5126 if (io_handler_sp)
Zachary Turner7529df92015-09-01 20:02:29 +00005127 return GetTarget().GetDebugger().PopIOHandler (io_handler_sp);
Greg Claytonb4874f12014-02-28 18:22:24 +00005128 return false;
Caroline Ticeef5c6d02010-11-16 05:07:41 +00005129}
5130
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005131// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00005132void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005133Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005134{
Greg Clayton6920b522012-08-22 18:39:03 +00005135 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005136}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005137
Greg Clayton99d0faf2010-11-18 23:32:35 +00005138void
Caroline Tice20bd37f2011-03-10 22:14:10 +00005139Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00005140{
Greg Clayton6920b522012-08-22 18:39:03 +00005141 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00005142}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00005143
Jim Inghamc60963c2015-10-12 19:11:03 +00005144namespace
5145{
5146 // RestorePlanState is used to record the "is private", "is master" and "okay to discard" fields of
5147 // the plan we are running, and reset it on Clean or on destruction.
5148 // It will only reset the state once, so you can call Clean and then monkey with the state and it
5149 // won't get reset on you again.
5150
5151 class RestorePlanState
5152 {
5153 public:
5154 RestorePlanState (lldb::ThreadPlanSP thread_plan_sp) :
5155 m_thread_plan_sp(thread_plan_sp),
5156 m_already_reset(false)
5157 {
5158 if (m_thread_plan_sp)
5159 {
5160 m_private = m_thread_plan_sp->GetPrivate();
5161 m_is_master = m_thread_plan_sp->IsMasterPlan();
5162 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
5163 }
5164 }
5165
5166 ~RestorePlanState()
5167 {
5168 Clean();
5169 }
5170
5171 void
5172 Clean ()
5173 {
5174 if (!m_already_reset && m_thread_plan_sp)
5175 {
5176 m_already_reset = true;
5177 m_thread_plan_sp->SetPrivate(m_private);
5178 m_thread_plan_sp->SetIsMasterPlan (m_is_master);
5179 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
5180 }
5181 }
Eugene Zelenko8f30a652015-10-23 18:39:37 +00005182
Jim Inghamc60963c2015-10-12 19:11:03 +00005183 private:
5184 lldb::ThreadPlanSP m_thread_plan_sp;
5185 bool m_already_reset;
5186 bool m_private;
5187 bool m_is_master;
5188 bool m_okay_to_discard;
5189 };
Eugene Zelenko8f30a652015-10-23 18:39:37 +00005190} // anonymous namespace
Jim Inghamc60963c2015-10-12 19:11:03 +00005191
Jim Ingham1624a2d2014-05-05 02:26:40 +00005192ExpressionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00005193Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00005194 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005195 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00005196 Stream &errors)
5197{
Jim Ingham8646d3c2014-05-05 02:47:44 +00005198 ExpressionResults return_value = eExpressionSetupError;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005199
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005200 if (!thread_plan_sp)
Jim Ingham77787032011-01-20 02:03:18 +00005201 {
5202 errors.Printf("RunThreadPlan called with empty thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005203 return eExpressionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00005204 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005205
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005206 if (!thread_plan_sp->ValidatePlan(nullptr))
Jim Ingham7d7931d2013-03-28 00:05:34 +00005207 {
5208 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005209 return eExpressionSetupError;
Jim Ingham7d7931d2013-03-28 00:05:34 +00005210 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005211
Greg Claytonc14ee322011-09-22 04:58:26 +00005212 if (exe_ctx.GetProcessPtr() != this)
5213 {
5214 errors.Printf("RunThreadPlan called on wrong process.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005215 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005216 }
5217
5218 Thread *thread = exe_ctx.GetThreadPtr();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005219 if (thread == nullptr)
Greg Claytonc14ee322011-09-22 04:58:26 +00005220 {
5221 errors.Printf("RunThreadPlan called with invalid thread.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005222 return eExpressionSetupError;
Greg Claytonc14ee322011-09-22 04:58:26 +00005223 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005224
Jim Inghamc60963c2015-10-12 19:11:03 +00005225 // We need to change some of the thread plan attributes for the thread plan runner. This will restore them
5226 // when we are done:
5227
5228 RestorePlanState thread_plan_restorer(thread_plan_sp);
5229
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005230 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
5231 // For that to be true the plan can't be private - since private plans suppress themselves in the
5232 // GetCompletedPlan call.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005233
Jim Ingham17e5c4e2011-05-17 22:24:54 +00005234 thread_plan_sp->SetPrivate(false);
Jim Inghamc60963c2015-10-12 19:11:03 +00005235
5236 // The plans run with RunThreadPlan also need to be terminal master plans or when they are done we will end
5237 // up asking the plan above us whether we should stop, which may give the wrong answer.
5238
5239 thread_plan_sp->SetIsMasterPlan (true);
5240 thread_plan_sp->SetOkayToDiscard(false);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005241
Jim Ingham444586b2011-01-24 06:34:17 +00005242 if (m_private_state.GetValue() != eStateStopped)
5243 {
5244 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005245 return eExpressionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00005246 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005247
Jim Ingham66243842011-08-13 00:56:10 +00005248 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00005249 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00005250 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00005251 if (!selected_frame_sp)
5252 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005253 thread->SetSelectedFrame(nullptr);
Jim Ingham11b0e052013-02-19 23:22:45 +00005254 selected_frame_sp = thread->GetSelectedFrame();
5255 if (!selected_frame_sp)
5256 {
5257 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005258 return eExpressionSetupError;
Jim Ingham11b0e052013-02-19 23:22:45 +00005259 }
5260 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005261
Jim Ingham11b0e052013-02-19 23:22:45 +00005262 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005263
5264 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
5265 // so we should arrange to reset them as well.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005266
Greg Claytonc14ee322011-09-22 04:58:26 +00005267 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005268
Jim Ingham66243842011-08-13 00:56:10 +00005269 uint32_t selected_tid;
5270 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00005271 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005272 {
5273 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00005274 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00005275 }
5276 else
5277 {
5278 selected_tid = LLDB_INVALID_THREAD_ID;
5279 }
5280
Zachary Turner39de3112014-09-09 20:54:56 +00005281 HostThread backup_private_state_thread;
Jason Molenda76513fd2014-10-15 23:39:31 +00005282 lldb::StateType old_state = eStateInvalid;
Jim Ingham076b3042012-04-10 01:21:57 +00005283 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00005284
Greg Clayton5160ce52013-03-27 23:08:40 +00005285 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Zachary Turner39de3112014-09-09 20:54:56 +00005286 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
Jim Ingham372787f2012-04-07 00:00:41 +00005287 {
Jim Ingham076b3042012-04-10 01:21:57 +00005288 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
5289 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00005290 // 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 +00005291 // we are fielding public events here.
5292 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00005293 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 +00005294
Jim Ingham372787f2012-04-07 00:00:41 +00005295 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00005296
5297 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
5298 // returning control here.
5299 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
5300 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
5301 // before the plan we want to run. Since base plans always stop and return control to the user, that will
5302 // do just what we want.
5303 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
5304 thread->QueueThreadPlan (stopper_base_plan_sp, false);
5305 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
5306 old_state = m_public_state.GetValue();
5307 m_public_state.SetValueNoLock(eStateStopped);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005308
Jim Ingham076b3042012-04-10 01:21:57 +00005309 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00005310 StartPrivateStateThread(true);
5311 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005312
Jim Ingham372787f2012-04-07 00:00:41 +00005313 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005314
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005315 if (options.GetDebug())
5316 {
5317 // In this case, we aren't actually going to run, we just want to stop right away.
5318 // Flush this thread so we will refetch the stacks and show the correct backtrace.
5319 // FIXME: To make this prettier we should invent some stop reason for this, but that
5320 // is only cosmetic, and this functionality is only of use to lldb developers who can
5321 // live with not pretty...
5322 thread->Flush();
Jim Ingham8646d3c2014-05-05 02:47:44 +00005323 return eExpressionStoppedForDebug;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005324 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005325
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00005326 Listener listener("lldb.process.listener.run-thread-plan");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005327
Sean Callanana46ec452012-07-11 21:31:24 +00005328 lldb::EventSP event_to_broadcast_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005329
Jim Ingham77787032011-01-20 02:03:18 +00005330 {
Sean Callanana46ec452012-07-11 21:31:24 +00005331 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
5332 // restored on exit to the function.
5333 //
5334 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
5335 // is put into event_to_broadcast_sp for rebroadcasting.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005336
Sean Callanana46ec452012-07-11 21:31:24 +00005337 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005338
Jim Inghamf48169b2010-11-30 02:22:11 +00005339 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00005340 {
5341 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00005342 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00005343 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00005344 thread->GetIndexID(),
5345 thread->GetID(),
5346 s.GetData());
5347 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005348
Sean Callanana46ec452012-07-11 21:31:24 +00005349 bool got_event;
5350 lldb::EventSP event_sp;
5351 lldb::StateType stop_state = lldb::eStateInvalid;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005352
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005353 TimeValue* timeout_ptr = nullptr;
Sean Callanana46ec452012-07-11 21:31:24 +00005354 TimeValue real_timeout;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005355
Jim Ingham0161b492013-02-09 01:29:05 +00005356 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 +00005357 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005358 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00005359 const uint64_t default_one_thread_timeout_usec = 250000;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005360
Jim Ingham0161b492013-02-09 01:29:05 +00005361 // This is just for accounting:
5362 uint32_t num_resumes = 0;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005363
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005364 uint32_t timeout_usec = options.GetTimeoutUsec();
Jim Inghamfd95f892014-04-22 01:41:52 +00005365 uint32_t one_thread_timeout_usec;
5366 uint32_t all_threads_timeout_usec = 0;
Jim Inghamfe1c3422014-04-16 02:24:48 +00005367
5368 // If we are going to run all threads the whole time, or if we are only going to run one thread,
5369 // then we don't need the first timeout. So we set the final timeout, and pretend we are after the
5370 // first timeout already.
5371
5372 if (!options.GetStopOthers() || !options.GetTryAllThreads())
Jim Ingham286fb1e2014-02-28 02:52:06 +00005373 {
5374 before_first_timeout = false;
Jim Inghamfd95f892014-04-22 01:41:52 +00005375 one_thread_timeout_usec = 0;
5376 all_threads_timeout_usec = timeout_usec;
Jim Ingham286fb1e2014-02-28 02:52:06 +00005377 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005378 else
Jim Ingham0161b492013-02-09 01:29:05 +00005379 {
Jim Inghamfd95f892014-04-22 01:41:52 +00005380 uint32_t option_one_thread_timeout = options.GetOneThreadTimeoutUsec();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005381
Jim Ingham914f4e72014-03-28 21:58:28 +00005382 // If the overall wait is forever, then we only need to set the one thread timeout:
5383 if (timeout_usec == 0)
5384 {
Ed Maste801335c2014-03-31 19:28:14 +00005385 if (option_one_thread_timeout != 0)
Jim Inghamfd95f892014-04-22 01:41:52 +00005386 one_thread_timeout_usec = option_one_thread_timeout;
Jim Ingham914f4e72014-03-28 21:58:28 +00005387 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005388 one_thread_timeout_usec = default_one_thread_timeout_usec;
Jim Ingham914f4e72014-03-28 21:58:28 +00005389 }
Jim Ingham0161b492013-02-09 01:29:05 +00005390 else
5391 {
Jim Ingham914f4e72014-03-28 21:58:28 +00005392 // Otherwise, if the one thread timeout is set, make sure it isn't longer than the overall timeout,
5393 // and use it, otherwise use half the total timeout, bounded by the default_one_thread_timeout_usec.
5394 uint64_t computed_one_thread_timeout;
5395 if (option_one_thread_timeout != 0)
5396 {
5397 if (timeout_usec < option_one_thread_timeout)
5398 {
5399 errors.Printf("RunThreadPlan called without one thread timeout greater than total timeout");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005400 return eExpressionSetupError;
Jim Ingham914f4e72014-03-28 21:58:28 +00005401 }
5402 computed_one_thread_timeout = option_one_thread_timeout;
5403 }
5404 else
5405 {
5406 computed_one_thread_timeout = timeout_usec / 2;
5407 if (computed_one_thread_timeout > default_one_thread_timeout_usec)
5408 computed_one_thread_timeout = default_one_thread_timeout_usec;
5409 }
Jim Inghamfd95f892014-04-22 01:41:52 +00005410 one_thread_timeout_usec = computed_one_thread_timeout;
5411 all_threads_timeout_usec = timeout_usec - one_thread_timeout_usec;
Jim Ingham0161b492013-02-09 01:29:05 +00005412 }
Jim Ingham0161b492013-02-09 01:29:05 +00005413 }
Jim Inghamfe1c3422014-04-16 02:24:48 +00005414
5415 if (log)
Jim Inghamfd95f892014-04-22 01:41:52 +00005416 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 +00005417 options.GetStopOthers(),
5418 options.GetTryAllThreads(),
Jim Inghamfd95f892014-04-22 01:41:52 +00005419 before_first_timeout,
5420 one_thread_timeout_usec,
5421 all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005422
Jim Ingham1460e4b2014-01-10 23:46:59 +00005423 // This isn't going to work if there are unfetched events on the queue.
5424 // Are there cases where we might want to run the remaining events here, and then try to
5425 // call the function? That's probably being too tricky for our own good.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005426
Jim Ingham1460e4b2014-01-10 23:46:59 +00005427 Event *other_events = listener.PeekAtNextEvent();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005428 if (other_events != nullptr)
Jim Ingham1460e4b2014-01-10 23:46:59 +00005429 {
5430 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005431 return eExpressionSetupError;
Jim Ingham1460e4b2014-01-10 23:46:59 +00005432 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005433
Jim Ingham1460e4b2014-01-10 23:46:59 +00005434 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5435 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5436 // event coalescing to cause us to lose OUR running event...
5437 ForceNextEventDelivery();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005438
Jim Ingham8559a352012-11-26 23:52:18 +00005439 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5440 // So don't call return anywhere within it.
Jim Ingham35878c42014-04-08 21:33:21 +00005441
5442#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5443 // It's pretty much impossible to write test cases for things like:
5444 // One thread timeout expires, I go to halt, but the process already stopped
5445 // on the function call stop breakpoint. Turning on this define will make us not
5446 // fetch the first event till after the halt. So if you run a quick function, it will have
5447 // completed, and the completion event will be waiting, when you interrupt for halt.
5448 // The expression evaluation should still succeed.
5449 bool miss_first_event = true;
5450#endif
Jim Inghamfd95f892014-04-22 01:41:52 +00005451 TimeValue one_thread_timeout;
5452 TimeValue final_timeout;
Eugene Zelenko8f30a652015-10-23 18:39:37 +00005453
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005454 while (true)
Sean Callanana46ec452012-07-11 21:31:24 +00005455 {
5456 // We usually want to resume the process if we get to the top of the loop.
5457 // The only exception is if we get two running events with no intervening
5458 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005459 if (log)
5460 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5461 do_resume,
5462 handle_running_event,
5463 before_first_timeout);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005464
Jim Ingham184e9812013-01-15 02:47:48 +00005465 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005466 {
5467 // Do the initial resume and wait for the running event before going further.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005468
Jim Ingham184e9812013-01-15 02:47:48 +00005469 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005470 {
Jim Ingham0161b492013-02-09 01:29:05 +00005471 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005472 Error resume_error = PrivateResume ();
5473 if (!resume_error.Success())
5474 {
Jim Ingham0161b492013-02-09 01:29:05 +00005475 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5476 num_resumes,
5477 resume_error.AsCString());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005478 return_value = eExpressionSetupError;
Jim Ingham184e9812013-01-15 02:47:48 +00005479 break;
5480 }
Sean Callanana46ec452012-07-11 21:31:24 +00005481 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005482
Jim Ingham0161b492013-02-09 01:29:05 +00005483 TimeValue resume_timeout = TimeValue::Now();
5484 resume_timeout.OffsetWithMicroSeconds(500000);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005485
Jim Ingham0161b492013-02-09 01:29:05 +00005486 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005487 if (!got_event)
5488 {
5489 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005490 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5491 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005492
Jim Ingham0161b492013-02-09 01:29:05 +00005493 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005494 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005495 break;
5496 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005497
Sean Callanana46ec452012-07-11 21:31:24 +00005498 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005499
Sean Callanana46ec452012-07-11 21:31:24 +00005500 if (stop_state != eStateRunning)
5501 {
Jim Ingham0161b492013-02-09 01:29:05 +00005502 bool restarted = false;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005503
Jim Ingham0161b492013-02-09 01:29:05 +00005504 if (stop_state == eStateStopped)
5505 {
5506 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5507 if (log)
5508 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5509 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5510 num_resumes,
5511 StateAsCString(stop_state),
5512 restarted,
5513 do_resume,
5514 handle_running_event);
5515 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005516
Jim Ingham0161b492013-02-09 01:29:05 +00005517 if (restarted)
5518 {
5519 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5520 // 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 +00005521 const bool clear_thread_plans = false;
5522 const bool use_run_lock = false;
5523 Halt(clear_thread_plans, use_run_lock);
Jim Ingham0161b492013-02-09 01:29:05 +00005524 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005525
Jim Ingham35e1bda2012-10-16 21:41:58 +00005526 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5527 StateAsCString(stop_state));
Jim Ingham8646d3c2014-05-05 02:47:44 +00005528 return_value = eExpressionSetupError;
Sean Callanana46ec452012-07-11 21:31:24 +00005529 break;
5530 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005531
Sean Callanana46ec452012-07-11 21:31:24 +00005532 if (log)
5533 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5534 // We need to call the function synchronously, so spin waiting for it to return.
5535 // If we get interrupted while executing, we're going to lose our context, and
5536 // won't be able to gather the result at this point.
5537 // We set the timeout AFTER the resume, since the resume takes some time and we
5538 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005539 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005540 else
5541 {
Sean Callanana46ec452012-07-11 21:31:24 +00005542 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005543 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005544 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005545
Jim Ingham0161b492013-02-09 01:29:05 +00005546 if (before_first_timeout)
5547 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005548 if (options.GetTryAllThreads())
Jim Inghamfd95f892014-04-22 01:41:52 +00005549 {
5550 one_thread_timeout = TimeValue::Now();
5551 one_thread_timeout.OffsetWithMicroSeconds(one_thread_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005552 timeout_ptr = &one_thread_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005553 }
Jim Ingham0161b492013-02-09 01:29:05 +00005554 else
5555 {
5556 if (timeout_usec == 0)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005557 timeout_ptr = nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00005558 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005559 {
5560 final_timeout = TimeValue::Now();
5561 final_timeout.OffsetWithMicroSeconds (timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005562 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005563 }
Jim Ingham0161b492013-02-09 01:29:05 +00005564 }
5565 }
5566 else
5567 {
5568 if (timeout_usec == 0)
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005569 timeout_ptr = nullptr;
Jim Ingham0161b492013-02-09 01:29:05 +00005570 else
Jim Inghamfd95f892014-04-22 01:41:52 +00005571 {
5572 final_timeout = TimeValue::Now();
5573 final_timeout.OffsetWithMicroSeconds (all_threads_timeout_usec);
Jim Ingham0161b492013-02-09 01:29:05 +00005574 timeout_ptr = &final_timeout;
Jim Inghamfd95f892014-04-22 01:41:52 +00005575 }
Jim Ingham0161b492013-02-09 01:29:05 +00005576 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005577
Jim Ingham0161b492013-02-09 01:29:05 +00005578 do_resume = true;
5579 handle_running_event = true;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005580
Sean Callanana46ec452012-07-11 21:31:24 +00005581 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005582 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005583
Jim Ingham0f16e732011-02-08 05:20:59 +00005584 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005585 {
Sean Callanana46ec452012-07-11 21:31:24 +00005586 if (timeout_ptr)
5587 {
Matt Kopec676a4872013-02-21 23:55:31 +00005588 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005589 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5590 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005591 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005592 else
Sean Callanana46ec452012-07-11 21:31:24 +00005593 {
5594 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5595 }
5596 }
Jim Ingham35878c42014-04-08 21:33:21 +00005597
5598#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5599 // See comment above...
5600 if (miss_first_event)
5601 {
5602 usleep(1000);
5603 miss_first_event = false;
5604 got_event = false;
5605 }
5606 else
5607#endif
Sean Callanana46ec452012-07-11 21:31:24 +00005608 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005609
Sean Callanana46ec452012-07-11 21:31:24 +00005610 if (got_event)
5611 {
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005612 if (event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005613 {
5614 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005615 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005616 {
Pavel Labath19da1f12015-12-07 12:36:52 +00005617 const bool clear_thread_plans = false;
5618 const bool use_run_lock = false;
5619 Halt(clear_thread_plans, use_run_lock);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005620 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005621 errors.Printf ("Execution halted by user interrupt.");
5622 if (log)
5623 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005624 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005625 }
5626 else
5627 {
5628 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5629 if (log)
5630 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005631
Jim Inghamcfc09352012-07-27 23:57:19 +00005632 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005633 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005634 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005635 {
Jim Ingham0161b492013-02-09 01:29:05 +00005636 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005637 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5638 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005639 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005640 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005641 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005642 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Jim Ingham8646d3c2014-05-05 02:47:44 +00005643 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005644 }
5645 else
5646 {
Jim Ingham0161b492013-02-09 01:29:05 +00005647 // If we were restarted, we just need to go back up to fetch another event.
5648 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005649 {
5650 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005651 {
5652 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5653 }
5654 keep_going = true;
5655 do_resume = false;
5656 handle_running_event = true;
Jim Inghamcfc09352012-07-27 23:57:19 +00005657 }
5658 else
5659 {
Jim Ingham0161b492013-02-09 01:29:05 +00005660 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5661 StopReason stop_reason = eStopReasonInvalid;
5662 if (stop_info_sp)
5663 stop_reason = stop_info_sp->GetStopReason();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005664
Jim Ingham0161b492013-02-09 01:29:05 +00005665 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5666 // it is OUR plan that is complete?
5667 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005668 {
5669 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005670 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
Jim Inghamc60963c2015-10-12 19:11:03 +00005671
5672 // Restore the plan state so it will get reported as intended when we are done.
5673 thread_plan_restorer.Clean();
5674
Jim Ingham8646d3c2014-05-05 02:47:44 +00005675 return_value = eExpressionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005676 }
5677 else
5678 {
Jim Ingham0161b492013-02-09 01:29:05 +00005679 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005680 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005681 {
5682 if (log)
5683 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham8646d3c2014-05-05 02:47:44 +00005684 return_value = eExpressionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005685 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005686 {
Jim Inghamc60963c2015-10-12 19:11:03 +00005687 // Restore the plan state and then force Private to false. We are
5688 // going to stop because of this plan so we need it to become a public
5689 // plan or it won't report correctly when we continue to its termination
5690 // later on.
5691 thread_plan_restorer.Clean();
5692 if (thread_plan_sp)
5693 thread_plan_sp->SetPrivate(false);
Sean Callanan4b388c92013-07-30 19:54:09 +00005694 event_to_broadcast_sp = event_sp;
5695 }
Jim Ingham0161b492013-02-09 01:29:05 +00005696 }
Jim Ingham184e9812013-01-15 02:47:48 +00005697 else
Jim Ingham0161b492013-02-09 01:29:05 +00005698 {
5699 if (log)
5700 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005701 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005702 event_to_broadcast_sp = event_sp;
Jim Ingham8646d3c2014-05-05 02:47:44 +00005703 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005704 }
Jim Ingham184e9812013-01-15 02:47:48 +00005705 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005706 }
Sean Callanana46ec452012-07-11 21:31:24 +00005707 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005708 }
5709 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005710
Jim Inghamcfc09352012-07-27 23:57:19 +00005711 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005712 // This shouldn't really happen, but sometimes we do get two running events without an
5713 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005714 do_resume = false;
5715 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005716 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005717 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005718
Jim Inghamcfc09352012-07-27 23:57:19 +00005719 default:
5720 if (log)
5721 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005722
Jim Inghamcfc09352012-07-27 23:57:19 +00005723 if (stop_state == eStateExited)
5724 event_to_broadcast_sp = event_sp;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005725
Sean Callananbf154da2012-08-08 17:35:10 +00005726 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005727 return_value = eExpressionInterrupted;
Jim Inghamcfc09352012-07-27 23:57:19 +00005728 break;
5729 }
Sean Callanana46ec452012-07-11 21:31:24 +00005730 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005731
Sean Callanana46ec452012-07-11 21:31:24 +00005732 if (keep_going)
5733 continue;
5734 else
5735 break;
5736 }
5737 else
5738 {
5739 if (log)
5740 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005741 return_value = eExpressionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005742 break;
5743 }
5744 }
5745 else
5746 {
5747 // If we didn't get an event that means we've timed out...
5748 // We will interrupt the process here. Depending on what we were asked to do we will
5749 // either exit, or try with all threads running for the same timeout.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005750
Sean Callanana46ec452012-07-11 21:31:24 +00005751 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005752 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005753 {
Jim Ingham0161b492013-02-09 01:29:05 +00005754 if (before_first_timeout)
Jim Inghamfe1c3422014-04-16 02:24:48 +00005755 {
5756 if (timeout_usec != 0)
5757 {
Jim Inghamfe1c3422014-04-16 02:24:48 +00005758 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jim Inghamfd95f892014-04-22 01:41:52 +00005759 "running for %" PRIu32 " usec with all threads enabled.",
5760 all_threads_timeout_usec);
Jim Inghamfe1c3422014-04-16 02:24:48 +00005761 }
5762 else
5763 {
5764 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Ed Mastee61c7b02014-04-29 17:48:06 +00005765 "running forever with all threads enabled.");
Jim Inghamfe1c3422014-04-16 02:24:48 +00005766 }
5767 }
Sean Callanana46ec452012-07-11 21:31:24 +00005768 else
5769 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005770 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005771 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005772 }
5773 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005774 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005775 "abandoning execution.",
5776 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005777 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005778
Jim Ingham0161b492013-02-09 01:29:05 +00005779 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5780 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5781 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5782 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5783 // stopped event. That's what this while loop does.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005784
Jim Ingham0161b492013-02-09 01:29:05 +00005785 bool back_to_top = true;
5786 uint32_t try_halt_again = 0;
5787 bool do_halt = true;
5788 const uint32_t num_retries = 5;
5789 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005790 {
Jim Ingham0161b492013-02-09 01:29:05 +00005791 Error halt_error;
5792 if (do_halt)
5793 {
5794 if (log)
5795 log->Printf ("Process::RunThreadPlan(): Running Halt.");
Pavel Labath19da1f12015-12-07 12:36:52 +00005796 const bool clear_thread_plans = false;
5797 const bool use_run_lock = false;
5798 Halt(clear_thread_plans, use_run_lock);
Jim Ingham0161b492013-02-09 01:29:05 +00005799 }
5800 if (halt_error.Success())
5801 {
5802 if (log)
5803 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005804
Jim Ingham0161b492013-02-09 01:29:05 +00005805 real_timeout = TimeValue::Now();
5806 real_timeout.OffsetWithMicroSeconds(500000);
5807
5808 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005809
Jim Ingham0161b492013-02-09 01:29:05 +00005810 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005811 {
Jim Ingham0161b492013-02-09 01:29:05 +00005812 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5813 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005814 {
Jim Ingham0161b492013-02-09 01:29:05 +00005815 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5816 if (stop_state == lldb::eStateStopped
5817 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5818 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005819 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005820
Jim Ingham0161b492013-02-09 01:29:05 +00005821 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005822 {
Jim Ingham0161b492013-02-09 01:29:05 +00005823 // Between the time we initiated the Halt and the time we delivered it, the process could have
5824 // already finished its job. Check that here:
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005825
Jim Ingham0161b492013-02-09 01:29:05 +00005826 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5827 {
5828 if (log)
5829 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5830 "Exiting wait loop.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005831 return_value = eExpressionCompleted;
Jim Ingham0161b492013-02-09 01:29:05 +00005832 back_to_top = false;
5833 break;
5834 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005835
Jim Ingham0161b492013-02-09 01:29:05 +00005836 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5837 {
5838 if (log)
5839 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5840 "Exiting wait loop.");
5841 try_halt_again++;
5842 do_halt = false;
5843 continue;
5844 }
Sean Callanana46ec452012-07-11 21:31:24 +00005845
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005846 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005847 {
5848 if (log)
5849 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005850 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005851 back_to_top = false;
5852 break;
5853 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005854
Jim Ingham0161b492013-02-09 01:29:05 +00005855 if (before_first_timeout)
5856 {
5857 // Set all the other threads to run, and return to the top of the loop, which will continue;
5858 before_first_timeout = false;
5859 thread_plan_sp->SetStopOthers (false);
5860 if (log)
5861 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005862
Jim Ingham0161b492013-02-09 01:29:05 +00005863 back_to_top = true;
5864 break;
5865 }
5866 else
5867 {
5868 // Running all threads failed, so return Interrupted.
5869 if (log)
5870 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005871 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005872 back_to_top = false;
5873 break;
5874 }
Sean Callanana46ec452012-07-11 21:31:24 +00005875 }
5876 }
5877 else
Jim Ingham0161b492013-02-09 01:29:05 +00005878 { if (log)
5879 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5880 "I'm getting out of here passing Interrupted.");
Jim Ingham8646d3c2014-05-05 02:47:44 +00005881 return_value = eExpressionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005882 back_to_top = false;
5883 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005884 }
5885 }
Jim Ingham0161b492013-02-09 01:29:05 +00005886 else
5887 {
5888 try_halt_again++;
5889 continue;
5890 }
Sean Callanana46ec452012-07-11 21:31:24 +00005891 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005892
Jim Ingham0161b492013-02-09 01:29:05 +00005893 if (!back_to_top || try_halt_again > num_retries)
5894 break;
5895 else
5896 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005897 }
Sean Callanana46ec452012-07-11 21:31:24 +00005898 } // END WAIT LOOP
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005899
Sean Callanana46ec452012-07-11 21:31:24 +00005900 // 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 +00005901 if (backup_private_state_thread.IsJoinable())
Sean Callanana46ec452012-07-11 21:31:24 +00005902 {
5903 StopPrivateStateThread();
5904 Error error;
5905 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005906 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005907 {
5908 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5909 }
Jason Molenda76513fd2014-10-15 23:39:31 +00005910 if (old_state != eStateInvalid)
5911 m_public_state.SetValueNoLock(old_state);
Sean Callanana46ec452012-07-11 21:31:24 +00005912 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005913
Jim Inghamc60963c2015-10-12 19:11:03 +00005914 if (return_value != eExpressionCompleted && log)
5915 {
5916 // Print a backtrace into the log so we can figure out where we are:
5917 StreamString s;
5918 s.PutCString("Thread state after unsuccessful completion: \n");
5919 thread->GetStackFrameStatus (s,
5920 0,
5921 UINT32_MAX,
5922 true,
5923 UINT32_MAX);
5924 log->PutCString(s.GetData());
5925
5926 }
Jim Ingham184e9812013-01-15 02:47:48 +00005927 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5928 // could happen:
5929 // 1) The execution successfully completed
5930 // 2) We hit a breakpoint, and ignore_breakpoints was true
5931 // 3) We got some other error, and discard_on_error was true
Jim Ingham8646d3c2014-05-05 02:47:44 +00005932 bool should_unwind = (return_value == eExpressionInterrupted && options.DoesUnwindOnError())
5933 || (return_value == eExpressionHitBreakpoint && options.DoesIgnoreBreakpoints());
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005934
Jim Ingham8646d3c2014-05-05 02:47:44 +00005935 if (return_value == eExpressionCompleted
Jim Ingham184e9812013-01-15 02:47:48 +00005936 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005937 {
5938 thread_plan_sp->RestoreThreadState();
5939 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005940
Sean Callanana46ec452012-07-11 21:31:24 +00005941 // Now do some processing on the results of the run:
Jim Ingham8646d3c2014-05-05 02:47:44 +00005942 if (return_value == eExpressionInterrupted || return_value == eExpressionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005943 {
5944 if (log)
5945 {
5946 StreamString s;
5947 if (event_sp)
5948 event_sp->Dump (&s);
5949 else
5950 {
5951 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5952 }
5953
5954 StreamString ts;
5955
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00005956 const char *event_explanation = nullptr;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005957
Sean Callanana46ec452012-07-11 21:31:24 +00005958 do
5959 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005960 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005961 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005962 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005963 break;
5964 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005965 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005966 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005967 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005968 break;
5969 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005970 else
Sean Callanana46ec452012-07-11 21:31:24 +00005971 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005972 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5973
5974 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005975 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005976 event_explanation = "<no event data>";
5977 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005978 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005979
Jim Inghamcfc09352012-07-27 23:57:19 +00005980 Process *process = event_data->GetProcessSP().get();
5981
5982 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005983 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005984 event_explanation = "<no process>";
5985 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005986 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005987
Jim Inghamcfc09352012-07-27 23:57:19 +00005988 ThreadList &thread_list = process->GetThreadList();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005989
Jim Inghamcfc09352012-07-27 23:57:19 +00005990 uint32_t num_threads = thread_list.GetSize();
5991 uint32_t thread_index;
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005992
Jim Inghamcfc09352012-07-27 23:57:19 +00005993 ts.Printf("<%u threads> ", num_threads);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00005994
Jim Inghamcfc09352012-07-27 23:57:19 +00005995 for (thread_index = 0;
5996 thread_index < num_threads;
5997 ++thread_index)
5998 {
5999 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006000
Jim Inghamcfc09352012-07-27 23:57:19 +00006001 if (!thread)
6002 {
6003 ts.Printf("<?> ");
6004 continue;
6005 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006006
Daniel Malead01b2952012-11-29 21:49:15 +00006007 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00006008 RegisterContext *register_context = thread->GetRegisterContext().get();
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006009
Jim Inghamcfc09352012-07-27 23:57:19 +00006010 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00006011 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00006012 else
6013 ts.Printf("[ip unknown] ");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006014
Jim Inghamc60963c2015-10-12 19:11:03 +00006015 // Show the private stop info here, the public stop info will be from the last natural stop.
6016 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
Jim Inghamcfc09352012-07-27 23:57:19 +00006017 if (stop_info_sp)
6018 {
6019 const char *stop_desc = stop_info_sp->GetDescription();
6020 if (stop_desc)
6021 ts.PutCString (stop_desc);
6022 }
6023 ts.Printf(">");
6024 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006025
Jim Inghamcfc09352012-07-27 23:57:19 +00006026 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00006027 }
Sean Callanana46ec452012-07-11 21:31:24 +00006028 } while (0);
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006029
Jim Inghamcfc09352012-07-27 23:57:19 +00006030 if (event_explanation)
6031 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00006032 else
Jim Inghamcfc09352012-07-27 23:57:19 +00006033 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
6034 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006035
Jim Inghame4483cf2013-09-27 01:13:01 +00006036 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00006037 {
6038 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006039 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.",
6040 static_cast<void*>(thread_plan_sp.get()));
Jim Inghamcfc09352012-07-27 23:57:19 +00006041 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Inghamcfc09352012-07-27 23:57:19 +00006042 }
6043 else
6044 {
6045 if (log)
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006046 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.",
6047 static_cast<void*>(thread_plan_sp.get()));
Sean Callanana46ec452012-07-11 21:31:24 +00006048 }
6049 }
Jim Ingham8646d3c2014-05-05 02:47:44 +00006050 else if (return_value == eExpressionSetupError)
Sean Callanana46ec452012-07-11 21:31:24 +00006051 {
6052 if (log)
6053 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006054
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006055 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00006056 {
Greg Claytonc14ee322011-09-22 04:58:26 +00006057 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham0f16e732011-02-08 05:20:59 +00006058 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006059 }
6060 else
6061 {
Sean Callanana46ec452012-07-11 21:31:24 +00006062 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00006063 {
Jim Ingham0f16e732011-02-08 05:20:59 +00006064 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00006065 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006066 return_value = eExpressionCompleted;
Sean Callanana46ec452012-07-11 21:31:24 +00006067 }
6068 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
6069 {
6070 if (log)
6071 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Jim Ingham8646d3c2014-05-05 02:47:44 +00006072 return_value = eExpressionDiscarded;
Sean Callanana46ec452012-07-11 21:31:24 +00006073 }
6074 else
6075 {
6076 if (log)
6077 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006078 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00006079 {
6080 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00006081 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00006082 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00006083 }
6084 }
6085 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006086
Sean Callanana46ec452012-07-11 21:31:24 +00006087 // Thread we ran the function in may have gone away because we ran the target
6088 // Check that it's still there, and if it is put it back in the context. Also restore the
6089 // frame in the context if it is still present.
6090 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6091 if (thread)
6092 {
6093 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
6094 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006095
Sean Callanana46ec452012-07-11 21:31:24 +00006096 // Also restore the current process'es selected frame & thread, since this function calling may
6097 // be done behind the user's back.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006098
Sean Callanana46ec452012-07-11 21:31:24 +00006099 if (selected_tid != LLDB_INVALID_THREAD_ID)
6100 {
6101 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
6102 {
6103 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00006104 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00006105 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00006106 if (old_frame_sp)
6107 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00006108 }
Jim Inghamf48169b2010-11-30 02:22:11 +00006109 }
6110 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006111
Sean Callanana46ec452012-07-11 21:31:24 +00006112 // If the process exited during the run of the thread plan, notify everyone.
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006113
Sean Callanana46ec452012-07-11 21:31:24 +00006114 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00006115 {
Sean Callanana46ec452012-07-11 21:31:24 +00006116 if (log)
6117 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6118 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00006119 }
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00006120
Jim Inghamf48169b2010-11-30 02:22:11 +00006121 return return_value;
6122}
6123
6124const char *
Jim Ingham1624a2d2014-05-05 02:26:40 +00006125Process::ExecutionResultAsCString (ExpressionResults result)
Jim Inghamf48169b2010-11-30 02:22:11 +00006126{
6127 const char *result_name;
6128
6129 switch (result)
6130 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00006131 case eExpressionCompleted:
6132 result_name = "eExpressionCompleted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006133 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006134 case eExpressionDiscarded:
6135 result_name = "eExpressionDiscarded";
Jim Inghamf48169b2010-11-30 02:22:11 +00006136 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006137 case eExpressionInterrupted:
6138 result_name = "eExpressionInterrupted";
Jim Inghamf48169b2010-11-30 02:22:11 +00006139 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006140 case eExpressionHitBreakpoint:
6141 result_name = "eExpressionHitBreakpoint";
Jim Ingham184e9812013-01-15 02:47:48 +00006142 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006143 case eExpressionSetupError:
6144 result_name = "eExpressionSetupError";
Jim Inghamf48169b2010-11-30 02:22:11 +00006145 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006146 case eExpressionParseError:
6147 result_name = "eExpressionParseError";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006148 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006149 case eExpressionResultUnavailable:
6150 result_name = "eExpressionResultUnavailable";
Jim Ingham1624a2d2014-05-05 02:26:40 +00006151 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006152 case eExpressionTimedOut:
6153 result_name = "eExpressionTimedOut";
Jim Inghamf48169b2010-11-30 02:22:11 +00006154 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00006155 case eExpressionStoppedForDebug:
6156 result_name = "eExpressionStoppedForDebug";
Jim Ingham6fbc48b2013-11-07 00:11:47 +00006157 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00006158 }
6159 return result_name;
6160}
6161
Greg Clayton7260f622011-04-18 08:33:37 +00006162void
6163Process::GetStatus (Stream &strm)
6164{
6165 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00006166 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00006167 {
6168 if (state == eStateExited)
6169 {
6170 int exit_status = GetExitStatus();
6171 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00006172 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00006173 GetID(),
6174 exit_status,
6175 exit_status,
6176 exit_description ? exit_description : "");
6177 }
6178 else
6179 {
6180 if (state == eStateConnected)
6181 strm.Printf ("Connected to remote target.\n");
6182 else
Daniel Malead01b2952012-11-29 21:49:15 +00006183 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00006184 }
6185 }
6186 else
6187 {
Daniel Malead01b2952012-11-29 21:49:15 +00006188 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00006189 }
6190}
6191
6192size_t
6193Process::GetThreadStatus (Stream &strm,
6194 bool only_threads_with_stop_reason,
6195 uint32_t start_frame,
6196 uint32_t num_frames,
6197 uint32_t num_frames_with_source)
6198{
6199 size_t num_thread_infos_dumped = 0;
6200
Jim Ingham4a65fb12014-03-07 11:20:03 +00006201 // You can't hold the thread list lock while calling Thread::GetStatus. That very well might run code (e.g. if we need it
6202 // to get return values or arguments.) For that to work the process has to be able to acquire it. So instead copy the thread
6203 // ID's, and look them up one by one:
6204
6205 uint32_t num_threads;
Greg Clayton332e8b12015-01-13 21:13:08 +00006206 std::vector<lldb::tid_t> thread_id_array;
Jim Ingham4a65fb12014-03-07 11:20:03 +00006207 //Scope for thread list locker;
6208 {
6209 Mutex::Locker locker (GetThreadList().GetMutex());
6210 ThreadList &curr_thread_list = GetThreadList();
6211 num_threads = curr_thread_list.GetSize();
6212 uint32_t idx;
Greg Clayton332e8b12015-01-13 21:13:08 +00006213 thread_id_array.resize(num_threads);
Jim Ingham4a65fb12014-03-07 11:20:03 +00006214 for (idx = 0; idx < num_threads; ++idx)
Greg Clayton332e8b12015-01-13 21:13:08 +00006215 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
Jim Ingham4a65fb12014-03-07 11:20:03 +00006216 }
6217
Greg Clayton7260f622011-04-18 08:33:37 +00006218 for (uint32_t i = 0; i < num_threads; i++)
6219 {
Greg Clayton332e8b12015-01-13 21:13:08 +00006220 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
Jim Ingham4a65fb12014-03-07 11:20:03 +00006221 if (thread_sp)
Greg Clayton7260f622011-04-18 08:33:37 +00006222 {
6223 if (only_threads_with_stop_reason)
6224 {
Jim Ingham4a65fb12014-03-07 11:20:03 +00006225 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006226 if (!stop_info_sp || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00006227 continue;
6228 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006229 thread_sp->GetStatus (strm,
Greg Clayton7260f622011-04-18 08:33:37 +00006230 start_frame,
6231 num_frames,
6232 num_frames_with_source);
6233 ++num_thread_infos_dumped;
6234 }
Jim Ingham4a65fb12014-03-07 11:20:03 +00006235 else
6236 {
6237 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
6238 if (log)
6239 log->Printf("Process::GetThreadStatus - thread 0x" PRIu64 " vanished while running Thread::GetStatus.");
Jim Ingham4a65fb12014-03-07 11:20:03 +00006240 }
Greg Clayton7260f622011-04-18 08:33:37 +00006241 }
6242 return num_thread_infos_dumped;
6243}
6244
Greg Claytona9f40ad2012-02-22 04:37:26 +00006245void
6246Process::AddInvalidMemoryRegion (const LoadRange &region)
6247{
6248 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6249}
6250
6251bool
6252Process::RemoveInvalidMemoryRange (const LoadRange &region)
6253{
6254 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
6255}
6256
Jim Ingham372787f2012-04-07 00:00:41 +00006257void
6258Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
6259{
6260 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
6261}
6262
6263bool
6264Process::RunPreResumeActions ()
6265{
6266 bool result = true;
6267 while (!m_pre_resume_actions.empty())
6268 {
6269 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6270 m_pre_resume_actions.pop_back();
6271 bool this_result = action.callback (action.baton);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006272 if (result)
Jason Molenda55710932014-11-17 20:10:15 +00006273 result = this_result;
Jim Ingham372787f2012-04-07 00:00:41 +00006274 }
6275 return result;
6276}
6277
6278void
6279Process::ClearPreResumeActions ()
6280{
6281 m_pre_resume_actions.clear();
6282}
Greg Claytona9f40ad2012-02-22 04:37:26 +00006283
Zachary Turner93749ab2015-03-03 21:51:25 +00006284ProcessRunLock &
6285Process::GetRunLock()
6286{
6287 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
6288 return m_private_run_lock;
6289 else
6290 return m_public_run_lock;
6291}
6292
Greg Claytonfa559e52012-05-18 02:38:05 +00006293void
6294Process::Flush ()
6295{
6296 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00006297 m_extended_thread_list.Flush();
6298 m_extended_thread_stop_id = 0;
6299 m_queue_list.Clear();
6300 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00006301}
Greg Clayton90ba8112012-12-05 00:16:59 +00006302
6303void
6304Process::DidExec ()
6305{
Todd Fiala76e0fc92014-08-27 22:58:26 +00006306 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
6307 if (log)
6308 log->Printf ("Process::%s()", __FUNCTION__);
6309
Greg Clayton90ba8112012-12-05 00:16:59 +00006310 Target &target = GetTarget();
6311 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00006312 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00006313 m_dynamic_checkers_ap.reset();
6314 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00006315 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006316 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006317 m_dyld_ap.reset();
Andrew MacPherson17220c12014-03-05 10:12:43 +00006318 m_jit_loaders_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00006319 m_image_tokens.clear();
6320 m_allocated_memory_cache.Clear();
6321 m_language_runtimes.clear();
Kuba Breckaafdf8422014-10-10 23:43:03 +00006322 m_instrumentation_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006323 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00006324 m_memory_cache.Clear(true);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006325 m_stop_info_override_callback = nullptr;
Greg Clayton90ba8112012-12-05 00:16:59 +00006326 DoDidExec();
6327 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00006328 // Flush the process (threads and all stack frames) after running CompleteAttach()
6329 // in case the dynamic loader loaded things in new locations.
6330 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00006331
6332 // After we figure out what was loaded/unloaded in CompleteAttach,
6333 // we need to let the target know so it can do any cleanup it needs to.
6334 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00006335}
Greg Clayton095eeaa2013-11-05 23:28:00 +00006336
Jim Ingham1460e4b2014-01-10 23:46:59 +00006337addr_t
6338Process::ResolveIndirectFunction(const Address *address, Error &error)
6339{
6340 if (address == nullptr)
6341 {
Jean-Daniel Dupasef37711f2014-02-08 20:22:05 +00006342 error.SetErrorString("Invalid address argument");
Jim Ingham1460e4b2014-01-10 23:46:59 +00006343 return LLDB_INVALID_ADDRESS;
6344 }
6345
6346 addr_t function_addr = LLDB_INVALID_ADDRESS;
6347
6348 addr_t addr = address->GetLoadAddress(&GetTarget());
6349 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
6350 if (iter != m_resolved_indirect_addresses.end())
6351 {
6352 function_addr = (*iter).second;
6353 }
6354 else
6355 {
6356 if (!InferiorCall(this, address, function_addr))
6357 {
6358 Symbol *symbol = address->CalculateSymbolContextSymbol();
6359 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
6360 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
6361 function_addr = LLDB_INVALID_ADDRESS;
6362 }
6363 else
6364 {
6365 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
6366 }
6367 }
6368 return function_addr;
6369}
6370
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006371void
6372Process::ModulesDidLoad (ModuleList &module_list)
6373{
Kuba Breckaafdf8422014-10-10 23:43:03 +00006374 SystemRuntime *sys_runtime = GetSystemRuntime();
6375 if (sys_runtime)
6376 {
6377 sys_runtime->ModulesDidLoad (module_list);
6378 }
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006379
Kuba Breckaafdf8422014-10-10 23:43:03 +00006380 GetJITLoaders().ModulesDidLoad (module_list);
6381
6382 // Give runtimes a chance to be created.
6383 InstrumentationRuntime::ModulesDidLoad(module_list, this, m_instrumentation_runtimes);
6384
6385 // Tell runtimes about new modules.
6386 for (auto pos = m_instrumentation_runtimes.begin(); pos != m_instrumentation_runtimes.end(); ++pos)
6387 {
6388 InstrumentationRuntimeSP runtime = pos->second;
6389 runtime->ModulesDidLoad(module_list);
6390 }
6391
Greg Clayton35ca64b2015-04-16 17:13:34 +00006392 // Let any language runtimes we have already created know
6393 // about the modules that loaded.
6394
6395 // Iterate over a copy of this language runtime list in case
6396 // the language runtime ModulesDidLoad somehow causes the language
6397 // riuntime to be unloaded.
6398 LanguageRuntimeCollection language_runtimes(m_language_runtimes);
6399 for (const auto &pair: language_runtimes)
6400 {
6401 // We must check language_runtime_sp to make sure it is not
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006402 // nullptr as we might cache the fact that we didn't have a
Greg Clayton35ca64b2015-04-16 17:13:34 +00006403 // language runtime for a language.
6404 LanguageRuntimeSP language_runtime_sp = pair.second;
6405 if (language_runtime_sp)
6406 language_runtime_sp->ModulesDidLoad(module_list);
6407 }
Ryan Brown65d4d5c2015-09-16 21:20:44 +00006408
6409 LoadOperatingSystemPlugin(false);
Andrew MacPhersoneb4d0602014-03-13 09:37:02 +00006410}
Kuba Breckaa51ea382014-09-06 01:33:13 +00006411
Jason Molendaef7d6412015-08-06 03:27:10 +00006412void
Sean Callanan77decf52015-12-09 01:25:01 +00006413Process::PrintWarning (uint64_t warning_type, const void *repeat_key, const char *fmt, ...)
Jason Molendaef7d6412015-08-06 03:27:10 +00006414{
6415 bool print_warning = true;
6416
6417 StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006418 if (!stream_sp)
Jason Molendaef7d6412015-08-06 03:27:10 +00006419 return;
6420 if (warning_type == eWarningsOptimization
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006421 && !GetWarningsOptimization())
Jason Molendaef7d6412015-08-06 03:27:10 +00006422 {
6423 return;
6424 }
6425
6426 if (repeat_key != nullptr)
6427 {
6428 WarningsCollection::iterator it = m_warnings_issued.find (warning_type);
6429 if (it == m_warnings_issued.end())
6430 {
6431 m_warnings_issued[warning_type] = WarningsPointerSet();
6432 m_warnings_issued[warning_type].insert (repeat_key);
6433 }
6434 else
6435 {
6436 if (it->second.find (repeat_key) != it->second.end())
6437 {
6438 print_warning = false;
6439 }
6440 else
6441 {
6442 it->second.insert (repeat_key);
6443 }
6444 }
6445 }
6446
6447 if (print_warning)
6448 {
6449 va_list args;
6450 va_start (args, fmt);
6451 stream_sp->PrintfVarArg (fmt, args);
6452 va_end (args);
6453 }
6454}
6455
Jason Molenda484900b2015-08-10 07:55:25 +00006456void
6457Process::PrintWarningOptimization (const SymbolContext &sc)
6458{
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006459 if (GetWarningsOptimization()
6460 && sc.module_sp
6461 && !sc.module_sp->GetFileSpec().GetFilename().IsEmpty()
Jason Molenda484900b2015-08-10 07:55:25 +00006462 && sc.function
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006463 && sc.function->GetIsOptimized())
Jason Molenda484900b2015-08-10 07:55:25 +00006464 {
6465 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());
6466 }
6467}
6468
Kuba Breckaa51ea382014-09-06 01:33:13 +00006469ThreadCollectionSP
6470Process::GetHistoryThreads(lldb::addr_t addr)
6471{
6472 ThreadCollectionSP threads;
Greg Clayton35ca64b2015-04-16 17:13:34 +00006473
Kuba Breckaa51ea382014-09-06 01:33:13 +00006474 const MemoryHistorySP &memory_history = MemoryHistory::FindPlugin(shared_from_this());
6475
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006476 if (!memory_history) {
Kuba Breckaa51ea382014-09-06 01:33:13 +00006477 return threads;
6478 }
6479
6480 threads.reset(new ThreadCollection(memory_history->GetHistoryThreads(addr)));
6481
6482 return threads;
6483}
Kuba Brecka63927542014-10-11 01:59:32 +00006484
6485InstrumentationRuntimeSP
6486Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
6487{
6488 InstrumentationRuntimeCollection::iterator pos;
6489 pos = m_instrumentation_runtimes.find (type);
6490 if (pos == m_instrumentation_runtimes.end())
6491 {
6492 return InstrumentationRuntimeSP();
6493 }
6494 else
6495 return (*pos).second;
6496}
Tamas Berghammer7cb18bf2015-03-24 11:15:23 +00006497
6498bool
6499Process::GetModuleSpec(const FileSpec& module_file_spec,
6500 const ArchSpec& arch,
6501 ModuleSpec& module_spec)
6502{
6503 module_spec.Clear();
6504 return false;
6505}
Tamas Berghammer3cb132a2015-12-02 11:58:51 +00006506
6507size_t
6508Process::AddImageToken(lldb::addr_t image_ptr)
6509{
6510 m_image_tokens.push_back(image_ptr);
6511 return m_image_tokens.size() - 1;
6512}
6513
6514lldb::addr_t
6515Process::GetImagePtrFromToken(size_t token) const
6516{
6517 if (token < m_image_tokens.size())
6518 return m_image_tokens[token];
6519 return LLDB_INVALID_IMAGE_TOKEN;
6520}
6521
6522void
6523Process::ResetImageToken(size_t token)
6524{
6525 if (token < m_image_tokens.size())
6526 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
Enrico Granataf3129cb2015-12-03 23:53:45 +00006527}
Jason Molendafd4cea52016-01-08 21:40:11 +00006528
6529Address
6530Process::AdvanceAddressToNextBranchInstruction (Address default_stop_addr, AddressRange range_bounds)
6531{
6532 Target &target = GetTarget();
6533 DisassemblerSP disassembler_sp;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006534 InstructionList *insn_list = nullptr;
Jason Molendafd4cea52016-01-08 21:40:11 +00006535
6536 Address retval = default_stop_addr;
6537
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006538 if (!target.GetUseFastStepping())
Jason Molendafd4cea52016-01-08 21:40:11 +00006539 return retval;
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006540 if (!default_stop_addr.IsValid())
Jason Molendafd4cea52016-01-08 21:40:11 +00006541 return retval;
6542
6543 ExecutionContext exe_ctx (this);
6544 const char *plugin_name = nullptr;
6545 const char *flavor = nullptr;
6546 const bool prefer_file_cache = true;
6547 disassembler_sp = Disassembler::DisassembleRange(target.GetArchitecture(),
6548 plugin_name,
6549 flavor,
6550 exe_ctx,
6551 range_bounds,
6552 prefer_file_cache);
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006553 if (disassembler_sp)
Jason Molendafd4cea52016-01-08 21:40:11 +00006554 insn_list = &disassembler_sp->GetInstructionList();
6555
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006556 if (insn_list == nullptr)
Jason Molendafd4cea52016-01-08 21:40:11 +00006557 {
6558 return retval;
6559 }
6560
6561 size_t insn_offset = insn_list->GetIndexOfInstructionAtAddress (default_stop_addr);
6562 if (insn_offset == UINT32_MAX)
6563 {
6564 return retval;
6565 }
6566
6567 uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction (insn_offset, target);
6568 if (branch_index == UINT32_MAX)
6569 {
6570 return retval;
6571 }
6572
6573 if (branch_index > insn_offset)
6574 {
6575 Address next_branch_insn_address = insn_list->GetInstructionAtIndex (branch_index)->GetAddress();
6576 if (next_branch_insn_address.IsValid() && range_bounds.ContainsFileAddress (next_branch_insn_address))
6577 {
6578 retval = next_branch_insn_address;
6579 }
6580 }
6581
Eugene Zelenkoda8cf8a2016-03-01 00:55:51 +00006582 if (disassembler_sp)
Jason Molendafd4cea52016-01-08 21:40:11 +00006583 {
6584 // FIXME: The DisassemblerLLVMC has a reference cycle and won't go away if it has any active instructions.
6585 disassembler_sp->GetInstructionList().Clear();
6586 }
6587
6588 return retval;
6589}