blob: a6bbdcf83a712f07f97b780965ddb8d8279aa225 [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 Clayton64742742013-01-16 17:29:04 +0000917 static uint32_t g_process_unique_id = 0;
918
Greg Clayton46c9a352012-02-09 06:16:32 +0000919 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000920 ProcessCreateInstance create_callback = NULL;
921 if (plugin_name)
922 {
923 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
924 if (create_callback)
925 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000926 process_sp = create_callback(target, listener, crash_file_path);
927 if (process_sp)
928 {
Greg Clayton64742742013-01-16 17:29:04 +0000929 if (process_sp->CanDebug(target, true))
930 {
931 process_sp->m_process_unique_id = ++g_process_unique_id;
932 }
933 else
Greg Clayton46c9a352012-02-09 06:16:32 +0000934 process_sp.reset();
935 }
Chris Lattner24943d22010-06-08 16:52:24 +0000936 }
937 }
938 else
939 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000940 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000941 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000942 process_sp = create_callback(target, listener, crash_file_path);
943 if (process_sp)
944 {
Greg Clayton64742742013-01-16 17:29:04 +0000945 if (process_sp->CanDebug(target, false))
946 {
947 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Clayton46c9a352012-02-09 06:16:32 +0000948 break;
Greg Clayton64742742013-01-16 17:29:04 +0000949 }
950 else
951 process_sp.reset();
Greg Clayton46c9a352012-02-09 06:16:32 +0000952 }
Chris Lattner24943d22010-06-08 16:52:24 +0000953 }
954 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000955 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000956}
957
Jim Ingham5a15e692012-02-16 06:50:00 +0000958ConstString &
959Process::GetStaticBroadcasterClass ()
960{
961 static ConstString class_name ("lldb.process");
962 return class_name;
963}
Chris Lattner24943d22010-06-08 16:52:24 +0000964
965//----------------------------------------------------------------------
966// Process constructor
967//----------------------------------------------------------------------
968Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +0000969 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +0000970 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000971 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +0000972 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000973 m_public_state (eStateUnloaded),
974 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000975 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
976 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000977 m_private_state_listener ("lldb.process.internal_state_listener"),
978 m_private_state_control_wait(),
979 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000980 m_mod_id (),
Greg Clayton64742742013-01-16 17:29:04 +0000981 m_process_unique_id(0),
Chris Lattner24943d22010-06-08 16:52:24 +0000982 m_thread_index_id (0),
Han Ming Ongccd5c4e2013-01-08 22:10:01 +0000983 m_thread_id_to_index_id_map (),
Chris Lattner24943d22010-06-08 16:52:24 +0000984 m_exit_status (-1),
985 m_exit_string (),
986 m_thread_list (this),
987 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000988 m_image_tokens (),
989 m_listener (listener),
990 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000991 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000992 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000993 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000994 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000995 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000996 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000997 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000998 m_stderr_data (),
Han Ming Ongfb9cee62012-11-17 00:21:04 +0000999 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1000 m_profile_data (),
Greg Clayton613b8732011-05-17 03:37:42 +00001001 m_memory_cache (*this),
1002 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +00001003 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +00001004 m_next_event_action_ap(),
Bill Wendlingce96dad2012-04-06 00:10:21 +00001005 m_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +00001006 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001007 m_finalize_called(false),
Bill Wendlingce96dad2012-04-06 00:10:21 +00001008 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +00001009{
Jim Ingham5a15e692012-02-16 06:50:00 +00001010 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +00001011
Greg Claytone005f2c2010-11-06 01:53:30 +00001012 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001013 if (log)
1014 log->Printf ("%p Process::Process()", this);
1015
Greg Clayton49ce6822010-10-31 03:01:06 +00001016 SetEventName (eBroadcastBitStateChanged, "state-changed");
1017 SetEventName (eBroadcastBitInterrupt, "interrupt");
1018 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1019 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001020 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Clayton49ce6822010-10-31 03:01:06 +00001021
Greg Clayton84332782012-10-29 20:52:08 +00001022 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1023 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1024 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1025
Chris Lattner24943d22010-06-08 16:52:24 +00001026 listener.StartListeningForEvents (this,
1027 eBroadcastBitStateChanged |
1028 eBroadcastBitInterrupt |
1029 eBroadcastBitSTDOUT |
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001030 eBroadcastBitSTDERR |
1031 eBroadcastBitProfileData);
Chris Lattner24943d22010-06-08 16:52:24 +00001032
1033 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001034 eBroadcastBitStateChanged |
1035 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +00001036
1037 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1038 eBroadcastInternalStateControlStop |
1039 eBroadcastInternalStateControlPause |
1040 eBroadcastInternalStateControlResume);
1041}
1042
1043//----------------------------------------------------------------------
1044// Destructor
1045//----------------------------------------------------------------------
1046Process::~Process()
1047{
Greg Claytone005f2c2010-11-06 01:53:30 +00001048 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001049 if (log)
1050 log->Printf ("%p Process::~Process()", this);
1051 StopPrivateStateThread();
1052}
1053
Greg Clayton73844aa2012-08-22 17:17:09 +00001054const ProcessPropertiesSP &
1055Process::GetGlobalProperties()
1056{
1057 static ProcessPropertiesSP g_settings_sp;
1058 if (!g_settings_sp)
1059 g_settings_sp.reset (new ProcessProperties (true));
1060 return g_settings_sp;
1061}
1062
Chris Lattner24943d22010-06-08 16:52:24 +00001063void
1064Process::Finalize()
1065{
Greg Claytonffa43a62011-11-17 04:46:02 +00001066 switch (GetPrivateState())
1067 {
1068 case eStateConnected:
1069 case eStateAttaching:
1070 case eStateLaunching:
1071 case eStateStopped:
1072 case eStateRunning:
1073 case eStateStepping:
1074 case eStateCrashed:
1075 case eStateSuspended:
1076 if (GetShouldDetach())
1077 Detach();
1078 else
1079 Destroy();
1080 break;
1081
1082 case eStateInvalid:
1083 case eStateUnloaded:
1084 case eStateDetached:
1085 case eStateExited:
1086 break;
1087 }
1088
Greg Clayton2f57db02011-10-01 00:45:15 +00001089 // Clear our broadcaster before we proceed with destroying
1090 Broadcaster::Clear();
1091
Chris Lattner24943d22010-06-08 16:52:24 +00001092 // Do any cleanup needed prior to being destructed... Subclasses
1093 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001094
1095 // We need to destroy the loader before the derived Process class gets destroyed
1096 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001097 m_dynamic_checkers_ap.reset();
1098 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001099 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001100 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001101 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001102 std::vector<Notifications> empty_notifications;
1103 m_notifications.swap(empty_notifications);
1104 m_image_tokens.clear();
1105 m_memory_cache.Clear();
1106 m_allocated_memory_cache.Clear();
1107 m_language_runtimes.clear();
1108 m_next_event_action_ap.reset();
Greg Clayton84332782012-10-29 20:52:08 +00001109//#ifdef LLDB_CONFIGURATION_DEBUG
1110// StreamFile s(stdout, false);
1111// EventSP event_sp;
1112// while (m_private_state_listener.GetNextEvent(event_sp))
1113// {
1114// event_sp->Dump (&s);
1115// s.EOL();
1116// }
1117//#endif
1118 // We have to be very careful here as the m_private_state_listener might
1119 // contain events that have ProcessSP values in them which can keep this
1120 // process around forever. These events need to be cleared out.
1121 m_private_state_listener.Clear();
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001122 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001123}
1124
1125void
1126Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1127{
1128 m_notifications.push_back(callbacks);
1129 if (callbacks.initialize != NULL)
1130 callbacks.initialize (callbacks.baton, this);
1131}
1132
1133bool
1134Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1135{
1136 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1137 for (pos = m_notifications.begin(); pos != end; ++pos)
1138 {
1139 if (pos->baton == callbacks.baton &&
1140 pos->initialize == callbacks.initialize &&
1141 pos->process_state_changed == callbacks.process_state_changed)
1142 {
1143 m_notifications.erase(pos);
1144 return true;
1145 }
1146 }
1147 return false;
1148}
1149
1150void
1151Process::SynchronouslyNotifyStateChanged (StateType state)
1152{
1153 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1154 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1155 {
1156 if (notification_pos->process_state_changed)
1157 notification_pos->process_state_changed (notification_pos->baton, this, state);
1158 }
1159}
1160
1161// FIXME: We need to do some work on events before the general Listener sees them.
1162// For instance if we are continuing from a breakpoint, we need to ensure that we do
1163// the little "insert real insn, step & stop" trick. But we can't do that when the
1164// event is delivered by the broadcaster - since that is done on the thread that is
1165// waiting for new events, so if we needed more than one event for our handling, we would
1166// stall. So instead we do it when we fetch the event off of the queue.
1167//
1168
1169StateType
1170Process::GetNextEvent (EventSP &event_sp)
1171{
1172 StateType state = eStateInvalid;
1173
1174 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1175 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1176
1177 return state;
1178}
1179
1180
1181StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001182Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001183{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001184 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1185 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1186 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001187 if (event_sp_ptr)
1188 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001189 StateType state = GetState();
1190 // If we are exited or detached, we won't ever get back to any
1191 // other valid state...
1192 if (state == eStateDetached || state == eStateExited)
1193 return state;
1194
1195 while (state != eStateInvalid)
1196 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001197 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001198 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001199 if (event_sp_ptr && event_sp)
1200 *event_sp_ptr = event_sp;
1201
Jim Ingham21f37ad2011-08-09 02:12:22 +00001202 switch (state)
1203 {
1204 case eStateCrashed:
1205 case eStateDetached:
1206 case eStateExited:
1207 case eStateUnloaded:
1208 return state;
1209 case eStateStopped:
1210 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1211 continue;
1212 else
1213 return state;
1214 default:
1215 continue;
1216 }
1217 }
1218 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001219}
1220
1221
1222StateType
1223Process::WaitForState
1224(
1225 const TimeValue *timeout,
1226 const StateType *match_states, const uint32_t num_match_states
1227)
1228{
1229 EventSP event_sp;
1230 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001231 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001232 while (state != eStateInvalid)
1233 {
Greg Claytond8c62532010-10-07 04:19:01 +00001234 // If we are exited or detached, we won't ever get back to any
1235 // other valid state...
1236 if (state == eStateDetached || state == eStateExited)
1237 return state;
1238
Chris Lattner24943d22010-06-08 16:52:24 +00001239 state = WaitForStateChangedEvents (timeout, event_sp);
1240
1241 for (i=0; i<num_match_states; ++i)
1242 {
1243 if (match_states[i] == state)
1244 return state;
1245 }
1246 }
1247 return state;
1248}
1249
Jim Ingham63e24d72010-10-11 23:53:14 +00001250bool
1251Process::HijackProcessEvents (Listener *listener)
1252{
1253 if (listener != NULL)
1254 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001255 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001256 }
1257 else
1258 return false;
1259}
1260
1261void
1262Process::RestoreProcessEvents ()
1263{
1264 RestoreBroadcaster();
1265}
1266
Jim Inghamf9f40c22011-02-08 05:20:59 +00001267bool
1268Process::HijackPrivateProcessEvents (Listener *listener)
1269{
1270 if (listener != NULL)
1271 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001272 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001273 }
1274 else
1275 return false;
1276}
1277
1278void
1279Process::RestorePrivateProcessEvents ()
1280{
1281 m_private_state_broadcaster.RestoreBroadcaster();
1282}
1283
Chris Lattner24943d22010-06-08 16:52:24 +00001284StateType
1285Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1286{
Greg Claytone005f2c2010-11-06 01:53:30 +00001287 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001288
1289 if (log)
1290 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1291
1292 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001293 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1294 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001295 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001296 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001297 {
1298 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1299 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1300 else if (log)
1301 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1302 }
Chris Lattner24943d22010-06-08 16:52:24 +00001303
1304 if (log)
1305 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1306 __FUNCTION__,
1307 timeout,
1308 StateAsCString(state));
1309 return state;
1310}
1311
1312Event *
1313Process::PeekAtStateChangedEvents ()
1314{
Greg Claytone005f2c2010-11-06 01:53:30 +00001315 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001316
1317 if (log)
1318 log->Printf ("Process::%s...", __FUNCTION__);
1319
1320 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001321 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1322 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001323 if (log)
1324 {
1325 if (event_ptr)
1326 {
1327 log->Printf ("Process::%s (event_ptr) => %s",
1328 __FUNCTION__,
1329 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1330 }
1331 else
1332 {
1333 log->Printf ("Process::%s no events found",
1334 __FUNCTION__);
1335 }
1336 }
1337 return event_ptr;
1338}
1339
1340StateType
1341Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1342{
Greg Claytone005f2c2010-11-06 01:53:30 +00001343 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001344
1345 if (log)
1346 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1347
1348 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001349 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1350 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001351 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001352 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001353 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1354 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001355
1356 // This is a bit of a hack, but when we wait here we could very well return
1357 // to the command-line, and that could disable the log, which would render the
1358 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001359 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001360 {
1361 if (state == eStateInvalid)
1362 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1363 else
1364 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1365 }
Chris Lattner24943d22010-06-08 16:52:24 +00001366 return state;
1367}
1368
1369bool
1370Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1371{
Greg Claytone005f2c2010-11-06 01:53:30 +00001372 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001373
1374 if (log)
1375 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1376
1377 if (control_only)
1378 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1379 else
1380 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1381}
1382
1383bool
1384Process::IsRunning () const
1385{
1386 return StateIsRunningState (m_public_state.GetValue());
1387}
1388
1389int
1390Process::GetExitStatus ()
1391{
1392 if (m_public_state.GetValue() == eStateExited)
1393 return m_exit_status;
1394 return -1;
1395}
1396
Greg Clayton638351a2010-12-04 00:10:17 +00001397
Chris Lattner24943d22010-06-08 16:52:24 +00001398const char *
1399Process::GetExitDescription ()
1400{
1401 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1402 return m_exit_string.c_str();
1403 return NULL;
1404}
1405
Greg Clayton72e1c782011-01-22 23:43:18 +00001406bool
Chris Lattner24943d22010-06-08 16:52:24 +00001407Process::SetExitStatus (int status, const char *cstr)
1408{
Greg Clayton68ca8232011-01-25 02:58:48 +00001409 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1410 if (log)
1411 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1412 status, status,
1413 cstr ? "\"" : "",
1414 cstr ? cstr : "NULL",
1415 cstr ? "\"" : "");
1416
Greg Clayton72e1c782011-01-22 23:43:18 +00001417 // We were already in the exited state
1418 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001419 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001420 if (log)
1421 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001422 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001423 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001424
1425 m_exit_status = status;
1426 if (cstr)
1427 m_exit_string = cstr;
1428 else
1429 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001430
Greg Clayton72e1c782011-01-22 23:43:18 +00001431 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001432
Greg Clayton72e1c782011-01-22 23:43:18 +00001433 SetPrivateState (eStateExited);
1434 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001435}
1436
1437// This static callback can be used to watch for local child processes on
1438// the current host. The the child process exits, the process will be
1439// found in the global target list (we want to be completely sure that the
1440// lldb_private::Process doesn't go away before we can deliver the signal.
1441bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001442Process::SetProcessExitStatus (void *callback_baton,
1443 lldb::pid_t pid,
1444 bool exited,
1445 int signo, // Zero for no signal
1446 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001447)
1448{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001449 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1450 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001451 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001452 callback_baton,
1453 pid,
1454 exited,
1455 signo,
1456 exit_status);
1457
1458 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001459 {
Greg Clayton63094e02010-06-23 01:19:29 +00001460 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001461 if (target_sp)
1462 {
1463 ProcessSP process_sp (target_sp->GetProcessSP());
1464 if (process_sp)
1465 {
1466 const char *signal_cstr = NULL;
1467 if (signo)
1468 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1469
1470 process_sp->SetExitStatus (exit_status, signal_cstr);
1471 }
1472 }
1473 return true;
1474 }
1475 return false;
1476}
1477
1478
Greg Clayton37f962e2011-08-22 02:49:39 +00001479void
1480Process::UpdateThreadListIfNeeded ()
1481{
1482 const uint32_t stop_id = GetStopID();
1483 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1484 {
Greg Clayton20206082011-11-17 01:23:07 +00001485 const StateType state = GetPrivateState();
1486 if (StateIsStoppedState (state, true))
1487 {
1488 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001489 // m_thread_list does have its own mutex, but we need to
1490 // hold onto the mutex between the call to UpdateThreadList(...)
1491 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001492 ThreadList new_thread_list(this);
1493 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001494 // thread list, but only update if "true" is returned
1495 if (UpdateThreadList (m_thread_list, new_thread_list))
1496 {
1497 OperatingSystem *os = GetOperatingSystem ();
1498 if (os)
1499 os->UpdateThreadList (m_thread_list, new_thread_list);
1500 m_thread_list.Update (new_thread_list);
1501 m_thread_list.SetStopID (stop_id);
1502 }
Greg Clayton20206082011-11-17 01:23:07 +00001503 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001504 }
1505}
1506
Greg Clayton52ebc0a2013-01-18 23:41:08 +00001507ThreadSP
1508Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1509{
1510 OperatingSystem *os = GetOperatingSystem ();
1511 if (os)
1512 return os->CreateThread(tid, context);
1513 return ThreadSP();
1514}
1515
1516
1517
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001518// This is obsoleted. Staged removal for Xcode.
Chris Lattner24943d22010-06-08 16:52:24 +00001519uint32_t
1520Process::GetNextThreadIndexID ()
1521{
1522 return ++m_thread_index_id;
1523}
1524
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001525uint32_t
1526Process::GetNextThreadIndexID (uint64_t thread_id)
1527{
1528 return AssignIndexIDToThread(thread_id);
1529}
1530
1531bool
1532Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1533{
1534 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1535 if (iterator == m_thread_id_to_index_id_map.end())
1536 {
1537 return false;
1538 }
1539 else
1540 {
1541 return true;
1542 }
1543}
1544
1545uint32_t
1546Process::AssignIndexIDToThread(uint64_t thread_id)
1547{
1548 uint32_t result = 0;
1549 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1550 if (iterator == m_thread_id_to_index_id_map.end())
1551 {
1552 result = ++m_thread_index_id;
1553 m_thread_id_to_index_id_map[thread_id] = result;
1554 }
1555 else
1556 {
1557 result = iterator->second;
1558 }
1559
1560 return result;
1561}
1562
Chris Lattner24943d22010-06-08 16:52:24 +00001563StateType
1564Process::GetState()
1565{
1566 // If any other threads access this we will need a mutex for it
1567 return m_public_state.GetValue ();
1568}
1569
1570void
1571Process::SetPublicState (StateType new_state)
1572{
Greg Clayton68ca8232011-01-25 02:58:48 +00001573 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001574 if (log)
1575 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001576 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001577 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001578
1579 // On the transition from Run to Stopped, we unlock the writer end of the
1580 // run lock. The lock gets locked in Resume, which is the public API
1581 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001582 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1583 {
Sean Callanana3772862012-06-02 01:16:20 +00001584 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001585 {
Sean Callanana3772862012-06-02 01:16:20 +00001586 if (log)
1587 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1588 m_run_lock.WriteUnlock();
1589 }
1590 else
1591 {
1592 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1593 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1594 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001595 {
Sean Callanana3772862012-06-02 01:16:20 +00001596 if (new_state_is_stopped)
1597 {
1598 if (log)
1599 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1600 m_run_lock.WriteUnlock();
1601 }
Greg Claytona894fe72012-04-05 16:12:35 +00001602 }
Greg Claytona894fe72012-04-05 16:12:35 +00001603 }
1604 }
Chris Lattner24943d22010-06-08 16:52:24 +00001605}
1606
Jim Ingham027aaa72012-04-19 01:40:33 +00001607Error
1608Process::Resume ()
1609{
1610 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1611 if (log)
1612 log->Printf("Process::Resume -- locking run lock");
1613 if (!m_run_lock.WriteTryLock())
1614 {
1615 Error error("Resume request failed - process still running.");
1616 if (log)
1617 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1618 return error;
1619 }
1620 return PrivateResume();
1621}
1622
Chris Lattner24943d22010-06-08 16:52:24 +00001623StateType
1624Process::GetPrivateState ()
1625{
1626 return m_private_state.GetValue();
1627}
1628
1629void
1630Process::SetPrivateState (StateType new_state)
1631{
Greg Clayton68ca8232011-01-25 02:58:48 +00001632 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001633 bool state_changed = false;
1634
1635 if (log)
1636 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1637
1638 Mutex::Locker locker(m_private_state.GetMutex());
1639
1640 const StateType old_state = m_private_state.GetValueNoLock ();
1641 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001642 // This code is left commented out in case we ever need to control
1643 // the private process state with another run lock. Right now it doesn't
1644 // seem like we need to do this, but if we ever do, we can uncomment and
1645 // use this code.
1646// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1647// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1648// if (old_state_is_stopped != new_state_is_stopped)
1649// {
1650// if (new_state_is_stopped)
1651// m_private_run_lock.WriteUnlock();
1652// else
1653// m_private_run_lock.WriteLock();
1654// }
1655
Chris Lattner24943d22010-06-08 16:52:24 +00001656 if (state_changed)
1657 {
1658 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001659 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001660 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001661 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001662 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001663 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001664 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001665 }
1666 // Use our target to get a shared pointer to ourselves...
Greg Clayton84332782012-10-29 20:52:08 +00001667 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1668 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1669 else
1670 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001671 }
1672 else
1673 {
1674 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001675 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001676 }
1677}
1678
Jim Ingham0296fe72011-11-08 03:00:11 +00001679void
1680Process::SetRunningUserExpression (bool on)
1681{
1682 m_mod_id.SetRunningUserExpression (on);
1683}
1684
Chris Lattner24943d22010-06-08 16:52:24 +00001685addr_t
1686Process::GetImageInfoAddress()
1687{
1688 return LLDB_INVALID_ADDRESS;
1689}
1690
Greg Clayton0baa3942010-11-04 01:54:29 +00001691//----------------------------------------------------------------------
1692// LoadImage
1693//
1694// This function provides a default implementation that works for most
1695// unix variants. Any Process subclasses that need to do shared library
1696// loading differently should override LoadImage and UnloadImage and
1697// do what is needed.
1698//----------------------------------------------------------------------
1699uint32_t
1700Process::LoadImage (const FileSpec &image_spec, Error &error)
1701{
Greg Clayton77d40712012-04-18 00:05:19 +00001702 char path[PATH_MAX];
1703 image_spec.GetPath(path, sizeof(path));
1704
Greg Clayton0baa3942010-11-04 01:54:29 +00001705 DynamicLoader *loader = GetDynamicLoader();
1706 if (loader)
1707 {
1708 error = loader->CanLoadImage();
1709 if (error.Fail())
1710 return LLDB_INVALID_IMAGE_TOKEN;
1711 }
1712
1713 if (error.Success())
1714 {
1715 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001716
1717 if (thread_sp)
1718 {
1719 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1720
1721 if (frame_sp)
1722 {
1723 ExecutionContext exe_ctx;
1724 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001725 const bool unwind_on_error = true;
1726 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001727 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001728 expr.Printf("dlopen (\"%s\", 2)", path);
1729 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001730 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001731 ClangUserExpression::Evaluate (exe_ctx,
1732 eExecutionPolicyAlways,
1733 lldb::eLanguageTypeUnknown,
1734 ClangUserExpression::eResultTypeAny,
1735 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001736 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001737 expr.GetData(),
1738 prefix,
1739 result_valobj_sp,
1740 true,
1741 ClangUserExpression::kDefaultTimeout);
Johnny Chenb14ec342011-09-09 00:01:43 +00001742 error = result_valobj_sp->GetError();
1743 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001744 {
1745 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001746 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001747 {
1748 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1749 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1750 {
1751 uint32_t image_token = m_image_tokens.size();
1752 m_image_tokens.push_back (image_ptr);
1753 return image_token;
1754 }
1755 }
1756 }
1757 }
1758 }
1759 }
Greg Clayton77d40712012-04-18 00:05:19 +00001760 if (!error.AsCString())
1761 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001762 return LLDB_INVALID_IMAGE_TOKEN;
1763}
1764
1765//----------------------------------------------------------------------
1766// UnloadImage
1767//
1768// This function provides a default implementation that works for most
1769// unix variants. Any Process subclasses that need to do shared library
1770// loading differently should override LoadImage and UnloadImage and
1771// do what is needed.
1772//----------------------------------------------------------------------
1773Error
1774Process::UnloadImage (uint32_t image_token)
1775{
1776 Error error;
1777 if (image_token < m_image_tokens.size())
1778 {
1779 const addr_t image_addr = m_image_tokens[image_token];
1780 if (image_addr == LLDB_INVALID_ADDRESS)
1781 {
1782 error.SetErrorString("image already unloaded");
1783 }
1784 else
1785 {
1786 DynamicLoader *loader = GetDynamicLoader();
1787 if (loader)
1788 error = loader->CanLoadImage();
1789
1790 if (error.Success())
1791 {
1792 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001793
1794 if (thread_sp)
1795 {
1796 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1797
1798 if (frame_sp)
1799 {
1800 ExecutionContext exe_ctx;
1801 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001802 const bool unwind_on_error = true;
1803 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001804 StreamString expr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001805 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton0baa3942010-11-04 01:54:29 +00001806 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001807 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001808 ClangUserExpression::Evaluate (exe_ctx,
1809 eExecutionPolicyAlways,
1810 lldb::eLanguageTypeUnknown,
1811 ClangUserExpression::eResultTypeAny,
1812 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001813 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001814 expr.GetData(),
1815 prefix,
1816 result_valobj_sp,
1817 true,
1818 ClangUserExpression::kDefaultTimeout);
Greg Clayton0baa3942010-11-04 01:54:29 +00001819 if (result_valobj_sp->GetError().Success())
1820 {
1821 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001822 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001823 {
1824 if (scalar.UInt(1))
1825 {
1826 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1827 }
1828 else
1829 {
1830 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1831 }
1832 }
1833 }
1834 else
1835 {
1836 error = result_valobj_sp->GetError();
1837 }
1838 }
1839 }
1840 }
1841 }
1842 }
1843 else
1844 {
1845 error.SetErrorString("invalid image token");
1846 }
1847 return error;
1848}
1849
Greg Clayton75906e42011-05-11 18:39:18 +00001850const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001851Process::GetABI()
1852{
Greg Clayton75906e42011-05-11 18:39:18 +00001853 if (!m_abi_sp)
1854 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1855 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001856}
1857
Jim Ingham642036f2010-09-23 02:01:19 +00001858LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001859Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001860{
1861 LanguageRuntimeCollection::iterator pos;
1862 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001863 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001864 {
Jim Inghame3117662012-03-10 00:22:19 +00001865 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001866
Jim Inghame3117662012-03-10 00:22:19 +00001867 m_language_runtimes[language] = runtime_sp;
1868 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001869 }
1870 else
1871 return (*pos).second.get();
1872}
1873
1874CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001875Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001876{
Jim Inghame3117662012-03-10 00:22:19 +00001877 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001878 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1879 return static_cast<CPPLanguageRuntime *> (runtime);
1880 return NULL;
1881}
1882
1883ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001884Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001885{
Jim Inghame3117662012-03-10 00:22:19 +00001886 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001887 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1888 return static_cast<ObjCLanguageRuntime *> (runtime);
1889 return NULL;
1890}
1891
Enrico Granata6b1763b2012-05-21 16:51:35 +00001892bool
1893Process::IsPossibleDynamicValue (ValueObject& in_value)
1894{
1895 if (in_value.IsDynamic())
1896 return false;
1897 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1898
1899 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1900 {
1901 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1902 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1903 }
1904
1905 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1906 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1907 return true;
1908
1909 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1910 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1911}
1912
Chris Lattner24943d22010-06-08 16:52:24 +00001913BreakpointSiteList &
1914Process::GetBreakpointSiteList()
1915{
1916 return m_breakpoint_site_list;
1917}
1918
1919const BreakpointSiteList &
1920Process::GetBreakpointSiteList() const
1921{
1922 return m_breakpoint_site_list;
1923}
1924
1925
1926void
1927Process::DisableAllBreakpointSites ()
1928{
1929 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001930 size_t num_sites = m_breakpoint_site_list.GetSize();
1931 for (size_t i = 0; i < num_sites; i++)
1932 {
1933 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1934 }
Chris Lattner24943d22010-06-08 16:52:24 +00001935}
1936
1937Error
1938Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1939{
1940 Error error (DisableBreakpointSiteByID (break_id));
1941
1942 if (error.Success())
1943 m_breakpoint_site_list.Remove(break_id);
1944
1945 return error;
1946}
1947
1948Error
1949Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1950{
1951 Error error;
1952 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1953 if (bp_site_sp)
1954 {
1955 if (bp_site_sp->IsEnabled())
1956 error = DisableBreakpoint (bp_site_sp.get());
1957 }
1958 else
1959 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001960 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001961 }
1962
1963 return error;
1964}
1965
1966Error
1967Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1968{
1969 Error error;
1970 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1971 if (bp_site_sp)
1972 {
1973 if (!bp_site_sp->IsEnabled())
1974 error = EnableBreakpoint (bp_site_sp.get());
1975 }
1976 else
1977 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001978 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001979 }
1980 return error;
1981}
1982
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001983lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001984Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001985{
Greg Clayton265ab332011-05-19 18:17:41 +00001986 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001987 if (load_addr != LLDB_INVALID_ADDRESS)
1988 {
1989 BreakpointSiteSP bp_site_sp;
1990
1991 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1992 // create a new breakpoint site and add it.
1993
1994 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1995
1996 if (bp_site_sp)
1997 {
1998 bp_site_sp->AddOwner (owner);
1999 owner->SetBreakpointSite (bp_site_sp);
2000 return bp_site_sp->GetID();
2001 }
2002 else
2003 {
Greg Clayton36da2aa2013-01-25 18:06:21 +00002004 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner24943d22010-06-08 16:52:24 +00002005 if (bp_site_sp)
2006 {
2007 if (EnableBreakpoint (bp_site_sp.get()).Success())
2008 {
2009 owner->SetBreakpointSite (bp_site_sp);
2010 return m_breakpoint_site_list.Add (bp_site_sp);
2011 }
2012 }
2013 }
2014 }
2015 // We failed to enable the breakpoint
2016 return LLDB_INVALID_BREAK_ID;
2017
2018}
2019
2020void
2021Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2022{
2023 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2024 if (num_owners == 0)
2025 {
2026 DisableBreakpoint(bp_site_sp.get());
2027 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2028 }
2029}
2030
2031
2032size_t
2033Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2034{
2035 size_t bytes_removed = 0;
2036 addr_t intersect_addr;
2037 size_t intersect_size;
2038 size_t opcode_offset;
2039 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002040 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00002041 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00002042
Jim Ingham82820f92011-06-29 19:42:28 +00002043 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00002044 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002045 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00002046 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002047 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00002048 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002049 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00002050 {
2051 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2052 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00002053 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00002054 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002055 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00002056 }
Chris Lattner24943d22010-06-08 16:52:24 +00002057 }
2058 }
2059 }
2060 return bytes_removed;
2061}
2062
2063
Greg Claytonb1888f22011-03-19 01:12:21 +00002064
2065size_t
2066Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2067{
2068 PlatformSP platform_sp (m_target.GetPlatform());
2069 if (platform_sp)
2070 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2071 return 0;
2072}
2073
Chris Lattner24943d22010-06-08 16:52:24 +00002074Error
2075Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2076{
2077 Error error;
2078 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002079 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002080 const addr_t bp_addr = bp_site->GetLoadAddress();
2081 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002082 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002083 if (bp_site->IsEnabled())
2084 {
2085 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002086 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 +00002087 return error;
2088 }
2089
2090 if (bp_addr == LLDB_INVALID_ADDRESS)
2091 {
2092 error.SetErrorString("BreakpointSite contains an invalid load address.");
2093 return error;
2094 }
2095 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2096 // trap for the breakpoint site
2097 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2098
2099 if (bp_opcode_size == 0)
2100 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002101 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002102 }
2103 else
2104 {
2105 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2106
2107 if (bp_opcode_bytes == NULL)
2108 {
2109 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2110 return error;
2111 }
2112
2113 // Save the original opcode by reading it
2114 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2115 {
2116 // Write a software breakpoint in place of the original opcode
2117 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2118 {
2119 uint8_t verify_bp_opcode_bytes[64];
2120 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2121 {
2122 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2123 {
2124 bp_site->SetEnabled(true);
2125 bp_site->SetType (BreakpointSite::eSoftware);
2126 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002127 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner24943d22010-06-08 16:52:24 +00002128 bp_site->GetID(),
2129 (uint64_t)bp_addr);
2130 }
2131 else
Greg Clayton9c236732011-10-26 00:56:27 +00002132 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00002133 }
2134 else
2135 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2136 }
2137 else
2138 error.SetErrorString("Unable to write breakpoint trap to memory.");
2139 }
2140 else
2141 error.SetErrorString("Unable to read memory at breakpoint address.");
2142 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002143 if (log && error.Fail())
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002144 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002145 bp_site->GetID(),
2146 (uint64_t)bp_addr,
2147 error.AsCString());
2148 return error;
2149}
2150
2151Error
2152Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2153{
2154 Error error;
2155 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002156 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002157 addr_t bp_addr = bp_site->GetLoadAddress();
2158 lldb::user_id_t breakID = bp_site->GetID();
2159 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002160 log->Printf ("Process::DisableBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002161
2162 if (bp_site->IsHardware())
2163 {
2164 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2165 }
2166 else if (bp_site->IsEnabled())
2167 {
2168 const size_t break_op_size = bp_site->GetByteSize();
2169 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2170 if (break_op_size > 0)
2171 {
2172 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002173 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002174 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002175 bool break_op_found = false;
2176
2177 // Read the breakpoint opcode
2178 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2179 {
2180 bool verify = false;
2181 // Make sure we have the a breakpoint opcode exists at this address
2182 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2183 {
2184 break_op_found = true;
2185 // We found a valid breakpoint opcode at this address, now restore
2186 // the saved opcode.
2187 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2188 {
2189 verify = true;
2190 }
2191 else
2192 error.SetErrorString("Memory write failed when restoring original opcode.");
2193 }
2194 else
2195 {
2196 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2197 // Set verify to true and so we can check if the original opcode has already been restored
2198 verify = true;
2199 }
2200
2201 if (verify)
2202 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002203 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002204 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002205 // Verify that our original opcode made it back to the inferior
2206 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2207 {
2208 // compare the memory we just read with the original opcode
2209 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2210 {
2211 // SUCCESS
2212 bp_site->SetEnabled(false);
2213 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002214 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 +00002215 return error;
2216 }
2217 else
2218 {
2219 if (break_op_found)
2220 error.SetErrorString("Failed to restore original opcode.");
2221 }
2222 }
2223 else
2224 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2225 }
2226 }
2227 else
2228 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2229 }
2230 }
2231 else
2232 {
2233 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002234 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 +00002235 return error;
2236 }
2237
2238 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002239 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002240 bp_site->GetID(),
2241 (uint64_t)bp_addr,
2242 error.AsCString());
2243 return error;
2244
2245}
2246
Greg Claytonfd119992011-01-07 06:08:19 +00002247// Uncomment to verify memory caching works after making changes to caching code
2248//#define VERIFY_MEMORY_READS
2249
Sean Callananf90b5f32012-06-07 22:26:42 +00002250size_t
2251Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2252{
2253 if (!GetDisableMemoryCache())
2254 {
Greg Claytonfd119992011-01-07 06:08:19 +00002255#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002256 // Memory caching is enabled, with debug verification
2257
2258 if (buf && size)
2259 {
2260 // Uncomment the line below to make sure memory caching is working.
2261 // I ran this through the test suite and got no assertions, so I am
2262 // pretty confident this is working well. If any changes are made to
2263 // memory caching, uncomment the line below and test your changes!
2264
2265 // Verify all memory reads by using the cache first, then redundantly
2266 // reading the same memory from the inferior and comparing to make sure
2267 // everything is exactly the same.
2268 std::string verify_buf (size, '\0');
2269 assert (verify_buf.size() == size);
2270 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2271 Error verify_error;
2272 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2273 assert (cache_bytes_read == verify_bytes_read);
2274 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2275 assert (verify_error.Success() == error.Success());
2276 return cache_bytes_read;
2277 }
2278 return 0;
2279#else // !defined(VERIFY_MEMORY_READS)
2280 // Memory caching is enabled, without debug verification
2281
2282 return m_memory_cache.Read (addr, buf, size, error);
2283#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002284 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002285 else
2286 {
2287 // Memory caching is disabled
2288
2289 return ReadMemoryFromInferior (addr, buf, size, error);
2290 }
Greg Claytonfd119992011-01-07 06:08:19 +00002291}
Greg Claytonfd119992011-01-07 06:08:19 +00002292
Greg Claytondd29b972012-05-18 23:20:01 +00002293size_t
2294Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2295{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002296 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002297 out_str.clear();
2298 addr_t curr_addr = addr;
2299 while (1)
2300 {
2301 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2302 if (length == 0)
2303 break;
2304 out_str.append(buf, length);
2305 // If we got "length - 1" bytes, we didn't get the whole C string, we
2306 // need to read some more characters
2307 if (length == sizeof(buf) - 1)
2308 curr_addr += length;
2309 else
2310 break;
2311 }
2312 return out_str.size();
2313}
2314
Greg Claytonfd119992011-01-07 06:08:19 +00002315
2316size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002317Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002318{
2319 size_t total_cstr_len = 0;
2320 if (dst && dst_max_len)
2321 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002322 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002323 // NULL out everything just to be safe
2324 memset (dst, 0, dst_max_len);
2325 Error error;
2326 addr_t curr_addr = addr;
2327 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2328 size_t bytes_left = dst_max_len - 1;
2329 char *curr_dst = dst;
2330
2331 while (bytes_left > 0)
2332 {
2333 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2334 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2335 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2336
2337 if (bytes_read == 0)
2338 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002339 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002340 dst[total_cstr_len] = '\0';
2341 break;
2342 }
2343 const size_t len = strlen(curr_dst);
2344
2345 total_cstr_len += len;
2346
2347 if (len < bytes_to_read)
2348 break;
2349
2350 curr_dst += bytes_read;
2351 curr_addr += bytes_read;
2352 bytes_left -= bytes_read;
2353 }
2354 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002355 else
2356 {
2357 if (dst == NULL)
2358 result_error.SetErrorString("invalid arguments");
2359 else
2360 result_error.Clear();
2361 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002362 return total_cstr_len;
2363}
2364
2365size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002366Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2367{
Chris Lattner24943d22010-06-08 16:52:24 +00002368 if (buf == NULL || size == 0)
2369 return 0;
2370
2371 size_t bytes_read = 0;
2372 uint8_t *bytes = (uint8_t *)buf;
2373
2374 while (bytes_read < size)
2375 {
2376 const size_t curr_size = size - bytes_read;
2377 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2378 bytes + bytes_read,
2379 curr_size,
2380 error);
2381 bytes_read += curr_bytes_read;
2382 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2383 break;
2384 }
2385
2386 // Replace any software breakpoint opcodes that fall into this range back
2387 // into "buf" before we return
2388 if (bytes_read > 0)
2389 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2390 return bytes_read;
2391}
2392
Greg Claytonf72fdee2010-12-16 20:01:20 +00002393uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002394Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002395{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002396 Scalar scalar;
2397 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2398 return scalar.ULongLong(fail_value);
2399 return fail_value;
2400}
2401
2402addr_t
2403Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2404{
2405 Scalar scalar;
2406 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2407 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2408 return LLDB_INVALID_ADDRESS;
2409}
2410
2411
2412bool
2413Process::WritePointerToMemory (lldb::addr_t vm_addr,
2414 lldb::addr_t ptr_value,
2415 Error &error)
2416{
2417 Scalar scalar;
2418 const uint32_t addr_byte_size = GetAddressByteSize();
2419 if (addr_byte_size <= 4)
2420 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002421 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002422 scalar = ptr_value;
2423 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002424}
2425
Chris Lattner24943d22010-06-08 16:52:24 +00002426size_t
2427Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2428{
2429 size_t bytes_written = 0;
2430 const uint8_t *bytes = (const uint8_t *)buf;
2431
2432 while (bytes_written < size)
2433 {
2434 const size_t curr_size = size - bytes_written;
2435 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2436 bytes + bytes_written,
2437 curr_size,
2438 error);
2439 bytes_written += curr_bytes_written;
2440 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2441 break;
2442 }
2443 return bytes_written;
2444}
2445
2446size_t
2447Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2448{
Greg Claytonfd119992011-01-07 06:08:19 +00002449#if defined (ENABLE_MEMORY_CACHING)
2450 m_memory_cache.Flush (addr, size);
2451#endif
2452
Chris Lattner24943d22010-06-08 16:52:24 +00002453 if (buf == NULL || size == 0)
2454 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002455
Jim Ingham21f37ad2011-08-09 02:12:22 +00002456 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002457
Chris Lattner24943d22010-06-08 16:52:24 +00002458 // We need to write any data that would go where any current software traps
2459 // (enabled software breakpoints) any software traps (breakpoints) that we
2460 // may have placed in our tasks memory.
2461
2462 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2463 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2464
2465 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002466 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002467
2468 BreakpointSiteList::collection::const_iterator pos;
2469 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002470 addr_t intersect_addr = 0;
2471 size_t intersect_size = 0;
2472 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002473 const uint8_t *ubuf = (const uint8_t *)buf;
2474
2475 for (pos = iter; pos != end; ++pos)
2476 {
2477 BreakpointSiteSP bp;
2478 bp = pos->second;
2479
2480 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2481 assert(addr <= intersect_addr && intersect_addr < addr + size);
2482 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2483 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2484
2485 // Check for bytes before this breakpoint
2486 const addr_t curr_addr = addr + bytes_written;
2487 if (intersect_addr > curr_addr)
2488 {
2489 // There are some bytes before this breakpoint that we need to
2490 // just write to memory
2491 size_t curr_size = intersect_addr - curr_addr;
2492 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2493 ubuf + bytes_written,
2494 curr_size,
2495 error);
2496 bytes_written += curr_bytes_written;
2497 if (curr_bytes_written != curr_size)
2498 {
2499 // We weren't able to write all of the requested bytes, we
2500 // are done looping and will return the number of bytes that
2501 // we have written so far.
2502 break;
2503 }
2504 }
2505
2506 // Now write any bytes that would cover up any software breakpoints
2507 // directly into the breakpoint opcode buffer
2508 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2509 bytes_written += intersect_size;
2510 }
2511
2512 // Write any remaining bytes after the last breakpoint if we have any left
2513 if (bytes_written < size)
2514 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2515 ubuf + bytes_written,
2516 size - bytes_written,
2517 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002518
Chris Lattner24943d22010-06-08 16:52:24 +00002519 return bytes_written;
2520}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002521
2522size_t
Greg Clayton36da2aa2013-01-25 18:06:21 +00002523Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonc0fa5332011-05-22 22:46:53 +00002524{
2525 if (byte_size == UINT32_MAX)
2526 byte_size = scalar.GetByteSize();
2527 if (byte_size > 0)
2528 {
2529 uint8_t buf[32];
2530 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2531 if (mem_size > 0)
2532 return WriteMemory(addr, buf, mem_size, error);
2533 else
2534 error.SetErrorString ("failed to get scalar as memory data");
2535 }
2536 else
2537 {
2538 error.SetErrorString ("invalid scalar value");
2539 }
2540 return 0;
2541}
2542
2543size_t
2544Process::ReadScalarIntegerFromMemory (addr_t addr,
2545 uint32_t byte_size,
2546 bool is_signed,
2547 Scalar &scalar,
2548 Error &error)
2549{
2550 uint64_t uval;
2551
2552 if (byte_size <= sizeof(uval))
2553 {
2554 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2555 if (bytes_read == byte_size)
2556 {
2557 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Clayton36da2aa2013-01-25 18:06:21 +00002558 lldb::offset_t offset = 0;
Greg Claytonc0fa5332011-05-22 22:46:53 +00002559 if (byte_size <= 4)
2560 scalar = data.GetMaxU32 (&offset, byte_size);
2561 else
2562 scalar = data.GetMaxU64 (&offset, byte_size);
2563
2564 if (is_signed)
2565 scalar.SignExtend(byte_size * 8);
2566 return bytes_read;
2567 }
2568 }
2569 else
2570 {
2571 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2572 }
2573 return 0;
2574}
2575
Greg Clayton613b8732011-05-17 03:37:42 +00002576#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002577addr_t
2578Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2579{
Jim Inghame6bd1422011-06-20 17:32:44 +00002580 if (GetPrivateState() != eStateStopped)
2581 return LLDB_INVALID_ADDRESS;
2582
Greg Clayton613b8732011-05-17 03:37:42 +00002583#if defined (USE_ALLOCATE_MEMORY_CACHE)
2584 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2585#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002586 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2587 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2588 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002589 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 +00002590 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002591 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002592 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002593 m_mod_id.GetStopID(),
2594 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002595 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002596#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002597}
2598
Sean Callanan6cf6c472011-09-20 23:01:51 +00002599bool
2600Process::CanJIT ()
2601{
Sean Callanan04200f62012-02-14 22:50:38 +00002602 if (m_can_jit == eCanJITDontKnow)
2603 {
2604 Error err;
2605
2606 uint64_t allocated_memory = AllocateMemory(8,
2607 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2608 err);
2609
2610 if (err.Success())
2611 m_can_jit = eCanJITYes;
2612 else
2613 m_can_jit = eCanJITNo;
2614
2615 DeallocateMemory (allocated_memory);
2616 }
2617
Sean Callanan6cf6c472011-09-20 23:01:51 +00002618 return m_can_jit == eCanJITYes;
2619}
2620
2621void
2622Process::SetCanJIT (bool can_jit)
2623{
2624 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2625}
2626
Chris Lattner24943d22010-06-08 16:52:24 +00002627Error
2628Process::DeallocateMemory (addr_t ptr)
2629{
Greg Clayton613b8732011-05-17 03:37:42 +00002630 Error error;
2631#if defined (USE_ALLOCATE_MEMORY_CACHE)
2632 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2633 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002634 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Clayton613b8732011-05-17 03:37:42 +00002635 }
2636#else
2637 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002638
2639 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2640 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002641 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 +00002642 ptr,
2643 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002644 m_mod_id.GetStopID(),
2645 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002646#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002647 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002648}
2649
Han Ming Ong2529aa32012-11-17 00:33:14 +00002650
Greg Claytonb5a8f142012-02-05 02:38:54 +00002651ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002652Process::ReadModuleFromMemory (const FileSpec& file_spec,
2653 lldb::addr_t header_addr,
2654 bool add_image_to_target,
2655 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002656{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002657 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002658 if (module_sp)
2659 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002660 Error error;
2661 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2662 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002663 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002664 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002665 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002666 m_target.GetImages().Append(module_sp);
2667 if (load_sections_in_target)
2668 {
2669 bool changed = false;
2670 module_sp->SetLoadAddress (m_target, 0, changed);
2671 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002672 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002673 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002674 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002675 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002676 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002677}
Chris Lattner24943d22010-06-08 16:52:24 +00002678
2679Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002680Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002681{
2682 Error error;
2683 error.SetErrorString("watchpoints are not supported");
2684 return error;
2685}
2686
2687Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002688Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002689{
2690 Error error;
2691 error.SetErrorString("watchpoints are not supported");
2692 return error;
2693}
2694
2695StateType
2696Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2697{
2698 StateType state;
2699 // Now wait for the process to launch and return control to us, and then
2700 // call DidLaunch:
2701 while (1)
2702 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002703 event_sp.reset();
2704 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2705
Greg Clayton20206082011-11-17 01:23:07 +00002706 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002707 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002708
2709 // If state is invalid, then we timed out
2710 if (state == eStateInvalid)
2711 break;
2712
2713 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002714 HandlePrivateEvent (event_sp);
2715 }
2716 return state;
2717}
2718
2719Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002720Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002721{
2722 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002723 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002724 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002725 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002726 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002727
Greg Clayton5beb99d2011-08-11 02:48:45 +00002728 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002729 if (exe_module)
2730 {
Greg Clayton180546b2011-04-30 01:09:13 +00002731 char local_exec_file_path[PATH_MAX];
2732 char platform_exec_file_path[PATH_MAX];
2733 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2734 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002735 if (exe_module->GetFileSpec().Exists())
2736 {
Greg Claytona2f74232011-02-24 22:24:29 +00002737 if (PrivateStateThreadIsValid ())
2738 PausePrivateStateThread ();
2739
Chris Lattner24943d22010-06-08 16:52:24 +00002740 error = WillLaunch (exe_module);
2741 if (error.Success())
2742 {
Greg Claytond8c62532010-10-07 04:19:01 +00002743 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002744 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002745
Greg Clayton777c6b72012-09-04 20:29:05 +00002746 if (m_run_lock.WriteTryLock())
2747 {
2748 // Now launch using these arguments.
2749 error = DoLaunch (exe_module, launch_info);
2750 }
2751 else
2752 {
2753 // This shouldn't happen
2754 error.SetErrorString("failed to acquire process run lock");
2755 }
Chris Lattner24943d22010-06-08 16:52:24 +00002756
2757 if (error.Fail())
2758 {
2759 if (GetID() != LLDB_INVALID_PROCESS_ID)
2760 {
2761 SetID (LLDB_INVALID_PROCESS_ID);
2762 const char *error_string = error.AsCString();
2763 if (error_string == NULL)
2764 error_string = "launch failed";
2765 SetExitStatus (-1, error_string);
2766 }
2767 }
2768 else
2769 {
2770 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002771 TimeValue timeout_time;
2772 timeout_time = TimeValue::Now();
2773 timeout_time.OffsetWithSeconds(10);
2774 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002775
Greg Clayton49859592011-06-22 01:42:17 +00002776 if (state == eStateInvalid || event_sp.get() == NULL)
2777 {
2778 // We were able to launch the process, but we failed to
2779 // catch the initial stop.
2780 SetExitStatus (0, "failed to catch stop after launch");
2781 Destroy();
2782 }
2783 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002784 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002785
Chris Lattner24943d22010-06-08 16:52:24 +00002786 DidLaunch ();
2787
Greg Clayton9ce95382012-02-13 23:10:39 +00002788 DynamicLoader *dyld = GetDynamicLoader ();
2789 if (dyld)
2790 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002791
Greg Clayton37f962e2011-08-22 02:49:39 +00002792 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002793 // This delays passing the stopped event to listeners till DidLaunch gets
2794 // a chance to complete...
2795 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002796
2797 if (PrivateStateThreadIsValid ())
2798 ResumePrivateStateThread ();
2799 else
2800 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002801 }
2802 else if (state == eStateExited)
2803 {
2804 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2805 // not likely to work, and return an invalid pid.
2806 HandlePrivateEvent (event_sp);
2807 }
2808 }
2809 }
2810 }
2811 else
2812 {
Greg Clayton9c236732011-10-26 00:56:27 +00002813 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002814 }
2815 }
2816 return error;
2817}
2818
Greg Clayton46c9a352012-02-09 06:16:32 +00002819
2820Error
2821Process::LoadCore ()
2822{
2823 Error error = DoLoadCore();
2824 if (error.Success())
2825 {
2826 if (PrivateStateThreadIsValid ())
2827 ResumePrivateStateThread ();
2828 else
2829 StartPrivateStateThread ();
2830
Greg Clayton9ce95382012-02-13 23:10:39 +00002831 DynamicLoader *dyld = GetDynamicLoader ();
2832 if (dyld)
2833 dyld->DidAttach();
2834
2835 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002836 // We successfully loaded a core file, now pretend we stopped so we can
2837 // show all of the threads in the core file and explore the crashed
2838 // state.
2839 SetPrivateState (eStateStopped);
2840
2841 }
2842 return error;
2843}
2844
Greg Clayton9ce95382012-02-13 23:10:39 +00002845DynamicLoader *
2846Process::GetDynamicLoader ()
2847{
2848 if (m_dyld_ap.get() == NULL)
2849 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2850 return m_dyld_ap.get();
2851}
Greg Clayton46c9a352012-02-09 06:16:32 +00002852
2853
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002854Process::NextEventAction::EventActionResult
2855Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002856{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002857 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2858 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002859 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002860 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002861 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002862 return eEventActionRetry;
2863
2864 case eStateStopped:
2865 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002866 {
2867 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002868 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002869 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2870 if (m_exec_count > 0)
2871 {
2872 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002873 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002874 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002875 return eEventActionRetry;
2876 }
2877 else
2878 {
2879 m_process->CompleteAttach ();
2880 return eEventActionSuccess;
2881 }
2882 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002883 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002884
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002885 default:
2886 case eStateExited:
2887 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002888 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002889 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002890
2891 m_exit_string.assign ("No valid Process");
2892 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002893}
Chris Lattner24943d22010-06-08 16:52:24 +00002894
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002895Process::NextEventAction::EventActionResult
2896Process::AttachCompletionHandler::HandleBeingInterrupted()
2897{
2898 return eEventActionSuccess;
2899}
2900
2901const char *
2902Process::AttachCompletionHandler::GetExitString ()
2903{
2904 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002905}
2906
2907Error
Greg Clayton527154d2011-11-15 03:53:30 +00002908Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002909{
Chris Lattner24943d22010-06-08 16:52:24 +00002910 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002911 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002912 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002913 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002914
Greg Clayton527154d2011-11-15 03:53:30 +00002915 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002916 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002917 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002918 {
Greg Clayton527154d2011-11-15 03:53:30 +00002919 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002920
Greg Clayton527154d2011-11-15 03:53:30 +00002921 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002922 {
Greg Clayton527154d2011-11-15 03:53:30 +00002923 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2924
2925 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002926 {
Greg Clayton527154d2011-11-15 03:53:30 +00002927 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2928 if (error.Success())
2929 {
Greg Claytond34a3b22012-10-12 16:10:12 +00002930 if (m_run_lock.WriteTryLock())
2931 {
2932 m_should_detach = true;
2933 SetPublicState (eStateAttaching);
2934 // Now attach using these arguments.
2935 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2936 }
2937 else
2938 {
2939 // This shouldn't happen
2940 error.SetErrorString("failed to acquire process run lock");
2941 }
Greg Claytonffa43a62011-11-17 04:46:02 +00002942
Greg Clayton527154d2011-11-15 03:53:30 +00002943 if (error.Fail())
2944 {
2945 if (GetID() != LLDB_INVALID_PROCESS_ID)
2946 {
2947 SetID (LLDB_INVALID_PROCESS_ID);
2948 if (error.AsCString() == NULL)
2949 error.SetErrorString("attach failed");
2950
2951 SetExitStatus(-1, error.AsCString());
2952 }
2953 }
2954 else
2955 {
2956 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2957 StartPrivateStateThread();
2958 }
2959 return error;
2960 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002961 }
Greg Clayton527154d2011-11-15 03:53:30 +00002962 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002963 {
Greg Clayton527154d2011-11-15 03:53:30 +00002964 ProcessInstanceInfoList process_infos;
2965 PlatformSP platform_sp (m_target.GetPlatform ());
2966
2967 if (platform_sp)
2968 {
2969 ProcessInstanceInfoMatch match_info;
2970 match_info.GetProcessInfo() = attach_info;
2971 match_info.SetNameMatchType (eNameMatchEquals);
2972 platform_sp->FindProcesses (match_info, process_infos);
2973 const uint32_t num_matches = process_infos.GetSize();
2974 if (num_matches == 1)
2975 {
2976 attach_pid = process_infos.GetProcessIDAtIndex(0);
2977 // Fall through and attach using the above process ID
2978 }
2979 else
2980 {
2981 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2982 if (num_matches > 1)
2983 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2984 else
2985 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2986 }
2987 }
2988 else
2989 {
2990 error.SetErrorString ("invalid platform, can't find processes by name");
2991 return error;
2992 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002993 }
Chris Lattner24943d22010-06-08 16:52:24 +00002994 }
2995 else
Greg Clayton527154d2011-11-15 03:53:30 +00002996 {
2997 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002998 }
2999 }
Greg Clayton527154d2011-11-15 03:53:30 +00003000
3001 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003002 {
Greg Clayton527154d2011-11-15 03:53:30 +00003003 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003004 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00003005 {
Greg Clayton527154d2011-11-15 03:53:30 +00003006
Greg Claytond34a3b22012-10-12 16:10:12 +00003007 if (m_run_lock.WriteTryLock())
3008 {
3009 // Now attach using these arguments.
3010 m_should_detach = true;
3011 SetPublicState (eStateAttaching);
3012 error = DoAttachToProcessWithID (attach_pid, attach_info);
3013 }
3014 else
3015 {
3016 // This shouldn't happen
3017 error.SetErrorString("failed to acquire process run lock");
3018 }
3019
Greg Clayton527154d2011-11-15 03:53:30 +00003020 if (error.Success())
3021 {
3022
3023 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3024 StartPrivateStateThread();
3025 }
3026 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003027 {
3028 if (GetID() != LLDB_INVALID_PROCESS_ID)
3029 {
3030 SetID (LLDB_INVALID_PROCESS_ID);
3031 const char *error_string = error.AsCString();
3032 if (error_string == NULL)
3033 error_string = "attach failed";
3034
3035 SetExitStatus(-1, error_string);
3036 }
3037 }
Chris Lattner24943d22010-06-08 16:52:24 +00003038 }
3039 }
3040 return error;
3041}
3042
Greg Clayton75c703d2011-02-16 04:46:07 +00003043void
3044Process::CompleteAttach ()
3045{
3046 // Let the process subclass figure out at much as it can about the process
3047 // before we go looking for a dynamic loader plug-in.
3048 DidAttach();
3049
Jim Ingham0d7f7772011-09-15 01:10:17 +00003050 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3051 // the same as the one we've already set, switch architectures.
3052 PlatformSP platform_sp (m_target.GetPlatform ());
3053 assert (platform_sp.get());
3054 if (platform_sp)
3055 {
Greg Claytonb170aee2012-05-08 01:45:38 +00003056 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Claytonaad2b0f2013-01-11 20:49:54 +00003057 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Claytonb170aee2012-05-08 01:45:38 +00003058 {
3059 ArchSpec platform_arch;
3060 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3061 if (platform_sp)
3062 {
3063 m_target.SetPlatform (platform_sp);
3064 m_target.SetArchitecture(platform_arch);
3065 }
3066 }
3067 else
3068 {
3069 ProcessInstanceInfo process_info;
3070 platform_sp->GetProcessInfo (GetID(), process_info);
3071 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callanan40e278c2012-12-13 22:07:14 +00003072 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Claytonb170aee2012-05-08 01:45:38 +00003073 m_target.SetArchitecture (process_arch);
3074 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00003075 }
3076
3077 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00003078 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00003079 DynamicLoader *dyld = GetDynamicLoader ();
3080 if (dyld)
3081 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00003082
Greg Clayton37f962e2011-08-22 02:49:39 +00003083 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00003084 // Figure out which one is the executable, and set that in our target:
Enrico Granata146d9522012-11-08 02:22:02 +00003085 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham93367902012-05-30 02:19:25 +00003086 Mutex::Locker modules_locker(target_modules.GetMutex());
3087 size_t num_modules = target_modules.GetSize();
3088 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003089
Greg Clayton75c703d2011-02-16 04:46:07 +00003090 for (int i = 0; i < num_modules; i++)
3091 {
Jim Ingham93367902012-05-30 02:19:25 +00003092 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00003093 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00003094 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00003095 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00003096 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003097 break;
3098 }
3099 }
Jim Ingham93367902012-05-30 02:19:25 +00003100 if (new_executable_module_sp)
3101 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00003102}
3103
Chris Lattner24943d22010-06-08 16:52:24 +00003104Error
Jason Molendafac2e622012-09-29 04:02:01 +00003105Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00003106{
Greg Claytone71e2582011-02-04 01:58:07 +00003107 m_abi_sp.reset();
3108 m_process_input_reader.reset();
3109
3110 // Find the process and its architecture. Make sure it matches the architecture
3111 // of the current Target, and if not adjust it.
3112
Jason Molendafac2e622012-09-29 04:02:01 +00003113 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00003114 if (error.Success())
3115 {
Greg Claytona2f74232011-02-24 22:24:29 +00003116 if (GetID() != LLDB_INVALID_PROCESS_ID)
3117 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00003118 EventSP event_sp;
3119 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3120
3121 if (state == eStateStopped || state == eStateCrashed)
3122 {
3123 // If we attached and actually have a process on the other end, then
3124 // this ended up being the equivalent of an attach.
3125 CompleteAttach ();
3126
3127 // This delays passing the stopped event to listeners till
3128 // CompleteAttach gets a chance to complete...
3129 HandlePrivateEvent (event_sp);
3130
3131 }
Greg Claytona2f74232011-02-24 22:24:29 +00003132 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00003133
3134 if (PrivateStateThreadIsValid ())
3135 ResumePrivateStateThread ();
3136 else
3137 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00003138 }
3139 return error;
3140}
3141
3142
3143Error
Jim Ingham027aaa72012-04-19 01:40:33 +00003144Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00003145{
Jim Inghame1a654b2012-09-06 19:24:17 +00003146 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00003147 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00003148 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00003149 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00003150 StateAsCString(m_public_state.GetValue()),
3151 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00003152
3153 Error error (WillResume());
3154 // Tell the process it is about to resume before the thread list
3155 if (error.Success())
3156 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003157 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003158 // can let all of our threads know that they are about to be
3159 // resumed. Threads will each be called with
3160 // Thread::WillResume(StateType) where StateType contains the state
3161 // that they are supposed to have when the process is resumed
3162 // (suspended/running/stepping). Threads should also check
3163 // their resume signal in lldb::Thread::GetResumeSignal()
3164 // to see if they are suppoed to start back up with a signal.
3165 if (m_thread_list.WillResume())
3166 {
Jim Ingham1831e782012-04-07 00:00:41 +00003167 // Last thing, do the PreResumeActions.
3168 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003169 {
Jim Ingham1831e782012-04-07 00:00:41 +00003170 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3171 }
3172 else
3173 {
3174 m_mod_id.BumpResumeID();
3175 error = DoResume();
3176 if (error.Success())
3177 {
3178 DidResume();
3179 m_thread_list.DidResume();
3180 if (log)
3181 log->Printf ("Process thinks the process has resumed.");
3182 }
Chris Lattner24943d22010-06-08 16:52:24 +00003183 }
3184 }
3185 else
3186 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003187 // Somebody wanted to run without running. So generate a continue & a stopped event,
3188 // and let the world handle them.
3189 if (log)
3190 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3191
3192 SetPrivateState(eStateRunning);
3193 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003194 }
3195 }
Jim Inghamac959662011-01-24 06:34:17 +00003196 else if (log)
3197 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003198 return error;
3199}
3200
3201Error
3202Process::Halt ()
3203{
Jim Ingham43892562012-06-06 00:29:30 +00003204 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3205 // we could just straightaway get another event. It just narrows the window...
3206 m_currently_handling_event.WaitForValueEqualTo(false);
3207
3208
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003209 // Pause our private state thread so we can ensure no one else eats
3210 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003211 Listener halt_listener ("lldb.process.halt_listener");
3212 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003213
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003214 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003215 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003216
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003217 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003218 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003219
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003220 bool caused_stop = false;
3221
3222 // Ask the process subclass to actually halt our process
3223 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003224 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003225 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003226 if (m_public_state.GetValue() == eStateAttaching)
3227 {
3228 SetExitStatus(SIGKILL, "Cancelled async attach.");
3229 Destroy ();
3230 }
3231 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003232 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003233 // If "caused_stop" is true, then DoHalt stopped the process. If
3234 // "caused_stop" is false, the process was already stopped.
3235 // If the DoHalt caused the process to stop, then we want to catch
3236 // this event and set the interrupted bool to true before we pass
3237 // this along so clients know that the process was interrupted by
3238 // a halt command.
3239 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003240 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003241 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003242 TimeValue timeout_time;
3243 timeout_time = TimeValue::Now();
3244 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003245 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3246 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003247
Jim Inghamf9f40c22011-02-08 05:20:59 +00003248 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003249 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003250 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003251 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003252 }
3253 else
3254 {
Greg Clayton20206082011-11-17 01:23:07 +00003255 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003256 {
3257 // We caused the process to interrupt itself, so mark this
3258 // as such in the stop event so clients can tell an interrupted
3259 // process from a natural stop
3260 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3261 }
3262 else
3263 {
3264 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3265 if (log)
3266 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3267 error.SetErrorString ("Did not get stopped event after halt.");
3268 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003269 }
3270 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003271 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003272 }
3273 }
Chris Lattner24943d22010-06-08 16:52:24 +00003274 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003275 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003276 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003277
3278 // Post any event we might have consumed. If all goes well, we will have
3279 // stopped the process, intercepted the event and set the interrupted
3280 // bool in the event. Post it to the private event queue and that will end up
3281 // correctly setting the state.
3282 if (event_sp)
3283 m_private_state_broadcaster.BroadcastEvent(event_sp);
3284
Chris Lattner24943d22010-06-08 16:52:24 +00003285 return error;
3286}
3287
3288Error
3289Process::Detach ()
3290{
3291 Error error (WillDetach());
3292
3293 if (error.Success())
3294 {
3295 DisableAllBreakpointSites();
3296 error = DoDetach();
3297 if (error.Success())
3298 {
3299 DidDetach();
3300 StopPrivateStateThread();
3301 }
3302 }
3303 return error;
3304}
3305
3306Error
3307Process::Destroy ()
3308{
3309 Error error (WillDestroy());
3310 if (error.Success())
3311 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003312 EventSP exit_event_sp;
Jim Inghamf4928de2012-05-23 15:46:31 +00003313 if (m_public_state.GetValue() == eStateRunning)
3314 {
Greg Clayton38ae5b92012-09-05 00:37:58 +00003315 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003316 if (log)
3317 log->Printf("Process::Destroy() About to halt.");
Jim Inghamf4928de2012-05-23 15:46:31 +00003318 error = Halt();
3319 if (error.Success())
3320 {
3321 // Consume the halt event.
Jim Inghamf4928de2012-05-23 15:46:31 +00003322 TimeValue timeout (TimeValue::Now());
Jim Ingham43892562012-06-06 00:29:30 +00003323 timeout.OffsetWithSeconds(1);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003324 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3325 if (state != eStateExited)
3326 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3327
Jim Inghamf4928de2012-05-23 15:46:31 +00003328 if (state != eStateStopped)
3329 {
Jim Inghamf4928de2012-05-23 15:46:31 +00003330 if (log)
3331 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Ingham43892562012-06-06 00:29:30 +00003332 // If we really couldn't stop the process then we should just error out here, but if the
3333 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3334 StateType private_state = m_private_state.GetValue();
3335 if (private_state != eStateStopped && private_state != eStateExited)
3336 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003337 // If we exited when we were waiting for a process to stop, then
3338 // forward the event here so we don't lose the event
Jim Ingham43892562012-06-06 00:29:30 +00003339 return error;
3340 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003341 }
3342 }
3343 else
3344 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003345 if (log)
3346 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3347 return error;
Jim Inghamf4928de2012-05-23 15:46:31 +00003348 }
3349 }
Jim Ingham43892562012-06-06 00:29:30 +00003350
3351 if (m_public_state.GetValue() != eStateRunning)
3352 {
3353 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3354 // kill it, we don't want it hitting a breakpoint...
3355 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3356 // we're not going to have much luck doing this now.
3357 m_thread_list.DiscardThreadPlans();
3358 DisableAllBreakpointSites();
3359 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003360
Chris Lattner24943d22010-06-08 16:52:24 +00003361 error = DoDestroy();
3362 if (error.Success())
3363 {
3364 DidDestroy();
3365 StopPrivateStateThread();
3366 }
Caroline Tice861efb32010-11-16 05:07:41 +00003367 m_stdio_communication.StopReadThread();
3368 m_stdio_communication.Disconnect();
3369 if (m_process_input_reader && m_process_input_reader->IsActive())
3370 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3371 if (m_process_input_reader)
3372 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003373
3374 // If we exited when we were waiting for a process to stop, then
3375 // forward the event here so we don't lose the event
3376 if (exit_event_sp)
3377 {
3378 // Directly broadcast our exited event because we shut down our
3379 // private state thread above
3380 BroadcastEvent(exit_event_sp);
3381 }
3382
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003383 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3384 // the last events through the event system, in which case we might strand the write lock. Unlock
3385 // it here so when we do to tear down the process we don't get an error destroying the lock.
3386 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003387 }
3388 return error;
3389}
3390
3391Error
3392Process::Signal (int signal)
3393{
3394 Error error (WillSignal());
3395 if (error.Success())
3396 {
3397 error = DoSignal(signal);
3398 if (error.Success())
3399 DidSignal();
3400 }
3401 return error;
3402}
3403
Greg Clayton395fc332011-02-15 21:59:32 +00003404lldb::ByteOrder
3405Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003406{
Greg Clayton395fc332011-02-15 21:59:32 +00003407 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003408}
3409
3410uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003411Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003412{
Greg Clayton395fc332011-02-15 21:59:32 +00003413 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003414}
3415
Greg Clayton395fc332011-02-15 21:59:32 +00003416
Chris Lattner24943d22010-06-08 16:52:24 +00003417bool
3418Process::ShouldBroadcastEvent (Event *event_ptr)
3419{
3420 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3421 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00003422 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003423
3424 switch (state)
3425 {
Greg Claytone71e2582011-02-04 01:58:07 +00003426 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003427 case eStateAttaching:
3428 case eStateLaunching:
3429 case eStateDetached:
3430 case eStateExited:
3431 case eStateUnloaded:
3432 // These events indicate changes in the state of the debugging session, always report them.
3433 return_value = true;
3434 break;
3435 case eStateInvalid:
3436 // We stopped for no apparent reason, don't report it.
3437 return_value = false;
3438 break;
3439 case eStateRunning:
3440 case eStateStepping:
3441 // If we've started the target running, we handle the cases where we
3442 // are already running and where there is a transition from stopped to
3443 // running differently.
3444 // running -> running: Automatically suppress extra running events
3445 // stopped -> running: Report except when there is one or more no votes
3446 // and no yes votes.
3447 SynchronouslyNotifyStateChanged (state);
3448 switch (m_public_state.GetValue())
3449 {
3450 case eStateRunning:
3451 case eStateStepping:
3452 // We always suppress multiple runnings with no PUBLIC stop in between.
3453 return_value = false;
3454 break;
3455 default:
3456 // TODO: make this work correctly. For now always report
3457 // run if we aren't running so we don't miss any runnning
3458 // events. If I run the lldb/test/thread/a.out file and
3459 // break at main.cpp:58, run and hit the breakpoints on
3460 // multiple threads, then somehow during the stepping over
3461 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003462
3463 // This is a transition from stop to run.
3464 switch (m_thread_list.ShouldReportRun (event_ptr))
3465 {
3466 case eVoteYes:
3467 case eVoteNoOpinion:
3468 return_value = true;
3469 break;
3470 case eVoteNo:
3471 return_value = false;
3472 break;
3473 }
3474 break;
3475 }
3476 break;
3477 case eStateStopped:
3478 case eStateCrashed:
3479 case eStateSuspended:
3480 {
3481 // We've stopped. First see if we're going to restart the target.
3482 // If we are going to stop, then we always broadcast the event.
3483 // 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 +00003484 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003485
3486 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003487 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003488 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003489 if (log)
3490 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003491 return true;
3492 }
3493 else
3494 {
Chris Lattner24943d22010-06-08 16:52:24 +00003495
3496 if (m_thread_list.ShouldStop (event_ptr) == false)
3497 {
Jim Ingham8290bba2012-09-05 21:13:56 +00003498 // ShouldStop may have restarted the target already. If so, don't
3499 // resume it twice.
3500 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00003501 switch (m_thread_list.ShouldReportStop (event_ptr))
3502 {
3503 case eVoteYes:
3504 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003505 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003506 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003507 case eVoteNo:
3508 return_value = false;
3509 break;
3510 }
3511
3512 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003513 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham8290bba2012-09-05 21:13:56 +00003514 if (!was_restarted)
3515 PrivateResume ();
Chris Lattner24943d22010-06-08 16:52:24 +00003516 }
3517 else
3518 {
3519 return_value = true;
3520 SynchronouslyNotifyStateChanged (state);
3521 }
3522 }
3523 }
3524 }
3525
3526 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003527 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003528 return return_value;
3529}
3530
Chris Lattner24943d22010-06-08 16:52:24 +00003531
3532bool
Jim Ingham1831e782012-04-07 00:00:41 +00003533Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003534{
Greg Claytone005f2c2010-11-06 01:53:30 +00003535 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003536
Greg Claytonb72d0f02011-04-12 05:54:46 +00003537 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003538 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003539 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3540
Jim Ingham1831e782012-04-07 00:00:41 +00003541 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003542 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003543
3544 // Create a thread that watches our internal state and controls which
3545 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003546 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003547 if (already_running)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003548 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham1831e782012-04-07 00:00:41 +00003549 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003550 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003551
3552 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003553 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003554 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3555 if (success)
3556 {
3557 ResumePrivateStateThread();
3558 return true;
3559 }
3560 else
3561 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003562}
3563
3564void
3565Process::PausePrivateStateThread ()
3566{
3567 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3568}
3569
3570void
3571Process::ResumePrivateStateThread ()
3572{
3573 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3574}
3575
3576void
3577Process::StopPrivateStateThread ()
3578{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003579 if (PrivateStateThreadIsValid ())
3580 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003581 else
3582 {
3583 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3584 if (log)
3585 printf ("Went to stop the private state thread, but it was already invalid.");
3586 }
Chris Lattner24943d22010-06-08 16:52:24 +00003587}
3588
3589void
3590Process::ControlPrivateStateThread (uint32_t signal)
3591{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003592 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003593
3594 assert (signal == eBroadcastInternalStateControlStop ||
3595 signal == eBroadcastInternalStateControlPause ||
3596 signal == eBroadcastInternalStateControlResume);
3597
3598 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003599 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003600
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003601 // Signal the private state thread. First we should copy this is case the
3602 // thread starts exiting since the private state thread will NULL this out
3603 // when it exits
3604 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003605 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003606 {
3607 TimeValue timeout_time;
3608 bool timed_out;
3609
3610 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3611
3612 timeout_time = TimeValue::Now();
3613 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003614 if (log)
3615 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003616 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3617 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3618
3619 if (signal == eBroadcastInternalStateControlStop)
3620 {
3621 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003622 {
3623 Error error;
3624 Host::ThreadCancel (private_state_thread, &error);
3625 if (log)
3626 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3627 }
3628 else
3629 {
3630 if (log)
3631 log->Printf ("The control event killed the private state thread without having to cancel.");
3632 }
Chris Lattner24943d22010-06-08 16:52:24 +00003633
3634 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003635 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003636 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003637 }
3638 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003639 else
3640 {
3641 if (log)
3642 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3643 }
Chris Lattner24943d22010-06-08 16:52:24 +00003644}
3645
3646void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003647Process::SendAsyncInterrupt ()
3648{
3649 if (PrivateStateThreadIsValid())
3650 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3651 else
3652 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3653}
3654
3655void
Chris Lattner24943d22010-06-08 16:52:24 +00003656Process::HandlePrivateEvent (EventSP &event_sp)
3657{
Greg Claytone005f2c2010-11-06 01:53:30 +00003658 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003659 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003660
Greg Clayton68ca8232011-01-25 02:58:48 +00003661 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003662
3663 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003664 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003665 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003666 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003667 switch (action_result)
3668 {
3669 case NextEventAction::eEventActionSuccess:
3670 SetNextEventAction(NULL);
3671 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003672
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003673 case NextEventAction::eEventActionRetry:
3674 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003675
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003676 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003677 // Handle Exiting Here. If we already got an exited event,
3678 // we should just propagate it. Otherwise, swallow this event,
3679 // and set our state to exit so the next event will kill us.
3680 if (new_state != eStateExited)
3681 {
3682 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003683 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003684 SetNextEventAction(NULL);
3685 return;
3686 }
3687 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003688 break;
3689 }
3690 }
3691
Chris Lattner24943d22010-06-08 16:52:24 +00003692 // See if we should broadcast this state to external clients?
3693 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003694
3695 if (should_broadcast)
3696 {
3697 if (log)
3698 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003699 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003700 __FUNCTION__,
3701 GetID(),
3702 StateAsCString(new_state),
3703 StateAsCString (GetState ()),
3704 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003705 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003706 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003707 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003708 PushProcessInputReader ();
3709 else
3710 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003711
Chris Lattner24943d22010-06-08 16:52:24 +00003712 BroadcastEvent (event_sp);
3713 }
3714 else
3715 {
3716 if (log)
3717 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003718 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003719 __FUNCTION__,
3720 GetID(),
3721 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003722 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003723 }
3724 }
Jim Ingham43892562012-06-06 00:29:30 +00003725 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003726}
3727
3728void *
3729Process::PrivateStateThread (void *arg)
3730{
3731 Process *proc = static_cast<Process*> (arg);
3732 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003733 return result;
3734}
3735
3736void *
3737Process::RunPrivateStateThread ()
3738{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003739 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003740 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003741
Greg Claytone005f2c2010-11-06 01:53:30 +00003742 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003743 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003744 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003745
3746 bool exit_now = false;
3747 while (!exit_now)
3748 {
3749 EventSP event_sp;
3750 WaitForEventsPrivate (NULL, event_sp, control_only);
3751 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3752 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003753 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003754 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 +00003755
Chris Lattner24943d22010-06-08 16:52:24 +00003756 switch (event_sp->GetType())
3757 {
3758 case eBroadcastInternalStateControlStop:
3759 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003760 break; // doing any internal state managment below
3761
3762 case eBroadcastInternalStateControlPause:
3763 control_only = true;
3764 break;
3765
3766 case eBroadcastInternalStateControlResume:
3767 control_only = false;
3768 break;
3769 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003770
Chris Lattner24943d22010-06-08 16:52:24 +00003771 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003772 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003773 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003774 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3775 {
3776 if (m_public_state.GetValue() == eStateAttaching)
3777 {
3778 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003779 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 +00003780 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3781 }
3782 else
3783 {
3784 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003785 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00003786 Halt();
3787 }
3788 continue;
3789 }
Chris Lattner24943d22010-06-08 16:52:24 +00003790
3791 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3792
3793 if (internal_state != eStateInvalid)
3794 {
3795 HandlePrivateEvent (event_sp);
3796 }
3797
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003798 if (internal_state == eStateInvalid ||
3799 internal_state == eStateExited ||
3800 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003801 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003802 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003803 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 +00003804
Chris Lattner24943d22010-06-08 16:52:24 +00003805 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003806 }
Chris Lattner24943d22010-06-08 16:52:24 +00003807 }
3808
Caroline Tice926060e2010-10-29 21:48:37 +00003809 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003810 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003811 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003812
Greg Claytona4881d02011-01-22 07:12:45 +00003813 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3814 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003815 return NULL;
3816}
3817
Chris Lattner24943d22010-06-08 16:52:24 +00003818//------------------------------------------------------------------
3819// Process Event Data
3820//------------------------------------------------------------------
3821
3822Process::ProcessEventData::ProcessEventData () :
3823 EventData (),
3824 m_process_sp (),
3825 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003826 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003827 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003828 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003829{
3830}
3831
3832Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3833 EventData (),
3834 m_process_sp (process_sp),
3835 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003836 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003837 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003838 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003839{
3840}
3841
3842Process::ProcessEventData::~ProcessEventData()
3843{
3844}
3845
3846const ConstString &
3847Process::ProcessEventData::GetFlavorString ()
3848{
3849 static ConstString g_flavor ("Process::ProcessEventData");
3850 return g_flavor;
3851}
3852
3853const ConstString &
3854Process::ProcessEventData::GetFlavor () const
3855{
3856 return ProcessEventData::GetFlavorString ();
3857}
3858
Chris Lattner24943d22010-06-08 16:52:24 +00003859void
3860Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3861{
3862 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003863 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3864 // the public event queue, then other times when we're pretending that this is where we stopped at the
3865 // end of expression evaluation. m_update_state is used to distinguish these
3866 // three cases; it is 0 when we're just pulling it off for private handling,
3867 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003868
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003869 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003870 return;
3871
3872 m_process_sp->SetPublicState (m_state);
3873
3874 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3875 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003876 {
3877 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003878 uint32_t num_threads = curr_thread_list.GetSize();
3879 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003880
Jim Ingham21f37ad2011-08-09 02:12:22 +00003881 // The actions might change one of the thread's stop_info's opinions about whether we should
3882 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003883
3884 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3885 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3886 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3887 // 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
3888 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003889 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003890 for (idx = 0; idx < num_threads; ++idx)
3891 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3892
Jim Inghamb6059b22012-12-13 22:24:15 +00003893 // Use this to track whether we should continue from here. We will only continue the target running if
3894 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
3895 // then it doesn't matter what the other threads say...
3896
3897 bool still_should_stop = false;
Jim Ingham21f37ad2011-08-09 02:12:22 +00003898
Chris Lattner24943d22010-06-08 16:52:24 +00003899 for (idx = 0; idx < num_threads; ++idx)
3900 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003901 curr_thread_list = m_process_sp->GetThreadList();
3902 if (curr_thread_list.GetSize() != num_threads)
3903 {
3904 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003905 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003906 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 +00003907 break;
3908 }
3909
3910 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3911
3912 if (thread_sp->GetIndexID() != thread_index_array[idx])
3913 {
3914 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003915 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003916 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003917 idx,
3918 thread_index_array[idx],
3919 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003920 break;
3921 }
3922
Jim Ingham6297a3a2010-10-20 00:39:53 +00003923 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00003924 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00003925 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003926 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003927 // The stop action might restart the target. If it does, then we want to mark that in the
3928 // event so that whoever is receiving it will know to wait for the running event and reflect
3929 // that state appropriately.
3930 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003931
3932 // FIXME: we might have run.
3933 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003934 {
3935 SetRestarted (true);
3936 break;
3937 }
Jim Inghamb6059b22012-12-13 22:24:15 +00003938
3939 bool this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
3940 if (still_should_stop == false)
3941 still_should_stop = this_thread_wants_to_stop;
Chris Lattner24943d22010-06-08 16:52:24 +00003942 }
3943 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003944
Jim Ingham21f37ad2011-08-09 02:12:22 +00003945
3946 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003947 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003948 if (!still_should_stop)
3949 {
3950 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003951 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00003952 // Use the public resume method here, since this is just
3953 // extending a public resume.
Jim Ingham21f37ad2011-08-09 02:12:22 +00003954 m_process_sp->Resume();
3955 }
3956 else
3957 {
3958 // If we didn't restart, run the Stop Hooks here:
3959 // They might also restart the target, so watch for that.
3960 m_process_sp->GetTarget().RunStopHooks();
3961 if (m_process_sp->GetPrivateState() == eStateRunning)
3962 SetRestarted(true);
3963 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003964 }
3965
Chris Lattner24943d22010-06-08 16:52:24 +00003966 }
3967}
3968
3969void
3970Process::ProcessEventData::Dump (Stream *s) const
3971{
3972 if (m_process_sp)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003973 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003974
Greg Claytonb72d0f02011-04-12 05:54:46 +00003975 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003976}
3977
3978const Process::ProcessEventData *
3979Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3980{
3981 if (event_ptr)
3982 {
3983 const EventData *event_data = event_ptr->GetData();
3984 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3985 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3986 }
3987 return NULL;
3988}
3989
3990ProcessSP
3991Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3992{
3993 ProcessSP process_sp;
3994 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3995 if (data)
3996 process_sp = data->GetProcessSP();
3997 return process_sp;
3998}
3999
4000StateType
4001Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4002{
4003 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4004 if (data == NULL)
4005 return eStateInvalid;
4006 else
4007 return data->GetState();
4008}
4009
4010bool
4011Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4012{
4013 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4014 if (data == NULL)
4015 return false;
4016 else
4017 return data->GetRestarted();
4018}
4019
4020void
4021Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4022{
4023 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4024 if (data != NULL)
4025 data->SetRestarted(new_value);
4026}
4027
4028bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00004029Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4030{
4031 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4032 if (data == NULL)
4033 return false;
4034 else
4035 return data->GetInterrupted ();
4036}
4037
4038void
4039Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4040{
4041 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4042 if (data != NULL)
4043 data->SetInterrupted(new_value);
4044}
4045
4046bool
Chris Lattner24943d22010-06-08 16:52:24 +00004047Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4048{
4049 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4050 if (data)
4051 {
4052 data->SetUpdateStateOnRemoval();
4053 return true;
4054 }
4055 return false;
4056}
4057
Greg Clayton289afcb2012-02-18 05:35:26 +00004058lldb::TargetSP
4059Process::CalculateTarget ()
4060{
4061 return m_target.shared_from_this();
4062}
4063
Chris Lattner24943d22010-06-08 16:52:24 +00004064void
Greg Claytona830adb2010-10-04 01:05:56 +00004065Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00004066{
Greg Clayton567e7f32011-09-22 04:58:26 +00004067 exe_ctx.SetTargetPtr (&m_target);
4068 exe_ctx.SetProcessPtr (this);
4069 exe_ctx.SetThreadPtr(NULL);
4070 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00004071}
4072
Greg Claytone4b9c1f2011-03-08 22:40:15 +00004073//uint32_t
4074//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4075//{
4076// return 0;
4077//}
4078//
4079//ArchSpec
4080//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4081//{
4082// return Host::GetArchSpecForExistingProcess (pid);
4083//}
4084//
4085//ArchSpec
4086//Process::GetArchSpecForExistingProcess (const char *process_name)
4087//{
4088// return Host::GetArchSpecForExistingProcess (process_name);
4089//}
4090//
Caroline Tice861efb32010-11-16 05:07:41 +00004091void
4092Process::AppendSTDOUT (const char * s, size_t len)
4093{
Greg Clayton20d338f2010-11-18 05:57:03 +00004094 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00004095 m_stdout_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004096 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00004097}
4098
4099void
Greg Claytonbd06ff42011-11-13 04:45:22 +00004100Process::AppendSTDERR (const char * s, size_t len)
4101{
4102 Mutex::Locker locker (m_stdio_communication_mutex);
4103 m_stderr_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004104 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004105}
4106
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004107void
4108Process::BroadcastAsyncProfileData(const char *s, size_t len)
4109{
4110 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004111 m_profile_data.push_back(s);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004112 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4113}
4114
4115size_t
4116Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4117{
4118 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004119 if (m_profile_data.empty())
4120 return 0;
4121
4122 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004123 if (bytes_available > 0)
4124 {
4125 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4126 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004127 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004128 if (bytes_available > buf_size)
4129 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004130 memcpy(buf, m_profile_data.front().data(), buf_size);
4131 m_profile_data.front().erase(0, buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004132 bytes_available = buf_size;
4133 }
4134 else
4135 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004136 memcpy(buf, m_profile_data.front().data(), bytes_available);
4137 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004138 }
4139 }
4140 return bytes_available;
4141}
4142
4143
Greg Claytonbd06ff42011-11-13 04:45:22 +00004144//------------------------------------------------------------------
4145// Process STDIO
4146//------------------------------------------------------------------
4147
4148size_t
4149Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4150{
4151 Mutex::Locker locker(m_stdio_communication_mutex);
4152 size_t bytes_available = m_stdout_data.size();
4153 if (bytes_available > 0)
4154 {
4155 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4156 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004157 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004158 if (bytes_available > buf_size)
4159 {
4160 memcpy(buf, m_stdout_data.c_str(), buf_size);
4161 m_stdout_data.erase(0, buf_size);
4162 bytes_available = buf_size;
4163 }
4164 else
4165 {
4166 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4167 m_stdout_data.clear();
4168 }
4169 }
4170 return bytes_available;
4171}
4172
4173
4174size_t
4175Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4176{
4177 Mutex::Locker locker(m_stdio_communication_mutex);
4178 size_t bytes_available = m_stderr_data.size();
4179 if (bytes_available > 0)
4180 {
4181 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4182 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004183 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004184 if (bytes_available > buf_size)
4185 {
4186 memcpy(buf, m_stderr_data.c_str(), buf_size);
4187 m_stderr_data.erase(0, buf_size);
4188 bytes_available = buf_size;
4189 }
4190 else
4191 {
4192 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4193 m_stderr_data.clear();
4194 }
4195 }
4196 return bytes_available;
4197}
4198
4199void
Caroline Tice861efb32010-11-16 05:07:41 +00004200Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4201{
4202 Process *process = (Process *) baton;
4203 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4204}
4205
4206size_t
4207Process::ProcessInputReaderCallback (void *baton,
4208 InputReader &reader,
4209 lldb::InputReaderAction notification,
4210 const char *bytes,
4211 size_t bytes_len)
4212{
4213 Process *process = (Process *) baton;
4214
4215 switch (notification)
4216 {
4217 case eInputReaderActivate:
4218 break;
4219
4220 case eInputReaderDeactivate:
4221 break;
4222
4223 case eInputReaderReactivate:
4224 break;
4225
Caroline Tice4a348082011-05-02 20:41:46 +00004226 case eInputReaderAsynchronousOutputWritten:
4227 break;
4228
Caroline Tice861efb32010-11-16 05:07:41 +00004229 case eInputReaderGotToken:
4230 {
4231 Error error;
4232 process->PutSTDIN (bytes, bytes_len, error);
4233 }
4234 break;
4235
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004236 case eInputReaderInterrupt:
4237 process->Halt ();
4238 break;
4239
4240 case eInputReaderEndOfFile:
4241 process->AppendSTDOUT ("^D", 2);
4242 break;
4243
Caroline Tice861efb32010-11-16 05:07:41 +00004244 case eInputReaderDone:
4245 break;
4246
4247 }
4248
4249 return bytes_len;
4250}
4251
4252void
4253Process::ResetProcessInputReader ()
4254{
4255 m_process_input_reader.reset();
4256}
4257
4258void
Greg Clayton464c6162011-11-17 22:14:31 +00004259Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004260{
4261 // First set up the Read Thread for reading/handling process I/O
4262
4263 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4264
4265 if (conn_ap.get())
4266 {
4267 m_stdio_communication.SetConnection (conn_ap.release());
4268 if (m_stdio_communication.IsConnected())
4269 {
4270 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4271 m_stdio_communication.StartReadThread();
4272
4273 // Now read thread is set up, set up input reader.
4274
4275 if (!m_process_input_reader.get())
4276 {
4277 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4278 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4279 this,
4280 eInputReaderGranularityByte,
4281 NULL,
4282 NULL,
4283 false));
4284
4285 if (err.Fail())
4286 m_process_input_reader.reset();
4287 }
4288 }
4289 }
4290}
4291
4292void
4293Process::PushProcessInputReader ()
4294{
4295 if (m_process_input_reader && !m_process_input_reader->IsActive())
4296 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4297}
4298
4299void
4300Process::PopProcessInputReader ()
4301{
4302 if (m_process_input_reader && m_process_input_reader->IsActive())
4303 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4304}
4305
Greg Claytond284b662011-02-18 01:44:25 +00004306// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004307void
Caroline Tice2a456812011-03-10 22:14:10 +00004308Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004309{
Greg Clayton73844aa2012-08-22 17:17:09 +00004310// static std::vector<OptionEnumValueElement> g_plugins;
4311//
4312// int i=0;
4313// const char *name;
4314// OptionEnumValueElement option_enum;
4315// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4316// {
4317// if (name)
4318// {
4319// option_enum.value = i;
4320// option_enum.string_value = name;
4321// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4322// g_plugins.push_back (option_enum);
4323// }
4324// ++i;
4325// }
4326// option_enum.value = 0;
4327// option_enum.string_value = NULL;
4328// option_enum.usage = NULL;
4329// g_plugins.push_back (option_enum);
4330//
4331// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4332// {
4333// if (::strcmp (name, "plugin") == 0)
4334// {
4335// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4336// break;
4337// }
4338// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004339//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004340 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004341}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004342
Greg Clayton990de7b2010-11-18 23:32:35 +00004343void
Caroline Tice2a456812011-03-10 22:14:10 +00004344Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004345{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004346 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004347}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004348
Greg Clayton427f2902010-12-14 02:59:59 +00004349ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004350Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004351 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004352 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004353 bool run_others,
Jim Inghamb7940202013-01-15 02:47:48 +00004354 bool unwind_on_error,
4355 bool ignore_breakpoints,
Jim Ingham47beabb2012-10-16 21:41:58 +00004356 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004357 Stream &errors)
4358{
4359 ExecutionResults return_value = eExecutionSetupError;
4360
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004361 if (thread_plan_sp.get() == NULL)
4362 {
4363 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004364 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004365 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004366
4367 if (exe_ctx.GetProcessPtr() != this)
4368 {
4369 errors.Printf("RunThreadPlan called on wrong process.");
4370 return eExecutionSetupError;
4371 }
4372
4373 Thread *thread = exe_ctx.GetThreadPtr();
4374 if (thread == NULL)
4375 {
4376 errors.Printf("RunThreadPlan called with invalid thread.");
4377 return eExecutionSetupError;
4378 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004379
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004380 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4381 // For that to be true the plan can't be private - since private plans suppress themselves in the
4382 // GetCompletedPlan call.
4383
4384 bool orig_plan_private = thread_plan_sp->GetPrivate();
4385 thread_plan_sp->SetPrivate(false);
4386
Jim Inghamac959662011-01-24 06:34:17 +00004387 if (m_private_state.GetValue() != eStateStopped)
4388 {
4389 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004390 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004391 }
4392
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004393 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004394 const uint32_t thread_idx_id = thread->GetIndexID();
4395 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004396
4397 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4398 // so we should arrange to reset them as well.
4399
Greg Clayton567e7f32011-09-22 04:58:26 +00004400 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004401
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004402 uint32_t selected_tid;
4403 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004404 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004405 {
4406 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004407 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004408 }
4409 else
4410 {
4411 selected_tid = LLDB_INVALID_THREAD_ID;
4412 }
4413
Jim Ingham1831e782012-04-07 00:00:41 +00004414 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004415 lldb::StateType old_state;
4416 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004417
Jim Inghamd21d98b2012-04-10 01:21:57 +00004418 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004419 if (Host::GetCurrentThread() == m_private_state_thread)
4420 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004421 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4422 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004423 // 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 +00004424 // we are fielding public events here.
4425 if (log)
Jason Molenda559cf6e2012-11-17 01:41:04 +00004426 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 +00004427
4428
Jim Ingham1831e782012-04-07 00:00:41 +00004429 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004430
4431 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4432 // returning control here.
4433 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4434 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4435 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4436 // do just what we want.
4437 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4438 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4439 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4440 old_state = m_public_state.GetValue();
4441 m_public_state.SetValueNoLock(eStateStopped);
4442
4443 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004444 StartPrivateStateThread(true);
4445 }
4446
4447 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004448
Jim Ingham6ae318c2011-01-23 21:14:08 +00004449 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004450
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004451 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004452
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004453 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004454 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4455 // restored on exit to the function.
4456 //
4457 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4458 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004459
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004460 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004461
Jim Ingham360f53f2010-11-30 02:22:11 +00004462 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004463 {
4464 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004465 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004466 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004467 thread->GetIndexID(),
4468 thread->GetID(),
4469 s.GetData());
4470 }
4471
4472 bool got_event;
4473 lldb::EventSP event_sp;
4474 lldb::StateType stop_state = lldb::eStateInvalid;
4475
4476 TimeValue* timeout_ptr = NULL;
4477 TimeValue real_timeout;
4478
4479 bool first_timeout = true;
4480 bool do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004481 bool handle_running_event = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004482 const uint64_t default_one_thread_timeout_usec = 250000;
4483 uint64_t computed_timeout = 0;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004484
Jim Ingham76b258d2012-11-26 23:52:18 +00004485 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4486 // So don't call return anywhere within it.
4487
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004488 while (1)
4489 {
4490 // We usually want to resume the process if we get to the top of the loop.
4491 // The only exception is if we get two running events with no intervening
4492 // stop, which can happen, we will just wait for then next stop event.
4493
Jim Inghamb7940202013-01-15 02:47:48 +00004494 if (do_resume || handle_running_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004495 {
4496 // Do the initial resume and wait for the running event before going further.
4497
Jim Inghamb7940202013-01-15 02:47:48 +00004498 if (do_resume)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004499 {
Jim Inghamb7940202013-01-15 02:47:48 +00004500 Error resume_error = PrivateResume ();
4501 if (!resume_error.Success())
4502 {
4503 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4504 return_value = eExecutionSetupError;
4505 break;
4506 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004507 }
4508
4509 real_timeout = TimeValue::Now();
4510 real_timeout.OffsetWithMicroSeconds(500000);
4511 timeout_ptr = &real_timeout;
4512
4513 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4514 if (!got_event)
4515 {
4516 if (log)
4517 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4518
4519 errors.Printf("Didn't get any event after initial resume, exiting.");
4520 return_value = eExecutionSetupError;
4521 break;
4522 }
4523
4524 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4525 if (stop_state != eStateRunning)
4526 {
4527 if (log)
Jim Ingham47beabb2012-10-16 21:41:58 +00004528 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4529 "initial resume, got %s instead.",
4530 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004531
Jim Ingham47beabb2012-10-16 21:41:58 +00004532 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4533 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004534 return_value = eExecutionSetupError;
4535 break;
4536 }
4537
4538 if (log)
4539 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4540 // We need to call the function synchronously, so spin waiting for it to return.
4541 // If we get interrupted while executing, we're going to lose our context, and
4542 // won't be able to gather the result at this point.
4543 // We set the timeout AFTER the resume, since the resume takes some time and we
4544 // don't want to charge that to the timeout.
4545
Jim Ingham47beabb2012-10-16 21:41:58 +00004546 if (first_timeout)
4547 {
4548 if (run_others)
4549 {
4550 // If we are running all threads then we take half the time to run all threads, bounded by
4551 // .25 sec.
4552 if (timeout_usec == 0)
4553 computed_timeout = default_one_thread_timeout_usec;
4554 else
4555 {
4556 computed_timeout = timeout_usec / 2;
4557 if (computed_timeout > default_one_thread_timeout_usec)
4558 {
4559 computed_timeout = default_one_thread_timeout_usec;
4560 }
4561 timeout_usec -= computed_timeout;
4562 }
4563 }
4564 else
4565 {
4566 computed_timeout = timeout_usec;
4567 }
4568 }
4569 else
4570 {
4571 computed_timeout = timeout_usec;
4572 }
4573
4574 if (computed_timeout != 0)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004575 {
Enrico Granata6cca9692012-07-16 23:10:35 +00004576 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004577 real_timeout = TimeValue::Now();
Jim Ingham47beabb2012-10-16 21:41:58 +00004578 real_timeout.OffsetWithMicroSeconds(computed_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004579
4580 timeout_ptr = &real_timeout;
4581 }
Enrico Granata6cca9692012-07-16 23:10:35 +00004582 else
4583 {
Jim Ingham47beabb2012-10-16 21:41:58 +00004584 timeout_ptr = NULL;
Enrico Granata6cca9692012-07-16 23:10:35 +00004585 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004586 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004587 else
4588 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004589 if (log)
4590 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4591 do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004592 handle_running_event = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004593 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004594
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004595 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004596 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004597
Jim Inghamf9f40c22011-02-08 05:20:59 +00004598 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004599 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004600 if (timeout_ptr)
4601 {
4602 StreamString s;
4603 s.Printf ("about to wait - timeout is:\n ");
4604 timeout_ptr->Dump (&s, 120);
4605 s.Printf ("\nNow is:\n ");
4606 TimeValue::Now().Dump (&s, 120);
4607 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4608 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004609 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004610 {
4611 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4612 }
4613 }
4614
4615 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4616
4617 if (got_event)
4618 {
4619 if (event_sp.get())
4620 {
4621 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004622 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004623 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004624 Halt();
4625 keep_going = false;
4626 return_value = eExecutionInterrupted;
4627 errors.Printf ("Execution halted by user interrupt.");
4628 if (log)
4629 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4630 }
4631 else
4632 {
4633 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4634 if (log)
4635 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4636
4637 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004638 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004639 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004640 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004641 // Yay, we're done. Now make sure that our thread plan actually completed.
4642 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4643 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004644 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004645 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004646 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004647 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4648 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004649 }
4650 else
4651 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004652 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4653 StopReason stop_reason = eStopReasonInvalid;
4654 if (stop_info_sp)
4655 stop_reason = stop_info_sp->GetStopReason();
4656 if (stop_reason == eStopReasonPlanComplete)
4657 {
4658 if (log)
4659 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4660 // Now mark this plan as private so it doesn't get reported as the stop reason
4661 // after this point.
4662 if (thread_plan_sp)
4663 thread_plan_sp->SetPrivate (orig_plan_private);
4664 return_value = eExecutionCompleted;
4665 }
4666 else
4667 {
Jim Inghamb7940202013-01-15 02:47:48 +00004668 // Something restarted the target, so just wait for it to stop for real.
4669 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4670 {
4671 if (log)
4672 log->PutCString ("Process::RunThreadPlan(): Somebody stopped and then restarted, we'll continue waiting.");
4673 keep_going = true;
4674 do_resume = false;
4675 handle_running_event = true;
4676 }
4677 else
4678 {
4679 if (log)
4680 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
4681 if (stop_reason == eStopReasonBreakpoint)
4682 return_value = eExecutionHitBreakpoint;
4683 else
4684 return_value = eExecutionInterrupted;
4685 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004686 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004687 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004688 }
4689 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004690
Jim Ingham5d90ade2012-07-27 23:57:19 +00004691 case lldb::eStateCrashed:
4692 if (log)
4693 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4694 return_value = eExecutionInterrupted;
4695 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004696
Jim Ingham5d90ade2012-07-27 23:57:19 +00004697 case lldb::eStateRunning:
4698 do_resume = false;
4699 keep_going = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004700 handle_running_event = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004701 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004702
Jim Ingham5d90ade2012-07-27 23:57:19 +00004703 default:
4704 if (log)
4705 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4706
4707 if (stop_state == eStateExited)
4708 event_to_broadcast_sp = event_sp;
4709
Sean Callanan96abc622012-08-08 17:35:10 +00004710 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00004711 return_value = eExecutionInterrupted;
4712 break;
4713 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004714 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004715
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004716 if (keep_going)
4717 continue;
4718 else
4719 break;
4720 }
4721 else
4722 {
4723 if (log)
4724 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4725 return_value = eExecutionInterrupted;
4726 break;
4727 }
4728 }
4729 else
4730 {
4731 // If we didn't get an event that means we've timed out...
4732 // We will interrupt the process here. Depending on what we were asked to do we will
4733 // either exit, or try with all threads running for the same timeout.
4734 // Not really sure what to do if Halt fails here...
4735
4736 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00004737 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004738 {
4739 if (first_timeout)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004740 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %" PRId64 " timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004741 "trying for %d usec with all threads enabled.",
4742 computed_timeout, timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004743 else
4744 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00004745 "and timeout: %d timed out, abandoning execution.",
4746 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004747 }
4748 else
4749 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004750 "abandoning execution.",
4751 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004752 }
4753
4754 Error halt_error = Halt();
4755 if (halt_error.Success())
4756 {
4757 if (log)
4758 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4759
4760 // If halt succeeds, it always produces a stopped event. Wait for that:
4761
4762 real_timeout = TimeValue::Now();
4763 real_timeout.OffsetWithMicroSeconds(500000);
4764
4765 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4766
4767 if (got_event)
4768 {
4769 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4770 if (log)
4771 {
4772 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4773 if (stop_state == lldb::eStateStopped
4774 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4775 log->PutCString (" Event was the Halt interruption event.");
4776 }
4777
4778 if (stop_state == lldb::eStateStopped)
4779 {
4780 // Between the time we initiated the Halt and the time we delivered it, the process could have
4781 // already finished its job. Check that here:
4782
4783 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4784 {
4785 if (log)
4786 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4787 "Exiting wait loop.");
4788 return_value = eExecutionCompleted;
4789 break;
4790 }
4791
Jim Ingham47beabb2012-10-16 21:41:58 +00004792 if (!run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004793 {
4794 if (log)
4795 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4796 return_value = eExecutionInterrupted;
4797 break;
4798 }
4799
4800 if (first_timeout)
4801 {
4802 // Set all the other threads to run, and return to the top of the loop, which will continue;
4803 first_timeout = false;
4804 thread_plan_sp->SetStopOthers (false);
4805 if (log)
4806 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4807
4808 continue;
4809 }
4810 else
4811 {
4812 // Running all threads failed, so return Interrupted.
4813 if (log)
4814 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4815 return_value = eExecutionInterrupted;
4816 break;
4817 }
4818 }
4819 }
4820 else
4821 { if (log)
4822 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4823 "I'm getting out of here passing Interrupted.");
4824 return_value = eExecutionInterrupted;
4825 break;
4826 }
4827 }
4828 else
4829 {
4830 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4831 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4832 if (log)
4833 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.",
4834 halt_error.AsCString());
4835 real_timeout = TimeValue::Now();
4836 real_timeout.OffsetWithMicroSeconds(500000);
4837 timeout_ptr = &real_timeout;
4838 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4839 if (!got_event || event_sp.get() == NULL)
4840 {
4841 // This is not going anywhere, bag out.
4842 if (log)
4843 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4844 return_value = eExecutionInterrupted;
4845 break;
4846 }
4847 else
4848 {
4849 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4850 if (log)
4851 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4852 if (stop_state == lldb::eStateStopped)
4853 {
4854 // Between the time we initiated the Halt and the time we delivered it, the process could have
4855 // already finished its job. Check that here:
4856
4857 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4858 {
4859 if (log)
4860 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4861 "Exiting wait loop.");
4862 return_value = eExecutionCompleted;
4863 break;
4864 }
4865
4866 if (first_timeout)
4867 {
4868 // Set all the other threads to run, and return to the top of the loop, which will continue;
4869 first_timeout = false;
4870 thread_plan_sp->SetStopOthers (false);
4871 if (log)
4872 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4873
4874 continue;
4875 }
4876 else
4877 {
4878 // Running all threads failed, so return Interrupted.
4879 if (log)
4880 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4881 return_value = eExecutionInterrupted;
4882 break;
4883 }
4884 }
4885 else
4886 {
4887 if (log)
4888 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4889 " a stopped event, instead got %s.", StateAsCString(stop_state));
4890 return_value = eExecutionInterrupted;
4891 break;
4892 }
4893 }
4894 }
4895
4896 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004897 } // END WAIT LOOP
4898
4899 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4900 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4901 {
4902 StopPrivateStateThread();
4903 Error error;
4904 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00004905 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004906 {
4907 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4908 }
4909 m_public_state.SetValueNoLock(old_state);
4910
4911 }
4912
Jim Inghamb7940202013-01-15 02:47:48 +00004913 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
4914 // could happen:
4915 // 1) The execution successfully completed
4916 // 2) We hit a breakpoint, and ignore_breakpoints was true
4917 // 3) We got some other error, and discard_on_error was true
4918 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
4919 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham76b258d2012-11-26 23:52:18 +00004920
Jim Inghamb7940202013-01-15 02:47:48 +00004921 if (return_value == eExecutionCompleted
4922 || should_unwind)
Jim Ingham76b258d2012-11-26 23:52:18 +00004923 {
4924 thread_plan_sp->RestoreThreadState();
4925 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004926
4927 // Now do some processing on the results of the run:
Jim Inghamb7940202013-01-15 02:47:48 +00004928 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004929 {
4930 if (log)
4931 {
4932 StreamString s;
4933 if (event_sp)
4934 event_sp->Dump (&s);
4935 else
4936 {
4937 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4938 }
4939
4940 StreamString ts;
4941
4942 const char *event_explanation = NULL;
4943
4944 do
4945 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004946 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004947 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004948 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004949 break;
4950 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004951 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004952 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004953 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004954 break;
4955 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004956 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004957 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004958 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4959
4960 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004961 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004962 event_explanation = "<no event data>";
4963 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004964 }
4965
Jim Ingham5d90ade2012-07-27 23:57:19 +00004966 Process *process = event_data->GetProcessSP().get();
4967
4968 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004969 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004970 event_explanation = "<no process>";
4971 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004972 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004973
4974 ThreadList &thread_list = process->GetThreadList();
4975
4976 uint32_t num_threads = thread_list.GetSize();
4977 uint32_t thread_index;
4978
4979 ts.Printf("<%u threads> ", num_threads);
4980
4981 for (thread_index = 0;
4982 thread_index < num_threads;
4983 ++thread_index)
4984 {
4985 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4986
4987 if (!thread)
4988 {
4989 ts.Printf("<?> ");
4990 continue;
4991 }
4992
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004993 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00004994 RegisterContext *register_context = thread->GetRegisterContext().get();
4995
4996 if (register_context)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004997 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Ingham5d90ade2012-07-27 23:57:19 +00004998 else
4999 ts.Printf("[ip unknown] ");
5000
5001 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5002 if (stop_info_sp)
5003 {
5004 const char *stop_desc = stop_info_sp->GetDescription();
5005 if (stop_desc)
5006 ts.PutCString (stop_desc);
5007 }
5008 ts.Printf(">");
5009 }
5010
5011 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005012 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005013 } while (0);
5014
Jim Ingham5d90ade2012-07-27 23:57:19 +00005015 if (event_explanation)
5016 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005017 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00005018 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5019 }
5020
Jim Inghamb7940202013-01-15 02:47:48 +00005021 if (should_unwind && thread_plan_sp)
Jim Ingham5d90ade2012-07-27 23:57:19 +00005022 {
5023 if (log)
5024 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5025 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5026 thread_plan_sp->SetPrivate (orig_plan_private);
5027 }
5028 else
5029 {
5030 if (log)
5031 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005032 }
5033 }
5034 else if (return_value == eExecutionSetupError)
5035 {
5036 if (log)
5037 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00005038
Jim Inghamb7940202013-01-15 02:47:48 +00005039 if (unwind_on_error && thread_plan_sp)
Jim Inghamf9f40c22011-02-08 05:20:59 +00005040 {
Greg Clayton567e7f32011-09-22 04:58:26 +00005041 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00005042 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00005043 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005044 }
5045 else
5046 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005047 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00005048 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00005049 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005050 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5051 return_value = eExecutionCompleted;
5052 }
5053 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5054 {
5055 if (log)
5056 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5057 return_value = eExecutionDiscarded;
5058 }
5059 else
5060 {
5061 if (log)
5062 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamb7940202013-01-15 02:47:48 +00005063 if (unwind_on_error && thread_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005064 {
5065 if (log)
Jim Inghamb7940202013-01-15 02:47:48 +00005066 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005067 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5068 thread_plan_sp->SetPrivate (orig_plan_private);
5069 }
5070 }
5071 }
5072
5073 // Thread we ran the function in may have gone away because we ran the target
5074 // Check that it's still there, and if it is put it back in the context. Also restore the
5075 // frame in the context if it is still present.
5076 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5077 if (thread)
5078 {
5079 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5080 }
5081
5082 // Also restore the current process'es selected frame & thread, since this function calling may
5083 // be done behind the user's back.
5084
5085 if (selected_tid != LLDB_INVALID_THREAD_ID)
5086 {
5087 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5088 {
5089 // We were able to restore the selected thread, now restore the frame:
5090 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5091 if (old_frame_sp)
5092 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00005093 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005094 }
5095 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005096
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005097 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00005098
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005099 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00005100 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005101 if (log)
5102 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5103 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00005104 }
5105
5106 return return_value;
5107}
5108
5109const char *
5110Process::ExecutionResultAsCString (ExecutionResults result)
5111{
5112 const char *result_name;
5113
5114 switch (result)
5115 {
Greg Claytonb3448432011-03-24 21:19:54 +00005116 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005117 result_name = "eExecutionCompleted";
5118 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005119 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00005120 result_name = "eExecutionDiscarded";
5121 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005122 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005123 result_name = "eExecutionInterrupted";
5124 break;
Jim Inghamb7940202013-01-15 02:47:48 +00005125 case eExecutionHitBreakpoint:
5126 result_name = "eExecutionHitBreakpoint";
5127 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005128 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00005129 result_name = "eExecutionSetupError";
5130 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005131 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00005132 result_name = "eExecutionTimedOut";
5133 break;
5134 }
5135 return result_name;
5136}
5137
Greg Claytonabe0fed2011-04-18 08:33:37 +00005138void
5139Process::GetStatus (Stream &strm)
5140{
5141 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00005142 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00005143 {
5144 if (state == eStateExited)
5145 {
5146 int exit_status = GetExitStatus();
5147 const char *exit_description = GetExitDescription();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005148 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00005149 GetID(),
5150 exit_status,
5151 exit_status,
5152 exit_description ? exit_description : "");
5153 }
5154 else
5155 {
5156 if (state == eStateConnected)
5157 strm.Printf ("Connected to remote target.\n");
5158 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005159 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00005160 }
5161 }
5162 else
5163 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005164 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005165 }
5166}
5167
5168size_t
5169Process::GetThreadStatus (Stream &strm,
5170 bool only_threads_with_stop_reason,
5171 uint32_t start_frame,
5172 uint32_t num_frames,
5173 uint32_t num_frames_with_source)
5174{
5175 size_t num_thread_infos_dumped = 0;
5176
Jim Inghamb9950592012-09-10 20:50:15 +00005177 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005178 const size_t num_threads = GetThreadList().GetSize();
5179 for (uint32_t i = 0; i < num_threads; i++)
5180 {
5181 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5182 if (thread)
5183 {
5184 if (only_threads_with_stop_reason)
5185 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00005186 StopInfoSP stop_info_sp = thread->GetStopInfo();
5187 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00005188 continue;
5189 }
5190 thread->GetStatus (strm,
5191 start_frame,
5192 num_frames,
5193 num_frames_with_source);
5194 ++num_thread_infos_dumped;
5195 }
5196 }
5197 return num_thread_infos_dumped;
5198}
5199
Greg Clayton76113302012-02-22 04:37:26 +00005200void
5201Process::AddInvalidMemoryRegion (const LoadRange &region)
5202{
5203 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5204}
5205
5206bool
5207Process::RemoveInvalidMemoryRange (const LoadRange &region)
5208{
5209 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5210}
5211
Jim Ingham1831e782012-04-07 00:00:41 +00005212void
5213Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5214{
5215 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5216}
5217
5218bool
5219Process::RunPreResumeActions ()
5220{
5221 bool result = true;
5222 while (!m_pre_resume_actions.empty())
5223 {
5224 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5225 m_pre_resume_actions.pop_back();
5226 bool this_result = action.callback (action.baton);
5227 if (result == true) result = this_result;
5228 }
5229 return result;
5230}
5231
5232void
5233Process::ClearPreResumeActions ()
5234{
5235 m_pre_resume_actions.clear();
5236}
Greg Clayton76113302012-02-22 04:37:26 +00005237
Greg Claytoncf5927e2012-05-18 02:38:05 +00005238void
5239Process::Flush ()
5240{
5241 m_thread_list.Flush();
5242}
Greg Clayton0bce9a22012-12-05 00:16:59 +00005243
5244void
5245Process::DidExec ()
5246{
5247 Target &target = GetTarget();
5248 target.CleanupProcess ();
5249 ModuleList unloaded_modules (target.GetImages());
5250 target.ModulesDidUnload (unloaded_modules);
5251 target.GetSectionLoadList().Clear();
5252 m_dynamic_checkers_ap.reset();
5253 m_abi_sp.reset();
5254 m_os_ap.reset();
5255 m_dyld_ap.reset();
5256 m_image_tokens.clear();
5257 m_allocated_memory_cache.Clear();
5258 m_language_runtimes.clear();
5259 DoDidExec();
5260 CompleteAttach ();
5261}