blob: e0ea32a021ef2c1416ef19b9559a784b0a4a9c5b [file] [log] [blame]
Chris Lattner24943d22010-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
Daniel Malead891f9b2012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner24943d22010-06-08 16:52:24 +000012#include "lldb/Target/Process.h"
13
14#include "lldb/lldb-private-log.h"
15
16#include "lldb/Breakpoint/StoppointCallbackContext.h"
17#include "lldb/Breakpoint/BreakpointLocation.h"
18#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000021#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000022#include "lldb/Core/Log.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
25#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000026#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000027#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#include "lldb/Host/Host.h"
29#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000030#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000031#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000032#include "lldb/Target/LanguageRuntime.h"
33#include "lldb/Target/CPPLanguageRuntime.h"
34#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000035#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000037#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Target/Target.h"
39#include "lldb/Target/TargetList.h"
40#include "lldb/Target/Thread.h"
41#include "lldb/Target/ThreadPlan.h"
Jim Inghamd21d98b2012-04-10 01:21:57 +000042#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner24943d22010-06-08 16:52:24 +000043
44using namespace lldb;
45using namespace lldb_private;
46
Greg Clayton73844aa2012-08-22 17:17:09 +000047
48// Comment out line below to disable memory caching, overriding the process setting
49// target.process.disable-memory-cache
50#define ENABLE_MEMORY_CACHING
51
52#ifdef ENABLE_MEMORY_CACHING
53#define DISABLE_MEM_CACHE_DEFAULT false
54#else
55#define DISABLE_MEM_CACHE_DEFAULT true
56#endif
57
58class ProcessOptionValueProperties : public OptionValueProperties
59{
60public:
61 ProcessOptionValueProperties (const ConstString &name) :
62 OptionValueProperties (name)
63 {
64 }
65
66 // This constructor is used when creating ProcessOptionValueProperties when it
67 // is part of a new lldb_private::Process instance. It will copy all current
68 // global property values as needed
69 ProcessOptionValueProperties (ProcessProperties *global_properties) :
70 OptionValueProperties(*global_properties->GetValueProperties())
71 {
72 }
73
74 virtual const Property *
75 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
76 {
77 // When gettings the value for a key from the process options, we will always
78 // try and grab the setting from the current process if there is one. Else we just
79 // use the one from this instance.
80 if (exe_ctx)
81 {
82 Process *process = exe_ctx->GetProcessPtr();
83 if (process)
84 {
85 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
86 if (this != instance_properties)
87 return instance_properties->ProtectedGetPropertyAtIndex (idx);
88 }
89 }
90 return ProtectedGetPropertyAtIndex (idx);
91 }
92};
93
94static PropertyDefinition
95g_properties[] =
96{
97 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
Jim Inghamdacdc012012-11-29 00:41:12 +000098 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
99 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Ingham46be7f22013-01-31 19:48:57 +0000100 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
101 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
Greg Clayton507a6382012-11-29 18:48:47 +0000102 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
Jim Ingham090f8312013-01-26 02:19:28 +0000103 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
Jim Inghamb4e08ab2013-04-30 23:46:08 +0000104 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
Greg Clayton73844aa2012-08-22 17:17:09 +0000105 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
106};
107
108enum {
109 ePropertyDisableMemCache,
Greg Clayton2e7f3132012-10-18 22:40:37 +0000110 ePropertyExtraStartCommand,
Jim Inghamb7940202013-01-15 02:47:48 +0000111 ePropertyIgnoreBreakpointsInExpressions,
112 ePropertyUnwindOnErrorInExpressions,
Jim Ingham090f8312013-01-26 02:19:28 +0000113 ePropertyPythonOSPluginPath,
Jim Inghamb4e08ab2013-04-30 23:46:08 +0000114 ePropertyStopOnSharedLibraryEvents,
115 ePropertyDetachKeepsStopped
Greg Clayton73844aa2012-08-22 17:17:09 +0000116};
117
118ProcessProperties::ProcessProperties (bool is_global) :
119 Properties ()
120{
121 if (is_global)
122 {
123 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
124 m_collection_sp->Initialize(g_properties);
125 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham090f8312013-01-26 02:19:28 +0000126 ConstString("Settings specific to threads."),
Greg Clayton73844aa2012-08-22 17:17:09 +0000127 true,
128 Thread::GetGlobalProperties()->GetValueProperties());
129 }
130 else
131 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
132}
133
134ProcessProperties::~ProcessProperties()
135{
136}
137
138bool
139ProcessProperties::GetDisableMemoryCache() const
140{
141 const uint32_t idx = ePropertyDisableMemCache;
142 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
143}
144
145Args
146ProcessProperties::GetExtraStartupCommands () const
147{
148 Args args;
149 const uint32_t idx = ePropertyExtraStartCommand;
150 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
151 return args;
152}
153
154void
155ProcessProperties::SetExtraStartupCommands (const Args &args)
156{
157 const uint32_t idx = ePropertyExtraStartCommand;
158 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
159}
160
Greg Clayton2e7f3132012-10-18 22:40:37 +0000161FileSpec
162ProcessProperties::GetPythonOSPluginPath () const
163{
164 const uint32_t idx = ePropertyPythonOSPluginPath;
165 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
166}
167
168void
169ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
170{
171 const uint32_t idx = ePropertyPythonOSPluginPath;
172 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
173}
174
Jim Inghamb7940202013-01-15 02:47:48 +0000175
176bool
177ProcessProperties::GetIgnoreBreakpointsInExpressions () const
178{
179 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
180 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
181}
182
183void
184ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
185{
186 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
187 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
188}
189
190bool
191ProcessProperties::GetUnwindOnErrorInExpressions () const
192{
193 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
194 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
195}
196
197void
198ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
199{
200 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
201 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
202}
203
Jim Ingham090f8312013-01-26 02:19:28 +0000204bool
205ProcessProperties::GetStopOnSharedLibraryEvents () const
206{
207 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
208 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
209}
210
211void
212ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
213{
214 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
215 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
216}
217
Jim Inghamb4e08ab2013-04-30 23:46:08 +0000218bool
219ProcessProperties::GetDetachKeepsStopped () const
220{
221 const uint32_t idx = ePropertyDetachKeepsStopped;
222 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
223}
224
225void
226ProcessProperties::SetDetachKeepsStopped (bool stop)
227{
228 const uint32_t idx = ePropertyDetachKeepsStopped;
229 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
230}
231
Greg Clayton24bc5d92011-03-30 18:16:51 +0000232void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000233ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000234{
235 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +0000236 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000237 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000238
239 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000240 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000241
242 if (m_executable)
243 {
244 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
245 s.PutCString (" file = ");
246 m_executable.Dump(&s);
247 s.EOL();
248 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000249 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000250 if (argc > 0)
251 {
252 for (uint32_t i=0; i<argc; i++)
253 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000254 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +0000255 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000256 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000257 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000258 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000259 }
260 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000261
262 const uint32_t envc = m_environment.GetArgumentCount();
263 if (envc > 0)
264 {
265 for (uint32_t i=0; i<envc; i++)
266 {
267 const char *env = m_environment.GetArgumentAtIndex(i);
268 if (i < 10)
269 s.Printf (" env[%u] = %s\n", i, env);
270 else
271 s.Printf ("env[%u] = %s\n", i, env);
272 }
273 }
274
Greg Claytonff39f742011-04-01 00:29:43 +0000275 if (m_arch.IsValid())
276 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
277
Greg Claytonb72d0f02011-04-12 05:54:46 +0000278 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000279 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000280 cstr = platform->GetUserName (m_uid);
281 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000282 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000283 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000284 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000285 cstr = platform->GetGroupName (m_gid);
286 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000287 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000288 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000289 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000290 cstr = platform->GetUserName (m_euid);
291 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000292 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000293 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000294 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000295 cstr = platform->GetGroupName (m_egid);
296 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000297 }
298}
299
300void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000301ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000302{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000303 const char *label;
304 if (show_args || verbose)
305 label = "ARGUMENTS";
306 else
307 label = "NAME";
308
Greg Claytonff39f742011-04-01 00:29:43 +0000309 if (verbose)
310 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000311 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000312 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
313 }
314 else
315 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000316 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000317 s.PutCString ("====== ====== ========== ======= ============================\n");
318 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000319}
320
321void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000322ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000323{
324 if (m_pid != LLDB_INVALID_PROCESS_ID)
325 {
326 const char *cstr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000327 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000328
Greg Clayton24bc5d92011-03-30 18:16:51 +0000329
Greg Claytonff39f742011-04-01 00:29:43 +0000330 if (verbose)
331 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000332 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000333 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
334 s.Printf ("%-10s ", cstr);
335 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000336 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000337
Greg Claytonb72d0f02011-04-12 05:54:46 +0000338 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000339 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
340 s.Printf ("%-10s ", cstr);
341 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000342 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000343
Greg Claytonb72d0f02011-04-12 05:54:46 +0000344 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000345 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
346 s.Printf ("%-10s ", cstr);
347 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000348 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000349
Greg Claytonb72d0f02011-04-12 05:54:46 +0000350 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000351 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
352 s.Printf ("%-10s ", cstr);
353 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000354 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000355 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
356 }
357 else
358 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000359 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000360 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000361 (int)m_arch.GetTriple().getArchName().size(),
362 m_arch.GetTriple().getArchName().data());
363 }
364
Greg Claytonb72d0f02011-04-12 05:54:46 +0000365 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000366 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000367 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000368 if (argc > 0)
369 {
370 for (uint32_t i=0; i<argc; i++)
371 {
372 if (i > 0)
373 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000374 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000375 }
376 }
377 }
378 else
379 {
380 s.PutCString (GetName());
381 }
382
383 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000384 }
385}
386
Greg Claytonb72d0f02011-04-12 05:54:46 +0000387
388void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000389ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000390{
391 m_arguments.SetArguments (argv);
392
393 // Is the first argument the executable?
394 if (first_arg_is_executable)
395 {
396 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
397 if (first_arg)
398 {
399 // Yes the first argument is an executable, set it as the executable
400 // in the launch options. Don't resolve the file path as the path
401 // could be a remote platform path
402 const bool resolve = false;
403 m_executable.SetFile(first_arg, resolve);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000404 }
405 }
406}
407void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000408ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000409{
410 // Copy all arguments
411 m_arguments = args;
412
413 // Is the first argument the executable?
414 if (first_arg_is_executable)
415 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000416 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000417 if (first_arg)
418 {
419 // Yes the first argument is an executable, set it as the executable
420 // in the launch options. Don't resolve the file path as the path
421 // could be a remote platform path
422 const bool resolve = false;
423 m_executable.SetFile(first_arg, resolve);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000424 }
425 }
426}
427
Greg Claytonabb33022011-11-08 02:43:13 +0000428void
Greg Clayton464c6162011-11-17 22:14:31 +0000429ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000430{
431 // If notthing was specified, then check the process for any default
432 // settings that were set with "settings set"
433 if (m_file_actions.empty())
434 {
Greg Claytonabb33022011-11-08 02:43:13 +0000435 if (m_flags.Test(eLaunchFlagDisableSTDIO))
436 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000437 AppendSuppressFileAction (STDIN_FILENO , true, false);
438 AppendSuppressFileAction (STDOUT_FILENO, false, true);
439 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000440 }
441 else
442 {
443 // Check for any values that might have gotten set with any of:
444 // (lldb) settings set target.input-path
445 // (lldb) settings set target.output-path
446 // (lldb) settings set target.error-path
Greg Clayton73844aa2012-08-22 17:17:09 +0000447 FileSpec in_path;
448 FileSpec out_path;
449 FileSpec err_path;
Greg Claytonabb33022011-11-08 02:43:13 +0000450 if (target)
451 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000452 in_path = target->GetStandardInputPath();
453 out_path = target->GetStandardOutputPath();
454 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000455 }
456
Greg Clayton73844aa2012-08-22 17:17:09 +0000457 if (in_path || out_path || err_path)
458 {
459 char path[PATH_MAX];
460 if (in_path && in_path.GetPath(path, sizeof(path)))
461 AppendOpenFileAction(STDIN_FILENO, path, true, false);
462
463 if (out_path && out_path.GetPath(path, sizeof(path)))
464 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
465
466 if (err_path && err_path.GetPath(path, sizeof(path)))
467 AppendOpenFileAction(STDERR_FILENO, path, false, true);
468 }
469 else if (default_to_use_pty)
Greg Clayton464c6162011-11-17 22:14:31 +0000470 {
471 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000472 {
Greg Clayton73844aa2012-08-22 17:17:09 +0000473 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
474 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
475 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
476 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000477 }
478 }
Greg Claytonabb33022011-11-08 02:43:13 +0000479 }
480 }
481}
482
Greg Clayton527154d2011-11-15 03:53:30 +0000483
484bool
Greg Clayton97471182012-04-14 01:42:46 +0000485ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
486 bool localhost,
487 bool will_debug,
488 bool first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000489{
490 error.Clear();
491
492 if (GetFlags().Test (eLaunchFlagLaunchInShell))
493 {
494 const char *shell_executable = GetShell();
495 if (shell_executable)
496 {
497 char shell_resolved_path[PATH_MAX];
498
499 if (localhost)
500 {
501 FileSpec shell_filespec (shell_executable, true);
502
503 if (!shell_filespec.Exists())
504 {
505 // Resolve the path in case we just got "bash", "sh" or "tcsh"
506 if (!shell_filespec.ResolveExecutableLocation ())
507 {
508 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
509 return false;
510 }
511 }
512 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
513 shell_executable = shell_resolved_path;
514 }
515
Greg Clayton0c8446c2012-10-17 22:57:12 +0000516 const char **argv = GetArguments().GetConstArgumentVector ();
517 if (argv == NULL || argv[0] == NULL)
518 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000519 Args shell_arguments;
520 std::string safe_arg;
521 shell_arguments.AppendArgument (shell_executable);
Greg Clayton527154d2011-11-15 03:53:30 +0000522 shell_arguments.AppendArgument ("-c");
Greg Clayton97471182012-04-14 01:42:46 +0000523 StreamString shell_command;
524 if (will_debug)
Greg Clayton527154d2011-11-15 03:53:30 +0000525 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000526 // Add a modified PATH environment variable in case argv[0]
527 // is a relative path
528 const char *argv0 = argv[0];
529 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
530 {
531 // We have a relative path to our executable which may not work if
532 // we just try to run "a.out" (without it being converted to "./a.out")
533 const char *working_dir = GetWorkingDirectory();
Greg Clayton68bd76f2013-02-14 03:54:39 +0000534 // Be sure to put quotes around PATH's value in case any paths have spaces...
535 std::string new_path("PATH=\"");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000536 const size_t empty_path_len = new_path.size();
537
538 if (working_dir && working_dir[0])
539 {
540 new_path += working_dir;
541 }
542 else
543 {
544 char current_working_dir[PATH_MAX];
545 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
546 if (cwd && cwd[0])
547 new_path += cwd;
548 }
549 const char *curr_path = getenv("PATH");
550 if (curr_path)
551 {
552 if (new_path.size() > empty_path_len)
553 new_path += ':';
554 new_path += curr_path;
555 }
Greg Clayton68bd76f2013-02-14 03:54:39 +0000556 new_path += "\" ";
Greg Clayton0c8446c2012-10-17 22:57:12 +0000557 shell_command.PutCString(new_path.c_str());
558 }
559
Greg Clayton97471182012-04-14 01:42:46 +0000560 shell_command.PutCString ("exec");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000561
562#if defined(__APPLE__)
563 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Clayton97471182012-04-14 01:42:46 +0000564 if (GetArchitecture().IsValid())
565 {
566 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton0c8446c2012-10-17 22:57:12 +0000567 // Set the resume count to 2:
Greg Clayton97471182012-04-14 01:42:46 +0000568 // 1 - stop in shell
569 // 2 - stop in /usr/bin/arch
570 // 3 - then we will stop in our program
571 SetResumeCount(2);
572 }
573 else
574 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000575 // Set the resume count to 1:
Greg Clayton97471182012-04-14 01:42:46 +0000576 // 1 - stop in shell
577 // 2 - then we will stop in our program
578 SetResumeCount(1);
579 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000580#else
581 // Set the resume count to 1:
582 // 1 - stop in shell
583 // 2 - then we will stop in our program
584 SetResumeCount(1);
585#endif
Greg Clayton527154d2011-11-15 03:53:30 +0000586 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000587
588 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000589 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000590 // There should only be one argument that is the shell command itself to be used as is
591 if (argv[0] && !argv[1])
592 shell_command.Printf("%s", argv[0]);
Greg Clayton97471182012-04-14 01:42:46 +0000593 else
Greg Clayton0c8446c2012-10-17 22:57:12 +0000594 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000595 }
Greg Clayton97471182012-04-14 01:42:46 +0000596 else
597 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000598 for (size_t i=0; argv[i] != NULL; ++i)
599 {
600 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
601 shell_command.Printf(" %s", arg);
602 }
Greg Clayton97471182012-04-14 01:42:46 +0000603 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000604 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000605 m_executable.SetFile(shell_executable, false);
606 m_arguments = shell_arguments;
607 return true;
608 }
609 else
610 {
611 error.SetErrorString ("invalid shell path");
612 }
613 }
614 else
615 {
616 error.SetErrorString ("not launching in shell");
617 }
618 return false;
619}
620
621
Greg Clayton24bc5d92011-03-30 18:16:51 +0000622bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000623ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
624{
625 if ((read || write) && fd >= 0 && path && path[0])
626 {
627 m_action = eFileActionOpen;
628 m_fd = fd;
629 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000630 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000631 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000632 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000633 else
Greg Clayton527154d2011-11-15 03:53:30 +0000634 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000635 m_path.assign (path);
636 return true;
637 }
638 else
639 {
640 Clear();
641 }
642 return false;
643}
644
645bool
646ProcessLaunchInfo::FileAction::Close (int fd)
647{
648 Clear();
649 if (fd >= 0)
650 {
651 m_action = eFileActionClose;
652 m_fd = fd;
653 }
654 return m_fd >= 0;
655}
656
657
658bool
659ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
660{
661 Clear();
662 if (fd >= 0 && dup_fd >= 0)
663 {
664 m_action = eFileActionDuplicate;
665 m_fd = fd;
666 m_arg = dup_fd;
667 }
668 return m_fd >= 0;
669}
670
671
672
673bool
674ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
675 const FileAction *info,
676 Log *log,
677 Error& error)
678{
679 if (info == NULL)
680 return false;
681
682 switch (info->m_action)
683 {
684 case eFileActionNone:
685 error.Clear();
686 break;
687
688 case eFileActionClose:
689 if (info->m_fd == -1)
690 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
691 else
692 {
693 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
694 eErrorTypePOSIX);
695 if (log && (error.Fail() || log))
696 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
697 file_actions, info->m_fd);
698 }
699 break;
700
701 case eFileActionDuplicate:
702 if (info->m_fd == -1)
703 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
704 else if (info->m_arg == -1)
705 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
706 else
707 {
708 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
709 eErrorTypePOSIX);
710 if (log && (error.Fail() || log))
711 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
712 file_actions, info->m_fd, info->m_arg);
713 }
714 break;
715
716 case eFileActionOpen:
717 if (info->m_fd == -1)
718 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
719 else
720 {
721 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000722
Greg Claytonb72d0f02011-04-12 05:54:46 +0000723 mode_t mode = 0;
724
Greg Clayton527154d2011-11-15 03:53:30 +0000725 if (oflag & O_CREAT)
726 mode = 0640;
727
Greg Claytonb72d0f02011-04-12 05:54:46 +0000728 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
729 info->m_fd,
730 info->m_path.c_str(),
731 oflag,
732 mode),
733 eErrorTypePOSIX);
734 if (error.Fail() || log)
735 error.PutToLog(log,
736 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
737 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
738 }
739 break;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000740 }
741 return error.Success();
742}
743
744Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000745ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000746{
747 Error error;
Greg Clayton6475c422012-12-04 00:32:51 +0000748 const int short_option = m_getopt_table[option_idx].val;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000749
750 switch (short_option)
751 {
752 case 's': // Stop at program entry point
753 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
754 break;
755
Greg Claytonb72d0f02011-04-12 05:54:46 +0000756 case 'i': // STDIN for read only
757 {
758 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000759 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000760 launch_info.AppendFileAction (action);
761 }
762 break;
763
764 case 'o': // Open STDOUT for write only
765 {
766 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000767 if (action.Open (STDOUT_FILENO, option_arg, false, true))
768 launch_info.AppendFileAction (action);
769 }
770 break;
771
772 case 'e': // STDERR for write only
773 {
774 ProcessLaunchInfo::FileAction action;
775 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000776 launch_info.AppendFileAction (action);
777 }
778 break;
779
Greg Clayton95ec1682012-03-06 04:01:04 +0000780
Greg Claytonb72d0f02011-04-12 05:54:46 +0000781 case 'p': // Process plug-in name
782 launch_info.SetProcessPluginName (option_arg);
783 break;
784
785 case 'n': // Disable STDIO
786 {
787 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000788 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000789 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000790 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000791 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000792 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000793 launch_info.AppendFileAction (action);
794 }
795 break;
796
797 case 'w':
798 launch_info.SetWorkingDirectory (option_arg);
799 break;
800
801 case 't': // Open process in new terminal window
802 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
803 break;
804
805 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000806 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
807 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000808 break;
809
810 case 'A':
811 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
812 break;
813
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000814 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000815 if (option_arg && option_arg[0])
816 launch_info.SetShell (option_arg);
817 else
818 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000819 break;
820
Greg Claytonb72d0f02011-04-12 05:54:46 +0000821 case 'v':
822 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
823 break;
824
825 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000826 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000827 break;
828
829 }
830 return error;
831}
832
833OptionDefinition
834ProcessLaunchCommandOptions::g_option_table[] =
835{
836{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
837{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
838{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
Sean Callanan9a91ef62012-10-24 01:12:14 +0000839{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000840{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
841{ LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Sean Callanan9a91ef62012-10-24 01:12:14 +0000842{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000843
Sean Callanan9a91ef62012-10-24 01:12:14 +0000844{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
845{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
846{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000847
848{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
849
850{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', no_argument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
851
852{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
853};
854
855
856
857bool
858ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000859{
860 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
861 return true;
862 const char *match_name = m_match_info.GetName();
863 if (!match_name)
864 return true;
865
866 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
867}
868
869bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000870ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000871{
872 if (!NameMatches (proc_info.GetName()))
873 return false;
874
875 if (m_match_info.ProcessIDIsValid() &&
876 m_match_info.GetProcessID() != proc_info.GetProcessID())
877 return false;
878
879 if (m_match_info.ParentProcessIDIsValid() &&
880 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
881 return false;
882
Greg Claytonb72d0f02011-04-12 05:54:46 +0000883 if (m_match_info.UserIDIsValid () &&
884 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000885 return false;
886
Greg Claytonb72d0f02011-04-12 05:54:46 +0000887 if (m_match_info.GroupIDIsValid () &&
888 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000889 return false;
890
891 if (m_match_info.EffectiveUserIDIsValid () &&
892 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
893 return false;
894
895 if (m_match_info.EffectiveGroupIDIsValid () &&
896 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
897 return false;
898
899 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callanan40e278c2012-12-13 22:07:14 +0000900 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton24bc5d92011-03-30 18:16:51 +0000901 return false;
902 return true;
903}
904
905bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000906ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000907{
908 if (m_name_match_type != eNameMatchIgnore)
909 return false;
910
911 if (m_match_info.ProcessIDIsValid())
912 return false;
913
914 if (m_match_info.ParentProcessIDIsValid())
915 return false;
916
Greg Claytonb72d0f02011-04-12 05:54:46 +0000917 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000918 return false;
919
Greg Claytonb72d0f02011-04-12 05:54:46 +0000920 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000921 return false;
922
923 if (m_match_info.EffectiveUserIDIsValid ())
924 return false;
925
926 if (m_match_info.EffectiveGroupIDIsValid ())
927 return false;
928
929 if (m_match_info.GetArchitecture().IsValid())
930 return false;
931
932 if (m_match_all_users)
933 return false;
934
935 return true;
936
937}
938
939void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000940ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000941{
942 m_match_info.Clear();
943 m_name_match_type = eNameMatchIgnore;
944 m_match_all_users = false;
945}
Greg Claytonfd119992011-01-07 06:08:19 +0000946
Greg Clayton46c9a352012-02-09 06:16:32 +0000947ProcessSP
948Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000949{
Greg Clayton64742742013-01-16 17:29:04 +0000950 static uint32_t g_process_unique_id = 0;
951
Greg Clayton46c9a352012-02-09 06:16:32 +0000952 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000953 ProcessCreateInstance create_callback = NULL;
954 if (plugin_name)
955 {
956 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
957 if (create_callback)
958 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000959 process_sp = create_callback(target, listener, crash_file_path);
960 if (process_sp)
961 {
Greg Clayton64742742013-01-16 17:29:04 +0000962 if (process_sp->CanDebug(target, true))
963 {
964 process_sp->m_process_unique_id = ++g_process_unique_id;
965 }
966 else
Greg Clayton46c9a352012-02-09 06:16:32 +0000967 process_sp.reset();
968 }
Chris Lattner24943d22010-06-08 16:52:24 +0000969 }
970 }
971 else
972 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000973 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000974 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000975 process_sp = create_callback(target, listener, crash_file_path);
976 if (process_sp)
977 {
Greg Clayton64742742013-01-16 17:29:04 +0000978 if (process_sp->CanDebug(target, false))
979 {
980 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Clayton46c9a352012-02-09 06:16:32 +0000981 break;
Greg Clayton64742742013-01-16 17:29:04 +0000982 }
983 else
984 process_sp.reset();
Greg Clayton46c9a352012-02-09 06:16:32 +0000985 }
Chris Lattner24943d22010-06-08 16:52:24 +0000986 }
987 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000988 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000989}
990
Jim Ingham5a15e692012-02-16 06:50:00 +0000991ConstString &
992Process::GetStaticBroadcasterClass ()
993{
994 static ConstString class_name ("lldb.process");
995 return class_name;
996}
Chris Lattner24943d22010-06-08 16:52:24 +0000997
998//----------------------------------------------------------------------
999// Process constructor
1000//----------------------------------------------------------------------
1001Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +00001002 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +00001003 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +00001004 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +00001005 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +00001006 m_public_state (eStateUnloaded),
1007 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +00001008 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1009 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +00001010 m_private_state_listener ("lldb.process.internal_state_listener"),
1011 m_private_state_control_wait(),
1012 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +00001013 m_mod_id (),
Greg Clayton64742742013-01-16 17:29:04 +00001014 m_process_unique_id(0),
Chris Lattner24943d22010-06-08 16:52:24 +00001015 m_thread_index_id (0),
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001016 m_thread_id_to_index_id_map (),
Chris Lattner24943d22010-06-08 16:52:24 +00001017 m_exit_status (-1),
1018 m_exit_string (),
1019 m_thread_list (this),
1020 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001021 m_image_tokens (),
1022 m_listener (listener),
1023 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001024 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +00001025 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001026 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +00001027 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +00001028 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +00001029 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +00001030 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +00001031 m_stderr_data (),
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001032 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1033 m_profile_data (),
Greg Clayton613b8732011-05-17 03:37:42 +00001034 m_memory_cache (*this),
1035 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +00001036 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +00001037 m_next_event_action_ap(),
Greg Clayton061ca652013-04-18 16:57:27 +00001038 m_public_run_lock (),
1039#if defined(__APPLE__)
1040 m_private_run_lock (),
1041#endif
Jim Ingham43892562012-06-06 00:29:30 +00001042 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001043 m_finalize_called(false),
Jim Ingham89e248f2013-02-09 01:29:05 +00001044 m_last_broadcast_state (eStateInvalid),
Jason Molenda1d9c8022013-03-05 03:33:59 +00001045 m_destroy_in_process (false),
1046 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +00001047{
Jim Ingham5a15e692012-02-16 06:50:00 +00001048 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +00001049
Greg Clayton952e9dc2013-03-27 23:08:40 +00001050 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001051 if (log)
1052 log->Printf ("%p Process::Process()", this);
1053
Greg Clayton49ce6822010-10-31 03:01:06 +00001054 SetEventName (eBroadcastBitStateChanged, "state-changed");
1055 SetEventName (eBroadcastBitInterrupt, "interrupt");
1056 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1057 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001058 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Clayton49ce6822010-10-31 03:01:06 +00001059
Greg Clayton84332782012-10-29 20:52:08 +00001060 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1061 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1062 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1063
Chris Lattner24943d22010-06-08 16:52:24 +00001064 listener.StartListeningForEvents (this,
1065 eBroadcastBitStateChanged |
1066 eBroadcastBitInterrupt |
1067 eBroadcastBitSTDOUT |
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001068 eBroadcastBitSTDERR |
1069 eBroadcastBitProfileData);
Chris Lattner24943d22010-06-08 16:52:24 +00001070
1071 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001072 eBroadcastBitStateChanged |
1073 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +00001074
1075 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1076 eBroadcastInternalStateControlStop |
1077 eBroadcastInternalStateControlPause |
1078 eBroadcastInternalStateControlResume);
1079}
1080
1081//----------------------------------------------------------------------
1082// Destructor
1083//----------------------------------------------------------------------
1084Process::~Process()
1085{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001086 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001087 if (log)
1088 log->Printf ("%p Process::~Process()", this);
1089 StopPrivateStateThread();
1090}
1091
Greg Clayton73844aa2012-08-22 17:17:09 +00001092const ProcessPropertiesSP &
1093Process::GetGlobalProperties()
1094{
1095 static ProcessPropertiesSP g_settings_sp;
1096 if (!g_settings_sp)
1097 g_settings_sp.reset (new ProcessProperties (true));
1098 return g_settings_sp;
1099}
1100
Chris Lattner24943d22010-06-08 16:52:24 +00001101void
1102Process::Finalize()
1103{
Greg Claytonffa43a62011-11-17 04:46:02 +00001104 switch (GetPrivateState())
1105 {
1106 case eStateConnected:
1107 case eStateAttaching:
1108 case eStateLaunching:
1109 case eStateStopped:
1110 case eStateRunning:
1111 case eStateStepping:
1112 case eStateCrashed:
1113 case eStateSuspended:
1114 if (GetShouldDetach())
Jim Inghamb4e08ab2013-04-30 23:46:08 +00001115 {
1116 // FIXME: This will have to be a process setting:
1117 bool keep_stopped = false;
1118 Detach(keep_stopped);
1119 }
Greg Claytonffa43a62011-11-17 04:46:02 +00001120 else
1121 Destroy();
1122 break;
1123
1124 case eStateInvalid:
1125 case eStateUnloaded:
1126 case eStateDetached:
1127 case eStateExited:
1128 break;
1129 }
1130
Greg Clayton2f57db02011-10-01 00:45:15 +00001131 // Clear our broadcaster before we proceed with destroying
1132 Broadcaster::Clear();
1133
Chris Lattner24943d22010-06-08 16:52:24 +00001134 // Do any cleanup needed prior to being destructed... Subclasses
1135 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001136
1137 // We need to destroy the loader before the derived Process class gets destroyed
1138 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001139 m_dynamic_checkers_ap.reset();
1140 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001141 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001142 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001143 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001144 std::vector<Notifications> empty_notifications;
1145 m_notifications.swap(empty_notifications);
1146 m_image_tokens.clear();
1147 m_memory_cache.Clear();
1148 m_allocated_memory_cache.Clear();
1149 m_language_runtimes.clear();
1150 m_next_event_action_ap.reset();
Greg Clayton84332782012-10-29 20:52:08 +00001151//#ifdef LLDB_CONFIGURATION_DEBUG
1152// StreamFile s(stdout, false);
1153// EventSP event_sp;
1154// while (m_private_state_listener.GetNextEvent(event_sp))
1155// {
1156// event_sp->Dump (&s);
1157// s.EOL();
1158// }
1159//#endif
1160 // We have to be very careful here as the m_private_state_listener might
1161 // contain events that have ProcessSP values in them which can keep this
1162 // process around forever. These events need to be cleared out.
1163 m_private_state_listener.Clear();
Greg Clayton061ca652013-04-18 16:57:27 +00001164 m_public_run_lock.WriteUnlock();
1165#if defined(__APPLE__)
1166 m_private_run_lock.WriteUnlock();
1167#endif
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001168 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001169}
1170
1171void
1172Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1173{
1174 m_notifications.push_back(callbacks);
1175 if (callbacks.initialize != NULL)
1176 callbacks.initialize (callbacks.baton, this);
1177}
1178
1179bool
1180Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1181{
1182 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1183 for (pos = m_notifications.begin(); pos != end; ++pos)
1184 {
1185 if (pos->baton == callbacks.baton &&
1186 pos->initialize == callbacks.initialize &&
1187 pos->process_state_changed == callbacks.process_state_changed)
1188 {
1189 m_notifications.erase(pos);
1190 return true;
1191 }
1192 }
1193 return false;
1194}
1195
1196void
1197Process::SynchronouslyNotifyStateChanged (StateType state)
1198{
1199 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1200 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1201 {
1202 if (notification_pos->process_state_changed)
1203 notification_pos->process_state_changed (notification_pos->baton, this, state);
1204 }
1205}
1206
1207// FIXME: We need to do some work on events before the general Listener sees them.
1208// For instance if we are continuing from a breakpoint, we need to ensure that we do
1209// the little "insert real insn, step & stop" trick. But we can't do that when the
1210// event is delivered by the broadcaster - since that is done on the thread that is
1211// waiting for new events, so if we needed more than one event for our handling, we would
1212// stall. So instead we do it when we fetch the event off of the queue.
1213//
1214
1215StateType
1216Process::GetNextEvent (EventSP &event_sp)
1217{
1218 StateType state = eStateInvalid;
1219
1220 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1221 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1222
1223 return state;
1224}
1225
1226
1227StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001228Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001229{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001230 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1231 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1232 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001233 if (event_sp_ptr)
1234 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001235 StateType state = GetState();
1236 // If we are exited or detached, we won't ever get back to any
1237 // other valid state...
1238 if (state == eStateDetached || state == eStateExited)
1239 return state;
1240
1241 while (state != eStateInvalid)
1242 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001243 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001244 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001245 if (event_sp_ptr && event_sp)
1246 *event_sp_ptr = event_sp;
1247
Jim Ingham21f37ad2011-08-09 02:12:22 +00001248 switch (state)
1249 {
1250 case eStateCrashed:
1251 case eStateDetached:
1252 case eStateExited:
1253 case eStateUnloaded:
1254 return state;
1255 case eStateStopped:
1256 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1257 continue;
1258 else
1259 return state;
1260 default:
1261 continue;
1262 }
1263 }
1264 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001265}
1266
1267
1268StateType
1269Process::WaitForState
1270(
1271 const TimeValue *timeout,
1272 const StateType *match_states, const uint32_t num_match_states
1273)
1274{
1275 EventSP event_sp;
1276 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001277 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001278 while (state != eStateInvalid)
1279 {
Greg Claytond8c62532010-10-07 04:19:01 +00001280 // If we are exited or detached, we won't ever get back to any
1281 // other valid state...
1282 if (state == eStateDetached || state == eStateExited)
1283 return state;
1284
Chris Lattner24943d22010-06-08 16:52:24 +00001285 state = WaitForStateChangedEvents (timeout, event_sp);
1286
1287 for (i=0; i<num_match_states; ++i)
1288 {
1289 if (match_states[i] == state)
1290 return state;
1291 }
1292 }
1293 return state;
1294}
1295
Jim Ingham63e24d72010-10-11 23:53:14 +00001296bool
1297Process::HijackProcessEvents (Listener *listener)
1298{
1299 if (listener != NULL)
1300 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001301 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001302 }
1303 else
1304 return false;
1305}
1306
1307void
1308Process::RestoreProcessEvents ()
1309{
1310 RestoreBroadcaster();
1311}
1312
Jim Inghamf9f40c22011-02-08 05:20:59 +00001313bool
1314Process::HijackPrivateProcessEvents (Listener *listener)
1315{
1316 if (listener != NULL)
1317 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001318 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001319 }
1320 else
1321 return false;
1322}
1323
1324void
1325Process::RestorePrivateProcessEvents ()
1326{
1327 m_private_state_broadcaster.RestoreBroadcaster();
1328}
1329
Chris Lattner24943d22010-06-08 16:52:24 +00001330StateType
1331Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1332{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001333 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001334
1335 if (log)
1336 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1337
1338 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001339 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1340 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001341 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001342 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001343 {
1344 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1345 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1346 else if (log)
1347 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1348 }
Chris Lattner24943d22010-06-08 16:52:24 +00001349
1350 if (log)
1351 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1352 __FUNCTION__,
1353 timeout,
1354 StateAsCString(state));
1355 return state;
1356}
1357
1358Event *
1359Process::PeekAtStateChangedEvents ()
1360{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001361 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001362
1363 if (log)
1364 log->Printf ("Process::%s...", __FUNCTION__);
1365
1366 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001367 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1368 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001369 if (log)
1370 {
1371 if (event_ptr)
1372 {
1373 log->Printf ("Process::%s (event_ptr) => %s",
1374 __FUNCTION__,
1375 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1376 }
1377 else
1378 {
1379 log->Printf ("Process::%s no events found",
1380 __FUNCTION__);
1381 }
1382 }
1383 return event_ptr;
1384}
1385
1386StateType
1387Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1388{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001389 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001390
1391 if (log)
1392 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1393
1394 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001395 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1396 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001397 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001398 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001399 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1400 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001401
1402 // This is a bit of a hack, but when we wait here we could very well return
1403 // to the command-line, and that could disable the log, which would render the
1404 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001405 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001406 {
1407 if (state == eStateInvalid)
1408 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1409 else
1410 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1411 }
Chris Lattner24943d22010-06-08 16:52:24 +00001412 return state;
1413}
1414
1415bool
1416Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1417{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001418 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001419
1420 if (log)
1421 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1422
1423 if (control_only)
1424 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1425 else
1426 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1427}
1428
1429bool
1430Process::IsRunning () const
1431{
1432 return StateIsRunningState (m_public_state.GetValue());
1433}
1434
1435int
1436Process::GetExitStatus ()
1437{
1438 if (m_public_state.GetValue() == eStateExited)
1439 return m_exit_status;
1440 return -1;
1441}
1442
Greg Clayton638351a2010-12-04 00:10:17 +00001443
Chris Lattner24943d22010-06-08 16:52:24 +00001444const char *
1445Process::GetExitDescription ()
1446{
1447 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1448 return m_exit_string.c_str();
1449 return NULL;
1450}
1451
Greg Clayton72e1c782011-01-22 23:43:18 +00001452bool
Chris Lattner24943d22010-06-08 16:52:24 +00001453Process::SetExitStatus (int status, const char *cstr)
1454{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001455 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton68ca8232011-01-25 02:58:48 +00001456 if (log)
1457 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1458 status, status,
1459 cstr ? "\"" : "",
1460 cstr ? cstr : "NULL",
1461 cstr ? "\"" : "");
1462
Greg Clayton72e1c782011-01-22 23:43:18 +00001463 // We were already in the exited state
1464 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001465 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001466 if (log)
1467 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001468 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001469 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001470
1471 m_exit_status = status;
1472 if (cstr)
1473 m_exit_string = cstr;
1474 else
1475 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001476
Greg Clayton72e1c782011-01-22 23:43:18 +00001477 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001478
Greg Clayton72e1c782011-01-22 23:43:18 +00001479 SetPrivateState (eStateExited);
1480 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001481}
1482
1483// This static callback can be used to watch for local child processes on
1484// the current host. The the child process exits, the process will be
1485// found in the global target list (we want to be completely sure that the
1486// lldb_private::Process doesn't go away before we can deliver the signal.
1487bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001488Process::SetProcessExitStatus (void *callback_baton,
1489 lldb::pid_t pid,
1490 bool exited,
1491 int signo, // Zero for no signal
1492 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001493)
1494{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001495 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton1c4642c2011-11-16 05:37:56 +00001496 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001497 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001498 callback_baton,
1499 pid,
1500 exited,
1501 signo,
1502 exit_status);
1503
1504 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001505 {
Greg Clayton63094e02010-06-23 01:19:29 +00001506 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001507 if (target_sp)
1508 {
1509 ProcessSP process_sp (target_sp->GetProcessSP());
1510 if (process_sp)
1511 {
1512 const char *signal_cstr = NULL;
1513 if (signo)
1514 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1515
1516 process_sp->SetExitStatus (exit_status, signal_cstr);
1517 }
1518 }
1519 return true;
1520 }
1521 return false;
1522}
1523
1524
Greg Clayton37f962e2011-08-22 02:49:39 +00001525void
1526Process::UpdateThreadListIfNeeded ()
1527{
1528 const uint32_t stop_id = GetStopID();
1529 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1530 {
Greg Clayton20206082011-11-17 01:23:07 +00001531 const StateType state = GetPrivateState();
1532 if (StateIsStoppedState (state, true))
1533 {
1534 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001535 // m_thread_list does have its own mutex, but we need to
1536 // hold onto the mutex between the call to UpdateThreadList(...)
1537 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001538 ThreadList new_thread_list(this);
1539 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001540 // thread list, but only update if "true" is returned
1541 if (UpdateThreadList (m_thread_list, new_thread_list))
1542 {
Jim Inghameb175302013-03-01 20:04:25 +00001543 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1544 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1545 // shutting us down, causing a deadlock.
1546 if (!m_destroy_in_process)
1547 {
1548 OperatingSystem *os = GetOperatingSystem ();
1549 if (os)
Greg Clayton9acf3692013-04-12 20:07:46 +00001550 {
1551 // Clear any old backing threads where memory threads might have been
1552 // backed by actual threads from the lldb_private::Process subclass
1553 size_t num_old_threads = m_thread_list.GetSize(false);
1554 for (size_t i=0; i<num_old_threads; ++i)
1555 m_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1556
1557 // Now let the OperatingSystem plug-in update the thread list
Jim Inghameb175302013-03-01 20:04:25 +00001558 os->UpdateThreadList (m_thread_list, new_thread_list);
Greg Clayton9acf3692013-04-12 20:07:46 +00001559 }
Jim Inghameb175302013-03-01 20:04:25 +00001560 m_thread_list.Update (new_thread_list);
1561 m_thread_list.SetStopID (stop_id);
1562 }
Greg Claytonae932352012-04-10 00:18:59 +00001563 }
Greg Clayton20206082011-11-17 01:23:07 +00001564 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001565 }
1566}
1567
Greg Clayton52ebc0a2013-01-18 23:41:08 +00001568ThreadSP
1569Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1570{
1571 OperatingSystem *os = GetOperatingSystem ();
1572 if (os)
1573 return os->CreateThread(tid, context);
1574 return ThreadSP();
1575}
1576
1577
1578
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001579// This is obsoleted. Staged removal for Xcode.
Chris Lattner24943d22010-06-08 16:52:24 +00001580uint32_t
1581Process::GetNextThreadIndexID ()
1582{
1583 return ++m_thread_index_id;
1584}
1585
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001586uint32_t
1587Process::GetNextThreadIndexID (uint64_t thread_id)
1588{
1589 return AssignIndexIDToThread(thread_id);
1590}
1591
1592bool
1593Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1594{
1595 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1596 if (iterator == m_thread_id_to_index_id_map.end())
1597 {
1598 return false;
1599 }
1600 else
1601 {
1602 return true;
1603 }
1604}
1605
1606uint32_t
1607Process::AssignIndexIDToThread(uint64_t thread_id)
1608{
1609 uint32_t result = 0;
1610 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1611 if (iterator == m_thread_id_to_index_id_map.end())
1612 {
1613 result = ++m_thread_index_id;
1614 m_thread_id_to_index_id_map[thread_id] = result;
1615 }
1616 else
1617 {
1618 result = iterator->second;
1619 }
1620
1621 return result;
1622}
1623
Chris Lattner24943d22010-06-08 16:52:24 +00001624StateType
1625Process::GetState()
1626{
1627 // If any other threads access this we will need a mutex for it
1628 return m_public_state.GetValue ();
1629}
1630
1631void
1632Process::SetPublicState (StateType new_state)
1633{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001634 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001635 if (log)
1636 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001637 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001638 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001639
1640 // On the transition from Run to Stopped, we unlock the writer end of the
1641 // run lock. The lock gets locked in Resume, which is the public API
1642 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001643 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1644 {
Sean Callanana3772862012-06-02 01:16:20 +00001645 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001646 {
Sean Callanana3772862012-06-02 01:16:20 +00001647 if (log)
1648 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Greg Clayton061ca652013-04-18 16:57:27 +00001649 m_public_run_lock.WriteUnlock();
Sean Callanana3772862012-06-02 01:16:20 +00001650 }
1651 else
1652 {
1653 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1654 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1655 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001656 {
Sean Callanana3772862012-06-02 01:16:20 +00001657 if (new_state_is_stopped)
1658 {
1659 if (log)
1660 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Greg Clayton061ca652013-04-18 16:57:27 +00001661 m_public_run_lock.WriteUnlock();
Sean Callanana3772862012-06-02 01:16:20 +00001662 }
Greg Claytona894fe72012-04-05 16:12:35 +00001663 }
Greg Claytona894fe72012-04-05 16:12:35 +00001664 }
1665 }
Chris Lattner24943d22010-06-08 16:52:24 +00001666}
1667
Jim Ingham027aaa72012-04-19 01:40:33 +00001668Error
1669Process::Resume ()
1670{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001671 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham027aaa72012-04-19 01:40:33 +00001672 if (log)
1673 log->Printf("Process::Resume -- locking run lock");
Greg Clayton061ca652013-04-18 16:57:27 +00001674 if (!m_public_run_lock.WriteTryLock())
Jim Ingham027aaa72012-04-19 01:40:33 +00001675 {
1676 Error error("Resume request failed - process still running.");
1677 if (log)
1678 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1679 return error;
1680 }
1681 return PrivateResume();
1682}
1683
Chris Lattner24943d22010-06-08 16:52:24 +00001684StateType
1685Process::GetPrivateState ()
1686{
1687 return m_private_state.GetValue();
1688}
1689
1690void
1691Process::SetPrivateState (StateType new_state)
1692{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001693 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001694 bool state_changed = false;
1695
1696 if (log)
1697 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1698
1699 Mutex::Locker locker(m_private_state.GetMutex());
1700
1701 const StateType old_state = m_private_state.GetValueNoLock ();
1702 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001703 // This code is left commented out in case we ever need to control
1704 // the private process state with another run lock. Right now it doesn't
1705 // seem like we need to do this, but if we ever do, we can uncomment and
1706 // use this code.
1707// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1708// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1709// if (old_state_is_stopped != new_state_is_stopped)
1710// {
1711// if (new_state_is_stopped)
1712// m_private_run_lock.WriteUnlock();
1713// else
1714// m_private_run_lock.WriteLock();
1715// }
1716
Chris Lattner24943d22010-06-08 16:52:24 +00001717 if (state_changed)
1718 {
1719 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001720 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001721 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001722 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001723 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001724 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001725 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001726 }
1727 // Use our target to get a shared pointer to ourselves...
Greg Clayton84332782012-10-29 20:52:08 +00001728 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1729 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1730 else
1731 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001732 }
1733 else
1734 {
1735 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001736 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001737 }
1738}
1739
Jim Ingham0296fe72011-11-08 03:00:11 +00001740void
1741Process::SetRunningUserExpression (bool on)
1742{
1743 m_mod_id.SetRunningUserExpression (on);
1744}
1745
Chris Lattner24943d22010-06-08 16:52:24 +00001746addr_t
1747Process::GetImageInfoAddress()
1748{
1749 return LLDB_INVALID_ADDRESS;
1750}
1751
Greg Clayton0baa3942010-11-04 01:54:29 +00001752//----------------------------------------------------------------------
1753// LoadImage
1754//
1755// This function provides a default implementation that works for most
1756// unix variants. Any Process subclasses that need to do shared library
1757// loading differently should override LoadImage and UnloadImage and
1758// do what is needed.
1759//----------------------------------------------------------------------
1760uint32_t
1761Process::LoadImage (const FileSpec &image_spec, Error &error)
1762{
Greg Clayton77d40712012-04-18 00:05:19 +00001763 char path[PATH_MAX];
1764 image_spec.GetPath(path, sizeof(path));
1765
Greg Clayton0baa3942010-11-04 01:54:29 +00001766 DynamicLoader *loader = GetDynamicLoader();
1767 if (loader)
1768 {
1769 error = loader->CanLoadImage();
1770 if (error.Fail())
1771 return LLDB_INVALID_IMAGE_TOKEN;
1772 }
1773
1774 if (error.Success())
1775 {
1776 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001777
1778 if (thread_sp)
1779 {
1780 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1781
1782 if (frame_sp)
1783 {
1784 ExecutionContext exe_ctx;
1785 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001786 const bool unwind_on_error = true;
1787 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001788 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001789 expr.Printf("dlopen (\"%s\", 2)", path);
1790 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001791 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001792 ClangUserExpression::Evaluate (exe_ctx,
1793 eExecutionPolicyAlways,
1794 lldb::eLanguageTypeUnknown,
1795 ClangUserExpression::eResultTypeAny,
1796 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001797 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001798 expr.GetData(),
1799 prefix,
1800 result_valobj_sp,
1801 true,
1802 ClangUserExpression::kDefaultTimeout);
Johnny Chenb14ec342011-09-09 00:01:43 +00001803 error = result_valobj_sp->GetError();
1804 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001805 {
1806 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001807 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001808 {
1809 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1810 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1811 {
1812 uint32_t image_token = m_image_tokens.size();
1813 m_image_tokens.push_back (image_ptr);
1814 return image_token;
1815 }
1816 }
1817 }
1818 }
1819 }
1820 }
Greg Clayton77d40712012-04-18 00:05:19 +00001821 if (!error.AsCString())
1822 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001823 return LLDB_INVALID_IMAGE_TOKEN;
1824}
1825
1826//----------------------------------------------------------------------
1827// UnloadImage
1828//
1829// This function provides a default implementation that works for most
1830// unix variants. Any Process subclasses that need to do shared library
1831// loading differently should override LoadImage and UnloadImage and
1832// do what is needed.
1833//----------------------------------------------------------------------
1834Error
1835Process::UnloadImage (uint32_t image_token)
1836{
1837 Error error;
1838 if (image_token < m_image_tokens.size())
1839 {
1840 const addr_t image_addr = m_image_tokens[image_token];
1841 if (image_addr == LLDB_INVALID_ADDRESS)
1842 {
1843 error.SetErrorString("image already unloaded");
1844 }
1845 else
1846 {
1847 DynamicLoader *loader = GetDynamicLoader();
1848 if (loader)
1849 error = loader->CanLoadImage();
1850
1851 if (error.Success())
1852 {
1853 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001854
1855 if (thread_sp)
1856 {
1857 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1858
1859 if (frame_sp)
1860 {
1861 ExecutionContext exe_ctx;
1862 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001863 const bool unwind_on_error = true;
1864 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001865 StreamString expr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001866 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton0baa3942010-11-04 01:54:29 +00001867 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001868 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001869 ClangUserExpression::Evaluate (exe_ctx,
1870 eExecutionPolicyAlways,
1871 lldb::eLanguageTypeUnknown,
1872 ClangUserExpression::eResultTypeAny,
1873 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001874 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001875 expr.GetData(),
1876 prefix,
1877 result_valobj_sp,
1878 true,
1879 ClangUserExpression::kDefaultTimeout);
Greg Clayton0baa3942010-11-04 01:54:29 +00001880 if (result_valobj_sp->GetError().Success())
1881 {
1882 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001883 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001884 {
1885 if (scalar.UInt(1))
1886 {
1887 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1888 }
1889 else
1890 {
1891 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1892 }
1893 }
1894 }
1895 else
1896 {
1897 error = result_valobj_sp->GetError();
1898 }
1899 }
1900 }
1901 }
1902 }
1903 }
1904 else
1905 {
1906 error.SetErrorString("invalid image token");
1907 }
1908 return error;
1909}
1910
Greg Clayton75906e42011-05-11 18:39:18 +00001911const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001912Process::GetABI()
1913{
Greg Clayton75906e42011-05-11 18:39:18 +00001914 if (!m_abi_sp)
1915 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1916 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001917}
1918
Jim Ingham642036f2010-09-23 02:01:19 +00001919LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001920Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001921{
1922 LanguageRuntimeCollection::iterator pos;
1923 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001924 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001925 {
Jim Inghame3117662012-03-10 00:22:19 +00001926 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001927
Jim Inghame3117662012-03-10 00:22:19 +00001928 m_language_runtimes[language] = runtime_sp;
1929 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001930 }
1931 else
1932 return (*pos).second.get();
1933}
1934
1935CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001936Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001937{
Jim Inghame3117662012-03-10 00:22:19 +00001938 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001939 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1940 return static_cast<CPPLanguageRuntime *> (runtime);
1941 return NULL;
1942}
1943
1944ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001945Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001946{
Jim Inghame3117662012-03-10 00:22:19 +00001947 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001948 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1949 return static_cast<ObjCLanguageRuntime *> (runtime);
1950 return NULL;
1951}
1952
Enrico Granata6b1763b2012-05-21 16:51:35 +00001953bool
1954Process::IsPossibleDynamicValue (ValueObject& in_value)
1955{
1956 if (in_value.IsDynamic())
1957 return false;
1958 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1959
1960 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1961 {
1962 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1963 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1964 }
1965
1966 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1967 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1968 return true;
1969
1970 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1971 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1972}
1973
Chris Lattner24943d22010-06-08 16:52:24 +00001974BreakpointSiteList &
1975Process::GetBreakpointSiteList()
1976{
1977 return m_breakpoint_site_list;
1978}
1979
1980const BreakpointSiteList &
1981Process::GetBreakpointSiteList() const
1982{
1983 return m_breakpoint_site_list;
1984}
1985
1986
1987void
1988Process::DisableAllBreakpointSites ()
1989{
1990 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001991 size_t num_sites = m_breakpoint_site_list.GetSize();
1992 for (size_t i = 0; i < num_sites; i++)
1993 {
Jim Inghamefb4aeb2013-02-15 02:06:30 +00001994 DisableBreakpointSite (m_breakpoint_site_list.GetByIndex(i).get());
Jim Ingham06b84492012-07-04 00:35:43 +00001995 }
Chris Lattner24943d22010-06-08 16:52:24 +00001996}
1997
1998Error
1999Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2000{
2001 Error error (DisableBreakpointSiteByID (break_id));
2002
2003 if (error.Success())
2004 m_breakpoint_site_list.Remove(break_id);
2005
2006 return error;
2007}
2008
2009Error
2010Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2011{
2012 Error error;
2013 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2014 if (bp_site_sp)
2015 {
2016 if (bp_site_sp->IsEnabled())
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002017 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002018 }
2019 else
2020 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002021 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00002022 }
2023
2024 return error;
2025}
2026
2027Error
2028Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2029{
2030 Error error;
2031 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2032 if (bp_site_sp)
2033 {
2034 if (!bp_site_sp->IsEnabled())
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002035 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002036 }
2037 else
2038 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002039 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00002040 }
2041 return error;
2042}
2043
Stephen Wilson3fd1f362010-07-17 00:56:13 +00002044lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00002045Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00002046{
Greg Clayton265ab332011-05-19 18:17:41 +00002047 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002048 if (load_addr != LLDB_INVALID_ADDRESS)
2049 {
2050 BreakpointSiteSP bp_site_sp;
2051
2052 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2053 // create a new breakpoint site and add it.
2054
2055 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2056
2057 if (bp_site_sp)
2058 {
2059 bp_site_sp->AddOwner (owner);
2060 owner->SetBreakpointSite (bp_site_sp);
2061 return bp_site_sp->GetID();
2062 }
2063 else
2064 {
Greg Clayton36da2aa2013-01-25 18:06:21 +00002065 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner24943d22010-06-08 16:52:24 +00002066 if (bp_site_sp)
2067 {
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002068 if (EnableBreakpointSite (bp_site_sp.get()).Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002069 {
2070 owner->SetBreakpointSite (bp_site_sp);
2071 return m_breakpoint_site_list.Add (bp_site_sp);
2072 }
2073 }
2074 }
2075 }
2076 // We failed to enable the breakpoint
2077 return LLDB_INVALID_BREAK_ID;
2078
2079}
2080
2081void
2082Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2083{
2084 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2085 if (num_owners == 0)
2086 {
Jim Ingham700ff7e2013-04-06 00:16:39 +00002087 // Don't try to disable the site if we don't have a live process anymore.
2088 if (IsAlive())
2089 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002090 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2091 }
2092}
2093
2094
2095size_t
2096Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2097{
2098 size_t bytes_removed = 0;
2099 addr_t intersect_addr;
2100 size_t intersect_size;
2101 size_t opcode_offset;
2102 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002103 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00002104 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00002105
Jim Ingham82820f92011-06-29 19:42:28 +00002106 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00002107 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002108 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00002109 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002110 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00002111 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002112 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00002113 {
2114 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2115 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00002116 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00002117 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002118 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00002119 }
Chris Lattner24943d22010-06-08 16:52:24 +00002120 }
2121 }
2122 }
2123 return bytes_removed;
2124}
2125
2126
Greg Claytonb1888f22011-03-19 01:12:21 +00002127
2128size_t
2129Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2130{
2131 PlatformSP platform_sp (m_target.GetPlatform());
2132 if (platform_sp)
2133 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2134 return 0;
2135}
2136
Chris Lattner24943d22010-06-08 16:52:24 +00002137Error
2138Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2139{
2140 Error error;
2141 assert (bp_site != NULL);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002142 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002143 const addr_t bp_addr = bp_site->GetLoadAddress();
2144 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002145 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002146 if (bp_site->IsEnabled())
2147 {
2148 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002149 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002150 return error;
2151 }
2152
2153 if (bp_addr == LLDB_INVALID_ADDRESS)
2154 {
2155 error.SetErrorString("BreakpointSite contains an invalid load address.");
2156 return error;
2157 }
2158 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2159 // trap for the breakpoint site
2160 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2161
2162 if (bp_opcode_size == 0)
2163 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002164 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002165 }
2166 else
2167 {
2168 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2169
2170 if (bp_opcode_bytes == NULL)
2171 {
2172 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2173 return error;
2174 }
2175
2176 // Save the original opcode by reading it
2177 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2178 {
2179 // Write a software breakpoint in place of the original opcode
2180 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2181 {
2182 uint8_t verify_bp_opcode_bytes[64];
2183 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2184 {
2185 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2186 {
2187 bp_site->SetEnabled(true);
2188 bp_site->SetType (BreakpointSite::eSoftware);
2189 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002190 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner24943d22010-06-08 16:52:24 +00002191 bp_site->GetID(),
2192 (uint64_t)bp_addr);
2193 }
2194 else
Greg Clayton9c236732011-10-26 00:56:27 +00002195 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00002196 }
2197 else
2198 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2199 }
2200 else
2201 error.SetErrorString("Unable to write breakpoint trap to memory.");
2202 }
2203 else
2204 error.SetErrorString("Unable to read memory at breakpoint address.");
2205 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002206 if (log && error.Fail())
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002207 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002208 bp_site->GetID(),
2209 (uint64_t)bp_addr,
2210 error.AsCString());
2211 return error;
2212}
2213
2214Error
2215Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2216{
2217 Error error;
2218 assert (bp_site != NULL);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002219 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002220 addr_t bp_addr = bp_site->GetLoadAddress();
2221 lldb::user_id_t breakID = bp_site->GetID();
2222 if (log)
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002223 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002224
2225 if (bp_site->IsHardware())
2226 {
2227 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2228 }
2229 else if (bp_site->IsEnabled())
2230 {
2231 const size_t break_op_size = bp_site->GetByteSize();
2232 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2233 if (break_op_size > 0)
2234 {
2235 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002236 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002237 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002238 bool break_op_found = false;
2239
2240 // Read the breakpoint opcode
2241 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2242 {
2243 bool verify = false;
2244 // Make sure we have the a breakpoint opcode exists at this address
2245 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2246 {
2247 break_op_found = true;
2248 // We found a valid breakpoint opcode at this address, now restore
2249 // the saved opcode.
2250 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2251 {
2252 verify = true;
2253 }
2254 else
2255 error.SetErrorString("Memory write failed when restoring original opcode.");
2256 }
2257 else
2258 {
2259 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2260 // Set verify to true and so we can check if the original opcode has already been restored
2261 verify = true;
2262 }
2263
2264 if (verify)
2265 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002266 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002267 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002268 // Verify that our original opcode made it back to the inferior
2269 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2270 {
2271 // compare the memory we just read with the original opcode
2272 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2273 {
2274 // SUCCESS
2275 bp_site->SetEnabled(false);
2276 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002277 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002278 return error;
2279 }
2280 else
2281 {
2282 if (break_op_found)
2283 error.SetErrorString("Failed to restore original opcode.");
2284 }
2285 }
2286 else
2287 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2288 }
2289 }
2290 else
2291 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2292 }
2293 }
2294 else
2295 {
2296 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002297 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002298 return error;
2299 }
2300
2301 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002302 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002303 bp_site->GetID(),
2304 (uint64_t)bp_addr,
2305 error.AsCString());
2306 return error;
2307
2308}
2309
Greg Claytonfd119992011-01-07 06:08:19 +00002310// Uncomment to verify memory caching works after making changes to caching code
2311//#define VERIFY_MEMORY_READS
2312
Sean Callananf90b5f32012-06-07 22:26:42 +00002313size_t
2314Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2315{
2316 if (!GetDisableMemoryCache())
2317 {
Greg Claytonfd119992011-01-07 06:08:19 +00002318#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002319 // Memory caching is enabled, with debug verification
2320
2321 if (buf && size)
2322 {
2323 // Uncomment the line below to make sure memory caching is working.
2324 // I ran this through the test suite and got no assertions, so I am
2325 // pretty confident this is working well. If any changes are made to
2326 // memory caching, uncomment the line below and test your changes!
2327
2328 // Verify all memory reads by using the cache first, then redundantly
2329 // reading the same memory from the inferior and comparing to make sure
2330 // everything is exactly the same.
2331 std::string verify_buf (size, '\0');
2332 assert (verify_buf.size() == size);
2333 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2334 Error verify_error;
2335 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2336 assert (cache_bytes_read == verify_bytes_read);
2337 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2338 assert (verify_error.Success() == error.Success());
2339 return cache_bytes_read;
2340 }
2341 return 0;
2342#else // !defined(VERIFY_MEMORY_READS)
2343 // Memory caching is enabled, without debug verification
2344
2345 return m_memory_cache.Read (addr, buf, size, error);
2346#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002347 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002348 else
2349 {
2350 // Memory caching is disabled
2351
2352 return ReadMemoryFromInferior (addr, buf, size, error);
2353 }
Greg Claytonfd119992011-01-07 06:08:19 +00002354}
Greg Claytonfd119992011-01-07 06:08:19 +00002355
Greg Claytondd29b972012-05-18 23:20:01 +00002356size_t
2357Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2358{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002359 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002360 out_str.clear();
2361 addr_t curr_addr = addr;
2362 while (1)
2363 {
2364 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2365 if (length == 0)
2366 break;
2367 out_str.append(buf, length);
2368 // If we got "length - 1" bytes, we didn't get the whole C string, we
2369 // need to read some more characters
2370 if (length == sizeof(buf) - 1)
2371 curr_addr += length;
2372 else
2373 break;
2374 }
2375 return out_str.size();
2376}
2377
Greg Claytonfd119992011-01-07 06:08:19 +00002378
2379size_t
Ashok Thirumurthi347d7222013-04-19 15:58:38 +00002380Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2381 size_t type_width)
2382{
2383 size_t total_bytes_read = 0;
2384 if (dst && max_bytes && type_width && max_bytes >= type_width)
2385 {
2386 // Ensure a null terminator independent of the number of bytes that is read.
2387 memset (dst, 0, max_bytes);
2388 size_t bytes_left = max_bytes - type_width;
2389
2390 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2391 assert(sizeof(terminator) >= type_width &&
2392 "Attempting to validate a string with more than 4 bytes per character!");
2393
2394 addr_t curr_addr = addr;
2395 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2396 char *curr_dst = dst;
2397
2398 error.Clear();
2399 while (bytes_left > 0 && error.Success())
2400 {
2401 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2402 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2403 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2404
2405 if (bytes_read == 0)
2406 break;
2407
2408 // Search for a null terminator of correct size and alignment in bytes_read
2409 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2410 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2411 if (::strncmp(&dst[i], terminator, type_width) == 0)
2412 {
2413 error.Clear();
2414 return i;
2415 }
2416
2417 total_bytes_read += bytes_read;
2418 curr_dst += bytes_read;
2419 curr_addr += bytes_read;
2420 bytes_left -= bytes_read;
2421 }
2422 }
2423 else
2424 {
2425 if (max_bytes)
2426 error.SetErrorString("invalid arguments");
2427 }
2428 return total_bytes_read;
2429}
2430
2431// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2432// null terminators.
2433size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002434Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002435{
2436 size_t total_cstr_len = 0;
2437 if (dst && dst_max_len)
2438 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002439 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002440 // NULL out everything just to be safe
2441 memset (dst, 0, dst_max_len);
2442 Error error;
2443 addr_t curr_addr = addr;
2444 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2445 size_t bytes_left = dst_max_len - 1;
2446 char *curr_dst = dst;
2447
2448 while (bytes_left > 0)
2449 {
2450 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2451 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2452 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2453
2454 if (bytes_read == 0)
2455 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002456 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002457 dst[total_cstr_len] = '\0';
2458 break;
2459 }
2460 const size_t len = strlen(curr_dst);
2461
2462 total_cstr_len += len;
2463
2464 if (len < bytes_to_read)
2465 break;
2466
2467 curr_dst += bytes_read;
2468 curr_addr += bytes_read;
2469 bytes_left -= bytes_read;
2470 }
2471 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002472 else
2473 {
2474 if (dst == NULL)
2475 result_error.SetErrorString("invalid arguments");
2476 else
2477 result_error.Clear();
2478 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002479 return total_cstr_len;
2480}
2481
2482size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002483Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2484{
Chris Lattner24943d22010-06-08 16:52:24 +00002485 if (buf == NULL || size == 0)
2486 return 0;
2487
2488 size_t bytes_read = 0;
2489 uint8_t *bytes = (uint8_t *)buf;
2490
2491 while (bytes_read < size)
2492 {
2493 const size_t curr_size = size - bytes_read;
2494 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2495 bytes + bytes_read,
2496 curr_size,
2497 error);
2498 bytes_read += curr_bytes_read;
2499 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2500 break;
2501 }
2502
2503 // Replace any software breakpoint opcodes that fall into this range back
2504 // into "buf" before we return
2505 if (bytes_read > 0)
2506 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2507 return bytes_read;
2508}
2509
Greg Claytonf72fdee2010-12-16 20:01:20 +00002510uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002511Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002512{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002513 Scalar scalar;
2514 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2515 return scalar.ULongLong(fail_value);
2516 return fail_value;
2517}
2518
2519addr_t
2520Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2521{
2522 Scalar scalar;
2523 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2524 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2525 return LLDB_INVALID_ADDRESS;
2526}
2527
2528
2529bool
2530Process::WritePointerToMemory (lldb::addr_t vm_addr,
2531 lldb::addr_t ptr_value,
2532 Error &error)
2533{
2534 Scalar scalar;
2535 const uint32_t addr_byte_size = GetAddressByteSize();
2536 if (addr_byte_size <= 4)
2537 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002538 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002539 scalar = ptr_value;
2540 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002541}
2542
Chris Lattner24943d22010-06-08 16:52:24 +00002543size_t
2544Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2545{
2546 size_t bytes_written = 0;
2547 const uint8_t *bytes = (const uint8_t *)buf;
2548
2549 while (bytes_written < size)
2550 {
2551 const size_t curr_size = size - bytes_written;
2552 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2553 bytes + bytes_written,
2554 curr_size,
2555 error);
2556 bytes_written += curr_bytes_written;
2557 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2558 break;
2559 }
2560 return bytes_written;
2561}
2562
2563size_t
2564Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2565{
Greg Claytonfd119992011-01-07 06:08:19 +00002566#if defined (ENABLE_MEMORY_CACHING)
2567 m_memory_cache.Flush (addr, size);
2568#endif
2569
Chris Lattner24943d22010-06-08 16:52:24 +00002570 if (buf == NULL || size == 0)
2571 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002572
Jim Ingham21f37ad2011-08-09 02:12:22 +00002573 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002574
Chris Lattner24943d22010-06-08 16:52:24 +00002575 // We need to write any data that would go where any current software traps
2576 // (enabled software breakpoints) any software traps (breakpoints) that we
2577 // may have placed in our tasks memory.
2578
2579 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2580 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2581
2582 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002583 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002584
2585 BreakpointSiteList::collection::const_iterator pos;
2586 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002587 addr_t intersect_addr = 0;
2588 size_t intersect_size = 0;
2589 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002590 const uint8_t *ubuf = (const uint8_t *)buf;
2591
2592 for (pos = iter; pos != end; ++pos)
2593 {
2594 BreakpointSiteSP bp;
2595 bp = pos->second;
2596
2597 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2598 assert(addr <= intersect_addr && intersect_addr < addr + size);
2599 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2600 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2601
2602 // Check for bytes before this breakpoint
2603 const addr_t curr_addr = addr + bytes_written;
2604 if (intersect_addr > curr_addr)
2605 {
2606 // There are some bytes before this breakpoint that we need to
2607 // just write to memory
2608 size_t curr_size = intersect_addr - curr_addr;
2609 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2610 ubuf + bytes_written,
2611 curr_size,
2612 error);
2613 bytes_written += curr_bytes_written;
2614 if (curr_bytes_written != curr_size)
2615 {
2616 // We weren't able to write all of the requested bytes, we
2617 // are done looping and will return the number of bytes that
2618 // we have written so far.
2619 break;
2620 }
2621 }
2622
2623 // Now write any bytes that would cover up any software breakpoints
2624 // directly into the breakpoint opcode buffer
2625 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2626 bytes_written += intersect_size;
2627 }
2628
2629 // Write any remaining bytes after the last breakpoint if we have any left
2630 if (bytes_written < size)
2631 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2632 ubuf + bytes_written,
2633 size - bytes_written,
2634 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002635
Chris Lattner24943d22010-06-08 16:52:24 +00002636 return bytes_written;
2637}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002638
2639size_t
Greg Clayton36da2aa2013-01-25 18:06:21 +00002640Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonc0fa5332011-05-22 22:46:53 +00002641{
2642 if (byte_size == UINT32_MAX)
2643 byte_size = scalar.GetByteSize();
2644 if (byte_size > 0)
2645 {
2646 uint8_t buf[32];
2647 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2648 if (mem_size > 0)
2649 return WriteMemory(addr, buf, mem_size, error);
2650 else
2651 error.SetErrorString ("failed to get scalar as memory data");
2652 }
2653 else
2654 {
2655 error.SetErrorString ("invalid scalar value");
2656 }
2657 return 0;
2658}
2659
2660size_t
2661Process::ReadScalarIntegerFromMemory (addr_t addr,
2662 uint32_t byte_size,
2663 bool is_signed,
2664 Scalar &scalar,
2665 Error &error)
2666{
2667 uint64_t uval;
2668
2669 if (byte_size <= sizeof(uval))
2670 {
2671 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2672 if (bytes_read == byte_size)
2673 {
2674 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Clayton36da2aa2013-01-25 18:06:21 +00002675 lldb::offset_t offset = 0;
Greg Claytonc0fa5332011-05-22 22:46:53 +00002676 if (byte_size <= 4)
2677 scalar = data.GetMaxU32 (&offset, byte_size);
2678 else
2679 scalar = data.GetMaxU64 (&offset, byte_size);
2680
2681 if (is_signed)
2682 scalar.SignExtend(byte_size * 8);
2683 return bytes_read;
2684 }
2685 }
2686 else
2687 {
2688 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2689 }
2690 return 0;
2691}
2692
Greg Clayton613b8732011-05-17 03:37:42 +00002693#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002694addr_t
2695Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2696{
Jim Inghame6bd1422011-06-20 17:32:44 +00002697 if (GetPrivateState() != eStateStopped)
2698 return LLDB_INVALID_ADDRESS;
2699
Greg Clayton613b8732011-05-17 03:37:42 +00002700#if defined (USE_ALLOCATE_MEMORY_CACHE)
2701 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2702#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002703 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002704 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2860ba92011-01-23 19:58:49 +00002705 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002706 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002707 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002708 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002709 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002710 m_mod_id.GetStopID(),
2711 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002712 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002713#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002714}
2715
Sean Callanan6cf6c472011-09-20 23:01:51 +00002716bool
2717Process::CanJIT ()
2718{
Sean Callanan04200f62012-02-14 22:50:38 +00002719 if (m_can_jit == eCanJITDontKnow)
2720 {
2721 Error err;
2722
2723 uint64_t allocated_memory = AllocateMemory(8,
2724 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2725 err);
2726
2727 if (err.Success())
2728 m_can_jit = eCanJITYes;
2729 else
2730 m_can_jit = eCanJITNo;
2731
2732 DeallocateMemory (allocated_memory);
2733 }
2734
Sean Callanan6cf6c472011-09-20 23:01:51 +00002735 return m_can_jit == eCanJITYes;
2736}
2737
2738void
2739Process::SetCanJIT (bool can_jit)
2740{
2741 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2742}
2743
Chris Lattner24943d22010-06-08 16:52:24 +00002744Error
2745Process::DeallocateMemory (addr_t ptr)
2746{
Greg Clayton613b8732011-05-17 03:37:42 +00002747 Error error;
2748#if defined (USE_ALLOCATE_MEMORY_CACHE)
2749 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2750 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002751 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Clayton613b8732011-05-17 03:37:42 +00002752 }
2753#else
2754 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002755
Greg Clayton952e9dc2013-03-27 23:08:40 +00002756 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2860ba92011-01-23 19:58:49 +00002757 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002758 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002759 ptr,
2760 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002761 m_mod_id.GetStopID(),
2762 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002763#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002764 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002765}
2766
Han Ming Ong2529aa32012-11-17 00:33:14 +00002767
Greg Claytonb5a8f142012-02-05 02:38:54 +00002768ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002769Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton2ddb2b82013-02-01 21:38:35 +00002770 lldb::addr_t header_addr)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002771{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002772 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002773 if (module_sp)
2774 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002775 Error error;
2776 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2777 if (objfile)
Greg Clayton6c5438b2012-02-24 21:55:59 +00002778 return module_sp;
Greg Claytonb5a8f142012-02-05 02:38:54 +00002779 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002780 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002781}
Chris Lattner24943d22010-06-08 16:52:24 +00002782
2783Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002784Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002785{
2786 Error error;
2787 error.SetErrorString("watchpoints are not supported");
2788 return error;
2789}
2790
2791Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002792Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002793{
2794 Error error;
2795 error.SetErrorString("watchpoints are not supported");
2796 return error;
2797}
2798
2799StateType
2800Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2801{
2802 StateType state;
2803 // Now wait for the process to launch and return control to us, and then
2804 // call DidLaunch:
2805 while (1)
2806 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002807 event_sp.reset();
2808 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2809
Greg Clayton20206082011-11-17 01:23:07 +00002810 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002811 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002812
2813 // If state is invalid, then we timed out
2814 if (state == eStateInvalid)
2815 break;
2816
2817 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002818 HandlePrivateEvent (event_sp);
2819 }
2820 return state;
2821}
2822
2823Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002824Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002825{
2826 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002827 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002828 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002829 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002830 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002831
Greg Clayton5beb99d2011-08-11 02:48:45 +00002832 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002833 if (exe_module)
2834 {
Greg Clayton180546b2011-04-30 01:09:13 +00002835 char local_exec_file_path[PATH_MAX];
2836 char platform_exec_file_path[PATH_MAX];
2837 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2838 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002839 if (exe_module->GetFileSpec().Exists())
2840 {
Greg Claytona2f74232011-02-24 22:24:29 +00002841 if (PrivateStateThreadIsValid ())
2842 PausePrivateStateThread ();
2843
Chris Lattner24943d22010-06-08 16:52:24 +00002844 error = WillLaunch (exe_module);
2845 if (error.Success())
2846 {
Greg Claytond8c62532010-10-07 04:19:01 +00002847 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002848 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002849
Greg Clayton061ca652013-04-18 16:57:27 +00002850 if (m_public_run_lock.WriteTryLock())
Greg Clayton777c6b72012-09-04 20:29:05 +00002851 {
2852 // Now launch using these arguments.
2853 error = DoLaunch (exe_module, launch_info);
2854 }
2855 else
2856 {
2857 // This shouldn't happen
2858 error.SetErrorString("failed to acquire process run lock");
2859 }
Chris Lattner24943d22010-06-08 16:52:24 +00002860
2861 if (error.Fail())
2862 {
2863 if (GetID() != LLDB_INVALID_PROCESS_ID)
2864 {
2865 SetID (LLDB_INVALID_PROCESS_ID);
2866 const char *error_string = error.AsCString();
2867 if (error_string == NULL)
2868 error_string = "launch failed";
2869 SetExitStatus (-1, error_string);
2870 }
2871 }
2872 else
2873 {
2874 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002875 TimeValue timeout_time;
2876 timeout_time = TimeValue::Now();
2877 timeout_time.OffsetWithSeconds(10);
2878 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002879
Greg Clayton49859592011-06-22 01:42:17 +00002880 if (state == eStateInvalid || event_sp.get() == NULL)
2881 {
2882 // We were able to launch the process, but we failed to
2883 // catch the initial stop.
2884 SetExitStatus (0, "failed to catch stop after launch");
2885 Destroy();
2886 }
2887 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002888 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002889
Chris Lattner24943d22010-06-08 16:52:24 +00002890 DidLaunch ();
2891
Greg Clayton9ce95382012-02-13 23:10:39 +00002892 DynamicLoader *dyld = GetDynamicLoader ();
2893 if (dyld)
2894 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002895
Greg Clayton37f962e2011-08-22 02:49:39 +00002896 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002897 // This delays passing the stopped event to listeners till DidLaunch gets
2898 // a chance to complete...
2899 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002900
2901 if (PrivateStateThreadIsValid ())
2902 ResumePrivateStateThread ();
2903 else
2904 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002905 }
2906 else if (state == eStateExited)
2907 {
2908 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2909 // not likely to work, and return an invalid pid.
2910 HandlePrivateEvent (event_sp);
2911 }
2912 }
2913 }
2914 }
2915 else
2916 {
Greg Clayton9c236732011-10-26 00:56:27 +00002917 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002918 }
2919 }
2920 return error;
2921}
2922
Greg Clayton46c9a352012-02-09 06:16:32 +00002923
2924Error
2925Process::LoadCore ()
2926{
2927 Error error = DoLoadCore();
2928 if (error.Success())
2929 {
2930 if (PrivateStateThreadIsValid ())
2931 ResumePrivateStateThread ();
2932 else
2933 StartPrivateStateThread ();
2934
Greg Clayton9ce95382012-02-13 23:10:39 +00002935 DynamicLoader *dyld = GetDynamicLoader ();
2936 if (dyld)
2937 dyld->DidAttach();
2938
2939 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002940 // We successfully loaded a core file, now pretend we stopped so we can
2941 // show all of the threads in the core file and explore the crashed
2942 // state.
2943 SetPrivateState (eStateStopped);
2944
2945 }
2946 return error;
2947}
2948
Greg Clayton9ce95382012-02-13 23:10:39 +00002949DynamicLoader *
2950Process::GetDynamicLoader ()
2951{
2952 if (m_dyld_ap.get() == NULL)
2953 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2954 return m_dyld_ap.get();
2955}
Greg Clayton46c9a352012-02-09 06:16:32 +00002956
2957
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002958Process::NextEventAction::EventActionResult
2959Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002960{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002961 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2962 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002963 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002964 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002965 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002966 return eEventActionRetry;
2967
2968 case eStateStopped:
2969 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002970 {
2971 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002972 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002973 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2974 if (m_exec_count > 0)
2975 {
2976 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002977 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002978 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002979 return eEventActionRetry;
2980 }
2981 else
2982 {
2983 m_process->CompleteAttach ();
2984 return eEventActionSuccess;
2985 }
2986 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002987 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002988
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002989 default:
2990 case eStateExited:
2991 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002992 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002993 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002994
2995 m_exit_string.assign ("No valid Process");
2996 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002997}
Chris Lattner24943d22010-06-08 16:52:24 +00002998
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002999Process::NextEventAction::EventActionResult
3000Process::AttachCompletionHandler::HandleBeingInterrupted()
3001{
3002 return eEventActionSuccess;
3003}
3004
3005const char *
3006Process::AttachCompletionHandler::GetExitString ()
3007{
3008 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00003009}
3010
3011Error
Greg Clayton527154d2011-11-15 03:53:30 +00003012Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00003013{
Chris Lattner24943d22010-06-08 16:52:24 +00003014 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00003015 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00003016 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00003017 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00003018
Greg Clayton527154d2011-11-15 03:53:30 +00003019 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003020 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00003021 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00003022 {
Greg Clayton527154d2011-11-15 03:53:30 +00003023 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00003024
Greg Clayton527154d2011-11-15 03:53:30 +00003025 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00003026 {
Greg Clayton527154d2011-11-15 03:53:30 +00003027 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3028
3029 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00003030 {
Greg Clayton527154d2011-11-15 03:53:30 +00003031 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3032 if (error.Success())
3033 {
Greg Clayton061ca652013-04-18 16:57:27 +00003034 if (m_public_run_lock.WriteTryLock())
Greg Claytond34a3b22012-10-12 16:10:12 +00003035 {
3036 m_should_detach = true;
3037 SetPublicState (eStateAttaching);
3038 // Now attach using these arguments.
3039 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
3040 }
3041 else
3042 {
3043 // This shouldn't happen
3044 error.SetErrorString("failed to acquire process run lock");
3045 }
Greg Claytonffa43a62011-11-17 04:46:02 +00003046
Greg Clayton527154d2011-11-15 03:53:30 +00003047 if (error.Fail())
3048 {
3049 if (GetID() != LLDB_INVALID_PROCESS_ID)
3050 {
3051 SetID (LLDB_INVALID_PROCESS_ID);
3052 if (error.AsCString() == NULL)
3053 error.SetErrorString("attach failed");
3054
3055 SetExitStatus(-1, error.AsCString());
3056 }
3057 }
3058 else
3059 {
3060 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3061 StartPrivateStateThread();
3062 }
3063 return error;
3064 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003065 }
Greg Clayton527154d2011-11-15 03:53:30 +00003066 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003067 {
Greg Clayton527154d2011-11-15 03:53:30 +00003068 ProcessInstanceInfoList process_infos;
3069 PlatformSP platform_sp (m_target.GetPlatform ());
3070
3071 if (platform_sp)
3072 {
3073 ProcessInstanceInfoMatch match_info;
3074 match_info.GetProcessInfo() = attach_info;
3075 match_info.SetNameMatchType (eNameMatchEquals);
3076 platform_sp->FindProcesses (match_info, process_infos);
3077 const uint32_t num_matches = process_infos.GetSize();
3078 if (num_matches == 1)
3079 {
3080 attach_pid = process_infos.GetProcessIDAtIndex(0);
3081 // Fall through and attach using the above process ID
3082 }
3083 else
3084 {
3085 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3086 if (num_matches > 1)
3087 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3088 else
3089 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3090 }
3091 }
3092 else
3093 {
3094 error.SetErrorString ("invalid platform, can't find processes by name");
3095 return error;
3096 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003097 }
Chris Lattner24943d22010-06-08 16:52:24 +00003098 }
3099 else
Greg Clayton527154d2011-11-15 03:53:30 +00003100 {
3101 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003102 }
3103 }
Greg Clayton527154d2011-11-15 03:53:30 +00003104
3105 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003106 {
Greg Clayton527154d2011-11-15 03:53:30 +00003107 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003108 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00003109 {
Greg Clayton527154d2011-11-15 03:53:30 +00003110
Greg Clayton061ca652013-04-18 16:57:27 +00003111 if (m_public_run_lock.WriteTryLock())
Greg Claytond34a3b22012-10-12 16:10:12 +00003112 {
3113 // Now attach using these arguments.
3114 m_should_detach = true;
3115 SetPublicState (eStateAttaching);
3116 error = DoAttachToProcessWithID (attach_pid, attach_info);
3117 }
3118 else
3119 {
3120 // This shouldn't happen
3121 error.SetErrorString("failed to acquire process run lock");
3122 }
3123
Greg Clayton527154d2011-11-15 03:53:30 +00003124 if (error.Success())
3125 {
3126
3127 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3128 StartPrivateStateThread();
3129 }
3130 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003131 {
3132 if (GetID() != LLDB_INVALID_PROCESS_ID)
3133 {
3134 SetID (LLDB_INVALID_PROCESS_ID);
3135 const char *error_string = error.AsCString();
3136 if (error_string == NULL)
3137 error_string = "attach failed";
3138
3139 SetExitStatus(-1, error_string);
3140 }
3141 }
Chris Lattner24943d22010-06-08 16:52:24 +00003142 }
3143 }
3144 return error;
3145}
3146
Greg Clayton75c703d2011-02-16 04:46:07 +00003147void
3148Process::CompleteAttach ()
3149{
3150 // Let the process subclass figure out at much as it can about the process
3151 // before we go looking for a dynamic loader plug-in.
3152 DidAttach();
3153
Jim Ingham0d7f7772011-09-15 01:10:17 +00003154 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3155 // the same as the one we've already set, switch architectures.
3156 PlatformSP platform_sp (m_target.GetPlatform ());
3157 assert (platform_sp.get());
3158 if (platform_sp)
3159 {
Greg Claytonb170aee2012-05-08 01:45:38 +00003160 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Claytonaad2b0f2013-01-11 20:49:54 +00003161 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Claytonb170aee2012-05-08 01:45:38 +00003162 {
3163 ArchSpec platform_arch;
3164 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3165 if (platform_sp)
3166 {
3167 m_target.SetPlatform (platform_sp);
3168 m_target.SetArchitecture(platform_arch);
3169 }
3170 }
3171 else
3172 {
3173 ProcessInstanceInfo process_info;
3174 platform_sp->GetProcessInfo (GetID(), process_info);
3175 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callanan40e278c2012-12-13 22:07:14 +00003176 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Claytonb170aee2012-05-08 01:45:38 +00003177 m_target.SetArchitecture (process_arch);
3178 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00003179 }
3180
3181 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00003182 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00003183 DynamicLoader *dyld = GetDynamicLoader ();
3184 if (dyld)
3185 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00003186
Greg Clayton37f962e2011-08-22 02:49:39 +00003187 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00003188 // Figure out which one is the executable, and set that in our target:
Enrico Granata146d9522012-11-08 02:22:02 +00003189 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham93367902012-05-30 02:19:25 +00003190 Mutex::Locker modules_locker(target_modules.GetMutex());
3191 size_t num_modules = target_modules.GetSize();
3192 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003193
Greg Clayton75c703d2011-02-16 04:46:07 +00003194 for (int i = 0; i < num_modules; i++)
3195 {
Jim Ingham93367902012-05-30 02:19:25 +00003196 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00003197 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00003198 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00003199 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00003200 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003201 break;
3202 }
3203 }
Jim Ingham93367902012-05-30 02:19:25 +00003204 if (new_executable_module_sp)
3205 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00003206}
3207
Chris Lattner24943d22010-06-08 16:52:24 +00003208Error
Jason Molendafac2e622012-09-29 04:02:01 +00003209Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00003210{
Greg Claytone71e2582011-02-04 01:58:07 +00003211 m_abi_sp.reset();
3212 m_process_input_reader.reset();
3213
3214 // Find the process and its architecture. Make sure it matches the architecture
3215 // of the current Target, and if not adjust it.
3216
Jason Molendafac2e622012-09-29 04:02:01 +00003217 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00003218 if (error.Success())
3219 {
Greg Claytona2f74232011-02-24 22:24:29 +00003220 if (GetID() != LLDB_INVALID_PROCESS_ID)
3221 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00003222 EventSP event_sp;
3223 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3224
3225 if (state == eStateStopped || state == eStateCrashed)
3226 {
3227 // If we attached and actually have a process on the other end, then
3228 // this ended up being the equivalent of an attach.
3229 CompleteAttach ();
3230
3231 // This delays passing the stopped event to listeners till
3232 // CompleteAttach gets a chance to complete...
3233 HandlePrivateEvent (event_sp);
3234
3235 }
Greg Claytona2f74232011-02-24 22:24:29 +00003236 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00003237
3238 if (PrivateStateThreadIsValid ())
3239 ResumePrivateStateThread ();
3240 else
3241 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00003242 }
3243 return error;
3244}
3245
3246
3247Error
Jim Ingham027aaa72012-04-19 01:40:33 +00003248Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00003249{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003250 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00003251 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003252 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00003253 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00003254 StateAsCString(m_public_state.GetValue()),
3255 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00003256
3257 Error error (WillResume());
3258 // Tell the process it is about to resume before the thread list
3259 if (error.Success())
3260 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003261 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003262 // can let all of our threads know that they are about to be
3263 // resumed. Threads will each be called with
3264 // Thread::WillResume(StateType) where StateType contains the state
3265 // that they are supposed to have when the process is resumed
3266 // (suspended/running/stepping). Threads should also check
3267 // their resume signal in lldb::Thread::GetResumeSignal()
3268 // to see if they are suppoed to start back up with a signal.
3269 if (m_thread_list.WillResume())
3270 {
Jim Ingham1831e782012-04-07 00:00:41 +00003271 // Last thing, do the PreResumeActions.
3272 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003273 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003274 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham1831e782012-04-07 00:00:41 +00003275 }
3276 else
3277 {
3278 m_mod_id.BumpResumeID();
Greg Clayton061ca652013-04-18 16:57:27 +00003279#if defined(__APPLE__)
3280 m_private_run_lock.WriteLock();
3281#endif
Jim Ingham1831e782012-04-07 00:00:41 +00003282 error = DoResume();
3283 if (error.Success())
3284 {
3285 DidResume();
3286 m_thread_list.DidResume();
3287 if (log)
3288 log->Printf ("Process thinks the process has resumed.");
3289 }
Greg Clayton061ca652013-04-18 16:57:27 +00003290#if defined(__APPLE__)
3291 else
3292 {
3293 m_private_run_lock.WriteUnlock();
3294 }
3295#endif
Chris Lattner24943d22010-06-08 16:52:24 +00003296 }
3297 }
3298 else
3299 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003300 // Somebody wanted to run without running. So generate a continue & a stopped event,
3301 // and let the world handle them.
3302 if (log)
3303 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3304
3305 SetPrivateState(eStateRunning);
3306 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003307 }
3308 }
Jim Inghamac959662011-01-24 06:34:17 +00003309 else if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003310 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003311 return error;
3312}
3313
3314Error
3315Process::Halt ()
3316{
Jim Ingham43892562012-06-06 00:29:30 +00003317 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3318 // we could just straightaway get another event. It just narrows the window...
3319 m_currently_handling_event.WaitForValueEqualTo(false);
3320
3321
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003322 // Pause our private state thread so we can ensure no one else eats
3323 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003324 Listener halt_listener ("lldb.process.halt_listener");
3325 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003326
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003327 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003328 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003329
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003330 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003331 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003332
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003333 bool caused_stop = false;
3334
3335 // Ask the process subclass to actually halt our process
3336 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003337 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003338 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003339 if (m_public_state.GetValue() == eStateAttaching)
3340 {
3341 SetExitStatus(SIGKILL, "Cancelled async attach.");
3342 Destroy ();
3343 }
3344 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003345 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003346 // If "caused_stop" is true, then DoHalt stopped the process. If
3347 // "caused_stop" is false, the process was already stopped.
3348 // If the DoHalt caused the process to stop, then we want to catch
3349 // this event and set the interrupted bool to true before we pass
3350 // this along so clients know that the process was interrupted by
3351 // a halt command.
3352 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003353 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003354 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003355 TimeValue timeout_time;
3356 timeout_time = TimeValue::Now();
3357 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003358 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3359 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003360
Jim Inghamf9f40c22011-02-08 05:20:59 +00003361 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003362 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003363 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003364 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003365 }
3366 else
3367 {
Greg Clayton20206082011-11-17 01:23:07 +00003368 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003369 {
3370 // We caused the process to interrupt itself, so mark this
3371 // as such in the stop event so clients can tell an interrupted
3372 // process from a natural stop
3373 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3374 }
3375 else
3376 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00003377 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003378 if (log)
3379 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3380 error.SetErrorString ("Did not get stopped event after halt.");
3381 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003382 }
3383 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003384 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003385 }
3386 }
Chris Lattner24943d22010-06-08 16:52:24 +00003387 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003388 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003389 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003390
3391 // Post any event we might have consumed. If all goes well, we will have
3392 // stopped the process, intercepted the event and set the interrupted
3393 // bool in the event. Post it to the private event queue and that will end up
3394 // correctly setting the state.
3395 if (event_sp)
3396 m_private_state_broadcaster.BroadcastEvent(event_sp);
3397
Chris Lattner24943d22010-06-08 16:52:24 +00003398 return error;
3399}
3400
3401Error
Jim Inghame33bb5b2013-03-29 01:18:12 +00003402Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3403{
3404 Error error;
3405 if (m_public_state.GetValue() == eStateRunning)
3406 {
3407 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3408 if (log)
3409 log->Printf("Process::Destroy() About to halt.");
3410 error = Halt();
3411 if (error.Success())
3412 {
3413 // Consume the halt event.
3414 TimeValue timeout (TimeValue::Now());
3415 timeout.OffsetWithSeconds(1);
3416 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3417
3418 // If the process exited while we were waiting for it to stop, put the exited event into
3419 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3420 // they don't have a process anymore...
3421
3422 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3423 {
3424 if (log)
3425 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3426 return error;
3427 }
3428 else
3429 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3430
3431 if (state != eStateStopped)
3432 {
3433 if (log)
3434 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3435 // If we really couldn't stop the process then we should just error out here, but if the
3436 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3437 StateType private_state = m_private_state.GetValue();
3438 if (private_state != eStateStopped)
3439 {
3440 return error;
3441 }
3442 }
3443 }
3444 else
3445 {
3446 if (log)
3447 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3448 }
3449 }
3450 return error;
3451}
3452
3453Error
Jim Inghamb4e08ab2013-04-30 23:46:08 +00003454Process::Detach (bool keep_stopped)
Chris Lattner24943d22010-06-08 16:52:24 +00003455{
Jim Inghame33bb5b2013-03-29 01:18:12 +00003456 EventSP exit_event_sp;
3457 Error error;
3458 m_destroy_in_process = true;
3459
3460 error = WillDetach();
Chris Lattner24943d22010-06-08 16:52:24 +00003461
3462 if (error.Success())
3463 {
Jim Inghame33bb5b2013-03-29 01:18:12 +00003464 if (DetachRequiresHalt())
3465 {
3466 error = HaltForDestroyOrDetach (exit_event_sp);
3467 if (!error.Success())
3468 {
3469 m_destroy_in_process = false;
3470 return error;
3471 }
3472 else if (exit_event_sp)
3473 {
3474 // We shouldn't need to do anything else here. There's no process left to detach from...
3475 StopPrivateStateThread();
3476 m_destroy_in_process = false;
3477 return error;
3478 }
3479 }
3480
Jim Inghamb4e08ab2013-04-30 23:46:08 +00003481 error = DoDetach(keep_stopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003482 if (error.Success())
3483 {
3484 DidDetach();
3485 StopPrivateStateThread();
3486 }
Jim Inghamb4e08ab2013-04-30 23:46:08 +00003487 else
3488 {
3489 return error;
3490 }
Chris Lattner24943d22010-06-08 16:52:24 +00003491 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003492 m_destroy_in_process = false;
3493
3494 // If we exited when we were waiting for a process to stop, then
3495 // forward the event here so we don't lose the event
3496 if (exit_event_sp)
3497 {
3498 // Directly broadcast our exited event because we shut down our
3499 // private state thread above
3500 BroadcastEvent(exit_event_sp);
3501 }
3502
3503 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3504 // the last events through the event system, in which case we might strand the write lock. Unlock
3505 // it here so when we do to tear down the process we don't get an error destroying the lock.
3506
Greg Clayton061ca652013-04-18 16:57:27 +00003507 m_public_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003508 return error;
3509}
3510
3511Error
3512Process::Destroy ()
3513{
Jim Inghameb175302013-03-01 20:04:25 +00003514
3515 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3516 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3517 // failed and the process stays around for some reason it won't be in a confused state.
3518
3519 m_destroy_in_process = true;
3520
Chris Lattner24943d22010-06-08 16:52:24 +00003521 Error error (WillDestroy());
3522 if (error.Success())
3523 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003524 EventSP exit_event_sp;
Jim Inghame33bb5b2013-03-29 01:18:12 +00003525 if (DestroyRequiresHalt())
Jim Inghamf4928de2012-05-23 15:46:31 +00003526 {
Jim Inghame33bb5b2013-03-29 01:18:12 +00003527 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Inghamf4928de2012-05-23 15:46:31 +00003528 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003529
Jim Ingham43892562012-06-06 00:29:30 +00003530 if (m_public_state.GetValue() != eStateRunning)
3531 {
3532 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3533 // kill it, we don't want it hitting a breakpoint...
3534 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3535 // we're not going to have much luck doing this now.
3536 m_thread_list.DiscardThreadPlans();
3537 DisableAllBreakpointSites();
3538 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003539
Chris Lattner24943d22010-06-08 16:52:24 +00003540 error = DoDestroy();
3541 if (error.Success())
3542 {
3543 DidDestroy();
3544 StopPrivateStateThread();
3545 }
Caroline Tice861efb32010-11-16 05:07:41 +00003546 m_stdio_communication.StopReadThread();
3547 m_stdio_communication.Disconnect();
3548 if (m_process_input_reader && m_process_input_reader->IsActive())
3549 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3550 if (m_process_input_reader)
3551 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003552
3553 // If we exited when we were waiting for a process to stop, then
3554 // forward the event here so we don't lose the event
3555 if (exit_event_sp)
3556 {
3557 // Directly broadcast our exited event because we shut down our
3558 // private state thread above
3559 BroadcastEvent(exit_event_sp);
3560 }
3561
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003562 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3563 // the last events through the event system, in which case we might strand the write lock. Unlock
3564 // it here so when we do to tear down the process we don't get an error destroying the lock.
Greg Clayton061ca652013-04-18 16:57:27 +00003565 m_public_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003566 }
Jim Inghameb175302013-03-01 20:04:25 +00003567
3568 m_destroy_in_process = false;
3569
Chris Lattner24943d22010-06-08 16:52:24 +00003570 return error;
3571}
3572
3573Error
3574Process::Signal (int signal)
3575{
3576 Error error (WillSignal());
3577 if (error.Success())
3578 {
3579 error = DoSignal(signal);
3580 if (error.Success())
3581 DidSignal();
3582 }
3583 return error;
3584}
3585
Greg Clayton395fc332011-02-15 21:59:32 +00003586lldb::ByteOrder
3587Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003588{
Greg Clayton395fc332011-02-15 21:59:32 +00003589 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003590}
3591
3592uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003593Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003594{
Greg Clayton395fc332011-02-15 21:59:32 +00003595 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003596}
3597
Greg Clayton395fc332011-02-15 21:59:32 +00003598
Chris Lattner24943d22010-06-08 16:52:24 +00003599bool
3600Process::ShouldBroadcastEvent (Event *event_ptr)
3601{
3602 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3603 bool return_value = true;
Greg Clayton952e9dc2013-03-27 23:08:40 +00003604 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham89e248f2013-02-09 01:29:05 +00003605
Chris Lattner24943d22010-06-08 16:52:24 +00003606 switch (state)
3607 {
Greg Claytone71e2582011-02-04 01:58:07 +00003608 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003609 case eStateAttaching:
3610 case eStateLaunching:
3611 case eStateDetached:
3612 case eStateExited:
3613 case eStateUnloaded:
3614 // These events indicate changes in the state of the debugging session, always report them.
3615 return_value = true;
3616 break;
3617 case eStateInvalid:
3618 // We stopped for no apparent reason, don't report it.
3619 return_value = false;
3620 break;
3621 case eStateRunning:
3622 case eStateStepping:
3623 // If we've started the target running, we handle the cases where we
3624 // are already running and where there is a transition from stopped to
3625 // running differently.
3626 // running -> running: Automatically suppress extra running events
3627 // stopped -> running: Report except when there is one or more no votes
3628 // and no yes votes.
3629 SynchronouslyNotifyStateChanged (state);
Jim Ingham89e248f2013-02-09 01:29:05 +00003630 switch (m_last_broadcast_state)
Chris Lattner24943d22010-06-08 16:52:24 +00003631 {
3632 case eStateRunning:
3633 case eStateStepping:
3634 // We always suppress multiple runnings with no PUBLIC stop in between.
3635 return_value = false;
3636 break;
3637 default:
3638 // TODO: make this work correctly. For now always report
3639 // run if we aren't running so we don't miss any runnning
3640 // events. If I run the lldb/test/thread/a.out file and
3641 // break at main.cpp:58, run and hit the breakpoints on
3642 // multiple threads, then somehow during the stepping over
3643 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003644
3645 // This is a transition from stop to run.
3646 switch (m_thread_list.ShouldReportRun (event_ptr))
3647 {
3648 case eVoteYes:
3649 case eVoteNoOpinion:
3650 return_value = true;
3651 break;
3652 case eVoteNo:
3653 return_value = false;
3654 break;
3655 }
3656 break;
3657 }
3658 break;
3659 case eStateStopped:
3660 case eStateCrashed:
3661 case eStateSuspended:
3662 {
3663 // We've stopped. First see if we're going to restart the target.
3664 // If we are going to stop, then we always broadcast the event.
3665 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00003666 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003667
Greg Clayton061ca652013-04-18 16:57:27 +00003668#if defined(__APPLE__)
3669 m_private_run_lock.WriteUnlock();
3670#endif
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003671 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003672 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003673 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003674 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003675 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3676 event_ptr,
3677 StateAsCString(state));
3678 return_value = true;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003679 }
3680 else
3681 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003682 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3683 // Asking the thread list is also not likely to go well, since we are running again.
3684 // So in that case just report the event.
3685
3686 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3687 bool should_resume = false;
3688 if (!was_restarted)
3689 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
3690 if (was_restarted || should_resume)
Chris Lattner24943d22010-06-08 16:52:24 +00003691 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003692 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3693 if (log)
3694 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3695 should_resume,
3696 StateAsCString(state),
3697 was_restarted,
3698 stop_vote);
3699
3700 switch (stop_vote)
Chris Lattner24943d22010-06-08 16:52:24 +00003701 {
3702 case eVoteYes:
Jim Ingham89e248f2013-02-09 01:29:05 +00003703 return_value = true;
3704 break;
Chris Lattner24943d22010-06-08 16:52:24 +00003705 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003706 case eVoteNo:
3707 return_value = false;
3708 break;
3709 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003710
Jim Ingham8290bba2012-09-05 21:13:56 +00003711 if (!was_restarted)
Jim Ingham89e248f2013-02-09 01:29:05 +00003712 {
3713 if (log)
3714 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3715 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Ingham8290bba2012-09-05 21:13:56 +00003716 PrivateResume ();
Jim Ingham89e248f2013-02-09 01:29:05 +00003717 }
3718
Chris Lattner24943d22010-06-08 16:52:24 +00003719 }
3720 else
3721 {
3722 return_value = true;
3723 SynchronouslyNotifyStateChanged (state);
3724 }
3725 }
3726 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003727 break;
Chris Lattner24943d22010-06-08 16:52:24 +00003728 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003729
3730 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3731 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3732 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3733 // because the PublicState reflects the last event pulled off the queue, and there may be several
3734 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3735 // yet. m_last_broadcast_state gets updated here.
3736
3737 if (return_value)
3738 m_last_broadcast_state = state;
3739
Chris Lattner24943d22010-06-08 16:52:24 +00003740 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003741 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3742 event_ptr,
3743 StateAsCString(state),
3744 StateAsCString(m_last_broadcast_state),
3745 return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003746 return return_value;
3747}
3748
Chris Lattner24943d22010-06-08 16:52:24 +00003749
3750bool
Jim Ingham1831e782012-04-07 00:00:41 +00003751Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003752{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003753 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003754
Greg Claytonb72d0f02011-04-12 05:54:46 +00003755 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003756 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003757 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3758
Jim Ingham1831e782012-04-07 00:00:41 +00003759 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003760 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003761
3762 // Create a thread that watches our internal state and controls which
3763 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003764 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003765 if (already_running)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003766 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham1831e782012-04-07 00:00:41 +00003767 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003768 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003769
3770 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003771 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003772 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3773 if (success)
3774 {
3775 ResumePrivateStateThread();
3776 return true;
3777 }
3778 else
3779 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003780}
3781
3782void
3783Process::PausePrivateStateThread ()
3784{
3785 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3786}
3787
3788void
3789Process::ResumePrivateStateThread ()
3790{
3791 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3792}
3793
3794void
3795Process::StopPrivateStateThread ()
3796{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003797 if (PrivateStateThreadIsValid ())
3798 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003799 else
3800 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00003801 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003802 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003803 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003804 }
Chris Lattner24943d22010-06-08 16:52:24 +00003805}
3806
3807void
3808Process::ControlPrivateStateThread (uint32_t signal)
3809{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003810 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003811
3812 assert (signal == eBroadcastInternalStateControlStop ||
3813 signal == eBroadcastInternalStateControlPause ||
3814 signal == eBroadcastInternalStateControlResume);
3815
3816 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003817 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003818
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003819 // Signal the private state thread. First we should copy this is case the
3820 // thread starts exiting since the private state thread will NULL this out
3821 // when it exits
3822 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003823 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003824 {
3825 TimeValue timeout_time;
3826 bool timed_out;
3827
3828 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3829
3830 timeout_time = TimeValue::Now();
3831 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003832 if (log)
3833 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003834 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3835 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3836
3837 if (signal == eBroadcastInternalStateControlStop)
3838 {
3839 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003840 {
3841 Error error;
3842 Host::ThreadCancel (private_state_thread, &error);
3843 if (log)
3844 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3845 }
3846 else
3847 {
3848 if (log)
3849 log->Printf ("The control event killed the private state thread without having to cancel.");
3850 }
Chris Lattner24943d22010-06-08 16:52:24 +00003851
3852 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003853 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003854 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003855 }
3856 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003857 else
3858 {
3859 if (log)
3860 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3861 }
Chris Lattner24943d22010-06-08 16:52:24 +00003862}
3863
3864void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003865Process::SendAsyncInterrupt ()
3866{
3867 if (PrivateStateThreadIsValid())
3868 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3869 else
3870 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3871}
3872
3873void
Chris Lattner24943d22010-06-08 16:52:24 +00003874Process::HandlePrivateEvent (EventSP &event_sp)
3875{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003876 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003877 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003878
Greg Clayton68ca8232011-01-25 02:58:48 +00003879 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003880
3881 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003882 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003883 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003884 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham89e248f2013-02-09 01:29:05 +00003885 if (log)
3886 log->Printf ("Ran next event action, result was %d.", action_result);
3887
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003888 switch (action_result)
3889 {
3890 case NextEventAction::eEventActionSuccess:
3891 SetNextEventAction(NULL);
3892 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003893
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003894 case NextEventAction::eEventActionRetry:
3895 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003896
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003897 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003898 // Handle Exiting Here. If we already got an exited event,
3899 // we should just propagate it. Otherwise, swallow this event,
3900 // and set our state to exit so the next event will kill us.
3901 if (new_state != eStateExited)
3902 {
3903 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003904 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003905 SetNextEventAction(NULL);
3906 return;
3907 }
3908 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003909 break;
3910 }
3911 }
3912
Chris Lattner24943d22010-06-08 16:52:24 +00003913 // See if we should broadcast this state to external clients?
3914 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003915
3916 if (should_broadcast)
3917 {
3918 if (log)
3919 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003920 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003921 __FUNCTION__,
3922 GetID(),
3923 StateAsCString(new_state),
3924 StateAsCString (GetState ()),
3925 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003926 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003927 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003928 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003929 PushProcessInputReader ();
3930 else
3931 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003932
Chris Lattner24943d22010-06-08 16:52:24 +00003933 BroadcastEvent (event_sp);
3934 }
3935 else
3936 {
3937 if (log)
3938 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003939 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003940 __FUNCTION__,
3941 GetID(),
3942 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003943 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003944 }
3945 }
Jim Ingham43892562012-06-06 00:29:30 +00003946 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003947}
3948
3949void *
3950Process::PrivateStateThread (void *arg)
3951{
3952 Process *proc = static_cast<Process*> (arg);
3953 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003954 return result;
3955}
3956
3957void *
3958Process::RunPrivateStateThread ()
3959{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003960 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003961 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003962
Greg Clayton952e9dc2013-03-27 23:08:40 +00003963 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003964 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003965 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003966
3967 bool exit_now = false;
3968 while (!exit_now)
3969 {
3970 EventSP event_sp;
3971 WaitForEventsPrivate (NULL, event_sp, control_only);
3972 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3973 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003974 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003975 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003976
Chris Lattner24943d22010-06-08 16:52:24 +00003977 switch (event_sp->GetType())
3978 {
3979 case eBroadcastInternalStateControlStop:
3980 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003981 break; // doing any internal state managment below
3982
3983 case eBroadcastInternalStateControlPause:
3984 control_only = true;
3985 break;
3986
3987 case eBroadcastInternalStateControlResume:
3988 control_only = false;
3989 break;
3990 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003991
Chris Lattner24943d22010-06-08 16:52:24 +00003992 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003993 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003994 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003995 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3996 {
3997 if (m_public_state.GetValue() == eStateAttaching)
3998 {
3999 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004000 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00004001 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4002 }
4003 else
4004 {
4005 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004006 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00004007 Halt();
4008 }
4009 continue;
4010 }
Chris Lattner24943d22010-06-08 16:52:24 +00004011
4012 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4013
4014 if (internal_state != eStateInvalid)
4015 {
4016 HandlePrivateEvent (event_sp);
4017 }
4018
Greg Clayton3b2c41c2010-10-18 04:14:23 +00004019 if (internal_state == eStateInvalid ||
4020 internal_state == eStateExited ||
4021 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00004022 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00004023 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004024 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00004025
Chris Lattner24943d22010-06-08 16:52:24 +00004026 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00004027 }
Chris Lattner24943d22010-06-08 16:52:24 +00004028 }
4029
Caroline Tice926060e2010-10-29 21:48:37 +00004030 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00004031 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004032 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00004033
Greg Clayton061ca652013-04-18 16:57:27 +00004034 m_public_run_lock.WriteUnlock();
Greg Claytona4881d02011-01-22 07:12:45 +00004035 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4036 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00004037 return NULL;
4038}
4039
Chris Lattner24943d22010-06-08 16:52:24 +00004040//------------------------------------------------------------------
4041// Process Event Data
4042//------------------------------------------------------------------
4043
4044Process::ProcessEventData::ProcessEventData () :
4045 EventData (),
4046 m_process_sp (),
4047 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00004048 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00004049 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00004050 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00004051{
4052}
4053
4054Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4055 EventData (),
4056 m_process_sp (process_sp),
4057 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00004058 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00004059 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00004060 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00004061{
4062}
4063
4064Process::ProcessEventData::~ProcessEventData()
4065{
4066}
4067
4068const ConstString &
4069Process::ProcessEventData::GetFlavorString ()
4070{
4071 static ConstString g_flavor ("Process::ProcessEventData");
4072 return g_flavor;
4073}
4074
4075const ConstString &
4076Process::ProcessEventData::GetFlavor () const
4077{
4078 return ProcessEventData::GetFlavorString ();
4079}
4080
Chris Lattner24943d22010-06-08 16:52:24 +00004081void
4082Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4083{
4084 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00004085 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4086 // the public event queue, then other times when we're pretending that this is where we stopped at the
4087 // end of expression evaluation. m_update_state is used to distinguish these
4088 // three cases; it is 0 when we're just pulling it off for private handling,
4089 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00004090
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00004091 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00004092 return;
Jim Ingham89e248f2013-02-09 01:29:05 +00004093
Chris Lattner24943d22010-06-08 16:52:24 +00004094 m_process_sp->SetPublicState (m_state);
4095
4096 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4097 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00004098 {
4099 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00004100 uint32_t num_threads = curr_thread_list.GetSize();
4101 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00004102
Jim Ingham21f37ad2011-08-09 02:12:22 +00004103 // The actions might change one of the thread's stop_info's opinions about whether we should
4104 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00004105
4106 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4107 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4108 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4109 // 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
4110 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00004111 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00004112 for (idx = 0; idx < num_threads; ++idx)
4113 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4114
Jim Inghamb6059b22012-12-13 22:24:15 +00004115 // Use this to track whether we should continue from here. We will only continue the target running if
4116 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4117 // then it doesn't matter what the other threads say...
4118
4119 bool still_should_stop = false;
Jim Ingham21f37ad2011-08-09 02:12:22 +00004120
Jim Ingham68899da2013-04-25 02:04:59 +00004121 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4122 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4123 // thing to do is, and it's better to let the user decide than continue behind their backs.
4124
4125 bool does_anybody_have_an_opinion = false;
4126
Chris Lattner24943d22010-06-08 16:52:24 +00004127 for (idx = 0; idx < num_threads; ++idx)
4128 {
Jim Ingham0296fe72011-11-08 03:00:11 +00004129 curr_thread_list = m_process_sp->GetThreadList();
4130 if (curr_thread_list.GetSize() != num_threads)
4131 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004132 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00004133 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00004134 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0296fe72011-11-08 03:00:11 +00004135 break;
4136 }
4137
4138 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4139
4140 if (thread_sp->GetIndexID() != thread_index_array[idx])
4141 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004142 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00004143 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00004144 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00004145 idx,
4146 thread_index_array[idx],
4147 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00004148 break;
4149 }
4150
Jim Ingham6297a3a2010-10-20 00:39:53 +00004151 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00004152 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00004153 {
Jim Ingham68899da2013-04-25 02:04:59 +00004154 does_anybody_have_an_opinion = true;
Jim Ingham89e248f2013-02-09 01:29:05 +00004155 bool this_thread_wants_to_stop;
4156 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham21f37ad2011-08-09 02:12:22 +00004157 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004158 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4159 }
4160 else
4161 {
4162 stop_info_sp->PerformAction(event_ptr);
4163 // The stop action might restart the target. If it does, then we want to mark that in the
4164 // event so that whoever is receiving it will know to wait for the running event and reflect
4165 // that state appropriately.
4166 // We also need to stop processing actions, since they aren't expecting the target to be running.
4167
4168 // FIXME: we might have run.
4169 if (stop_info_sp->HasTargetRunSinceMe())
4170 {
4171 SetRestarted (true);
4172 break;
4173 }
4174
4175 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004176 }
Jim Inghamb6059b22012-12-13 22:24:15 +00004177
Jim Inghamb6059b22012-12-13 22:24:15 +00004178 if (still_should_stop == false)
4179 still_should_stop = this_thread_wants_to_stop;
Chris Lattner24943d22010-06-08 16:52:24 +00004180 }
4181 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00004182
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00004183
4184 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00004185 {
Jim Ingham68899da2013-04-25 02:04:59 +00004186 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham21f37ad2011-08-09 02:12:22 +00004187 {
4188 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00004189 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00004190 // Use the public resume method here, since this is just
4191 // extending a public resume.
Jim Ingham89e248f2013-02-09 01:29:05 +00004192 m_process_sp->PrivateResume();
Jim Ingham21f37ad2011-08-09 02:12:22 +00004193 }
4194 else
4195 {
4196 // If we didn't restart, run the Stop Hooks here:
4197 // They might also restart the target, so watch for that.
4198 m_process_sp->GetTarget().RunStopHooks();
4199 if (m_process_sp->GetPrivateState() == eStateRunning)
4200 SetRestarted(true);
4201 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00004202 }
Chris Lattner24943d22010-06-08 16:52:24 +00004203 }
4204}
4205
4206void
4207Process::ProcessEventData::Dump (Stream *s) const
4208{
4209 if (m_process_sp)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004210 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00004211
Greg Claytonb72d0f02011-04-12 05:54:46 +00004212 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00004213}
4214
4215const Process::ProcessEventData *
4216Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4217{
4218 if (event_ptr)
4219 {
4220 const EventData *event_data = event_ptr->GetData();
4221 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4222 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4223 }
4224 return NULL;
4225}
4226
4227ProcessSP
4228Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4229{
4230 ProcessSP process_sp;
4231 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4232 if (data)
4233 process_sp = data->GetProcessSP();
4234 return process_sp;
4235}
4236
4237StateType
4238Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4239{
4240 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4241 if (data == NULL)
4242 return eStateInvalid;
4243 else
4244 return data->GetState();
4245}
4246
4247bool
4248Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4249{
4250 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4251 if (data == NULL)
4252 return false;
4253 else
4254 return data->GetRestarted();
4255}
4256
4257void
4258Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4259{
4260 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4261 if (data != NULL)
4262 data->SetRestarted(new_value);
4263}
4264
Jim Ingham89e248f2013-02-09 01:29:05 +00004265size_t
4266Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4267{
4268 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4269 if (data != NULL)
4270 return data->GetNumRestartedReasons();
4271 else
4272 return 0;
4273}
4274
4275const char *
4276Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4277{
4278 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4279 if (data != NULL)
4280 return data->GetRestartedReasonAtIndex(idx);
4281 else
4282 return NULL;
4283}
4284
4285void
4286Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4287{
4288 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4289 if (data != NULL)
4290 data->AddRestartedReason(reason);
4291}
4292
Chris Lattner24943d22010-06-08 16:52:24 +00004293bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00004294Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4295{
4296 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4297 if (data == NULL)
4298 return false;
4299 else
4300 return data->GetInterrupted ();
4301}
4302
4303void
4304Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4305{
4306 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4307 if (data != NULL)
4308 data->SetInterrupted(new_value);
4309}
4310
4311bool
Chris Lattner24943d22010-06-08 16:52:24 +00004312Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4313{
4314 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4315 if (data)
4316 {
4317 data->SetUpdateStateOnRemoval();
4318 return true;
4319 }
4320 return false;
4321}
4322
Greg Clayton289afcb2012-02-18 05:35:26 +00004323lldb::TargetSP
4324Process::CalculateTarget ()
4325{
4326 return m_target.shared_from_this();
4327}
4328
Chris Lattner24943d22010-06-08 16:52:24 +00004329void
Greg Claytona830adb2010-10-04 01:05:56 +00004330Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00004331{
Greg Clayton567e7f32011-09-22 04:58:26 +00004332 exe_ctx.SetTargetPtr (&m_target);
4333 exe_ctx.SetProcessPtr (this);
4334 exe_ctx.SetThreadPtr(NULL);
4335 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00004336}
4337
Greg Claytone4b9c1f2011-03-08 22:40:15 +00004338//uint32_t
4339//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4340//{
4341// return 0;
4342//}
4343//
4344//ArchSpec
4345//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4346//{
4347// return Host::GetArchSpecForExistingProcess (pid);
4348//}
4349//
4350//ArchSpec
4351//Process::GetArchSpecForExistingProcess (const char *process_name)
4352//{
4353// return Host::GetArchSpecForExistingProcess (process_name);
4354//}
4355//
Caroline Tice861efb32010-11-16 05:07:41 +00004356void
4357Process::AppendSTDOUT (const char * s, size_t len)
4358{
Greg Clayton20d338f2010-11-18 05:57:03 +00004359 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00004360 m_stdout_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004361 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00004362}
4363
4364void
Greg Claytonbd06ff42011-11-13 04:45:22 +00004365Process::AppendSTDERR (const char * s, size_t len)
4366{
4367 Mutex::Locker locker (m_stdio_communication_mutex);
4368 m_stderr_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004369 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004370}
4371
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004372void
4373Process::BroadcastAsyncProfileData(const char *s, size_t len)
4374{
4375 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004376 m_profile_data.push_back(s);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004377 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4378}
4379
4380size_t
4381Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4382{
4383 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004384 if (m_profile_data.empty())
4385 return 0;
4386
4387 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004388 if (bytes_available > 0)
4389 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004390 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004391 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004392 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004393 if (bytes_available > buf_size)
4394 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004395 memcpy(buf, m_profile_data.front().data(), buf_size);
4396 m_profile_data.front().erase(0, buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004397 bytes_available = buf_size;
4398 }
4399 else
4400 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004401 memcpy(buf, m_profile_data.front().data(), bytes_available);
4402 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004403 }
4404 }
4405 return bytes_available;
4406}
4407
4408
Greg Claytonbd06ff42011-11-13 04:45:22 +00004409//------------------------------------------------------------------
4410// Process STDIO
4411//------------------------------------------------------------------
4412
4413size_t
4414Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4415{
4416 Mutex::Locker locker(m_stdio_communication_mutex);
4417 size_t bytes_available = m_stdout_data.size();
4418 if (bytes_available > 0)
4419 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004420 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004421 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004422 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004423 if (bytes_available > buf_size)
4424 {
4425 memcpy(buf, m_stdout_data.c_str(), buf_size);
4426 m_stdout_data.erase(0, buf_size);
4427 bytes_available = buf_size;
4428 }
4429 else
4430 {
4431 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4432 m_stdout_data.clear();
4433 }
4434 }
4435 return bytes_available;
4436}
4437
4438
4439size_t
4440Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4441{
4442 Mutex::Locker locker(m_stdio_communication_mutex);
4443 size_t bytes_available = m_stderr_data.size();
4444 if (bytes_available > 0)
4445 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004446 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004447 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004448 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004449 if (bytes_available > buf_size)
4450 {
4451 memcpy(buf, m_stderr_data.c_str(), buf_size);
4452 m_stderr_data.erase(0, buf_size);
4453 bytes_available = buf_size;
4454 }
4455 else
4456 {
4457 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4458 m_stderr_data.clear();
4459 }
4460 }
4461 return bytes_available;
4462}
4463
4464void
Caroline Tice861efb32010-11-16 05:07:41 +00004465Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4466{
4467 Process *process = (Process *) baton;
4468 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4469}
4470
4471size_t
4472Process::ProcessInputReaderCallback (void *baton,
4473 InputReader &reader,
4474 lldb::InputReaderAction notification,
4475 const char *bytes,
4476 size_t bytes_len)
4477{
4478 Process *process = (Process *) baton;
4479
4480 switch (notification)
4481 {
4482 case eInputReaderActivate:
4483 break;
4484
4485 case eInputReaderDeactivate:
4486 break;
4487
4488 case eInputReaderReactivate:
4489 break;
4490
Caroline Tice4a348082011-05-02 20:41:46 +00004491 case eInputReaderAsynchronousOutputWritten:
4492 break;
4493
Caroline Tice861efb32010-11-16 05:07:41 +00004494 case eInputReaderGotToken:
4495 {
4496 Error error;
4497 process->PutSTDIN (bytes, bytes_len, error);
4498 }
4499 break;
4500
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004501 case eInputReaderInterrupt:
4502 process->Halt ();
4503 break;
4504
4505 case eInputReaderEndOfFile:
4506 process->AppendSTDOUT ("^D", 2);
4507 break;
4508
Caroline Tice861efb32010-11-16 05:07:41 +00004509 case eInputReaderDone:
4510 break;
4511
4512 }
4513
4514 return bytes_len;
4515}
4516
4517void
4518Process::ResetProcessInputReader ()
4519{
4520 m_process_input_reader.reset();
4521}
4522
4523void
Greg Clayton464c6162011-11-17 22:14:31 +00004524Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004525{
4526 // First set up the Read Thread for reading/handling process I/O
4527
Greg Clayton102b2c22013-04-18 22:45:39 +00004528 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
Caroline Tice861efb32010-11-16 05:07:41 +00004529
4530 if (conn_ap.get())
4531 {
4532 m_stdio_communication.SetConnection (conn_ap.release());
4533 if (m_stdio_communication.IsConnected())
4534 {
4535 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4536 m_stdio_communication.StartReadThread();
4537
4538 // Now read thread is set up, set up input reader.
4539
4540 if (!m_process_input_reader.get())
4541 {
4542 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4543 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4544 this,
4545 eInputReaderGranularityByte,
4546 NULL,
4547 NULL,
4548 false));
4549
4550 if (err.Fail())
4551 m_process_input_reader.reset();
4552 }
4553 }
4554 }
4555}
4556
4557void
4558Process::PushProcessInputReader ()
4559{
4560 if (m_process_input_reader && !m_process_input_reader->IsActive())
4561 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4562}
4563
4564void
4565Process::PopProcessInputReader ()
4566{
4567 if (m_process_input_reader && m_process_input_reader->IsActive())
4568 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4569}
4570
Greg Claytond284b662011-02-18 01:44:25 +00004571// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004572void
Caroline Tice2a456812011-03-10 22:14:10 +00004573Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004574{
Greg Clayton73844aa2012-08-22 17:17:09 +00004575// static std::vector<OptionEnumValueElement> g_plugins;
4576//
4577// int i=0;
4578// const char *name;
4579// OptionEnumValueElement option_enum;
4580// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4581// {
4582// if (name)
4583// {
4584// option_enum.value = i;
4585// option_enum.string_value = name;
4586// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4587// g_plugins.push_back (option_enum);
4588// }
4589// ++i;
4590// }
4591// option_enum.value = 0;
4592// option_enum.string_value = NULL;
4593// option_enum.usage = NULL;
4594// g_plugins.push_back (option_enum);
4595//
4596// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4597// {
4598// if (::strcmp (name, "plugin") == 0)
4599// {
4600// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4601// break;
4602// }
4603// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004604//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004605 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004606}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004607
Greg Clayton990de7b2010-11-18 23:32:35 +00004608void
Caroline Tice2a456812011-03-10 22:14:10 +00004609Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004610{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004611 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004612}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004613
Greg Clayton427f2902010-12-14 02:59:59 +00004614ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004615Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004616 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004617 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004618 bool run_others,
Jim Inghamb7940202013-01-15 02:47:48 +00004619 bool unwind_on_error,
4620 bool ignore_breakpoints,
Jim Ingham47beabb2012-10-16 21:41:58 +00004621 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004622 Stream &errors)
4623{
4624 ExecutionResults return_value = eExecutionSetupError;
4625
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004626 if (thread_plan_sp.get() == NULL)
4627 {
4628 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004629 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004630 }
Jim Ingham698194c2013-03-28 00:05:34 +00004631
4632 if (!thread_plan_sp->ValidatePlan(NULL))
4633 {
4634 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4635 return eExecutionSetupError;
4636 }
4637
Greg Clayton567e7f32011-09-22 04:58:26 +00004638 if (exe_ctx.GetProcessPtr() != this)
4639 {
4640 errors.Printf("RunThreadPlan called on wrong process.");
4641 return eExecutionSetupError;
4642 }
4643
4644 Thread *thread = exe_ctx.GetThreadPtr();
4645 if (thread == NULL)
4646 {
4647 errors.Printf("RunThreadPlan called with invalid thread.");
4648 return eExecutionSetupError;
4649 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004650
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004651 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4652 // For that to be true the plan can't be private - since private plans suppress themselves in the
4653 // GetCompletedPlan call.
4654
4655 bool orig_plan_private = thread_plan_sp->GetPrivate();
4656 thread_plan_sp->SetPrivate(false);
4657
Jim Inghamac959662011-01-24 06:34:17 +00004658 if (m_private_state.GetValue() != eStateStopped)
4659 {
4660 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004661 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004662 }
4663
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004664 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004665 const uint32_t thread_idx_id = thread->GetIndexID();
Jim Ingham9da225f2013-02-19 23:22:45 +00004666 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4667 if (!selected_frame_sp)
4668 {
4669 thread->SetSelectedFrame(0);
4670 selected_frame_sp = thread->GetSelectedFrame();
4671 if (!selected_frame_sp)
4672 {
4673 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4674 return eExecutionSetupError;
4675 }
4676 }
4677
4678 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004679
4680 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4681 // so we should arrange to reset them as well.
4682
Greg Clayton567e7f32011-09-22 04:58:26 +00004683 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004684
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004685 uint32_t selected_tid;
4686 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004687 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004688 {
4689 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004690 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004691 }
4692 else
4693 {
4694 selected_tid = LLDB_INVALID_THREAD_ID;
4695 }
4696
Jim Ingham1831e782012-04-07 00:00:41 +00004697 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004698 lldb::StateType old_state;
4699 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004700
Greg Clayton952e9dc2013-03-27 23:08:40 +00004701 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004702 if (Host::GetCurrentThread() == m_private_state_thread)
4703 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004704 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4705 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004706 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Inghamd21d98b2012-04-10 01:21:57 +00004707 // we are fielding public events here.
4708 if (log)
Jason Molenda559cf6e2012-11-17 01:41:04 +00004709 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
Jim Inghamd21d98b2012-04-10 01:21:57 +00004710
4711
Jim Ingham1831e782012-04-07 00:00:41 +00004712 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004713
4714 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4715 // returning control here.
4716 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4717 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4718 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4719 // do just what we want.
4720 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4721 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4722 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4723 old_state = m_public_state.GetValue();
4724 m_public_state.SetValueNoLock(eStateStopped);
4725
4726 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004727 StartPrivateStateThread(true);
4728 }
4729
4730 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004731
Jim Ingham6ae318c2011-01-23 21:14:08 +00004732 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004733
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004734 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004735
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004736 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004737 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4738 // restored on exit to the function.
4739 //
4740 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4741 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004742
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004743 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004744
Jim Ingham360f53f2010-11-30 02:22:11 +00004745 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004746 {
4747 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004748 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004749 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004750 thread->GetIndexID(),
4751 thread->GetID(),
4752 s.GetData());
4753 }
4754
4755 bool got_event;
4756 lldb::EventSP event_sp;
4757 lldb::StateType stop_state = lldb::eStateInvalid;
4758
4759 TimeValue* timeout_ptr = NULL;
4760 TimeValue real_timeout;
4761
Jim Ingham89e248f2013-02-09 01:29:05 +00004762 bool before_first_timeout = true; // This is set to false the first time that we have to halt the target.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004763 bool do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004764 bool handle_running_event = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004765 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004766
Jim Ingham89e248f2013-02-09 01:29:05 +00004767 // This is just for accounting:
4768 uint32_t num_resumes = 0;
4769
4770 TimeValue one_thread_timeout = TimeValue::Now();
4771 TimeValue final_timeout = one_thread_timeout;
4772
4773 if (run_others)
4774 {
4775 // If we are running all threads then we take half the time to run all threads, bounded by
4776 // .25 sec.
4777 if (timeout_usec == 0)
4778 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4779 else
4780 {
Greg Claytond387b462013-04-19 21:31:16 +00004781 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham89e248f2013-02-09 01:29:05 +00004782 if (computed_timeout > default_one_thread_timeout_usec)
4783 computed_timeout = default_one_thread_timeout_usec;
4784 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4785 }
4786 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4787 }
4788 else
4789 {
4790 if (timeout_usec != 0)
4791 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4792 }
4793
Jim Ingham76b258d2012-11-26 23:52:18 +00004794 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4795 // So don't call return anywhere within it.
4796
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004797 while (1)
4798 {
4799 // We usually want to resume the process if we get to the top of the loop.
4800 // The only exception is if we get two running events with no intervening
4801 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham89e248f2013-02-09 01:29:05 +00004802 if (log)
4803 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4804 do_resume,
4805 handle_running_event,
4806 before_first_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004807
Jim Inghamb7940202013-01-15 02:47:48 +00004808 if (do_resume || handle_running_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004809 {
4810 // Do the initial resume and wait for the running event before going further.
4811
Jim Inghamb7940202013-01-15 02:47:48 +00004812 if (do_resume)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004813 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004814 num_resumes++;
Jim Inghamb7940202013-01-15 02:47:48 +00004815 Error resume_error = PrivateResume ();
4816 if (!resume_error.Success())
4817 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004818 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4819 num_resumes,
4820 resume_error.AsCString());
Jim Inghamb7940202013-01-15 02:47:48 +00004821 return_value = eExecutionSetupError;
4822 break;
4823 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004824 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004825
Jim Ingham89e248f2013-02-09 01:29:05 +00004826 TimeValue resume_timeout = TimeValue::Now();
4827 resume_timeout.OffsetWithMicroSeconds(500000);
4828
4829 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004830 if (!got_event)
4831 {
4832 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004833 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4834 num_resumes);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004835
Jim Ingham89e248f2013-02-09 01:29:05 +00004836 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004837 return_value = eExecutionSetupError;
4838 break;
4839 }
4840
4841 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham89e248f2013-02-09 01:29:05 +00004842
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004843 if (stop_state != eStateRunning)
4844 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004845 bool restarted = false;
4846
4847 if (stop_state == eStateStopped)
4848 {
4849 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4850 if (log)
4851 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4852 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4853 num_resumes,
4854 StateAsCString(stop_state),
4855 restarted,
4856 do_resume,
4857 handle_running_event);
4858 }
4859
4860 if (restarted)
4861 {
4862 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4863 // event here. But if I do, the best thing is to Halt and then get out of here.
4864 Halt();
4865 }
4866
Jim Ingham47beabb2012-10-16 21:41:58 +00004867 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4868 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004869 return_value = eExecutionSetupError;
4870 break;
4871 }
4872
4873 if (log)
4874 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4875 // We need to call the function synchronously, so spin waiting for it to return.
4876 // If we get interrupted while executing, we're going to lose our context, and
4877 // won't be able to gather the result at this point.
4878 // We set the timeout AFTER the resume, since the resume takes some time and we
4879 // don't want to charge that to the timeout.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004880 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004881 else
4882 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004883 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004884 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004885 }
Jim Ingham89e248f2013-02-09 01:29:05 +00004886
4887 if (before_first_timeout)
4888 {
4889 if (run_others)
4890 timeout_ptr = &one_thread_timeout;
4891 else
4892 {
4893 if (timeout_usec == 0)
4894 timeout_ptr = NULL;
4895 else
4896 timeout_ptr = &final_timeout;
4897 }
4898 }
4899 else
4900 {
4901 if (timeout_usec == 0)
4902 timeout_ptr = NULL;
4903 else
4904 timeout_ptr = &final_timeout;
4905 }
4906
4907 do_resume = true;
4908 handle_running_event = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004909
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004910 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004911 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004912
Jim Inghamf9f40c22011-02-08 05:20:59 +00004913 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004914 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004915 if (timeout_ptr)
4916 {
Matt Kopecfe21d4f2013-02-21 23:55:31 +00004917 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham89e248f2013-02-09 01:29:05 +00004918 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
4919 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004920 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004921 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004922 {
4923 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4924 }
4925 }
4926
4927 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4928
4929 if (got_event)
4930 {
4931 if (event_sp.get())
4932 {
4933 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004934 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004935 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004936 Halt();
Jim Ingham5d90ade2012-07-27 23:57:19 +00004937 return_value = eExecutionInterrupted;
4938 errors.Printf ("Execution halted by user interrupt.");
4939 if (log)
4940 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham89e248f2013-02-09 01:29:05 +00004941 break;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004942 }
4943 else
4944 {
4945 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4946 if (log)
4947 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4948
4949 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004950 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004951 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004952 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004953 // We stopped, figure out what we are going to do now.
Jim Ingham5d90ade2012-07-27 23:57:19 +00004954 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4955 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004956 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004957 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004958 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004959 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4960 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004961 }
4962 else
4963 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004964 // If we were restarted, we just need to go back up to fetch another event.
4965 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Ingham5d90ade2012-07-27 23:57:19 +00004966 {
4967 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004968 {
4969 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
4970 }
4971 keep_going = true;
4972 do_resume = false;
4973 handle_running_event = true;
4974
Jim Ingham5d90ade2012-07-27 23:57:19 +00004975 }
4976 else
4977 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004978
4979 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4980 StopReason stop_reason = eStopReasonInvalid;
4981 if (stop_info_sp)
4982 stop_reason = stop_info_sp->GetStopReason();
4983
4984
4985 // FIXME: We only check if the stop reason is plan complete, should we make sure that
4986 // it is OUR plan that is complete?
4987 if (stop_reason == eStopReasonPlanComplete)
Jim Inghamb7940202013-01-15 02:47:48 +00004988 {
4989 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004990 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4991 // Now mark this plan as private so it doesn't get reported as the stop reason
4992 // after this point.
4993 if (thread_plan_sp)
4994 thread_plan_sp->SetPrivate (orig_plan_private);
4995 return_value = eExecutionCompleted;
Jim Inghamb7940202013-01-15 02:47:48 +00004996 }
4997 else
4998 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004999 // Something restarted the target, so just wait for it to stop for real.
Jim Inghamb7940202013-01-15 02:47:48 +00005000 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham89e248f2013-02-09 01:29:05 +00005001 {
5002 if (log)
5003 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Inghamb7940202013-01-15 02:47:48 +00005004 return_value = eExecutionHitBreakpoint;
Jim Ingham89e248f2013-02-09 01:29:05 +00005005 }
Jim Inghamb7940202013-01-15 02:47:48 +00005006 else
Jim Ingham89e248f2013-02-09 01:29:05 +00005007 {
5008 if (log)
5009 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Inghamb7940202013-01-15 02:47:48 +00005010 return_value = eExecutionInterrupted;
Jim Ingham89e248f2013-02-09 01:29:05 +00005011 }
Jim Inghamb7940202013-01-15 02:47:48 +00005012 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005013 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005014 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005015 }
5016 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005017
Jim Ingham5d90ade2012-07-27 23:57:19 +00005018 case lldb::eStateRunning:
Jim Ingham89e248f2013-02-09 01:29:05 +00005019 // This shouldn't really happen, but sometimes we do get two running events without an
5020 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Ingham5d90ade2012-07-27 23:57:19 +00005021 do_resume = false;
5022 keep_going = true;
Jim Inghamb7940202013-01-15 02:47:48 +00005023 handle_running_event = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00005024 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005025
Jim Ingham5d90ade2012-07-27 23:57:19 +00005026 default:
5027 if (log)
5028 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5029
5030 if (stop_state == eStateExited)
5031 event_to_broadcast_sp = event_sp;
5032
Sean Callanan96abc622012-08-08 17:35:10 +00005033 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00005034 return_value = eExecutionInterrupted;
5035 break;
5036 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005037 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005038
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005039 if (keep_going)
5040 continue;
5041 else
5042 break;
5043 }
5044 else
5045 {
5046 if (log)
5047 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5048 return_value = eExecutionInterrupted;
5049 break;
5050 }
5051 }
5052 else
5053 {
5054 // If we didn't get an event that means we've timed out...
5055 // We will interrupt the process here. Depending on what we were asked to do we will
5056 // either exit, or try with all threads running for the same timeout.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005057
5058 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00005059 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005060 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005061 uint64_t remaining_time = final_timeout - TimeValue::Now();
5062 if (before_first_timeout)
5063 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
5064 "running till for %" PRId64 " usec with all threads enabled.",
5065 remaining_time);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005066 else
5067 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00005068 "and timeout: %d timed out, abandoning execution.",
5069 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005070 }
5071 else
5072 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00005073 "abandoning execution.",
5074 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005075 }
5076
Jim Ingham89e248f2013-02-09 01:29:05 +00005077 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5078 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5079 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5080 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5081 // stopped event. That's what this while loop does.
5082
5083 bool back_to_top = true;
5084 uint32_t try_halt_again = 0;
5085 bool do_halt = true;
5086 const uint32_t num_retries = 5;
5087 while (try_halt_again < num_retries)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005088 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005089 Error halt_error;
5090 if (do_halt)
5091 {
5092 if (log)
5093 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5094 halt_error = Halt();
5095 }
5096 if (halt_error.Success())
5097 {
5098 if (log)
5099 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5100
5101 real_timeout = TimeValue::Now();
5102 real_timeout.OffsetWithMicroSeconds(500000);
5103
5104 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005105
Jim Ingham89e248f2013-02-09 01:29:05 +00005106 if (got_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005107 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005108 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5109 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005110 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005111 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5112 if (stop_state == lldb::eStateStopped
5113 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5114 log->PutCString (" Event was the Halt interruption event.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005115 }
5116
Jim Ingham89e248f2013-02-09 01:29:05 +00005117 if (stop_state == lldb::eStateStopped)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005118 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005119 // Between the time we initiated the Halt and the time we delivered it, the process could have
5120 // already finished its job. Check that here:
5121
5122 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5123 {
5124 if (log)
5125 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5126 "Exiting wait loop.");
5127 return_value = eExecutionCompleted;
5128 back_to_top = false;
5129 break;
5130 }
5131
5132 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5133 {
5134 if (log)
5135 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5136 "Exiting wait loop.");
5137 try_halt_again++;
5138 do_halt = false;
5139 continue;
5140 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005141
Jim Ingham89e248f2013-02-09 01:29:05 +00005142 if (!run_others)
5143 {
5144 if (log)
5145 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5146 return_value = eExecutionInterrupted;
5147 back_to_top = false;
5148 break;
5149 }
5150
5151 if (before_first_timeout)
5152 {
5153 // Set all the other threads to run, and return to the top of the loop, which will continue;
5154 before_first_timeout = false;
5155 thread_plan_sp->SetStopOthers (false);
5156 if (log)
5157 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005158
Jim Ingham89e248f2013-02-09 01:29:05 +00005159 back_to_top = true;
5160 break;
5161 }
5162 else
5163 {
5164 // Running all threads failed, so return Interrupted.
5165 if (log)
5166 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5167 return_value = eExecutionInterrupted;
5168 back_to_top = false;
5169 break;
5170 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005171 }
5172 }
5173 else
Jim Ingham89e248f2013-02-09 01:29:05 +00005174 { if (log)
5175 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5176 "I'm getting out of here passing Interrupted.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005177 return_value = eExecutionInterrupted;
Jim Ingham89e248f2013-02-09 01:29:05 +00005178 back_to_top = false;
5179 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005180 }
5181 }
Jim Ingham89e248f2013-02-09 01:29:05 +00005182 else
5183 {
5184 try_halt_again++;
5185 continue;
5186 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005187 }
Jim Ingham89e248f2013-02-09 01:29:05 +00005188
5189 if (!back_to_top || try_halt_again > num_retries)
5190 break;
5191 else
5192 continue;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005193 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005194 } // END WAIT LOOP
5195
5196 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5197 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5198 {
5199 StopPrivateStateThread();
5200 Error error;
5201 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00005202 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005203 {
5204 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5205 }
5206 m_public_state.SetValueNoLock(old_state);
5207
5208 }
5209
Jim Inghamb7940202013-01-15 02:47:48 +00005210 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5211 // could happen:
5212 // 1) The execution successfully completed
5213 // 2) We hit a breakpoint, and ignore_breakpoints was true
5214 // 3) We got some other error, and discard_on_error was true
5215 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
5216 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham76b258d2012-11-26 23:52:18 +00005217
Jim Inghamb7940202013-01-15 02:47:48 +00005218 if (return_value == eExecutionCompleted
5219 || should_unwind)
Jim Ingham76b258d2012-11-26 23:52:18 +00005220 {
5221 thread_plan_sp->RestoreThreadState();
5222 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005223
5224 // Now do some processing on the results of the run:
Jim Inghamb7940202013-01-15 02:47:48 +00005225 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005226 {
5227 if (log)
5228 {
5229 StreamString s;
5230 if (event_sp)
5231 event_sp->Dump (&s);
5232 else
5233 {
5234 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5235 }
5236
5237 StreamString ts;
5238
5239 const char *event_explanation = NULL;
5240
5241 do
5242 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005243 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005244 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005245 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005246 break;
5247 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005248 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005249 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005250 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005251 break;
5252 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005253 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005254 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005255 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5256
5257 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005258 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005259 event_explanation = "<no event data>";
5260 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005261 }
5262
Jim Ingham5d90ade2012-07-27 23:57:19 +00005263 Process *process = event_data->GetProcessSP().get();
5264
5265 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005266 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005267 event_explanation = "<no process>";
5268 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005269 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005270
5271 ThreadList &thread_list = process->GetThreadList();
5272
5273 uint32_t num_threads = thread_list.GetSize();
5274 uint32_t thread_index;
5275
5276 ts.Printf("<%u threads> ", num_threads);
5277
5278 for (thread_index = 0;
5279 thread_index < num_threads;
5280 ++thread_index)
5281 {
5282 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5283
5284 if (!thread)
5285 {
5286 ts.Printf("<?> ");
5287 continue;
5288 }
5289
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005290 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00005291 RegisterContext *register_context = thread->GetRegisterContext().get();
5292
5293 if (register_context)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005294 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Ingham5d90ade2012-07-27 23:57:19 +00005295 else
5296 ts.Printf("[ip unknown] ");
5297
5298 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5299 if (stop_info_sp)
5300 {
5301 const char *stop_desc = stop_info_sp->GetDescription();
5302 if (stop_desc)
5303 ts.PutCString (stop_desc);
5304 }
5305 ts.Printf(">");
5306 }
5307
5308 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005309 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005310 } while (0);
5311
Jim Ingham5d90ade2012-07-27 23:57:19 +00005312 if (event_explanation)
5313 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005314 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00005315 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5316 }
5317
Jim Inghamb7940202013-01-15 02:47:48 +00005318 if (should_unwind && thread_plan_sp)
Jim Ingham5d90ade2012-07-27 23:57:19 +00005319 {
5320 if (log)
5321 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5322 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5323 thread_plan_sp->SetPrivate (orig_plan_private);
5324 }
5325 else
5326 {
5327 if (log)
5328 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005329 }
5330 }
5331 else if (return_value == eExecutionSetupError)
5332 {
5333 if (log)
5334 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00005335
Jim Inghamb7940202013-01-15 02:47:48 +00005336 if (unwind_on_error && thread_plan_sp)
Jim Inghamf9f40c22011-02-08 05:20:59 +00005337 {
Greg Clayton567e7f32011-09-22 04:58:26 +00005338 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00005339 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00005340 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005341 }
5342 else
5343 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005344 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00005345 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00005346 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005347 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5348 return_value = eExecutionCompleted;
5349 }
5350 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5351 {
5352 if (log)
5353 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5354 return_value = eExecutionDiscarded;
5355 }
5356 else
5357 {
5358 if (log)
5359 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamb7940202013-01-15 02:47:48 +00005360 if (unwind_on_error && thread_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005361 {
5362 if (log)
Jim Inghamb7940202013-01-15 02:47:48 +00005363 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005364 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5365 thread_plan_sp->SetPrivate (orig_plan_private);
5366 }
5367 }
5368 }
5369
5370 // Thread we ran the function in may have gone away because we ran the target
5371 // Check that it's still there, and if it is put it back in the context. Also restore the
5372 // frame in the context if it is still present.
5373 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5374 if (thread)
5375 {
5376 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5377 }
5378
5379 // Also restore the current process'es selected frame & thread, since this function calling may
5380 // be done behind the user's back.
5381
5382 if (selected_tid != LLDB_INVALID_THREAD_ID)
5383 {
5384 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5385 {
5386 // We were able to restore the selected thread, now restore the frame:
5387 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5388 if (old_frame_sp)
5389 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00005390 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005391 }
5392 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005393
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005394 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00005395
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005396 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00005397 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005398 if (log)
5399 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5400 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00005401 }
5402
5403 return return_value;
5404}
5405
5406const char *
5407Process::ExecutionResultAsCString (ExecutionResults result)
5408{
5409 const char *result_name;
5410
5411 switch (result)
5412 {
Greg Claytonb3448432011-03-24 21:19:54 +00005413 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005414 result_name = "eExecutionCompleted";
5415 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005416 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00005417 result_name = "eExecutionDiscarded";
5418 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005419 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005420 result_name = "eExecutionInterrupted";
5421 break;
Jim Inghamb7940202013-01-15 02:47:48 +00005422 case eExecutionHitBreakpoint:
5423 result_name = "eExecutionHitBreakpoint";
5424 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005425 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00005426 result_name = "eExecutionSetupError";
5427 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005428 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00005429 result_name = "eExecutionTimedOut";
5430 break;
5431 }
5432 return result_name;
5433}
5434
Greg Claytonabe0fed2011-04-18 08:33:37 +00005435void
5436Process::GetStatus (Stream &strm)
5437{
5438 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00005439 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00005440 {
5441 if (state == eStateExited)
5442 {
5443 int exit_status = GetExitStatus();
5444 const char *exit_description = GetExitDescription();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005445 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00005446 GetID(),
5447 exit_status,
5448 exit_status,
5449 exit_description ? exit_description : "");
5450 }
5451 else
5452 {
5453 if (state == eStateConnected)
5454 strm.Printf ("Connected to remote target.\n");
5455 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005456 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00005457 }
5458 }
5459 else
5460 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005461 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005462 }
5463}
5464
5465size_t
5466Process::GetThreadStatus (Stream &strm,
5467 bool only_threads_with_stop_reason,
5468 uint32_t start_frame,
5469 uint32_t num_frames,
5470 uint32_t num_frames_with_source)
5471{
5472 size_t num_thread_infos_dumped = 0;
5473
Jim Inghamb9950592012-09-10 20:50:15 +00005474 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005475 const size_t num_threads = GetThreadList().GetSize();
5476 for (uint32_t i = 0; i < num_threads; i++)
5477 {
5478 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5479 if (thread)
5480 {
5481 if (only_threads_with_stop_reason)
5482 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00005483 StopInfoSP stop_info_sp = thread->GetStopInfo();
5484 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00005485 continue;
5486 }
5487 thread->GetStatus (strm,
5488 start_frame,
5489 num_frames,
5490 num_frames_with_source);
5491 ++num_thread_infos_dumped;
5492 }
5493 }
5494 return num_thread_infos_dumped;
5495}
5496
Greg Clayton76113302012-02-22 04:37:26 +00005497void
5498Process::AddInvalidMemoryRegion (const LoadRange &region)
5499{
5500 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5501}
5502
5503bool
5504Process::RemoveInvalidMemoryRange (const LoadRange &region)
5505{
5506 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5507}
5508
Jim Ingham1831e782012-04-07 00:00:41 +00005509void
5510Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5511{
5512 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5513}
5514
5515bool
5516Process::RunPreResumeActions ()
5517{
5518 bool result = true;
5519 while (!m_pre_resume_actions.empty())
5520 {
5521 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5522 m_pre_resume_actions.pop_back();
5523 bool this_result = action.callback (action.baton);
5524 if (result == true) result = this_result;
5525 }
5526 return result;
5527}
5528
5529void
5530Process::ClearPreResumeActions ()
5531{
5532 m_pre_resume_actions.clear();
5533}
Greg Clayton76113302012-02-22 04:37:26 +00005534
Greg Claytoncf5927e2012-05-18 02:38:05 +00005535void
5536Process::Flush ()
5537{
5538 m_thread_list.Flush();
5539}
Greg Clayton0bce9a22012-12-05 00:16:59 +00005540
5541void
5542Process::DidExec ()
5543{
5544 Target &target = GetTarget();
5545 target.CleanupProcess ();
5546 ModuleList unloaded_modules (target.GetImages());
5547 target.ModulesDidUnload (unloaded_modules);
5548 target.GetSectionLoadList().Clear();
5549 m_dynamic_checkers_ap.reset();
5550 m_abi_sp.reset();
5551 m_os_ap.reset();
5552 m_dyld_ap.reset();
5553 m_image_tokens.clear();
5554 m_allocated_memory_cache.Clear();
5555 m_language_runtimes.clear();
5556 DoDidExec();
5557 CompleteAttach ();
5558}