blob: 18493de1e63eca842e80b98bf1e290270434136e [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 Inghamb7940202013-01-15 02:47:48 +0000100 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
101 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, false, 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." },
Greg Clayton73844aa2012-08-22 17:17:09 +0000103 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
104};
105
106enum {
107 ePropertyDisableMemCache,
Greg Clayton2e7f3132012-10-18 22:40:37 +0000108 ePropertyExtraStartCommand,
Jim Inghamb7940202013-01-15 02:47:48 +0000109 ePropertyIgnoreBreakpointsInExpressions,
110 ePropertyUnwindOnErrorInExpressions,
Greg Clayton2e7f3132012-10-18 22:40:37 +0000111 ePropertyPythonOSPluginPath
Greg Clayton73844aa2012-08-22 17:17:09 +0000112};
113
114ProcessProperties::ProcessProperties (bool is_global) :
115 Properties ()
116{
117 if (is_global)
118 {
119 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
120 m_collection_sp->Initialize(g_properties);
121 m_collection_sp->AppendProperty(ConstString("thread"),
122 ConstString("Settings specify to threads."),
123 true,
124 Thread::GetGlobalProperties()->GetValueProperties());
125 }
126 else
127 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
128}
129
130ProcessProperties::~ProcessProperties()
131{
132}
133
134bool
135ProcessProperties::GetDisableMemoryCache() const
136{
137 const uint32_t idx = ePropertyDisableMemCache;
138 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
139}
140
141Args
142ProcessProperties::GetExtraStartupCommands () const
143{
144 Args args;
145 const uint32_t idx = ePropertyExtraStartCommand;
146 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
147 return args;
148}
149
150void
151ProcessProperties::SetExtraStartupCommands (const Args &args)
152{
153 const uint32_t idx = ePropertyExtraStartCommand;
154 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
155}
156
Greg Clayton2e7f3132012-10-18 22:40:37 +0000157FileSpec
158ProcessProperties::GetPythonOSPluginPath () const
159{
160 const uint32_t idx = ePropertyPythonOSPluginPath;
161 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
162}
163
164void
165ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
166{
167 const uint32_t idx = ePropertyPythonOSPluginPath;
168 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
169}
170
Jim Inghamb7940202013-01-15 02:47:48 +0000171
172bool
173ProcessProperties::GetIgnoreBreakpointsInExpressions () const
174{
175 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
176 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
177}
178
179void
180ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
181{
182 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
183 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
184}
185
186bool
187ProcessProperties::GetUnwindOnErrorInExpressions () const
188{
189 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
190 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
191}
192
193void
194ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
195{
196 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
197 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
198}
199
Greg Clayton24bc5d92011-03-30 18:16:51 +0000200void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000201ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000202{
203 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +0000204 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000205 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000206
207 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000208 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000209
210 if (m_executable)
211 {
212 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
213 s.PutCString (" file = ");
214 m_executable.Dump(&s);
215 s.EOL();
216 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000217 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000218 if (argc > 0)
219 {
220 for (uint32_t i=0; i<argc; i++)
221 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000222 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +0000223 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000224 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000225 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000226 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000227 }
228 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000229
230 const uint32_t envc = m_environment.GetArgumentCount();
231 if (envc > 0)
232 {
233 for (uint32_t i=0; i<envc; i++)
234 {
235 const char *env = m_environment.GetArgumentAtIndex(i);
236 if (i < 10)
237 s.Printf (" env[%u] = %s\n", i, env);
238 else
239 s.Printf ("env[%u] = %s\n", i, env);
240 }
241 }
242
Greg Claytonff39f742011-04-01 00:29:43 +0000243 if (m_arch.IsValid())
244 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
245
Greg Claytonb72d0f02011-04-12 05:54:46 +0000246 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000247 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000248 cstr = platform->GetUserName (m_uid);
249 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000250 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000251 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000252 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000253 cstr = platform->GetGroupName (m_gid);
254 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000255 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000256 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000257 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000258 cstr = platform->GetUserName (m_euid);
259 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000260 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000261 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000262 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000263 cstr = platform->GetGroupName (m_egid);
264 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000265 }
266}
267
268void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000269ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000270{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000271 const char *label;
272 if (show_args || verbose)
273 label = "ARGUMENTS";
274 else
275 label = "NAME";
276
Greg Claytonff39f742011-04-01 00:29:43 +0000277 if (verbose)
278 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000279 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000280 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
281 }
282 else
283 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000284 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000285 s.PutCString ("====== ====== ========== ======= ============================\n");
286 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000287}
288
289void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000290ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000291{
292 if (m_pid != LLDB_INVALID_PROCESS_ID)
293 {
294 const char *cstr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000295 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000296
Greg Clayton24bc5d92011-03-30 18:16:51 +0000297
Greg Claytonff39f742011-04-01 00:29:43 +0000298 if (verbose)
299 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000300 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000301 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
302 s.Printf ("%-10s ", cstr);
303 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000304 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000305
Greg Claytonb72d0f02011-04-12 05:54:46 +0000306 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000307 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
308 s.Printf ("%-10s ", cstr);
309 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000310 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000311
Greg Claytonb72d0f02011-04-12 05:54:46 +0000312 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000313 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
314 s.Printf ("%-10s ", cstr);
315 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000316 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000317
Greg Claytonb72d0f02011-04-12 05:54:46 +0000318 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000319 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
320 s.Printf ("%-10s ", cstr);
321 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000322 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000323 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
324 }
325 else
326 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000327 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000328 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000329 (int)m_arch.GetTriple().getArchName().size(),
330 m_arch.GetTriple().getArchName().data());
331 }
332
Greg Claytonb72d0f02011-04-12 05:54:46 +0000333 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000334 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000335 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000336 if (argc > 0)
337 {
338 for (uint32_t i=0; i<argc; i++)
339 {
340 if (i > 0)
341 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000342 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000343 }
344 }
345 }
346 else
347 {
348 s.PutCString (GetName());
349 }
350
351 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000352 }
353}
354
Greg Claytonb72d0f02011-04-12 05:54:46 +0000355
356void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000357ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000358{
359 m_arguments.SetArguments (argv);
360
361 // Is the first argument the executable?
362 if (first_arg_is_executable)
363 {
364 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
365 if (first_arg)
366 {
367 // Yes the first argument is an executable, set it as the executable
368 // in the launch options. Don't resolve the file path as the path
369 // could be a remote platform path
370 const bool resolve = false;
371 m_executable.SetFile(first_arg, resolve);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000372 }
373 }
374}
375void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000376ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000377{
378 // Copy all arguments
379 m_arguments = args;
380
381 // Is the first argument the executable?
382 if (first_arg_is_executable)
383 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000384 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000385 if (first_arg)
386 {
387 // Yes the first argument is an executable, set it as the executable
388 // in the launch options. Don't resolve the file path as the path
389 // could be a remote platform path
390 const bool resolve = false;
391 m_executable.SetFile(first_arg, resolve);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000392 }
393 }
394}
395
Greg Claytonabb33022011-11-08 02:43:13 +0000396void
Greg Clayton464c6162011-11-17 22:14:31 +0000397ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000398{
399 // If notthing was specified, then check the process for any default
400 // settings that were set with "settings set"
401 if (m_file_actions.empty())
402 {
Greg Claytonabb33022011-11-08 02:43:13 +0000403 if (m_flags.Test(eLaunchFlagDisableSTDIO))
404 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000405 AppendSuppressFileAction (STDIN_FILENO , true, false);
406 AppendSuppressFileAction (STDOUT_FILENO, false, true);
407 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000408 }
409 else
410 {
411 // Check for any values that might have gotten set with any of:
412 // (lldb) settings set target.input-path
413 // (lldb) settings set target.output-path
414 // (lldb) settings set target.error-path
Greg Clayton73844aa2012-08-22 17:17:09 +0000415 FileSpec in_path;
416 FileSpec out_path;
417 FileSpec err_path;
Greg Claytonabb33022011-11-08 02:43:13 +0000418 if (target)
419 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000420 in_path = target->GetStandardInputPath();
421 out_path = target->GetStandardOutputPath();
422 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000423 }
424
Greg Clayton73844aa2012-08-22 17:17:09 +0000425 if (in_path || out_path || err_path)
426 {
427 char path[PATH_MAX];
428 if (in_path && in_path.GetPath(path, sizeof(path)))
429 AppendOpenFileAction(STDIN_FILENO, path, true, false);
430
431 if (out_path && out_path.GetPath(path, sizeof(path)))
432 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
433
434 if (err_path && err_path.GetPath(path, sizeof(path)))
435 AppendOpenFileAction(STDERR_FILENO, path, false, true);
436 }
437 else if (default_to_use_pty)
Greg Clayton464c6162011-11-17 22:14:31 +0000438 {
439 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000440 {
Greg Clayton73844aa2012-08-22 17:17:09 +0000441 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
442 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
443 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
444 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000445 }
446 }
Greg Claytonabb33022011-11-08 02:43:13 +0000447 }
448 }
449}
450
Greg Clayton527154d2011-11-15 03:53:30 +0000451
452bool
Greg Clayton97471182012-04-14 01:42:46 +0000453ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
454 bool localhost,
455 bool will_debug,
456 bool first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000457{
458 error.Clear();
459
460 if (GetFlags().Test (eLaunchFlagLaunchInShell))
461 {
462 const char *shell_executable = GetShell();
463 if (shell_executable)
464 {
465 char shell_resolved_path[PATH_MAX];
466
467 if (localhost)
468 {
469 FileSpec shell_filespec (shell_executable, true);
470
471 if (!shell_filespec.Exists())
472 {
473 // Resolve the path in case we just got "bash", "sh" or "tcsh"
474 if (!shell_filespec.ResolveExecutableLocation ())
475 {
476 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
477 return false;
478 }
479 }
480 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
481 shell_executable = shell_resolved_path;
482 }
483
Greg Clayton0c8446c2012-10-17 22:57:12 +0000484 const char **argv = GetArguments().GetConstArgumentVector ();
485 if (argv == NULL || argv[0] == NULL)
486 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000487 Args shell_arguments;
488 std::string safe_arg;
489 shell_arguments.AppendArgument (shell_executable);
Greg Clayton527154d2011-11-15 03:53:30 +0000490 shell_arguments.AppendArgument ("-c");
Greg Clayton97471182012-04-14 01:42:46 +0000491 StreamString shell_command;
492 if (will_debug)
Greg Clayton527154d2011-11-15 03:53:30 +0000493 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000494 // Add a modified PATH environment variable in case argv[0]
495 // is a relative path
496 const char *argv0 = argv[0];
497 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
498 {
499 // We have a relative path to our executable which may not work if
500 // we just try to run "a.out" (without it being converted to "./a.out")
501 const char *working_dir = GetWorkingDirectory();
502 std::string new_path("PATH=");
503 const size_t empty_path_len = new_path.size();
504
505 if (working_dir && working_dir[0])
506 {
507 new_path += working_dir;
508 }
509 else
510 {
511 char current_working_dir[PATH_MAX];
512 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
513 if (cwd && cwd[0])
514 new_path += cwd;
515 }
516 const char *curr_path = getenv("PATH");
517 if (curr_path)
518 {
519 if (new_path.size() > empty_path_len)
520 new_path += ':';
521 new_path += curr_path;
522 }
523 new_path += ' ';
524 shell_command.PutCString(new_path.c_str());
525 }
526
Greg Clayton97471182012-04-14 01:42:46 +0000527 shell_command.PutCString ("exec");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000528
529#if defined(__APPLE__)
530 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Clayton97471182012-04-14 01:42:46 +0000531 if (GetArchitecture().IsValid())
532 {
533 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton0c8446c2012-10-17 22:57:12 +0000534 // Set the resume count to 2:
Greg Clayton97471182012-04-14 01:42:46 +0000535 // 1 - stop in shell
536 // 2 - stop in /usr/bin/arch
537 // 3 - then we will stop in our program
538 SetResumeCount(2);
539 }
540 else
541 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000542 // Set the resume count to 1:
Greg Clayton97471182012-04-14 01:42:46 +0000543 // 1 - stop in shell
544 // 2 - then we will stop in our program
545 SetResumeCount(1);
546 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000547#else
548 // Set the resume count to 1:
549 // 1 - stop in shell
550 // 2 - then we will stop in our program
551 SetResumeCount(1);
552#endif
Greg Clayton527154d2011-11-15 03:53:30 +0000553 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000554
555 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000556 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000557 // There should only be one argument that is the shell command itself to be used as is
558 if (argv[0] && !argv[1])
559 shell_command.Printf("%s", argv[0]);
Greg Clayton97471182012-04-14 01:42:46 +0000560 else
Greg Clayton0c8446c2012-10-17 22:57:12 +0000561 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000562 }
Greg Clayton97471182012-04-14 01:42:46 +0000563 else
564 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000565 for (size_t i=0; argv[i] != NULL; ++i)
566 {
567 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
568 shell_command.Printf(" %s", arg);
569 }
Greg Clayton97471182012-04-14 01:42:46 +0000570 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000571 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000572 m_executable.SetFile(shell_executable, false);
573 m_arguments = shell_arguments;
574 return true;
575 }
576 else
577 {
578 error.SetErrorString ("invalid shell path");
579 }
580 }
581 else
582 {
583 error.SetErrorString ("not launching in shell");
584 }
585 return false;
586}
587
588
Greg Clayton24bc5d92011-03-30 18:16:51 +0000589bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000590ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
591{
592 if ((read || write) && fd >= 0 && path && path[0])
593 {
594 m_action = eFileActionOpen;
595 m_fd = fd;
596 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000597 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000598 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000599 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000600 else
Greg Clayton527154d2011-11-15 03:53:30 +0000601 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000602 m_path.assign (path);
603 return true;
604 }
605 else
606 {
607 Clear();
608 }
609 return false;
610}
611
612bool
613ProcessLaunchInfo::FileAction::Close (int fd)
614{
615 Clear();
616 if (fd >= 0)
617 {
618 m_action = eFileActionClose;
619 m_fd = fd;
620 }
621 return m_fd >= 0;
622}
623
624
625bool
626ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
627{
628 Clear();
629 if (fd >= 0 && dup_fd >= 0)
630 {
631 m_action = eFileActionDuplicate;
632 m_fd = fd;
633 m_arg = dup_fd;
634 }
635 return m_fd >= 0;
636}
637
638
639
640bool
641ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
642 const FileAction *info,
643 Log *log,
644 Error& error)
645{
646 if (info == NULL)
647 return false;
648
649 switch (info->m_action)
650 {
651 case eFileActionNone:
652 error.Clear();
653 break;
654
655 case eFileActionClose:
656 if (info->m_fd == -1)
657 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
658 else
659 {
660 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
661 eErrorTypePOSIX);
662 if (log && (error.Fail() || log))
663 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
664 file_actions, info->m_fd);
665 }
666 break;
667
668 case eFileActionDuplicate:
669 if (info->m_fd == -1)
670 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
671 else if (info->m_arg == -1)
672 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
673 else
674 {
675 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
676 eErrorTypePOSIX);
677 if (log && (error.Fail() || log))
678 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
679 file_actions, info->m_fd, info->m_arg);
680 }
681 break;
682
683 case eFileActionOpen:
684 if (info->m_fd == -1)
685 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
686 else
687 {
688 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000689
Greg Claytonb72d0f02011-04-12 05:54:46 +0000690 mode_t mode = 0;
691
Greg Clayton527154d2011-11-15 03:53:30 +0000692 if (oflag & O_CREAT)
693 mode = 0640;
694
Greg Claytonb72d0f02011-04-12 05:54:46 +0000695 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
696 info->m_fd,
697 info->m_path.c_str(),
698 oflag,
699 mode),
700 eErrorTypePOSIX);
701 if (error.Fail() || log)
702 error.PutToLog(log,
703 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
704 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
705 }
706 break;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000707 }
708 return error.Success();
709}
710
711Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000712ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000713{
714 Error error;
Greg Clayton6475c422012-12-04 00:32:51 +0000715 const int short_option = m_getopt_table[option_idx].val;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000716
717 switch (short_option)
718 {
719 case 's': // Stop at program entry point
720 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
721 break;
722
Greg Claytonb72d0f02011-04-12 05:54:46 +0000723 case 'i': // STDIN for read only
724 {
725 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000726 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000727 launch_info.AppendFileAction (action);
728 }
729 break;
730
731 case 'o': // Open STDOUT for write only
732 {
733 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000734 if (action.Open (STDOUT_FILENO, option_arg, false, true))
735 launch_info.AppendFileAction (action);
736 }
737 break;
738
739 case 'e': // STDERR for write only
740 {
741 ProcessLaunchInfo::FileAction action;
742 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000743 launch_info.AppendFileAction (action);
744 }
745 break;
746
Greg Clayton95ec1682012-03-06 04:01:04 +0000747
Greg Claytonb72d0f02011-04-12 05:54:46 +0000748 case 'p': // Process plug-in name
749 launch_info.SetProcessPluginName (option_arg);
750 break;
751
752 case 'n': // Disable STDIO
753 {
754 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000755 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000756 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000757 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000758 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000759 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000760 launch_info.AppendFileAction (action);
761 }
762 break;
763
764 case 'w':
765 launch_info.SetWorkingDirectory (option_arg);
766 break;
767
768 case 't': // Open process in new terminal window
769 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
770 break;
771
772 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000773 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
774 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000775 break;
776
777 case 'A':
778 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
779 break;
780
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000781 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000782 if (option_arg && option_arg[0])
783 launch_info.SetShell (option_arg);
784 else
785 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000786 break;
787
Greg Claytonb72d0f02011-04-12 05:54:46 +0000788 case 'v':
789 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
790 break;
791
792 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000793 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000794 break;
795
796 }
797 return error;
798}
799
800OptionDefinition
801ProcessLaunchCommandOptions::g_option_table[] =
802{
803{ 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."},
804{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
805{ 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 +0000806{ 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 +0000807{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
808{ 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 +0000809{ 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 +0000810
Sean Callanan9a91ef62012-10-24 01:12:14 +0000811{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
812{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
813{ 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 +0000814
815{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
816
817{ 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."},
818
819{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
820};
821
822
823
824bool
825ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000826{
827 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
828 return true;
829 const char *match_name = m_match_info.GetName();
830 if (!match_name)
831 return true;
832
833 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
834}
835
836bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000837ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000838{
839 if (!NameMatches (proc_info.GetName()))
840 return false;
841
842 if (m_match_info.ProcessIDIsValid() &&
843 m_match_info.GetProcessID() != proc_info.GetProcessID())
844 return false;
845
846 if (m_match_info.ParentProcessIDIsValid() &&
847 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
848 return false;
849
Greg Claytonb72d0f02011-04-12 05:54:46 +0000850 if (m_match_info.UserIDIsValid () &&
851 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000852 return false;
853
Greg Claytonb72d0f02011-04-12 05:54:46 +0000854 if (m_match_info.GroupIDIsValid () &&
855 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000856 return false;
857
858 if (m_match_info.EffectiveUserIDIsValid () &&
859 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
860 return false;
861
862 if (m_match_info.EffectiveGroupIDIsValid () &&
863 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
864 return false;
865
866 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callanan40e278c2012-12-13 22:07:14 +0000867 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton24bc5d92011-03-30 18:16:51 +0000868 return false;
869 return true;
870}
871
872bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000873ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000874{
875 if (m_name_match_type != eNameMatchIgnore)
876 return false;
877
878 if (m_match_info.ProcessIDIsValid())
879 return false;
880
881 if (m_match_info.ParentProcessIDIsValid())
882 return false;
883
Greg Claytonb72d0f02011-04-12 05:54:46 +0000884 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000885 return false;
886
Greg Claytonb72d0f02011-04-12 05:54:46 +0000887 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000888 return false;
889
890 if (m_match_info.EffectiveUserIDIsValid ())
891 return false;
892
893 if (m_match_info.EffectiveGroupIDIsValid ())
894 return false;
895
896 if (m_match_info.GetArchitecture().IsValid())
897 return false;
898
899 if (m_match_all_users)
900 return false;
901
902 return true;
903
904}
905
906void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000907ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000908{
909 m_match_info.Clear();
910 m_name_match_type = eNameMatchIgnore;
911 m_match_all_users = false;
912}
Greg Claytonfd119992011-01-07 06:08:19 +0000913
Greg Clayton46c9a352012-02-09 06:16:32 +0000914ProcessSP
915Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000916{
Greg Clayton46c9a352012-02-09 06:16:32 +0000917 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000918 ProcessCreateInstance create_callback = NULL;
919 if (plugin_name)
920 {
921 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
922 if (create_callback)
923 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000924 process_sp = create_callback(target, listener, crash_file_path);
925 if (process_sp)
926 {
927 if (!process_sp->CanDebug(target, true))
928 process_sp.reset();
929 }
Chris Lattner24943d22010-06-08 16:52:24 +0000930 }
931 }
932 else
933 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000934 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000935 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000936 process_sp = create_callback(target, listener, crash_file_path);
937 if (process_sp)
938 {
939 if (!process_sp->CanDebug(target, false))
940 process_sp.reset();
941 else
942 break;
943 }
Chris Lattner24943d22010-06-08 16:52:24 +0000944 }
945 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000946 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000947}
948
Jim Ingham5a15e692012-02-16 06:50:00 +0000949ConstString &
950Process::GetStaticBroadcasterClass ()
951{
952 static ConstString class_name ("lldb.process");
953 return class_name;
954}
Chris Lattner24943d22010-06-08 16:52:24 +0000955
956//----------------------------------------------------------------------
957// Process constructor
958//----------------------------------------------------------------------
959Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +0000960 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +0000961 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000962 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +0000963 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000964 m_public_state (eStateUnloaded),
965 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000966 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
967 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000968 m_private_state_listener ("lldb.process.internal_state_listener"),
969 m_private_state_control_wait(),
970 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000971 m_mod_id (),
Chris Lattner24943d22010-06-08 16:52:24 +0000972 m_thread_index_id (0),
Han Ming Ongccd5c4e2013-01-08 22:10:01 +0000973 m_thread_id_to_index_id_map (),
Chris Lattner24943d22010-06-08 16:52:24 +0000974 m_exit_status (-1),
975 m_exit_string (),
976 m_thread_list (this),
977 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000978 m_image_tokens (),
979 m_listener (listener),
980 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000981 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000982 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000983 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000984 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000985 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000986 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000987 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000988 m_stderr_data (),
Han Ming Ongfb9cee62012-11-17 00:21:04 +0000989 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
990 m_profile_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000991 m_memory_cache (*this),
992 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +0000993 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000994 m_next_event_action_ap(),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000995 m_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +0000996 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +0000997 m_finalize_called(false),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000998 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +0000999{
Jim Ingham5a15e692012-02-16 06:50:00 +00001000 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +00001001
Greg Claytone005f2c2010-11-06 01:53:30 +00001002 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001003 if (log)
1004 log->Printf ("%p Process::Process()", this);
1005
Greg Clayton49ce6822010-10-31 03:01:06 +00001006 SetEventName (eBroadcastBitStateChanged, "state-changed");
1007 SetEventName (eBroadcastBitInterrupt, "interrupt");
1008 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1009 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001010 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Clayton49ce6822010-10-31 03:01:06 +00001011
Greg Clayton84332782012-10-29 20:52:08 +00001012 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1013 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1014 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1015
Chris Lattner24943d22010-06-08 16:52:24 +00001016 listener.StartListeningForEvents (this,
1017 eBroadcastBitStateChanged |
1018 eBroadcastBitInterrupt |
1019 eBroadcastBitSTDOUT |
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001020 eBroadcastBitSTDERR |
1021 eBroadcastBitProfileData);
Chris Lattner24943d22010-06-08 16:52:24 +00001022
1023 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001024 eBroadcastBitStateChanged |
1025 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +00001026
1027 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1028 eBroadcastInternalStateControlStop |
1029 eBroadcastInternalStateControlPause |
1030 eBroadcastInternalStateControlResume);
1031}
1032
1033//----------------------------------------------------------------------
1034// Destructor
1035//----------------------------------------------------------------------
1036Process::~Process()
1037{
Greg Claytone005f2c2010-11-06 01:53:30 +00001038 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001039 if (log)
1040 log->Printf ("%p Process::~Process()", this);
1041 StopPrivateStateThread();
1042}
1043
Greg Clayton73844aa2012-08-22 17:17:09 +00001044const ProcessPropertiesSP &
1045Process::GetGlobalProperties()
1046{
1047 static ProcessPropertiesSP g_settings_sp;
1048 if (!g_settings_sp)
1049 g_settings_sp.reset (new ProcessProperties (true));
1050 return g_settings_sp;
1051}
1052
Chris Lattner24943d22010-06-08 16:52:24 +00001053void
1054Process::Finalize()
1055{
Greg Claytonffa43a62011-11-17 04:46:02 +00001056 switch (GetPrivateState())
1057 {
1058 case eStateConnected:
1059 case eStateAttaching:
1060 case eStateLaunching:
1061 case eStateStopped:
1062 case eStateRunning:
1063 case eStateStepping:
1064 case eStateCrashed:
1065 case eStateSuspended:
1066 if (GetShouldDetach())
1067 Detach();
1068 else
1069 Destroy();
1070 break;
1071
1072 case eStateInvalid:
1073 case eStateUnloaded:
1074 case eStateDetached:
1075 case eStateExited:
1076 break;
1077 }
1078
Greg Clayton2f57db02011-10-01 00:45:15 +00001079 // Clear our broadcaster before we proceed with destroying
1080 Broadcaster::Clear();
1081
Chris Lattner24943d22010-06-08 16:52:24 +00001082 // Do any cleanup needed prior to being destructed... Subclasses
1083 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001084
1085 // We need to destroy the loader before the derived Process class gets destroyed
1086 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001087 m_dynamic_checkers_ap.reset();
1088 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001089 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001090 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001091 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001092 std::vector<Notifications> empty_notifications;
1093 m_notifications.swap(empty_notifications);
1094 m_image_tokens.clear();
1095 m_memory_cache.Clear();
1096 m_allocated_memory_cache.Clear();
1097 m_language_runtimes.clear();
1098 m_next_event_action_ap.reset();
Greg Clayton84332782012-10-29 20:52:08 +00001099//#ifdef LLDB_CONFIGURATION_DEBUG
1100// StreamFile s(stdout, false);
1101// EventSP event_sp;
1102// while (m_private_state_listener.GetNextEvent(event_sp))
1103// {
1104// event_sp->Dump (&s);
1105// s.EOL();
1106// }
1107//#endif
1108 // We have to be very careful here as the m_private_state_listener might
1109 // contain events that have ProcessSP values in them which can keep this
1110 // process around forever. These events need to be cleared out.
1111 m_private_state_listener.Clear();
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001112 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001113}
1114
1115void
1116Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1117{
1118 m_notifications.push_back(callbacks);
1119 if (callbacks.initialize != NULL)
1120 callbacks.initialize (callbacks.baton, this);
1121}
1122
1123bool
1124Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1125{
1126 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1127 for (pos = m_notifications.begin(); pos != end; ++pos)
1128 {
1129 if (pos->baton == callbacks.baton &&
1130 pos->initialize == callbacks.initialize &&
1131 pos->process_state_changed == callbacks.process_state_changed)
1132 {
1133 m_notifications.erase(pos);
1134 return true;
1135 }
1136 }
1137 return false;
1138}
1139
1140void
1141Process::SynchronouslyNotifyStateChanged (StateType state)
1142{
1143 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1144 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1145 {
1146 if (notification_pos->process_state_changed)
1147 notification_pos->process_state_changed (notification_pos->baton, this, state);
1148 }
1149}
1150
1151// FIXME: We need to do some work on events before the general Listener sees them.
1152// For instance if we are continuing from a breakpoint, we need to ensure that we do
1153// the little "insert real insn, step & stop" trick. But we can't do that when the
1154// event is delivered by the broadcaster - since that is done on the thread that is
1155// waiting for new events, so if we needed more than one event for our handling, we would
1156// stall. So instead we do it when we fetch the event off of the queue.
1157//
1158
1159StateType
1160Process::GetNextEvent (EventSP &event_sp)
1161{
1162 StateType state = eStateInvalid;
1163
1164 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1165 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1166
1167 return state;
1168}
1169
1170
1171StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001172Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001173{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001174 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1175 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1176 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001177 if (event_sp_ptr)
1178 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001179 StateType state = GetState();
1180 // If we are exited or detached, we won't ever get back to any
1181 // other valid state...
1182 if (state == eStateDetached || state == eStateExited)
1183 return state;
1184
1185 while (state != eStateInvalid)
1186 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001187 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001188 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001189 if (event_sp_ptr && event_sp)
1190 *event_sp_ptr = event_sp;
1191
Jim Ingham21f37ad2011-08-09 02:12:22 +00001192 switch (state)
1193 {
1194 case eStateCrashed:
1195 case eStateDetached:
1196 case eStateExited:
1197 case eStateUnloaded:
1198 return state;
1199 case eStateStopped:
1200 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1201 continue;
1202 else
1203 return state;
1204 default:
1205 continue;
1206 }
1207 }
1208 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001209}
1210
1211
1212StateType
1213Process::WaitForState
1214(
1215 const TimeValue *timeout,
1216 const StateType *match_states, const uint32_t num_match_states
1217)
1218{
1219 EventSP event_sp;
1220 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001221 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001222 while (state != eStateInvalid)
1223 {
Greg Claytond8c62532010-10-07 04:19:01 +00001224 // If we are exited or detached, we won't ever get back to any
1225 // other valid state...
1226 if (state == eStateDetached || state == eStateExited)
1227 return state;
1228
Chris Lattner24943d22010-06-08 16:52:24 +00001229 state = WaitForStateChangedEvents (timeout, event_sp);
1230
1231 for (i=0; i<num_match_states; ++i)
1232 {
1233 if (match_states[i] == state)
1234 return state;
1235 }
1236 }
1237 return state;
1238}
1239
Jim Ingham63e24d72010-10-11 23:53:14 +00001240bool
1241Process::HijackProcessEvents (Listener *listener)
1242{
1243 if (listener != NULL)
1244 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001245 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001246 }
1247 else
1248 return false;
1249}
1250
1251void
1252Process::RestoreProcessEvents ()
1253{
1254 RestoreBroadcaster();
1255}
1256
Jim Inghamf9f40c22011-02-08 05:20:59 +00001257bool
1258Process::HijackPrivateProcessEvents (Listener *listener)
1259{
1260 if (listener != NULL)
1261 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001262 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001263 }
1264 else
1265 return false;
1266}
1267
1268void
1269Process::RestorePrivateProcessEvents ()
1270{
1271 m_private_state_broadcaster.RestoreBroadcaster();
1272}
1273
Chris Lattner24943d22010-06-08 16:52:24 +00001274StateType
1275Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1276{
Greg Claytone005f2c2010-11-06 01:53:30 +00001277 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001278
1279 if (log)
1280 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1281
1282 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001283 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1284 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001285 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001286 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001287 {
1288 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1289 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1290 else if (log)
1291 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1292 }
Chris Lattner24943d22010-06-08 16:52:24 +00001293
1294 if (log)
1295 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1296 __FUNCTION__,
1297 timeout,
1298 StateAsCString(state));
1299 return state;
1300}
1301
1302Event *
1303Process::PeekAtStateChangedEvents ()
1304{
Greg Claytone005f2c2010-11-06 01:53:30 +00001305 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001306
1307 if (log)
1308 log->Printf ("Process::%s...", __FUNCTION__);
1309
1310 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001311 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1312 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001313 if (log)
1314 {
1315 if (event_ptr)
1316 {
1317 log->Printf ("Process::%s (event_ptr) => %s",
1318 __FUNCTION__,
1319 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1320 }
1321 else
1322 {
1323 log->Printf ("Process::%s no events found",
1324 __FUNCTION__);
1325 }
1326 }
1327 return event_ptr;
1328}
1329
1330StateType
1331Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1332{
Greg Claytone005f2c2010-11-06 01:53:30 +00001333 LogSP 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 Clayton72e1c782011-01-22 23:43:18 +00001339 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1340 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001341 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001342 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001343 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1344 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001345
1346 // This is a bit of a hack, but when we wait here we could very well return
1347 // to the command-line, and that could disable the log, which would render the
1348 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001349 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001350 {
1351 if (state == eStateInvalid)
1352 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1353 else
1354 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1355 }
Chris Lattner24943d22010-06-08 16:52:24 +00001356 return state;
1357}
1358
1359bool
1360Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1361{
Greg Claytone005f2c2010-11-06 01:53:30 +00001362 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001363
1364 if (log)
1365 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1366
1367 if (control_only)
1368 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1369 else
1370 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1371}
1372
1373bool
1374Process::IsRunning () const
1375{
1376 return StateIsRunningState (m_public_state.GetValue());
1377}
1378
1379int
1380Process::GetExitStatus ()
1381{
1382 if (m_public_state.GetValue() == eStateExited)
1383 return m_exit_status;
1384 return -1;
1385}
1386
Greg Clayton638351a2010-12-04 00:10:17 +00001387
Chris Lattner24943d22010-06-08 16:52:24 +00001388const char *
1389Process::GetExitDescription ()
1390{
1391 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1392 return m_exit_string.c_str();
1393 return NULL;
1394}
1395
Greg Clayton72e1c782011-01-22 23:43:18 +00001396bool
Chris Lattner24943d22010-06-08 16:52:24 +00001397Process::SetExitStatus (int status, const char *cstr)
1398{
Greg Clayton68ca8232011-01-25 02:58:48 +00001399 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1400 if (log)
1401 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1402 status, status,
1403 cstr ? "\"" : "",
1404 cstr ? cstr : "NULL",
1405 cstr ? "\"" : "");
1406
Greg Clayton72e1c782011-01-22 23:43:18 +00001407 // We were already in the exited state
1408 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001409 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001410 if (log)
1411 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001412 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001413 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001414
1415 m_exit_status = status;
1416 if (cstr)
1417 m_exit_string = cstr;
1418 else
1419 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001420
Greg Clayton72e1c782011-01-22 23:43:18 +00001421 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001422
Greg Clayton72e1c782011-01-22 23:43:18 +00001423 SetPrivateState (eStateExited);
1424 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001425}
1426
1427// This static callback can be used to watch for local child processes on
1428// the current host. The the child process exits, the process will be
1429// found in the global target list (we want to be completely sure that the
1430// lldb_private::Process doesn't go away before we can deliver the signal.
1431bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001432Process::SetProcessExitStatus (void *callback_baton,
1433 lldb::pid_t pid,
1434 bool exited,
1435 int signo, // Zero for no signal
1436 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001437)
1438{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001439 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1440 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001441 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001442 callback_baton,
1443 pid,
1444 exited,
1445 signo,
1446 exit_status);
1447
1448 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001449 {
Greg Clayton63094e02010-06-23 01:19:29 +00001450 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001451 if (target_sp)
1452 {
1453 ProcessSP process_sp (target_sp->GetProcessSP());
1454 if (process_sp)
1455 {
1456 const char *signal_cstr = NULL;
1457 if (signo)
1458 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1459
1460 process_sp->SetExitStatus (exit_status, signal_cstr);
1461 }
1462 }
1463 return true;
1464 }
1465 return false;
1466}
1467
1468
Greg Clayton37f962e2011-08-22 02:49:39 +00001469void
1470Process::UpdateThreadListIfNeeded ()
1471{
1472 const uint32_t stop_id = GetStopID();
1473 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1474 {
Greg Clayton20206082011-11-17 01:23:07 +00001475 const StateType state = GetPrivateState();
1476 if (StateIsStoppedState (state, true))
1477 {
1478 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001479 // m_thread_list does have its own mutex, but we need to
1480 // hold onto the mutex between the call to UpdateThreadList(...)
1481 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001482 ThreadList new_thread_list(this);
1483 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001484 // thread list, but only update if "true" is returned
1485 if (UpdateThreadList (m_thread_list, new_thread_list))
1486 {
1487 OperatingSystem *os = GetOperatingSystem ();
1488 if (os)
1489 os->UpdateThreadList (m_thread_list, new_thread_list);
1490 m_thread_list.Update (new_thread_list);
1491 m_thread_list.SetStopID (stop_id);
1492 }
Greg Clayton20206082011-11-17 01:23:07 +00001493 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001494 }
1495}
1496
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001497// This is obsoleted. Staged removal for Xcode.
Chris Lattner24943d22010-06-08 16:52:24 +00001498uint32_t
1499Process::GetNextThreadIndexID ()
1500{
1501 return ++m_thread_index_id;
1502}
1503
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001504uint32_t
1505Process::GetNextThreadIndexID (uint64_t thread_id)
1506{
1507 return AssignIndexIDToThread(thread_id);
1508}
1509
1510bool
1511Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1512{
1513 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1514 if (iterator == m_thread_id_to_index_id_map.end())
1515 {
1516 return false;
1517 }
1518 else
1519 {
1520 return true;
1521 }
1522}
1523
1524uint32_t
1525Process::AssignIndexIDToThread(uint64_t thread_id)
1526{
1527 uint32_t result = 0;
1528 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1529 if (iterator == m_thread_id_to_index_id_map.end())
1530 {
1531 result = ++m_thread_index_id;
1532 m_thread_id_to_index_id_map[thread_id] = result;
1533 }
1534 else
1535 {
1536 result = iterator->second;
1537 }
1538
1539 return result;
1540}
1541
Chris Lattner24943d22010-06-08 16:52:24 +00001542StateType
1543Process::GetState()
1544{
1545 // If any other threads access this we will need a mutex for it
1546 return m_public_state.GetValue ();
1547}
1548
1549void
1550Process::SetPublicState (StateType new_state)
1551{
Greg Clayton68ca8232011-01-25 02:58:48 +00001552 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001553 if (log)
1554 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001555 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001556 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001557
1558 // On the transition from Run to Stopped, we unlock the writer end of the
1559 // run lock. The lock gets locked in Resume, which is the public API
1560 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001561 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1562 {
Sean Callanana3772862012-06-02 01:16:20 +00001563 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001564 {
Sean Callanana3772862012-06-02 01:16:20 +00001565 if (log)
1566 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1567 m_run_lock.WriteUnlock();
1568 }
1569 else
1570 {
1571 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1572 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1573 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001574 {
Sean Callanana3772862012-06-02 01:16:20 +00001575 if (new_state_is_stopped)
1576 {
1577 if (log)
1578 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1579 m_run_lock.WriteUnlock();
1580 }
Greg Claytona894fe72012-04-05 16:12:35 +00001581 }
Greg Claytona894fe72012-04-05 16:12:35 +00001582 }
1583 }
Chris Lattner24943d22010-06-08 16:52:24 +00001584}
1585
Jim Ingham027aaa72012-04-19 01:40:33 +00001586Error
1587Process::Resume ()
1588{
1589 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1590 if (log)
1591 log->Printf("Process::Resume -- locking run lock");
1592 if (!m_run_lock.WriteTryLock())
1593 {
1594 Error error("Resume request failed - process still running.");
1595 if (log)
1596 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1597 return error;
1598 }
1599 return PrivateResume();
1600}
1601
Chris Lattner24943d22010-06-08 16:52:24 +00001602StateType
1603Process::GetPrivateState ()
1604{
1605 return m_private_state.GetValue();
1606}
1607
1608void
1609Process::SetPrivateState (StateType new_state)
1610{
Greg Clayton68ca8232011-01-25 02:58:48 +00001611 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001612 bool state_changed = false;
1613
1614 if (log)
1615 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1616
1617 Mutex::Locker locker(m_private_state.GetMutex());
1618
1619 const StateType old_state = m_private_state.GetValueNoLock ();
1620 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001621 // This code is left commented out in case we ever need to control
1622 // the private process state with another run lock. Right now it doesn't
1623 // seem like we need to do this, but if we ever do, we can uncomment and
1624 // use this code.
1625// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1626// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1627// if (old_state_is_stopped != new_state_is_stopped)
1628// {
1629// if (new_state_is_stopped)
1630// m_private_run_lock.WriteUnlock();
1631// else
1632// m_private_run_lock.WriteLock();
1633// }
1634
Chris Lattner24943d22010-06-08 16:52:24 +00001635 if (state_changed)
1636 {
1637 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001638 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001639 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001640 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001641 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001642 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001643 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001644 }
1645 // Use our target to get a shared pointer to ourselves...
Greg Clayton84332782012-10-29 20:52:08 +00001646 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1647 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1648 else
1649 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001650 }
1651 else
1652 {
1653 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001654 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001655 }
1656}
1657
Jim Ingham0296fe72011-11-08 03:00:11 +00001658void
1659Process::SetRunningUserExpression (bool on)
1660{
1661 m_mod_id.SetRunningUserExpression (on);
1662}
1663
Chris Lattner24943d22010-06-08 16:52:24 +00001664addr_t
1665Process::GetImageInfoAddress()
1666{
1667 return LLDB_INVALID_ADDRESS;
1668}
1669
Greg Clayton0baa3942010-11-04 01:54:29 +00001670//----------------------------------------------------------------------
1671// LoadImage
1672//
1673// This function provides a default implementation that works for most
1674// unix variants. Any Process subclasses that need to do shared library
1675// loading differently should override LoadImage and UnloadImage and
1676// do what is needed.
1677//----------------------------------------------------------------------
1678uint32_t
1679Process::LoadImage (const FileSpec &image_spec, Error &error)
1680{
Greg Clayton77d40712012-04-18 00:05:19 +00001681 char path[PATH_MAX];
1682 image_spec.GetPath(path, sizeof(path));
1683
Greg Clayton0baa3942010-11-04 01:54:29 +00001684 DynamicLoader *loader = GetDynamicLoader();
1685 if (loader)
1686 {
1687 error = loader->CanLoadImage();
1688 if (error.Fail())
1689 return LLDB_INVALID_IMAGE_TOKEN;
1690 }
1691
1692 if (error.Success())
1693 {
1694 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001695
1696 if (thread_sp)
1697 {
1698 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1699
1700 if (frame_sp)
1701 {
1702 ExecutionContext exe_ctx;
1703 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001704 const bool unwind_on_error = true;
1705 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001706 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001707 expr.Printf("dlopen (\"%s\", 2)", path);
1708 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001709 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001710 ClangUserExpression::Evaluate (exe_ctx,
1711 eExecutionPolicyAlways,
1712 lldb::eLanguageTypeUnknown,
1713 ClangUserExpression::eResultTypeAny,
1714 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001715 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001716 expr.GetData(),
1717 prefix,
1718 result_valobj_sp,
1719 true,
1720 ClangUserExpression::kDefaultTimeout);
Johnny Chenb14ec342011-09-09 00:01:43 +00001721 error = result_valobj_sp->GetError();
1722 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001723 {
1724 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001725 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001726 {
1727 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1728 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1729 {
1730 uint32_t image_token = m_image_tokens.size();
1731 m_image_tokens.push_back (image_ptr);
1732 return image_token;
1733 }
1734 }
1735 }
1736 }
1737 }
1738 }
Greg Clayton77d40712012-04-18 00:05:19 +00001739 if (!error.AsCString())
1740 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001741 return LLDB_INVALID_IMAGE_TOKEN;
1742}
1743
1744//----------------------------------------------------------------------
1745// UnloadImage
1746//
1747// This function provides a default implementation that works for most
1748// unix variants. Any Process subclasses that need to do shared library
1749// loading differently should override LoadImage and UnloadImage and
1750// do what is needed.
1751//----------------------------------------------------------------------
1752Error
1753Process::UnloadImage (uint32_t image_token)
1754{
1755 Error error;
1756 if (image_token < m_image_tokens.size())
1757 {
1758 const addr_t image_addr = m_image_tokens[image_token];
1759 if (image_addr == LLDB_INVALID_ADDRESS)
1760 {
1761 error.SetErrorString("image already unloaded");
1762 }
1763 else
1764 {
1765 DynamicLoader *loader = GetDynamicLoader();
1766 if (loader)
1767 error = loader->CanLoadImage();
1768
1769 if (error.Success())
1770 {
1771 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001772
1773 if (thread_sp)
1774 {
1775 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1776
1777 if (frame_sp)
1778 {
1779 ExecutionContext exe_ctx;
1780 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001781 const bool unwind_on_error = true;
1782 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001783 StreamString expr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001784 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton0baa3942010-11-04 01:54:29 +00001785 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001786 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001787 ClangUserExpression::Evaluate (exe_ctx,
1788 eExecutionPolicyAlways,
1789 lldb::eLanguageTypeUnknown,
1790 ClangUserExpression::eResultTypeAny,
1791 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001792 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001793 expr.GetData(),
1794 prefix,
1795 result_valobj_sp,
1796 true,
1797 ClangUserExpression::kDefaultTimeout);
Greg Clayton0baa3942010-11-04 01:54:29 +00001798 if (result_valobj_sp->GetError().Success())
1799 {
1800 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001801 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001802 {
1803 if (scalar.UInt(1))
1804 {
1805 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1806 }
1807 else
1808 {
1809 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1810 }
1811 }
1812 }
1813 else
1814 {
1815 error = result_valobj_sp->GetError();
1816 }
1817 }
1818 }
1819 }
1820 }
1821 }
1822 else
1823 {
1824 error.SetErrorString("invalid image token");
1825 }
1826 return error;
1827}
1828
Greg Clayton75906e42011-05-11 18:39:18 +00001829const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001830Process::GetABI()
1831{
Greg Clayton75906e42011-05-11 18:39:18 +00001832 if (!m_abi_sp)
1833 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1834 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001835}
1836
Jim Ingham642036f2010-09-23 02:01:19 +00001837LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001838Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001839{
1840 LanguageRuntimeCollection::iterator pos;
1841 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001842 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001843 {
Jim Inghame3117662012-03-10 00:22:19 +00001844 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001845
Jim Inghame3117662012-03-10 00:22:19 +00001846 m_language_runtimes[language] = runtime_sp;
1847 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001848 }
1849 else
1850 return (*pos).second.get();
1851}
1852
1853CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001854Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001855{
Jim Inghame3117662012-03-10 00:22:19 +00001856 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001857 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1858 return static_cast<CPPLanguageRuntime *> (runtime);
1859 return NULL;
1860}
1861
1862ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001863Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001864{
Jim Inghame3117662012-03-10 00:22:19 +00001865 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001866 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1867 return static_cast<ObjCLanguageRuntime *> (runtime);
1868 return NULL;
1869}
1870
Enrico Granata6b1763b2012-05-21 16:51:35 +00001871bool
1872Process::IsPossibleDynamicValue (ValueObject& in_value)
1873{
1874 if (in_value.IsDynamic())
1875 return false;
1876 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1877
1878 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1879 {
1880 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1881 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1882 }
1883
1884 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1885 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1886 return true;
1887
1888 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1889 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1890}
1891
Chris Lattner24943d22010-06-08 16:52:24 +00001892BreakpointSiteList &
1893Process::GetBreakpointSiteList()
1894{
1895 return m_breakpoint_site_list;
1896}
1897
1898const BreakpointSiteList &
1899Process::GetBreakpointSiteList() const
1900{
1901 return m_breakpoint_site_list;
1902}
1903
1904
1905void
1906Process::DisableAllBreakpointSites ()
1907{
1908 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001909 size_t num_sites = m_breakpoint_site_list.GetSize();
1910 for (size_t i = 0; i < num_sites; i++)
1911 {
1912 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1913 }
Chris Lattner24943d22010-06-08 16:52:24 +00001914}
1915
1916Error
1917Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1918{
1919 Error error (DisableBreakpointSiteByID (break_id));
1920
1921 if (error.Success())
1922 m_breakpoint_site_list.Remove(break_id);
1923
1924 return error;
1925}
1926
1927Error
1928Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1929{
1930 Error error;
1931 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1932 if (bp_site_sp)
1933 {
1934 if (bp_site_sp->IsEnabled())
1935 error = DisableBreakpoint (bp_site_sp.get());
1936 }
1937 else
1938 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001939 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001940 }
1941
1942 return error;
1943}
1944
1945Error
1946Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1947{
1948 Error error;
1949 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1950 if (bp_site_sp)
1951 {
1952 if (!bp_site_sp->IsEnabled())
1953 error = EnableBreakpoint (bp_site_sp.get());
1954 }
1955 else
1956 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001957 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001958 }
1959 return error;
1960}
1961
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001962lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001963Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001964{
Greg Clayton265ab332011-05-19 18:17:41 +00001965 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001966 if (load_addr != LLDB_INVALID_ADDRESS)
1967 {
1968 BreakpointSiteSP bp_site_sp;
1969
1970 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1971 // create a new breakpoint site and add it.
1972
1973 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1974
1975 if (bp_site_sp)
1976 {
1977 bp_site_sp->AddOwner (owner);
1978 owner->SetBreakpointSite (bp_site_sp);
1979 return bp_site_sp->GetID();
1980 }
1981 else
1982 {
1983 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1984 if (bp_site_sp)
1985 {
1986 if (EnableBreakpoint (bp_site_sp.get()).Success())
1987 {
1988 owner->SetBreakpointSite (bp_site_sp);
1989 return m_breakpoint_site_list.Add (bp_site_sp);
1990 }
1991 }
1992 }
1993 }
1994 // We failed to enable the breakpoint
1995 return LLDB_INVALID_BREAK_ID;
1996
1997}
1998
1999void
2000Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2001{
2002 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2003 if (num_owners == 0)
2004 {
2005 DisableBreakpoint(bp_site_sp.get());
2006 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2007 }
2008}
2009
2010
2011size_t
2012Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2013{
2014 size_t bytes_removed = 0;
2015 addr_t intersect_addr;
2016 size_t intersect_size;
2017 size_t opcode_offset;
2018 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002019 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00002020 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00002021
Jim Ingham82820f92011-06-29 19:42:28 +00002022 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00002023 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002024 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00002025 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002026 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00002027 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002028 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00002029 {
2030 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2031 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00002032 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00002033 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002034 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00002035 }
Chris Lattner24943d22010-06-08 16:52:24 +00002036 }
2037 }
2038 }
2039 return bytes_removed;
2040}
2041
2042
Greg Claytonb1888f22011-03-19 01:12:21 +00002043
2044size_t
2045Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2046{
2047 PlatformSP platform_sp (m_target.GetPlatform());
2048 if (platform_sp)
2049 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2050 return 0;
2051}
2052
Chris Lattner24943d22010-06-08 16:52:24 +00002053Error
2054Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2055{
2056 Error error;
2057 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002058 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002059 const addr_t bp_addr = bp_site->GetLoadAddress();
2060 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002061 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002062 if (bp_site->IsEnabled())
2063 {
2064 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002065 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 +00002066 return error;
2067 }
2068
2069 if (bp_addr == LLDB_INVALID_ADDRESS)
2070 {
2071 error.SetErrorString("BreakpointSite contains an invalid load address.");
2072 return error;
2073 }
2074 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2075 // trap for the breakpoint site
2076 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2077
2078 if (bp_opcode_size == 0)
2079 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002080 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002081 }
2082 else
2083 {
2084 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2085
2086 if (bp_opcode_bytes == NULL)
2087 {
2088 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2089 return error;
2090 }
2091
2092 // Save the original opcode by reading it
2093 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2094 {
2095 // Write a software breakpoint in place of the original opcode
2096 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2097 {
2098 uint8_t verify_bp_opcode_bytes[64];
2099 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2100 {
2101 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2102 {
2103 bp_site->SetEnabled(true);
2104 bp_site->SetType (BreakpointSite::eSoftware);
2105 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002106 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner24943d22010-06-08 16:52:24 +00002107 bp_site->GetID(),
2108 (uint64_t)bp_addr);
2109 }
2110 else
Greg Clayton9c236732011-10-26 00:56:27 +00002111 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00002112 }
2113 else
2114 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2115 }
2116 else
2117 error.SetErrorString("Unable to write breakpoint trap to memory.");
2118 }
2119 else
2120 error.SetErrorString("Unable to read memory at breakpoint address.");
2121 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002122 if (log && error.Fail())
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002123 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002124 bp_site->GetID(),
2125 (uint64_t)bp_addr,
2126 error.AsCString());
2127 return error;
2128}
2129
2130Error
2131Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2132{
2133 Error error;
2134 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002135 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002136 addr_t bp_addr = bp_site->GetLoadAddress();
2137 lldb::user_id_t breakID = bp_site->GetID();
2138 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002139 log->Printf ("Process::DisableBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002140
2141 if (bp_site->IsHardware())
2142 {
2143 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2144 }
2145 else if (bp_site->IsEnabled())
2146 {
2147 const size_t break_op_size = bp_site->GetByteSize();
2148 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2149 if (break_op_size > 0)
2150 {
2151 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002152 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002153 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002154 bool break_op_found = false;
2155
2156 // Read the breakpoint opcode
2157 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2158 {
2159 bool verify = false;
2160 // Make sure we have the a breakpoint opcode exists at this address
2161 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2162 {
2163 break_op_found = true;
2164 // We found a valid breakpoint opcode at this address, now restore
2165 // the saved opcode.
2166 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2167 {
2168 verify = true;
2169 }
2170 else
2171 error.SetErrorString("Memory write failed when restoring original opcode.");
2172 }
2173 else
2174 {
2175 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2176 // Set verify to true and so we can check if the original opcode has already been restored
2177 verify = true;
2178 }
2179
2180 if (verify)
2181 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002182 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002183 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002184 // Verify that our original opcode made it back to the inferior
2185 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2186 {
2187 // compare the memory we just read with the original opcode
2188 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2189 {
2190 // SUCCESS
2191 bp_site->SetEnabled(false);
2192 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002193 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 +00002194 return error;
2195 }
2196 else
2197 {
2198 if (break_op_found)
2199 error.SetErrorString("Failed to restore original opcode.");
2200 }
2201 }
2202 else
2203 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2204 }
2205 }
2206 else
2207 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2208 }
2209 }
2210 else
2211 {
2212 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002213 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 +00002214 return error;
2215 }
2216
2217 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002218 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002219 bp_site->GetID(),
2220 (uint64_t)bp_addr,
2221 error.AsCString());
2222 return error;
2223
2224}
2225
Greg Claytonfd119992011-01-07 06:08:19 +00002226// Uncomment to verify memory caching works after making changes to caching code
2227//#define VERIFY_MEMORY_READS
2228
Sean Callananf90b5f32012-06-07 22:26:42 +00002229size_t
2230Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2231{
2232 if (!GetDisableMemoryCache())
2233 {
Greg Claytonfd119992011-01-07 06:08:19 +00002234#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002235 // Memory caching is enabled, with debug verification
2236
2237 if (buf && size)
2238 {
2239 // Uncomment the line below to make sure memory caching is working.
2240 // I ran this through the test suite and got no assertions, so I am
2241 // pretty confident this is working well. If any changes are made to
2242 // memory caching, uncomment the line below and test your changes!
2243
2244 // Verify all memory reads by using the cache first, then redundantly
2245 // reading the same memory from the inferior and comparing to make sure
2246 // everything is exactly the same.
2247 std::string verify_buf (size, '\0');
2248 assert (verify_buf.size() == size);
2249 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2250 Error verify_error;
2251 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2252 assert (cache_bytes_read == verify_bytes_read);
2253 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2254 assert (verify_error.Success() == error.Success());
2255 return cache_bytes_read;
2256 }
2257 return 0;
2258#else // !defined(VERIFY_MEMORY_READS)
2259 // Memory caching is enabled, without debug verification
2260
2261 return m_memory_cache.Read (addr, buf, size, error);
2262#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002263 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002264 else
2265 {
2266 // Memory caching is disabled
2267
2268 return ReadMemoryFromInferior (addr, buf, size, error);
2269 }
Greg Claytonfd119992011-01-07 06:08:19 +00002270}
Greg Claytonfd119992011-01-07 06:08:19 +00002271
Greg Claytondd29b972012-05-18 23:20:01 +00002272size_t
2273Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2274{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002275 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002276 out_str.clear();
2277 addr_t curr_addr = addr;
2278 while (1)
2279 {
2280 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2281 if (length == 0)
2282 break;
2283 out_str.append(buf, length);
2284 // If we got "length - 1" bytes, we didn't get the whole C string, we
2285 // need to read some more characters
2286 if (length == sizeof(buf) - 1)
2287 curr_addr += length;
2288 else
2289 break;
2290 }
2291 return out_str.size();
2292}
2293
Greg Claytonfd119992011-01-07 06:08:19 +00002294
2295size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002296Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002297{
2298 size_t total_cstr_len = 0;
2299 if (dst && dst_max_len)
2300 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002301 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002302 // NULL out everything just to be safe
2303 memset (dst, 0, dst_max_len);
2304 Error error;
2305 addr_t curr_addr = addr;
2306 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2307 size_t bytes_left = dst_max_len - 1;
2308 char *curr_dst = dst;
2309
2310 while (bytes_left > 0)
2311 {
2312 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2313 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2314 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2315
2316 if (bytes_read == 0)
2317 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002318 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002319 dst[total_cstr_len] = '\0';
2320 break;
2321 }
2322 const size_t len = strlen(curr_dst);
2323
2324 total_cstr_len += len;
2325
2326 if (len < bytes_to_read)
2327 break;
2328
2329 curr_dst += bytes_read;
2330 curr_addr += bytes_read;
2331 bytes_left -= bytes_read;
2332 }
2333 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002334 else
2335 {
2336 if (dst == NULL)
2337 result_error.SetErrorString("invalid arguments");
2338 else
2339 result_error.Clear();
2340 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002341 return total_cstr_len;
2342}
2343
2344size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002345Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2346{
Chris Lattner24943d22010-06-08 16:52:24 +00002347 if (buf == NULL || size == 0)
2348 return 0;
2349
2350 size_t bytes_read = 0;
2351 uint8_t *bytes = (uint8_t *)buf;
2352
2353 while (bytes_read < size)
2354 {
2355 const size_t curr_size = size - bytes_read;
2356 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2357 bytes + bytes_read,
2358 curr_size,
2359 error);
2360 bytes_read += curr_bytes_read;
2361 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2362 break;
2363 }
2364
2365 // Replace any software breakpoint opcodes that fall into this range back
2366 // into "buf" before we return
2367 if (bytes_read > 0)
2368 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2369 return bytes_read;
2370}
2371
Greg Claytonf72fdee2010-12-16 20:01:20 +00002372uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002373Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002374{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002375 Scalar scalar;
2376 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2377 return scalar.ULongLong(fail_value);
2378 return fail_value;
2379}
2380
2381addr_t
2382Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2383{
2384 Scalar scalar;
2385 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2386 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2387 return LLDB_INVALID_ADDRESS;
2388}
2389
2390
2391bool
2392Process::WritePointerToMemory (lldb::addr_t vm_addr,
2393 lldb::addr_t ptr_value,
2394 Error &error)
2395{
2396 Scalar scalar;
2397 const uint32_t addr_byte_size = GetAddressByteSize();
2398 if (addr_byte_size <= 4)
2399 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002400 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002401 scalar = ptr_value;
2402 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002403}
2404
Chris Lattner24943d22010-06-08 16:52:24 +00002405size_t
2406Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2407{
2408 size_t bytes_written = 0;
2409 const uint8_t *bytes = (const uint8_t *)buf;
2410
2411 while (bytes_written < size)
2412 {
2413 const size_t curr_size = size - bytes_written;
2414 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2415 bytes + bytes_written,
2416 curr_size,
2417 error);
2418 bytes_written += curr_bytes_written;
2419 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2420 break;
2421 }
2422 return bytes_written;
2423}
2424
2425size_t
2426Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2427{
Greg Claytonfd119992011-01-07 06:08:19 +00002428#if defined (ENABLE_MEMORY_CACHING)
2429 m_memory_cache.Flush (addr, size);
2430#endif
2431
Chris Lattner24943d22010-06-08 16:52:24 +00002432 if (buf == NULL || size == 0)
2433 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002434
Jim Ingham21f37ad2011-08-09 02:12:22 +00002435 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002436
Chris Lattner24943d22010-06-08 16:52:24 +00002437 // We need to write any data that would go where any current software traps
2438 // (enabled software breakpoints) any software traps (breakpoints) that we
2439 // may have placed in our tasks memory.
2440
2441 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2442 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2443
2444 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002445 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002446
2447 BreakpointSiteList::collection::const_iterator pos;
2448 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002449 addr_t intersect_addr = 0;
2450 size_t intersect_size = 0;
2451 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002452 const uint8_t *ubuf = (const uint8_t *)buf;
2453
2454 for (pos = iter; pos != end; ++pos)
2455 {
2456 BreakpointSiteSP bp;
2457 bp = pos->second;
2458
2459 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2460 assert(addr <= intersect_addr && intersect_addr < addr + size);
2461 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2462 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2463
2464 // Check for bytes before this breakpoint
2465 const addr_t curr_addr = addr + bytes_written;
2466 if (intersect_addr > curr_addr)
2467 {
2468 // There are some bytes before this breakpoint that we need to
2469 // just write to memory
2470 size_t curr_size = intersect_addr - curr_addr;
2471 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2472 ubuf + bytes_written,
2473 curr_size,
2474 error);
2475 bytes_written += curr_bytes_written;
2476 if (curr_bytes_written != curr_size)
2477 {
2478 // We weren't able to write all of the requested bytes, we
2479 // are done looping and will return the number of bytes that
2480 // we have written so far.
2481 break;
2482 }
2483 }
2484
2485 // Now write any bytes that would cover up any software breakpoints
2486 // directly into the breakpoint opcode buffer
2487 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2488 bytes_written += intersect_size;
2489 }
2490
2491 // Write any remaining bytes after the last breakpoint if we have any left
2492 if (bytes_written < size)
2493 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2494 ubuf + bytes_written,
2495 size - bytes_written,
2496 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002497
Chris Lattner24943d22010-06-08 16:52:24 +00002498 return bytes_written;
2499}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002500
2501size_t
2502Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2503{
2504 if (byte_size == UINT32_MAX)
2505 byte_size = scalar.GetByteSize();
2506 if (byte_size > 0)
2507 {
2508 uint8_t buf[32];
2509 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2510 if (mem_size > 0)
2511 return WriteMemory(addr, buf, mem_size, error);
2512 else
2513 error.SetErrorString ("failed to get scalar as memory data");
2514 }
2515 else
2516 {
2517 error.SetErrorString ("invalid scalar value");
2518 }
2519 return 0;
2520}
2521
2522size_t
2523Process::ReadScalarIntegerFromMemory (addr_t addr,
2524 uint32_t byte_size,
2525 bool is_signed,
2526 Scalar &scalar,
2527 Error &error)
2528{
2529 uint64_t uval;
2530
2531 if (byte_size <= sizeof(uval))
2532 {
2533 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2534 if (bytes_read == byte_size)
2535 {
2536 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2537 uint32_t offset = 0;
2538 if (byte_size <= 4)
2539 scalar = data.GetMaxU32 (&offset, byte_size);
2540 else
2541 scalar = data.GetMaxU64 (&offset, byte_size);
2542
2543 if (is_signed)
2544 scalar.SignExtend(byte_size * 8);
2545 return bytes_read;
2546 }
2547 }
2548 else
2549 {
2550 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2551 }
2552 return 0;
2553}
2554
Greg Clayton613b8732011-05-17 03:37:42 +00002555#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002556addr_t
2557Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2558{
Jim Inghame6bd1422011-06-20 17:32:44 +00002559 if (GetPrivateState() != eStateStopped)
2560 return LLDB_INVALID_ADDRESS;
2561
Greg Clayton613b8732011-05-17 03:37:42 +00002562#if defined (USE_ALLOCATE_MEMORY_CACHE)
2563 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2564#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002565 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2566 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2567 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002568 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 +00002569 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002570 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002571 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002572 m_mod_id.GetStopID(),
2573 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002574 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002575#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002576}
2577
Sean Callanan6cf6c472011-09-20 23:01:51 +00002578bool
2579Process::CanJIT ()
2580{
Sean Callanan04200f62012-02-14 22:50:38 +00002581 if (m_can_jit == eCanJITDontKnow)
2582 {
2583 Error err;
2584
2585 uint64_t allocated_memory = AllocateMemory(8,
2586 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2587 err);
2588
2589 if (err.Success())
2590 m_can_jit = eCanJITYes;
2591 else
2592 m_can_jit = eCanJITNo;
2593
2594 DeallocateMemory (allocated_memory);
2595 }
2596
Sean Callanan6cf6c472011-09-20 23:01:51 +00002597 return m_can_jit == eCanJITYes;
2598}
2599
2600void
2601Process::SetCanJIT (bool can_jit)
2602{
2603 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2604}
2605
Chris Lattner24943d22010-06-08 16:52:24 +00002606Error
2607Process::DeallocateMemory (addr_t ptr)
2608{
Greg Clayton613b8732011-05-17 03:37:42 +00002609 Error error;
2610#if defined (USE_ALLOCATE_MEMORY_CACHE)
2611 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2612 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002613 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Clayton613b8732011-05-17 03:37:42 +00002614 }
2615#else
2616 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002617
2618 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2619 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002620 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 +00002621 ptr,
2622 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002623 m_mod_id.GetStopID(),
2624 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002625#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002626 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002627}
2628
Han Ming Ong2529aa32012-11-17 00:33:14 +00002629
Greg Claytonb5a8f142012-02-05 02:38:54 +00002630ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002631Process::ReadModuleFromMemory (const FileSpec& file_spec,
2632 lldb::addr_t header_addr,
2633 bool add_image_to_target,
2634 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002635{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002636 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002637 if (module_sp)
2638 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002639 Error error;
2640 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2641 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002642 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002643 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002644 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002645 m_target.GetImages().Append(module_sp);
2646 if (load_sections_in_target)
2647 {
2648 bool changed = false;
2649 module_sp->SetLoadAddress (m_target, 0, changed);
2650 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002651 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002652 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002653 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002654 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002655 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002656}
Chris Lattner24943d22010-06-08 16:52:24 +00002657
2658Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002659Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002660{
2661 Error error;
2662 error.SetErrorString("watchpoints are not supported");
2663 return error;
2664}
2665
2666Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002667Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002668{
2669 Error error;
2670 error.SetErrorString("watchpoints are not supported");
2671 return error;
2672}
2673
2674StateType
2675Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2676{
2677 StateType state;
2678 // Now wait for the process to launch and return control to us, and then
2679 // call DidLaunch:
2680 while (1)
2681 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002682 event_sp.reset();
2683 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2684
Greg Clayton20206082011-11-17 01:23:07 +00002685 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002686 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002687
2688 // If state is invalid, then we timed out
2689 if (state == eStateInvalid)
2690 break;
2691
2692 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002693 HandlePrivateEvent (event_sp);
2694 }
2695 return state;
2696}
2697
2698Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002699Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002700{
2701 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002702 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002703 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002704 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002705 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002706
Greg Clayton5beb99d2011-08-11 02:48:45 +00002707 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002708 if (exe_module)
2709 {
Greg Clayton180546b2011-04-30 01:09:13 +00002710 char local_exec_file_path[PATH_MAX];
2711 char platform_exec_file_path[PATH_MAX];
2712 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2713 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002714 if (exe_module->GetFileSpec().Exists())
2715 {
Greg Claytona2f74232011-02-24 22:24:29 +00002716 if (PrivateStateThreadIsValid ())
2717 PausePrivateStateThread ();
2718
Chris Lattner24943d22010-06-08 16:52:24 +00002719 error = WillLaunch (exe_module);
2720 if (error.Success())
2721 {
Greg Claytond8c62532010-10-07 04:19:01 +00002722 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002723 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002724
Greg Clayton777c6b72012-09-04 20:29:05 +00002725 if (m_run_lock.WriteTryLock())
2726 {
2727 // Now launch using these arguments.
2728 error = DoLaunch (exe_module, launch_info);
2729 }
2730 else
2731 {
2732 // This shouldn't happen
2733 error.SetErrorString("failed to acquire process run lock");
2734 }
Chris Lattner24943d22010-06-08 16:52:24 +00002735
2736 if (error.Fail())
2737 {
2738 if (GetID() != LLDB_INVALID_PROCESS_ID)
2739 {
2740 SetID (LLDB_INVALID_PROCESS_ID);
2741 const char *error_string = error.AsCString();
2742 if (error_string == NULL)
2743 error_string = "launch failed";
2744 SetExitStatus (-1, error_string);
2745 }
2746 }
2747 else
2748 {
2749 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002750 TimeValue timeout_time;
2751 timeout_time = TimeValue::Now();
2752 timeout_time.OffsetWithSeconds(10);
2753 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002754
Greg Clayton49859592011-06-22 01:42:17 +00002755 if (state == eStateInvalid || event_sp.get() == NULL)
2756 {
2757 // We were able to launch the process, but we failed to
2758 // catch the initial stop.
2759 SetExitStatus (0, "failed to catch stop after launch");
2760 Destroy();
2761 }
2762 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002763 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002764
Chris Lattner24943d22010-06-08 16:52:24 +00002765 DidLaunch ();
2766
Greg Clayton9ce95382012-02-13 23:10:39 +00002767 DynamicLoader *dyld = GetDynamicLoader ();
2768 if (dyld)
2769 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002770
Greg Clayton37f962e2011-08-22 02:49:39 +00002771 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002772 // This delays passing the stopped event to listeners till DidLaunch gets
2773 // a chance to complete...
2774 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002775
2776 if (PrivateStateThreadIsValid ())
2777 ResumePrivateStateThread ();
2778 else
2779 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002780 }
2781 else if (state == eStateExited)
2782 {
2783 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2784 // not likely to work, and return an invalid pid.
2785 HandlePrivateEvent (event_sp);
2786 }
2787 }
2788 }
2789 }
2790 else
2791 {
Greg Clayton9c236732011-10-26 00:56:27 +00002792 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002793 }
2794 }
2795 return error;
2796}
2797
Greg Clayton46c9a352012-02-09 06:16:32 +00002798
2799Error
2800Process::LoadCore ()
2801{
2802 Error error = DoLoadCore();
2803 if (error.Success())
2804 {
2805 if (PrivateStateThreadIsValid ())
2806 ResumePrivateStateThread ();
2807 else
2808 StartPrivateStateThread ();
2809
Greg Clayton9ce95382012-02-13 23:10:39 +00002810 DynamicLoader *dyld = GetDynamicLoader ();
2811 if (dyld)
2812 dyld->DidAttach();
2813
2814 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002815 // We successfully loaded a core file, now pretend we stopped so we can
2816 // show all of the threads in the core file and explore the crashed
2817 // state.
2818 SetPrivateState (eStateStopped);
2819
2820 }
2821 return error;
2822}
2823
Greg Clayton9ce95382012-02-13 23:10:39 +00002824DynamicLoader *
2825Process::GetDynamicLoader ()
2826{
2827 if (m_dyld_ap.get() == NULL)
2828 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2829 return m_dyld_ap.get();
2830}
Greg Clayton46c9a352012-02-09 06:16:32 +00002831
2832
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002833Process::NextEventAction::EventActionResult
2834Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002835{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002836 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2837 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002838 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002839 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002840 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002841 return eEventActionRetry;
2842
2843 case eStateStopped:
2844 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002845 {
2846 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002847 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002848 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2849 if (m_exec_count > 0)
2850 {
2851 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002852 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002853 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002854 return eEventActionRetry;
2855 }
2856 else
2857 {
2858 m_process->CompleteAttach ();
2859 return eEventActionSuccess;
2860 }
2861 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002862 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002863
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002864 default:
2865 case eStateExited:
2866 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002867 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002868 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002869
2870 m_exit_string.assign ("No valid Process");
2871 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002872}
Chris Lattner24943d22010-06-08 16:52:24 +00002873
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002874Process::NextEventAction::EventActionResult
2875Process::AttachCompletionHandler::HandleBeingInterrupted()
2876{
2877 return eEventActionSuccess;
2878}
2879
2880const char *
2881Process::AttachCompletionHandler::GetExitString ()
2882{
2883 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002884}
2885
2886Error
Greg Clayton527154d2011-11-15 03:53:30 +00002887Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002888{
Chris Lattner24943d22010-06-08 16:52:24 +00002889 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002890 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002891 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002892 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002893
Greg Clayton527154d2011-11-15 03:53:30 +00002894 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002895 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002896 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002897 {
Greg Clayton527154d2011-11-15 03:53:30 +00002898 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002899
Greg Clayton527154d2011-11-15 03:53:30 +00002900 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002901 {
Greg Clayton527154d2011-11-15 03:53:30 +00002902 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2903
2904 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002905 {
Greg Clayton527154d2011-11-15 03:53:30 +00002906 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2907 if (error.Success())
2908 {
Greg Claytond34a3b22012-10-12 16:10:12 +00002909 if (m_run_lock.WriteTryLock())
2910 {
2911 m_should_detach = true;
2912 SetPublicState (eStateAttaching);
2913 // Now attach using these arguments.
2914 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2915 }
2916 else
2917 {
2918 // This shouldn't happen
2919 error.SetErrorString("failed to acquire process run lock");
2920 }
Greg Claytonffa43a62011-11-17 04:46:02 +00002921
Greg Clayton527154d2011-11-15 03:53:30 +00002922 if (error.Fail())
2923 {
2924 if (GetID() != LLDB_INVALID_PROCESS_ID)
2925 {
2926 SetID (LLDB_INVALID_PROCESS_ID);
2927 if (error.AsCString() == NULL)
2928 error.SetErrorString("attach failed");
2929
2930 SetExitStatus(-1, error.AsCString());
2931 }
2932 }
2933 else
2934 {
2935 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2936 StartPrivateStateThread();
2937 }
2938 return error;
2939 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002940 }
Greg Clayton527154d2011-11-15 03:53:30 +00002941 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002942 {
Greg Clayton527154d2011-11-15 03:53:30 +00002943 ProcessInstanceInfoList process_infos;
2944 PlatformSP platform_sp (m_target.GetPlatform ());
2945
2946 if (platform_sp)
2947 {
2948 ProcessInstanceInfoMatch match_info;
2949 match_info.GetProcessInfo() = attach_info;
2950 match_info.SetNameMatchType (eNameMatchEquals);
2951 platform_sp->FindProcesses (match_info, process_infos);
2952 const uint32_t num_matches = process_infos.GetSize();
2953 if (num_matches == 1)
2954 {
2955 attach_pid = process_infos.GetProcessIDAtIndex(0);
2956 // Fall through and attach using the above process ID
2957 }
2958 else
2959 {
2960 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2961 if (num_matches > 1)
2962 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2963 else
2964 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2965 }
2966 }
2967 else
2968 {
2969 error.SetErrorString ("invalid platform, can't find processes by name");
2970 return error;
2971 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002972 }
Chris Lattner24943d22010-06-08 16:52:24 +00002973 }
2974 else
Greg Clayton527154d2011-11-15 03:53:30 +00002975 {
2976 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002977 }
2978 }
Greg Clayton527154d2011-11-15 03:53:30 +00002979
2980 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002981 {
Greg Clayton527154d2011-11-15 03:53:30 +00002982 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002983 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002984 {
Greg Clayton527154d2011-11-15 03:53:30 +00002985
Greg Claytond34a3b22012-10-12 16:10:12 +00002986 if (m_run_lock.WriteTryLock())
2987 {
2988 // Now attach using these arguments.
2989 m_should_detach = true;
2990 SetPublicState (eStateAttaching);
2991 error = DoAttachToProcessWithID (attach_pid, attach_info);
2992 }
2993 else
2994 {
2995 // This shouldn't happen
2996 error.SetErrorString("failed to acquire process run lock");
2997 }
2998
Greg Clayton527154d2011-11-15 03:53:30 +00002999 if (error.Success())
3000 {
3001
3002 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3003 StartPrivateStateThread();
3004 }
3005 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003006 {
3007 if (GetID() != LLDB_INVALID_PROCESS_ID)
3008 {
3009 SetID (LLDB_INVALID_PROCESS_ID);
3010 const char *error_string = error.AsCString();
3011 if (error_string == NULL)
3012 error_string = "attach failed";
3013
3014 SetExitStatus(-1, error_string);
3015 }
3016 }
Chris Lattner24943d22010-06-08 16:52:24 +00003017 }
3018 }
3019 return error;
3020}
3021
Greg Clayton75c703d2011-02-16 04:46:07 +00003022void
3023Process::CompleteAttach ()
3024{
3025 // Let the process subclass figure out at much as it can about the process
3026 // before we go looking for a dynamic loader plug-in.
3027 DidAttach();
3028
Jim Ingham0d7f7772011-09-15 01:10:17 +00003029 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3030 // the same as the one we've already set, switch architectures.
3031 PlatformSP platform_sp (m_target.GetPlatform ());
3032 assert (platform_sp.get());
3033 if (platform_sp)
3034 {
Greg Claytonb170aee2012-05-08 01:45:38 +00003035 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Claytonaad2b0f2013-01-11 20:49:54 +00003036 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Claytonb170aee2012-05-08 01:45:38 +00003037 {
3038 ArchSpec platform_arch;
3039 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3040 if (platform_sp)
3041 {
3042 m_target.SetPlatform (platform_sp);
3043 m_target.SetArchitecture(platform_arch);
3044 }
3045 }
3046 else
3047 {
3048 ProcessInstanceInfo process_info;
3049 platform_sp->GetProcessInfo (GetID(), process_info);
3050 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callanan40e278c2012-12-13 22:07:14 +00003051 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Claytonb170aee2012-05-08 01:45:38 +00003052 m_target.SetArchitecture (process_arch);
3053 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00003054 }
3055
3056 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00003057 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00003058 DynamicLoader *dyld = GetDynamicLoader ();
3059 if (dyld)
3060 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00003061
Greg Clayton37f962e2011-08-22 02:49:39 +00003062 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00003063 // Figure out which one is the executable, and set that in our target:
Enrico Granata146d9522012-11-08 02:22:02 +00003064 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham93367902012-05-30 02:19:25 +00003065 Mutex::Locker modules_locker(target_modules.GetMutex());
3066 size_t num_modules = target_modules.GetSize();
3067 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003068
Greg Clayton75c703d2011-02-16 04:46:07 +00003069 for (int i = 0; i < num_modules; i++)
3070 {
Jim Ingham93367902012-05-30 02:19:25 +00003071 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00003072 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00003073 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00003074 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00003075 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003076 break;
3077 }
3078 }
Jim Ingham93367902012-05-30 02:19:25 +00003079 if (new_executable_module_sp)
3080 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00003081}
3082
Chris Lattner24943d22010-06-08 16:52:24 +00003083Error
Jason Molendafac2e622012-09-29 04:02:01 +00003084Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00003085{
Greg Claytone71e2582011-02-04 01:58:07 +00003086 m_abi_sp.reset();
3087 m_process_input_reader.reset();
3088
3089 // Find the process and its architecture. Make sure it matches the architecture
3090 // of the current Target, and if not adjust it.
3091
Jason Molendafac2e622012-09-29 04:02:01 +00003092 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00003093 if (error.Success())
3094 {
Greg Claytona2f74232011-02-24 22:24:29 +00003095 if (GetID() != LLDB_INVALID_PROCESS_ID)
3096 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00003097 EventSP event_sp;
3098 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3099
3100 if (state == eStateStopped || state == eStateCrashed)
3101 {
3102 // If we attached and actually have a process on the other end, then
3103 // this ended up being the equivalent of an attach.
3104 CompleteAttach ();
3105
3106 // This delays passing the stopped event to listeners till
3107 // CompleteAttach gets a chance to complete...
3108 HandlePrivateEvent (event_sp);
3109
3110 }
Greg Claytona2f74232011-02-24 22:24:29 +00003111 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00003112
3113 if (PrivateStateThreadIsValid ())
3114 ResumePrivateStateThread ();
3115 else
3116 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00003117 }
3118 return error;
3119}
3120
3121
3122Error
Jim Ingham027aaa72012-04-19 01:40:33 +00003123Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00003124{
Jim Inghame1a654b2012-09-06 19:24:17 +00003125 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00003126 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00003127 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00003128 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00003129 StateAsCString(m_public_state.GetValue()),
3130 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00003131
3132 Error error (WillResume());
3133 // Tell the process it is about to resume before the thread list
3134 if (error.Success())
3135 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003136 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003137 // can let all of our threads know that they are about to be
3138 // resumed. Threads will each be called with
3139 // Thread::WillResume(StateType) where StateType contains the state
3140 // that they are supposed to have when the process is resumed
3141 // (suspended/running/stepping). Threads should also check
3142 // their resume signal in lldb::Thread::GetResumeSignal()
3143 // to see if they are suppoed to start back up with a signal.
3144 if (m_thread_list.WillResume())
3145 {
Jim Ingham1831e782012-04-07 00:00:41 +00003146 // Last thing, do the PreResumeActions.
3147 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003148 {
Jim Ingham1831e782012-04-07 00:00:41 +00003149 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3150 }
3151 else
3152 {
3153 m_mod_id.BumpResumeID();
3154 error = DoResume();
3155 if (error.Success())
3156 {
3157 DidResume();
3158 m_thread_list.DidResume();
3159 if (log)
3160 log->Printf ("Process thinks the process has resumed.");
3161 }
Chris Lattner24943d22010-06-08 16:52:24 +00003162 }
3163 }
3164 else
3165 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003166 // Somebody wanted to run without running. So generate a continue & a stopped event,
3167 // and let the world handle them.
3168 if (log)
3169 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3170
3171 SetPrivateState(eStateRunning);
3172 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003173 }
3174 }
Jim Inghamac959662011-01-24 06:34:17 +00003175 else if (log)
3176 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003177 return error;
3178}
3179
3180Error
3181Process::Halt ()
3182{
Jim Ingham43892562012-06-06 00:29:30 +00003183 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3184 // we could just straightaway get another event. It just narrows the window...
3185 m_currently_handling_event.WaitForValueEqualTo(false);
3186
3187
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003188 // Pause our private state thread so we can ensure no one else eats
3189 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003190 Listener halt_listener ("lldb.process.halt_listener");
3191 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003192
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003193 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003194 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003195
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003196 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003197 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003198
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003199 bool caused_stop = false;
3200
3201 // Ask the process subclass to actually halt our process
3202 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003203 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003204 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003205 if (m_public_state.GetValue() == eStateAttaching)
3206 {
3207 SetExitStatus(SIGKILL, "Cancelled async attach.");
3208 Destroy ();
3209 }
3210 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003211 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003212 // If "caused_stop" is true, then DoHalt stopped the process. If
3213 // "caused_stop" is false, the process was already stopped.
3214 // If the DoHalt caused the process to stop, then we want to catch
3215 // this event and set the interrupted bool to true before we pass
3216 // this along so clients know that the process was interrupted by
3217 // a halt command.
3218 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003219 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003220 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003221 TimeValue timeout_time;
3222 timeout_time = TimeValue::Now();
3223 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003224 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3225 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003226
Jim Inghamf9f40c22011-02-08 05:20:59 +00003227 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003228 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003229 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003230 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003231 }
3232 else
3233 {
Greg Clayton20206082011-11-17 01:23:07 +00003234 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003235 {
3236 // We caused the process to interrupt itself, so mark this
3237 // as such in the stop event so clients can tell an interrupted
3238 // process from a natural stop
3239 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3240 }
3241 else
3242 {
3243 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3244 if (log)
3245 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3246 error.SetErrorString ("Did not get stopped event after halt.");
3247 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003248 }
3249 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003250 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003251 }
3252 }
Chris Lattner24943d22010-06-08 16:52:24 +00003253 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003254 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003255 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003256
3257 // Post any event we might have consumed. If all goes well, we will have
3258 // stopped the process, intercepted the event and set the interrupted
3259 // bool in the event. Post it to the private event queue and that will end up
3260 // correctly setting the state.
3261 if (event_sp)
3262 m_private_state_broadcaster.BroadcastEvent(event_sp);
3263
Chris Lattner24943d22010-06-08 16:52:24 +00003264 return error;
3265}
3266
3267Error
3268Process::Detach ()
3269{
3270 Error error (WillDetach());
3271
3272 if (error.Success())
3273 {
3274 DisableAllBreakpointSites();
3275 error = DoDetach();
3276 if (error.Success())
3277 {
3278 DidDetach();
3279 StopPrivateStateThread();
3280 }
3281 }
3282 return error;
3283}
3284
3285Error
3286Process::Destroy ()
3287{
3288 Error error (WillDestroy());
3289 if (error.Success())
3290 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003291 EventSP exit_event_sp;
Jim Inghamf4928de2012-05-23 15:46:31 +00003292 if (m_public_state.GetValue() == eStateRunning)
3293 {
Greg Clayton38ae5b92012-09-05 00:37:58 +00003294 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003295 if (log)
3296 log->Printf("Process::Destroy() About to halt.");
Jim Inghamf4928de2012-05-23 15:46:31 +00003297 error = Halt();
3298 if (error.Success())
3299 {
3300 // Consume the halt event.
Jim Inghamf4928de2012-05-23 15:46:31 +00003301 TimeValue timeout (TimeValue::Now());
Jim Ingham43892562012-06-06 00:29:30 +00003302 timeout.OffsetWithSeconds(1);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003303 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3304 if (state != eStateExited)
3305 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3306
Jim Inghamf4928de2012-05-23 15:46:31 +00003307 if (state != eStateStopped)
3308 {
Jim Inghamf4928de2012-05-23 15:46:31 +00003309 if (log)
3310 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Ingham43892562012-06-06 00:29:30 +00003311 // If we really couldn't stop the process then we should just error out here, but if the
3312 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3313 StateType private_state = m_private_state.GetValue();
3314 if (private_state != eStateStopped && private_state != eStateExited)
3315 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003316 // If we exited when we were waiting for a process to stop, then
3317 // forward the event here so we don't lose the event
Jim Ingham43892562012-06-06 00:29:30 +00003318 return error;
3319 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003320 }
3321 }
3322 else
3323 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003324 if (log)
3325 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3326 return error;
Jim Inghamf4928de2012-05-23 15:46:31 +00003327 }
3328 }
Jim Ingham43892562012-06-06 00:29:30 +00003329
3330 if (m_public_state.GetValue() != eStateRunning)
3331 {
3332 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3333 // kill it, we don't want it hitting a breakpoint...
3334 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3335 // we're not going to have much luck doing this now.
3336 m_thread_list.DiscardThreadPlans();
3337 DisableAllBreakpointSites();
3338 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003339
Chris Lattner24943d22010-06-08 16:52:24 +00003340 error = DoDestroy();
3341 if (error.Success())
3342 {
3343 DidDestroy();
3344 StopPrivateStateThread();
3345 }
Caroline Tice861efb32010-11-16 05:07:41 +00003346 m_stdio_communication.StopReadThread();
3347 m_stdio_communication.Disconnect();
3348 if (m_process_input_reader && m_process_input_reader->IsActive())
3349 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3350 if (m_process_input_reader)
3351 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003352
3353 // If we exited when we were waiting for a process to stop, then
3354 // forward the event here so we don't lose the event
3355 if (exit_event_sp)
3356 {
3357 // Directly broadcast our exited event because we shut down our
3358 // private state thread above
3359 BroadcastEvent(exit_event_sp);
3360 }
3361
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003362 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3363 // the last events through the event system, in which case we might strand the write lock. Unlock
3364 // it here so when we do to tear down the process we don't get an error destroying the lock.
3365 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003366 }
3367 return error;
3368}
3369
3370Error
3371Process::Signal (int signal)
3372{
3373 Error error (WillSignal());
3374 if (error.Success())
3375 {
3376 error = DoSignal(signal);
3377 if (error.Success())
3378 DidSignal();
3379 }
3380 return error;
3381}
3382
Greg Clayton395fc332011-02-15 21:59:32 +00003383lldb::ByteOrder
3384Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003385{
Greg Clayton395fc332011-02-15 21:59:32 +00003386 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003387}
3388
3389uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003390Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003391{
Greg Clayton395fc332011-02-15 21:59:32 +00003392 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003393}
3394
Greg Clayton395fc332011-02-15 21:59:32 +00003395
Chris Lattner24943d22010-06-08 16:52:24 +00003396bool
3397Process::ShouldBroadcastEvent (Event *event_ptr)
3398{
3399 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3400 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00003401 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003402
3403 switch (state)
3404 {
Greg Claytone71e2582011-02-04 01:58:07 +00003405 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003406 case eStateAttaching:
3407 case eStateLaunching:
3408 case eStateDetached:
3409 case eStateExited:
3410 case eStateUnloaded:
3411 // These events indicate changes in the state of the debugging session, always report them.
3412 return_value = true;
3413 break;
3414 case eStateInvalid:
3415 // We stopped for no apparent reason, don't report it.
3416 return_value = false;
3417 break;
3418 case eStateRunning:
3419 case eStateStepping:
3420 // If we've started the target running, we handle the cases where we
3421 // are already running and where there is a transition from stopped to
3422 // running differently.
3423 // running -> running: Automatically suppress extra running events
3424 // stopped -> running: Report except when there is one or more no votes
3425 // and no yes votes.
3426 SynchronouslyNotifyStateChanged (state);
3427 switch (m_public_state.GetValue())
3428 {
3429 case eStateRunning:
3430 case eStateStepping:
3431 // We always suppress multiple runnings with no PUBLIC stop in between.
3432 return_value = false;
3433 break;
3434 default:
3435 // TODO: make this work correctly. For now always report
3436 // run if we aren't running so we don't miss any runnning
3437 // events. If I run the lldb/test/thread/a.out file and
3438 // break at main.cpp:58, run and hit the breakpoints on
3439 // multiple threads, then somehow during the stepping over
3440 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003441
3442 // This is a transition from stop to run.
3443 switch (m_thread_list.ShouldReportRun (event_ptr))
3444 {
3445 case eVoteYes:
3446 case eVoteNoOpinion:
3447 return_value = true;
3448 break;
3449 case eVoteNo:
3450 return_value = false;
3451 break;
3452 }
3453 break;
3454 }
3455 break;
3456 case eStateStopped:
3457 case eStateCrashed:
3458 case eStateSuspended:
3459 {
3460 // We've stopped. First see if we're going to restart the target.
3461 // If we are going to stop, then we always broadcast the event.
3462 // 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 +00003463 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003464
3465 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003466 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003467 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003468 if (log)
3469 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003470 return true;
3471 }
3472 else
3473 {
Chris Lattner24943d22010-06-08 16:52:24 +00003474
3475 if (m_thread_list.ShouldStop (event_ptr) == false)
3476 {
Jim Ingham8290bba2012-09-05 21:13:56 +00003477 // ShouldStop may have restarted the target already. If so, don't
3478 // resume it twice.
3479 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00003480 switch (m_thread_list.ShouldReportStop (event_ptr))
3481 {
3482 case eVoteYes:
3483 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003484 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003485 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003486 case eVoteNo:
3487 return_value = false;
3488 break;
3489 }
3490
3491 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003492 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham8290bba2012-09-05 21:13:56 +00003493 if (!was_restarted)
3494 PrivateResume ();
Chris Lattner24943d22010-06-08 16:52:24 +00003495 }
3496 else
3497 {
3498 return_value = true;
3499 SynchronouslyNotifyStateChanged (state);
3500 }
3501 }
3502 }
3503 }
3504
3505 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003506 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003507 return return_value;
3508}
3509
Chris Lattner24943d22010-06-08 16:52:24 +00003510
3511bool
Jim Ingham1831e782012-04-07 00:00:41 +00003512Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003513{
Greg Claytone005f2c2010-11-06 01:53:30 +00003514 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003515
Greg Claytonb72d0f02011-04-12 05:54:46 +00003516 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003517 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003518 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3519
Jim Ingham1831e782012-04-07 00:00:41 +00003520 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003521 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003522
3523 // Create a thread that watches our internal state and controls which
3524 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003525 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003526 if (already_running)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003527 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham1831e782012-04-07 00:00:41 +00003528 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003529 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003530
3531 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003532 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003533 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3534 if (success)
3535 {
3536 ResumePrivateStateThread();
3537 return true;
3538 }
3539 else
3540 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003541}
3542
3543void
3544Process::PausePrivateStateThread ()
3545{
3546 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3547}
3548
3549void
3550Process::ResumePrivateStateThread ()
3551{
3552 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3553}
3554
3555void
3556Process::StopPrivateStateThread ()
3557{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003558 if (PrivateStateThreadIsValid ())
3559 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003560 else
3561 {
3562 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3563 if (log)
3564 printf ("Went to stop the private state thread, but it was already invalid.");
3565 }
Chris Lattner24943d22010-06-08 16:52:24 +00003566}
3567
3568void
3569Process::ControlPrivateStateThread (uint32_t signal)
3570{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003571 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003572
3573 assert (signal == eBroadcastInternalStateControlStop ||
3574 signal == eBroadcastInternalStateControlPause ||
3575 signal == eBroadcastInternalStateControlResume);
3576
3577 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003578 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003579
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003580 // Signal the private state thread. First we should copy this is case the
3581 // thread starts exiting since the private state thread will NULL this out
3582 // when it exits
3583 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003584 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003585 {
3586 TimeValue timeout_time;
3587 bool timed_out;
3588
3589 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3590
3591 timeout_time = TimeValue::Now();
3592 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003593 if (log)
3594 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003595 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3596 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3597
3598 if (signal == eBroadcastInternalStateControlStop)
3599 {
3600 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003601 {
3602 Error error;
3603 Host::ThreadCancel (private_state_thread, &error);
3604 if (log)
3605 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3606 }
3607 else
3608 {
3609 if (log)
3610 log->Printf ("The control event killed the private state thread without having to cancel.");
3611 }
Chris Lattner24943d22010-06-08 16:52:24 +00003612
3613 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003614 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003615 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003616 }
3617 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003618 else
3619 {
3620 if (log)
3621 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3622 }
Chris Lattner24943d22010-06-08 16:52:24 +00003623}
3624
3625void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003626Process::SendAsyncInterrupt ()
3627{
3628 if (PrivateStateThreadIsValid())
3629 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3630 else
3631 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3632}
3633
3634void
Chris Lattner24943d22010-06-08 16:52:24 +00003635Process::HandlePrivateEvent (EventSP &event_sp)
3636{
Greg Claytone005f2c2010-11-06 01:53:30 +00003637 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003638 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003639
Greg Clayton68ca8232011-01-25 02:58:48 +00003640 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003641
3642 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003643 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003644 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003645 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003646 switch (action_result)
3647 {
3648 case NextEventAction::eEventActionSuccess:
3649 SetNextEventAction(NULL);
3650 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003651
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003652 case NextEventAction::eEventActionRetry:
3653 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003654
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003655 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003656 // Handle Exiting Here. If we already got an exited event,
3657 // we should just propagate it. Otherwise, swallow this event,
3658 // and set our state to exit so the next event will kill us.
3659 if (new_state != eStateExited)
3660 {
3661 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003662 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003663 SetNextEventAction(NULL);
3664 return;
3665 }
3666 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003667 break;
3668 }
3669 }
3670
Chris Lattner24943d22010-06-08 16:52:24 +00003671 // See if we should broadcast this state to external clients?
3672 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003673
3674 if (should_broadcast)
3675 {
3676 if (log)
3677 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003678 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003679 __FUNCTION__,
3680 GetID(),
3681 StateAsCString(new_state),
3682 StateAsCString (GetState ()),
3683 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003684 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003685 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003686 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003687 PushProcessInputReader ();
3688 else
3689 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003690
Chris Lattner24943d22010-06-08 16:52:24 +00003691 BroadcastEvent (event_sp);
3692 }
3693 else
3694 {
3695 if (log)
3696 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003697 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003698 __FUNCTION__,
3699 GetID(),
3700 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003701 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003702 }
3703 }
Jim Ingham43892562012-06-06 00:29:30 +00003704 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003705}
3706
3707void *
3708Process::PrivateStateThread (void *arg)
3709{
3710 Process *proc = static_cast<Process*> (arg);
3711 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003712 return result;
3713}
3714
3715void *
3716Process::RunPrivateStateThread ()
3717{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003718 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003719 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003720
Greg Claytone005f2c2010-11-06 01:53:30 +00003721 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003722 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003723 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003724
3725 bool exit_now = false;
3726 while (!exit_now)
3727 {
3728 EventSP event_sp;
3729 WaitForEventsPrivate (NULL, event_sp, control_only);
3730 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3731 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003732 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003733 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 +00003734
Chris Lattner24943d22010-06-08 16:52:24 +00003735 switch (event_sp->GetType())
3736 {
3737 case eBroadcastInternalStateControlStop:
3738 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003739 break; // doing any internal state managment below
3740
3741 case eBroadcastInternalStateControlPause:
3742 control_only = true;
3743 break;
3744
3745 case eBroadcastInternalStateControlResume:
3746 control_only = false;
3747 break;
3748 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003749
Chris Lattner24943d22010-06-08 16:52:24 +00003750 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003751 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003752 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003753 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3754 {
3755 if (m_public_state.GetValue() == eStateAttaching)
3756 {
3757 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003758 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 +00003759 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3760 }
3761 else
3762 {
3763 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003764 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00003765 Halt();
3766 }
3767 continue;
3768 }
Chris Lattner24943d22010-06-08 16:52:24 +00003769
3770 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3771
3772 if (internal_state != eStateInvalid)
3773 {
3774 HandlePrivateEvent (event_sp);
3775 }
3776
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003777 if (internal_state == eStateInvalid ||
3778 internal_state == eStateExited ||
3779 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003780 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003781 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003782 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 +00003783
Chris Lattner24943d22010-06-08 16:52:24 +00003784 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003785 }
Chris Lattner24943d22010-06-08 16:52:24 +00003786 }
3787
Caroline Tice926060e2010-10-29 21:48:37 +00003788 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003789 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003790 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003791
Greg Claytona4881d02011-01-22 07:12:45 +00003792 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3793 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003794 return NULL;
3795}
3796
Chris Lattner24943d22010-06-08 16:52:24 +00003797//------------------------------------------------------------------
3798// Process Event Data
3799//------------------------------------------------------------------
3800
3801Process::ProcessEventData::ProcessEventData () :
3802 EventData (),
3803 m_process_sp (),
3804 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003805 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003806 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003807 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003808{
3809}
3810
3811Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3812 EventData (),
3813 m_process_sp (process_sp),
3814 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003815 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003816 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003817 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003818{
3819}
3820
3821Process::ProcessEventData::~ProcessEventData()
3822{
3823}
3824
3825const ConstString &
3826Process::ProcessEventData::GetFlavorString ()
3827{
3828 static ConstString g_flavor ("Process::ProcessEventData");
3829 return g_flavor;
3830}
3831
3832const ConstString &
3833Process::ProcessEventData::GetFlavor () const
3834{
3835 return ProcessEventData::GetFlavorString ();
3836}
3837
Chris Lattner24943d22010-06-08 16:52:24 +00003838void
3839Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3840{
3841 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003842 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3843 // the public event queue, then other times when we're pretending that this is where we stopped at the
3844 // end of expression evaluation. m_update_state is used to distinguish these
3845 // three cases; it is 0 when we're just pulling it off for private handling,
3846 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003847
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003848 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003849 return;
3850
3851 m_process_sp->SetPublicState (m_state);
3852
3853 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3854 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003855 {
3856 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003857 uint32_t num_threads = curr_thread_list.GetSize();
3858 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003859
Jim Ingham21f37ad2011-08-09 02:12:22 +00003860 // The actions might change one of the thread's stop_info's opinions about whether we should
3861 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003862
3863 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3864 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3865 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3866 // 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
3867 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003868 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003869 for (idx = 0; idx < num_threads; ++idx)
3870 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3871
Jim Inghamb6059b22012-12-13 22:24:15 +00003872 // Use this to track whether we should continue from here. We will only continue the target running if
3873 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
3874 // then it doesn't matter what the other threads say...
3875
3876 bool still_should_stop = false;
Jim Ingham21f37ad2011-08-09 02:12:22 +00003877
Chris Lattner24943d22010-06-08 16:52:24 +00003878 for (idx = 0; idx < num_threads; ++idx)
3879 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003880 curr_thread_list = m_process_sp->GetThreadList();
3881 if (curr_thread_list.GetSize() != num_threads)
3882 {
3883 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003884 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003885 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 +00003886 break;
3887 }
3888
3889 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3890
3891 if (thread_sp->GetIndexID() != thread_index_array[idx])
3892 {
3893 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003894 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003895 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003896 idx,
3897 thread_index_array[idx],
3898 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003899 break;
3900 }
3901
Jim Ingham6297a3a2010-10-20 00:39:53 +00003902 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00003903 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00003904 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003905 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003906 // The stop action might restart the target. If it does, then we want to mark that in the
3907 // event so that whoever is receiving it will know to wait for the running event and reflect
3908 // that state appropriately.
3909 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003910
3911 // FIXME: we might have run.
3912 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003913 {
3914 SetRestarted (true);
3915 break;
3916 }
Jim Inghamb6059b22012-12-13 22:24:15 +00003917
3918 bool this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
3919 if (still_should_stop == false)
3920 still_should_stop = this_thread_wants_to_stop;
Chris Lattner24943d22010-06-08 16:52:24 +00003921 }
3922 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003923
Jim Ingham21f37ad2011-08-09 02:12:22 +00003924
3925 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003926 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003927 if (!still_should_stop)
3928 {
3929 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003930 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00003931 // Use the public resume method here, since this is just
3932 // extending a public resume.
Jim Ingham21f37ad2011-08-09 02:12:22 +00003933 m_process_sp->Resume();
3934 }
3935 else
3936 {
3937 // If we didn't restart, run the Stop Hooks here:
3938 // They might also restart the target, so watch for that.
3939 m_process_sp->GetTarget().RunStopHooks();
3940 if (m_process_sp->GetPrivateState() == eStateRunning)
3941 SetRestarted(true);
3942 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003943 }
3944
Chris Lattner24943d22010-06-08 16:52:24 +00003945 }
3946}
3947
3948void
3949Process::ProcessEventData::Dump (Stream *s) const
3950{
3951 if (m_process_sp)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003952 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003953
Greg Claytonb72d0f02011-04-12 05:54:46 +00003954 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003955}
3956
3957const Process::ProcessEventData *
3958Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3959{
3960 if (event_ptr)
3961 {
3962 const EventData *event_data = event_ptr->GetData();
3963 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3964 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3965 }
3966 return NULL;
3967}
3968
3969ProcessSP
3970Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3971{
3972 ProcessSP process_sp;
3973 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3974 if (data)
3975 process_sp = data->GetProcessSP();
3976 return process_sp;
3977}
3978
3979StateType
3980Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3981{
3982 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3983 if (data == NULL)
3984 return eStateInvalid;
3985 else
3986 return data->GetState();
3987}
3988
3989bool
3990Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3991{
3992 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3993 if (data == NULL)
3994 return false;
3995 else
3996 return data->GetRestarted();
3997}
3998
3999void
4000Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4001{
4002 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4003 if (data != NULL)
4004 data->SetRestarted(new_value);
4005}
4006
4007bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00004008Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4009{
4010 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4011 if (data == NULL)
4012 return false;
4013 else
4014 return data->GetInterrupted ();
4015}
4016
4017void
4018Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4019{
4020 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4021 if (data != NULL)
4022 data->SetInterrupted(new_value);
4023}
4024
4025bool
Chris Lattner24943d22010-06-08 16:52:24 +00004026Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4027{
4028 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4029 if (data)
4030 {
4031 data->SetUpdateStateOnRemoval();
4032 return true;
4033 }
4034 return false;
4035}
4036
Greg Clayton289afcb2012-02-18 05:35:26 +00004037lldb::TargetSP
4038Process::CalculateTarget ()
4039{
4040 return m_target.shared_from_this();
4041}
4042
Chris Lattner24943d22010-06-08 16:52:24 +00004043void
Greg Claytona830adb2010-10-04 01:05:56 +00004044Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00004045{
Greg Clayton567e7f32011-09-22 04:58:26 +00004046 exe_ctx.SetTargetPtr (&m_target);
4047 exe_ctx.SetProcessPtr (this);
4048 exe_ctx.SetThreadPtr(NULL);
4049 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00004050}
4051
Greg Claytone4b9c1f2011-03-08 22:40:15 +00004052//uint32_t
4053//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4054//{
4055// return 0;
4056//}
4057//
4058//ArchSpec
4059//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4060//{
4061// return Host::GetArchSpecForExistingProcess (pid);
4062//}
4063//
4064//ArchSpec
4065//Process::GetArchSpecForExistingProcess (const char *process_name)
4066//{
4067// return Host::GetArchSpecForExistingProcess (process_name);
4068//}
4069//
Caroline Tice861efb32010-11-16 05:07:41 +00004070void
4071Process::AppendSTDOUT (const char * s, size_t len)
4072{
Greg Clayton20d338f2010-11-18 05:57:03 +00004073 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00004074 m_stdout_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004075 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00004076}
4077
4078void
Greg Claytonbd06ff42011-11-13 04:45:22 +00004079Process::AppendSTDERR (const char * s, size_t len)
4080{
4081 Mutex::Locker locker (m_stdio_communication_mutex);
4082 m_stderr_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004083 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004084}
4085
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004086void
4087Process::BroadcastAsyncProfileData(const char *s, size_t len)
4088{
4089 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004090 m_profile_data.push_back(s);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004091 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4092}
4093
4094size_t
4095Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4096{
4097 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004098 if (m_profile_data.empty())
4099 return 0;
4100
4101 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004102 if (bytes_available > 0)
4103 {
4104 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4105 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004106 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004107 if (bytes_available > buf_size)
4108 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004109 memcpy(buf, m_profile_data.front().data(), buf_size);
4110 m_profile_data.front().erase(0, buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004111 bytes_available = buf_size;
4112 }
4113 else
4114 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004115 memcpy(buf, m_profile_data.front().data(), bytes_available);
4116 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004117 }
4118 }
4119 return bytes_available;
4120}
4121
4122
Greg Claytonbd06ff42011-11-13 04:45:22 +00004123//------------------------------------------------------------------
4124// Process STDIO
4125//------------------------------------------------------------------
4126
4127size_t
4128Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4129{
4130 Mutex::Locker locker(m_stdio_communication_mutex);
4131 size_t bytes_available = m_stdout_data.size();
4132 if (bytes_available > 0)
4133 {
4134 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4135 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004136 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004137 if (bytes_available > buf_size)
4138 {
4139 memcpy(buf, m_stdout_data.c_str(), buf_size);
4140 m_stdout_data.erase(0, buf_size);
4141 bytes_available = buf_size;
4142 }
4143 else
4144 {
4145 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4146 m_stdout_data.clear();
4147 }
4148 }
4149 return bytes_available;
4150}
4151
4152
4153size_t
4154Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4155{
4156 Mutex::Locker locker(m_stdio_communication_mutex);
4157 size_t bytes_available = m_stderr_data.size();
4158 if (bytes_available > 0)
4159 {
4160 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4161 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004162 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004163 if (bytes_available > buf_size)
4164 {
4165 memcpy(buf, m_stderr_data.c_str(), buf_size);
4166 m_stderr_data.erase(0, buf_size);
4167 bytes_available = buf_size;
4168 }
4169 else
4170 {
4171 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4172 m_stderr_data.clear();
4173 }
4174 }
4175 return bytes_available;
4176}
4177
4178void
Caroline Tice861efb32010-11-16 05:07:41 +00004179Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4180{
4181 Process *process = (Process *) baton;
4182 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4183}
4184
4185size_t
4186Process::ProcessInputReaderCallback (void *baton,
4187 InputReader &reader,
4188 lldb::InputReaderAction notification,
4189 const char *bytes,
4190 size_t bytes_len)
4191{
4192 Process *process = (Process *) baton;
4193
4194 switch (notification)
4195 {
4196 case eInputReaderActivate:
4197 break;
4198
4199 case eInputReaderDeactivate:
4200 break;
4201
4202 case eInputReaderReactivate:
4203 break;
4204
Caroline Tice4a348082011-05-02 20:41:46 +00004205 case eInputReaderAsynchronousOutputWritten:
4206 break;
4207
Caroline Tice861efb32010-11-16 05:07:41 +00004208 case eInputReaderGotToken:
4209 {
4210 Error error;
4211 process->PutSTDIN (bytes, bytes_len, error);
4212 }
4213 break;
4214
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004215 case eInputReaderInterrupt:
4216 process->Halt ();
4217 break;
4218
4219 case eInputReaderEndOfFile:
4220 process->AppendSTDOUT ("^D", 2);
4221 break;
4222
Caroline Tice861efb32010-11-16 05:07:41 +00004223 case eInputReaderDone:
4224 break;
4225
4226 }
4227
4228 return bytes_len;
4229}
4230
4231void
4232Process::ResetProcessInputReader ()
4233{
4234 m_process_input_reader.reset();
4235}
4236
4237void
Greg Clayton464c6162011-11-17 22:14:31 +00004238Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004239{
4240 // First set up the Read Thread for reading/handling process I/O
4241
4242 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4243
4244 if (conn_ap.get())
4245 {
4246 m_stdio_communication.SetConnection (conn_ap.release());
4247 if (m_stdio_communication.IsConnected())
4248 {
4249 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4250 m_stdio_communication.StartReadThread();
4251
4252 // Now read thread is set up, set up input reader.
4253
4254 if (!m_process_input_reader.get())
4255 {
4256 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4257 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4258 this,
4259 eInputReaderGranularityByte,
4260 NULL,
4261 NULL,
4262 false));
4263
4264 if (err.Fail())
4265 m_process_input_reader.reset();
4266 }
4267 }
4268 }
4269}
4270
4271void
4272Process::PushProcessInputReader ()
4273{
4274 if (m_process_input_reader && !m_process_input_reader->IsActive())
4275 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4276}
4277
4278void
4279Process::PopProcessInputReader ()
4280{
4281 if (m_process_input_reader && m_process_input_reader->IsActive())
4282 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4283}
4284
Greg Claytond284b662011-02-18 01:44:25 +00004285// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004286void
Caroline Tice2a456812011-03-10 22:14:10 +00004287Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004288{
Greg Clayton73844aa2012-08-22 17:17:09 +00004289// static std::vector<OptionEnumValueElement> g_plugins;
4290//
4291// int i=0;
4292// const char *name;
4293// OptionEnumValueElement option_enum;
4294// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4295// {
4296// if (name)
4297// {
4298// option_enum.value = i;
4299// option_enum.string_value = name;
4300// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4301// g_plugins.push_back (option_enum);
4302// }
4303// ++i;
4304// }
4305// option_enum.value = 0;
4306// option_enum.string_value = NULL;
4307// option_enum.usage = NULL;
4308// g_plugins.push_back (option_enum);
4309//
4310// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4311// {
4312// if (::strcmp (name, "plugin") == 0)
4313// {
4314// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4315// break;
4316// }
4317// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004318//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004319 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004320}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004321
Greg Clayton990de7b2010-11-18 23:32:35 +00004322void
Caroline Tice2a456812011-03-10 22:14:10 +00004323Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004324{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004325 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004326}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004327
Greg Clayton427f2902010-12-14 02:59:59 +00004328ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004329Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004330 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004331 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004332 bool run_others,
Jim Inghamb7940202013-01-15 02:47:48 +00004333 bool unwind_on_error,
4334 bool ignore_breakpoints,
Jim Ingham47beabb2012-10-16 21:41:58 +00004335 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004336 Stream &errors)
4337{
4338 ExecutionResults return_value = eExecutionSetupError;
4339
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004340 if (thread_plan_sp.get() == NULL)
4341 {
4342 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004343 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004344 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004345
4346 if (exe_ctx.GetProcessPtr() != this)
4347 {
4348 errors.Printf("RunThreadPlan called on wrong process.");
4349 return eExecutionSetupError;
4350 }
4351
4352 Thread *thread = exe_ctx.GetThreadPtr();
4353 if (thread == NULL)
4354 {
4355 errors.Printf("RunThreadPlan called with invalid thread.");
4356 return eExecutionSetupError;
4357 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004358
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004359 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4360 // For that to be true the plan can't be private - since private plans suppress themselves in the
4361 // GetCompletedPlan call.
4362
4363 bool orig_plan_private = thread_plan_sp->GetPrivate();
4364 thread_plan_sp->SetPrivate(false);
4365
Jim Inghamac959662011-01-24 06:34:17 +00004366 if (m_private_state.GetValue() != eStateStopped)
4367 {
4368 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004369 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004370 }
4371
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004372 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004373 const uint32_t thread_idx_id = thread->GetIndexID();
4374 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004375
4376 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4377 // so we should arrange to reset them as well.
4378
Greg Clayton567e7f32011-09-22 04:58:26 +00004379 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004380
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004381 uint32_t selected_tid;
4382 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004383 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004384 {
4385 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004386 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004387 }
4388 else
4389 {
4390 selected_tid = LLDB_INVALID_THREAD_ID;
4391 }
4392
Jim Ingham1831e782012-04-07 00:00:41 +00004393 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004394 lldb::StateType old_state;
4395 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004396
Jim Inghamd21d98b2012-04-10 01:21:57 +00004397 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004398 if (Host::GetCurrentThread() == m_private_state_thread)
4399 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004400 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4401 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004402 // 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 +00004403 // we are fielding public events here.
4404 if (log)
Jason Molenda559cf6e2012-11-17 01:41:04 +00004405 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 +00004406
4407
Jim Ingham1831e782012-04-07 00:00:41 +00004408 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004409
4410 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4411 // returning control here.
4412 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4413 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4414 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4415 // do just what we want.
4416 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4417 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4418 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4419 old_state = m_public_state.GetValue();
4420 m_public_state.SetValueNoLock(eStateStopped);
4421
4422 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004423 StartPrivateStateThread(true);
4424 }
4425
4426 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004427
Jim Ingham6ae318c2011-01-23 21:14:08 +00004428 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004429
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004430 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004431
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004432 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004433 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4434 // restored on exit to the function.
4435 //
4436 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4437 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004438
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004439 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004440
Jim Ingham360f53f2010-11-30 02:22:11 +00004441 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004442 {
4443 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004444 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004445 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004446 thread->GetIndexID(),
4447 thread->GetID(),
4448 s.GetData());
4449 }
4450
4451 bool got_event;
4452 lldb::EventSP event_sp;
4453 lldb::StateType stop_state = lldb::eStateInvalid;
4454
4455 TimeValue* timeout_ptr = NULL;
4456 TimeValue real_timeout;
4457
4458 bool first_timeout = true;
4459 bool do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004460 bool handle_running_event = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004461 const uint64_t default_one_thread_timeout_usec = 250000;
4462 uint64_t computed_timeout = 0;
Jim Inghamb7940202013-01-15 02:47:48 +00004463 bool stopped_by_breakpoint = false;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004464
Jim Ingham76b258d2012-11-26 23:52:18 +00004465 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4466 // So don't call return anywhere within it.
4467
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004468 while (1)
4469 {
4470 // We usually want to resume the process if we get to the top of the loop.
4471 // The only exception is if we get two running events with no intervening
4472 // stop, which can happen, we will just wait for then next stop event.
4473
Jim Inghamb7940202013-01-15 02:47:48 +00004474 if (do_resume || handle_running_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004475 {
4476 // Do the initial resume and wait for the running event before going further.
4477
Jim Inghamb7940202013-01-15 02:47:48 +00004478 if (do_resume)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004479 {
Jim Inghamb7940202013-01-15 02:47:48 +00004480 Error resume_error = PrivateResume ();
4481 if (!resume_error.Success())
4482 {
4483 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4484 return_value = eExecutionSetupError;
4485 break;
4486 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004487 }
4488
4489 real_timeout = TimeValue::Now();
4490 real_timeout.OffsetWithMicroSeconds(500000);
4491 timeout_ptr = &real_timeout;
4492
4493 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4494 if (!got_event)
4495 {
4496 if (log)
4497 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4498
4499 errors.Printf("Didn't get any event after initial resume, exiting.");
4500 return_value = eExecutionSetupError;
4501 break;
4502 }
4503
4504 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4505 if (stop_state != eStateRunning)
4506 {
4507 if (log)
Jim Ingham47beabb2012-10-16 21:41:58 +00004508 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4509 "initial resume, got %s instead.",
4510 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004511
Jim Ingham47beabb2012-10-16 21:41:58 +00004512 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4513 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004514 return_value = eExecutionSetupError;
4515 break;
4516 }
4517
4518 if (log)
4519 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4520 // We need to call the function synchronously, so spin waiting for it to return.
4521 // If we get interrupted while executing, we're going to lose our context, and
4522 // won't be able to gather the result at this point.
4523 // We set the timeout AFTER the resume, since the resume takes some time and we
4524 // don't want to charge that to the timeout.
4525
Jim Ingham47beabb2012-10-16 21:41:58 +00004526 if (first_timeout)
4527 {
4528 if (run_others)
4529 {
4530 // If we are running all threads then we take half the time to run all threads, bounded by
4531 // .25 sec.
4532 if (timeout_usec == 0)
4533 computed_timeout = default_one_thread_timeout_usec;
4534 else
4535 {
4536 computed_timeout = timeout_usec / 2;
4537 if (computed_timeout > default_one_thread_timeout_usec)
4538 {
4539 computed_timeout = default_one_thread_timeout_usec;
4540 }
4541 timeout_usec -= computed_timeout;
4542 }
4543 }
4544 else
4545 {
4546 computed_timeout = timeout_usec;
4547 }
4548 }
4549 else
4550 {
4551 computed_timeout = timeout_usec;
4552 }
4553
4554 if (computed_timeout != 0)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004555 {
Enrico Granata6cca9692012-07-16 23:10:35 +00004556 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004557 real_timeout = TimeValue::Now();
Jim Ingham47beabb2012-10-16 21:41:58 +00004558 real_timeout.OffsetWithMicroSeconds(computed_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004559
4560 timeout_ptr = &real_timeout;
4561 }
Enrico Granata6cca9692012-07-16 23:10:35 +00004562 else
4563 {
Jim Ingham47beabb2012-10-16 21:41:58 +00004564 timeout_ptr = NULL;
Enrico Granata6cca9692012-07-16 23:10:35 +00004565 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004566 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004567 else
4568 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004569 if (log)
4570 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4571 do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004572 handle_running_event = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004573 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004574
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004575 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004576 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004577
Jim Inghamf9f40c22011-02-08 05:20:59 +00004578 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004579 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004580 if (timeout_ptr)
4581 {
4582 StreamString s;
4583 s.Printf ("about to wait - timeout is:\n ");
4584 timeout_ptr->Dump (&s, 120);
4585 s.Printf ("\nNow is:\n ");
4586 TimeValue::Now().Dump (&s, 120);
4587 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4588 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004589 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004590 {
4591 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4592 }
4593 }
4594
4595 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4596
4597 if (got_event)
4598 {
4599 if (event_sp.get())
4600 {
4601 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004602 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004603 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004604 Halt();
4605 keep_going = false;
4606 return_value = eExecutionInterrupted;
4607 errors.Printf ("Execution halted by user interrupt.");
4608 if (log)
4609 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4610 }
4611 else
4612 {
4613 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4614 if (log)
4615 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4616
4617 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004618 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004619 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004620 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004621 // Yay, we're done. Now make sure that our thread plan actually completed.
4622 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4623 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004624 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004625 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004626 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004627 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4628 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004629 }
4630 else
4631 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004632 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4633 StopReason stop_reason = eStopReasonInvalid;
4634 if (stop_info_sp)
4635 stop_reason = stop_info_sp->GetStopReason();
4636 if (stop_reason == eStopReasonPlanComplete)
4637 {
4638 if (log)
4639 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4640 // Now mark this plan as private so it doesn't get reported as the stop reason
4641 // after this point.
4642 if (thread_plan_sp)
4643 thread_plan_sp->SetPrivate (orig_plan_private);
4644 return_value = eExecutionCompleted;
4645 }
4646 else
4647 {
Jim Inghamb7940202013-01-15 02:47:48 +00004648 // Something restarted the target, so just wait for it to stop for real.
4649 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4650 {
4651 if (log)
4652 log->PutCString ("Process::RunThreadPlan(): Somebody stopped and then restarted, we'll continue waiting.");
4653 keep_going = true;
4654 do_resume = false;
4655 handle_running_event = true;
4656 }
4657 else
4658 {
4659 if (log)
4660 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
4661 if (stop_reason == eStopReasonBreakpoint)
4662 return_value = eExecutionHitBreakpoint;
4663 else
4664 return_value = eExecutionInterrupted;
4665 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004666 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004667 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004668 }
4669 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004670
Jim Ingham5d90ade2012-07-27 23:57:19 +00004671 case lldb::eStateCrashed:
4672 if (log)
4673 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4674 return_value = eExecutionInterrupted;
4675 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004676
Jim Ingham5d90ade2012-07-27 23:57:19 +00004677 case lldb::eStateRunning:
4678 do_resume = false;
4679 keep_going = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004680 handle_running_event = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004681 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004682
Jim Ingham5d90ade2012-07-27 23:57:19 +00004683 default:
4684 if (log)
4685 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4686
4687 if (stop_state == eStateExited)
4688 event_to_broadcast_sp = event_sp;
4689
Sean Callanan96abc622012-08-08 17:35:10 +00004690 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00004691 return_value = eExecutionInterrupted;
4692 break;
4693 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004694 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004695
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004696 if (keep_going)
4697 continue;
4698 else
4699 break;
4700 }
4701 else
4702 {
4703 if (log)
4704 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4705 return_value = eExecutionInterrupted;
4706 break;
4707 }
4708 }
4709 else
4710 {
4711 // If we didn't get an event that means we've timed out...
4712 // We will interrupt the process here. Depending on what we were asked to do we will
4713 // either exit, or try with all threads running for the same timeout.
4714 // Not really sure what to do if Halt fails here...
4715
4716 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00004717 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004718 {
4719 if (first_timeout)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004720 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %" PRId64 " timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004721 "trying for %d usec with all threads enabled.",
4722 computed_timeout, timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004723 else
4724 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00004725 "and timeout: %d timed out, abandoning execution.",
4726 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004727 }
4728 else
4729 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004730 "abandoning execution.",
4731 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004732 }
4733
4734 Error halt_error = Halt();
4735 if (halt_error.Success())
4736 {
4737 if (log)
4738 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4739
4740 // If halt succeeds, it always produces a stopped event. Wait for that:
4741
4742 real_timeout = TimeValue::Now();
4743 real_timeout.OffsetWithMicroSeconds(500000);
4744
4745 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4746
4747 if (got_event)
4748 {
4749 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4750 if (log)
4751 {
4752 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4753 if (stop_state == lldb::eStateStopped
4754 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4755 log->PutCString (" Event was the Halt interruption event.");
4756 }
4757
4758 if (stop_state == lldb::eStateStopped)
4759 {
4760 // Between the time we initiated the Halt and the time we delivered it, the process could have
4761 // already finished its job. Check that here:
4762
4763 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4764 {
4765 if (log)
4766 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4767 "Exiting wait loop.");
4768 return_value = eExecutionCompleted;
4769 break;
4770 }
4771
Jim Ingham47beabb2012-10-16 21:41:58 +00004772 if (!run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004773 {
4774 if (log)
4775 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4776 return_value = eExecutionInterrupted;
4777 break;
4778 }
4779
4780 if (first_timeout)
4781 {
4782 // Set all the other threads to run, and return to the top of the loop, which will continue;
4783 first_timeout = false;
4784 thread_plan_sp->SetStopOthers (false);
4785 if (log)
4786 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4787
4788 continue;
4789 }
4790 else
4791 {
4792 // Running all threads failed, so return Interrupted.
4793 if (log)
4794 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4795 return_value = eExecutionInterrupted;
4796 break;
4797 }
4798 }
4799 }
4800 else
4801 { if (log)
4802 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4803 "I'm getting out of here passing Interrupted.");
4804 return_value = eExecutionInterrupted;
4805 break;
4806 }
4807 }
4808 else
4809 {
4810 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4811 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4812 if (log)
4813 log->Printf ("Process::RunThreadPlan(): halt failed: error = \"%s\", I'm just going to wait a little longer and see if I get a stopped event.",
4814 halt_error.AsCString());
4815 real_timeout = TimeValue::Now();
4816 real_timeout.OffsetWithMicroSeconds(500000);
4817 timeout_ptr = &real_timeout;
4818 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4819 if (!got_event || event_sp.get() == NULL)
4820 {
4821 // This is not going anywhere, bag out.
4822 if (log)
4823 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4824 return_value = eExecutionInterrupted;
4825 break;
4826 }
4827 else
4828 {
4829 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4830 if (log)
4831 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4832 if (stop_state == lldb::eStateStopped)
4833 {
4834 // Between the time we initiated the Halt and the time we delivered it, the process could have
4835 // already finished its job. Check that here:
4836
4837 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4838 {
4839 if (log)
4840 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4841 "Exiting wait loop.");
4842 return_value = eExecutionCompleted;
4843 break;
4844 }
4845
4846 if (first_timeout)
4847 {
4848 // Set all the other threads to run, and return to the top of the loop, which will continue;
4849 first_timeout = false;
4850 thread_plan_sp->SetStopOthers (false);
4851 if (log)
4852 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4853
4854 continue;
4855 }
4856 else
4857 {
4858 // Running all threads failed, so return Interrupted.
4859 if (log)
4860 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4861 return_value = eExecutionInterrupted;
4862 break;
4863 }
4864 }
4865 else
4866 {
4867 if (log)
4868 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4869 " a stopped event, instead got %s.", StateAsCString(stop_state));
4870 return_value = eExecutionInterrupted;
4871 break;
4872 }
4873 }
4874 }
4875
4876 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004877 } // END WAIT LOOP
4878
4879 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4880 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4881 {
4882 StopPrivateStateThread();
4883 Error error;
4884 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00004885 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004886 {
4887 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4888 }
4889 m_public_state.SetValueNoLock(old_state);
4890
4891 }
4892
Jim Inghamb7940202013-01-15 02:47:48 +00004893 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
4894 // could happen:
4895 // 1) The execution successfully completed
4896 // 2) We hit a breakpoint, and ignore_breakpoints was true
4897 // 3) We got some other error, and discard_on_error was true
4898 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
4899 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham76b258d2012-11-26 23:52:18 +00004900
Jim Inghamb7940202013-01-15 02:47:48 +00004901 if (return_value == eExecutionCompleted
4902 || should_unwind)
Jim Ingham76b258d2012-11-26 23:52:18 +00004903 {
4904 thread_plan_sp->RestoreThreadState();
4905 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004906
4907 // Now do some processing on the results of the run:
Jim Inghamb7940202013-01-15 02:47:48 +00004908 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004909 {
4910 if (log)
4911 {
4912 StreamString s;
4913 if (event_sp)
4914 event_sp->Dump (&s);
4915 else
4916 {
4917 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4918 }
4919
4920 StreamString ts;
4921
4922 const char *event_explanation = NULL;
4923
4924 do
4925 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004926 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004927 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004928 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004929 break;
4930 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004931 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004932 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004933 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004934 break;
4935 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004936 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004937 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004938 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4939
4940 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004941 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004942 event_explanation = "<no event data>";
4943 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004944 }
4945
Jim Ingham5d90ade2012-07-27 23:57:19 +00004946 Process *process = event_data->GetProcessSP().get();
4947
4948 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004949 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004950 event_explanation = "<no process>";
4951 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004952 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004953
4954 ThreadList &thread_list = process->GetThreadList();
4955
4956 uint32_t num_threads = thread_list.GetSize();
4957 uint32_t thread_index;
4958
4959 ts.Printf("<%u threads> ", num_threads);
4960
4961 for (thread_index = 0;
4962 thread_index < num_threads;
4963 ++thread_index)
4964 {
4965 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4966
4967 if (!thread)
4968 {
4969 ts.Printf("<?> ");
4970 continue;
4971 }
4972
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004973 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00004974 RegisterContext *register_context = thread->GetRegisterContext().get();
4975
4976 if (register_context)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004977 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Ingham5d90ade2012-07-27 23:57:19 +00004978 else
4979 ts.Printf("[ip unknown] ");
4980
4981 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4982 if (stop_info_sp)
4983 {
4984 const char *stop_desc = stop_info_sp->GetDescription();
4985 if (stop_desc)
4986 ts.PutCString (stop_desc);
4987 }
4988 ts.Printf(">");
4989 }
4990
4991 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004992 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004993 } while (0);
4994
Jim Ingham5d90ade2012-07-27 23:57:19 +00004995 if (event_explanation)
4996 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004997 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00004998 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4999 }
5000
Jim Inghamb7940202013-01-15 02:47:48 +00005001 if (should_unwind && thread_plan_sp)
Jim Ingham5d90ade2012-07-27 23:57:19 +00005002 {
5003 if (log)
5004 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5005 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5006 thread_plan_sp->SetPrivate (orig_plan_private);
5007 }
5008 else
5009 {
5010 if (log)
5011 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005012 }
5013 }
5014 else if (return_value == eExecutionSetupError)
5015 {
5016 if (log)
5017 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00005018
Jim Inghamb7940202013-01-15 02:47:48 +00005019 if (unwind_on_error && thread_plan_sp)
Jim Inghamf9f40c22011-02-08 05:20:59 +00005020 {
Greg Clayton567e7f32011-09-22 04:58:26 +00005021 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00005022 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00005023 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005024 }
5025 else
5026 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005027 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00005028 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00005029 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005030 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5031 return_value = eExecutionCompleted;
5032 }
5033 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5034 {
5035 if (log)
5036 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5037 return_value = eExecutionDiscarded;
5038 }
5039 else
5040 {
5041 if (log)
5042 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamb7940202013-01-15 02:47:48 +00005043 if (unwind_on_error && thread_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005044 {
5045 if (log)
Jim Inghamb7940202013-01-15 02:47:48 +00005046 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005047 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5048 thread_plan_sp->SetPrivate (orig_plan_private);
5049 }
5050 }
5051 }
5052
5053 // Thread we ran the function in may have gone away because we ran the target
5054 // Check that it's still there, and if it is put it back in the context. Also restore the
5055 // frame in the context if it is still present.
5056 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5057 if (thread)
5058 {
5059 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5060 }
5061
5062 // Also restore the current process'es selected frame & thread, since this function calling may
5063 // be done behind the user's back.
5064
5065 if (selected_tid != LLDB_INVALID_THREAD_ID)
5066 {
5067 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5068 {
5069 // We were able to restore the selected thread, now restore the frame:
5070 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5071 if (old_frame_sp)
5072 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00005073 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005074 }
5075 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005076
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005077 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00005078
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005079 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00005080 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005081 if (log)
5082 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5083 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00005084 }
5085
5086 return return_value;
5087}
5088
5089const char *
5090Process::ExecutionResultAsCString (ExecutionResults result)
5091{
5092 const char *result_name;
5093
5094 switch (result)
5095 {
Greg Claytonb3448432011-03-24 21:19:54 +00005096 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005097 result_name = "eExecutionCompleted";
5098 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005099 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00005100 result_name = "eExecutionDiscarded";
5101 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005102 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005103 result_name = "eExecutionInterrupted";
5104 break;
Jim Inghamb7940202013-01-15 02:47:48 +00005105 case eExecutionHitBreakpoint:
5106 result_name = "eExecutionHitBreakpoint";
5107 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005108 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00005109 result_name = "eExecutionSetupError";
5110 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005111 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00005112 result_name = "eExecutionTimedOut";
5113 break;
5114 }
5115 return result_name;
5116}
5117
Greg Claytonabe0fed2011-04-18 08:33:37 +00005118void
5119Process::GetStatus (Stream &strm)
5120{
5121 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00005122 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00005123 {
5124 if (state == eStateExited)
5125 {
5126 int exit_status = GetExitStatus();
5127 const char *exit_description = GetExitDescription();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005128 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00005129 GetID(),
5130 exit_status,
5131 exit_status,
5132 exit_description ? exit_description : "");
5133 }
5134 else
5135 {
5136 if (state == eStateConnected)
5137 strm.Printf ("Connected to remote target.\n");
5138 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005139 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00005140 }
5141 }
5142 else
5143 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005144 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005145 }
5146}
5147
5148size_t
5149Process::GetThreadStatus (Stream &strm,
5150 bool only_threads_with_stop_reason,
5151 uint32_t start_frame,
5152 uint32_t num_frames,
5153 uint32_t num_frames_with_source)
5154{
5155 size_t num_thread_infos_dumped = 0;
5156
Jim Inghamb9950592012-09-10 20:50:15 +00005157 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005158 const size_t num_threads = GetThreadList().GetSize();
5159 for (uint32_t i = 0; i < num_threads; i++)
5160 {
5161 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5162 if (thread)
5163 {
5164 if (only_threads_with_stop_reason)
5165 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00005166 StopInfoSP stop_info_sp = thread->GetStopInfo();
5167 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00005168 continue;
5169 }
5170 thread->GetStatus (strm,
5171 start_frame,
5172 num_frames,
5173 num_frames_with_source);
5174 ++num_thread_infos_dumped;
5175 }
5176 }
5177 return num_thread_infos_dumped;
5178}
5179
Greg Clayton76113302012-02-22 04:37:26 +00005180void
5181Process::AddInvalidMemoryRegion (const LoadRange &region)
5182{
5183 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5184}
5185
5186bool
5187Process::RemoveInvalidMemoryRange (const LoadRange &region)
5188{
5189 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5190}
5191
Jim Ingham1831e782012-04-07 00:00:41 +00005192void
5193Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5194{
5195 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5196}
5197
5198bool
5199Process::RunPreResumeActions ()
5200{
5201 bool result = true;
5202 while (!m_pre_resume_actions.empty())
5203 {
5204 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5205 m_pre_resume_actions.pop_back();
5206 bool this_result = action.callback (action.baton);
5207 if (result == true) result = this_result;
5208 }
5209 return result;
5210}
5211
5212void
5213Process::ClearPreResumeActions ()
5214{
5215 m_pre_resume_actions.clear();
5216}
Greg Clayton76113302012-02-22 04:37:26 +00005217
Greg Claytoncf5927e2012-05-18 02:38:05 +00005218void
5219Process::Flush ()
5220{
5221 m_thread_list.Flush();
5222}
Greg Clayton0bce9a22012-12-05 00:16:59 +00005223
5224void
5225Process::DidExec ()
5226{
5227 Target &target = GetTarget();
5228 target.CleanupProcess ();
5229 ModuleList unloaded_modules (target.GetImages());
5230 target.ModulesDidUnload (unloaded_modules);
5231 target.GetSectionLoadList().Clear();
5232 m_dynamic_checkers_ap.reset();
5233 m_abi_sp.reset();
5234 m_os_ap.reset();
5235 m_dyld_ap.reset();
5236 m_image_tokens.clear();
5237 m_allocated_memory_cache.Clear();
5238 m_language_runtimes.clear();
5239 DoDidExec();
5240 CompleteAttach ();
5241}