blob: 65115b1b29cb0b14874122a3cfbb802faa84f82d [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
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000021#include "lldb/Core/Module.h"
Chris Lattner24943d22010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
23#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000024#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000025#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000026#include "lldb/Host/Host.h"
27#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000028#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000029#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000030#include "lldb/Target/LanguageRuntime.h"
31#include "lldb/Target/CPPLanguageRuntime.h"
32#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000033#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000035#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Target/Target.h"
37#include "lldb/Target/TargetList.h"
38#include "lldb/Target/Thread.h"
39#include "lldb/Target/ThreadPlan.h"
Jim Inghamd21d98b2012-04-10 01:21:57 +000040#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
42using namespace lldb;
43using namespace lldb_private;
44
Greg Clayton73844aa2012-08-22 17:17:09 +000045
46// Comment out line below to disable memory caching, overriding the process setting
47// target.process.disable-memory-cache
48#define ENABLE_MEMORY_CACHING
49
50#ifdef ENABLE_MEMORY_CACHING
51#define DISABLE_MEM_CACHE_DEFAULT false
52#else
53#define DISABLE_MEM_CACHE_DEFAULT true
54#endif
55
56class ProcessOptionValueProperties : public OptionValueProperties
57{
58public:
59 ProcessOptionValueProperties (const ConstString &name) :
60 OptionValueProperties (name)
61 {
62 }
63
64 // This constructor is used when creating ProcessOptionValueProperties when it
65 // is part of a new lldb_private::Process instance. It will copy all current
66 // global property values as needed
67 ProcessOptionValueProperties (ProcessProperties *global_properties) :
68 OptionValueProperties(*global_properties->GetValueProperties())
69 {
70 }
71
72 virtual const Property *
73 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
74 {
75 // When gettings the value for a key from the process options, we will always
76 // try and grab the setting from the current process if there is one. Else we just
77 // use the one from this instance.
78 if (exe_ctx)
79 {
80 Process *process = exe_ctx->GetProcessPtr();
81 if (process)
82 {
83 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
84 if (this != instance_properties)
85 return instance_properties->ProtectedGetPropertyAtIndex (idx);
86 }
87 }
88 return ProtectedGetPropertyAtIndex (idx);
89 }
90};
91
92static PropertyDefinition
93g_properties[] =
94{
95 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
96 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used." },
Greg Clayton2e7f3132012-10-18 22:40:37 +000097 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, 0, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
Greg Clayton73844aa2012-08-22 17:17:09 +000098 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
99};
100
101enum {
102 ePropertyDisableMemCache,
Greg Clayton2e7f3132012-10-18 22:40:37 +0000103 ePropertyExtraStartCommand,
104 ePropertyPythonOSPluginPath
Greg Clayton73844aa2012-08-22 17:17:09 +0000105};
106
107ProcessProperties::ProcessProperties (bool is_global) :
108 Properties ()
109{
110 if (is_global)
111 {
112 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
113 m_collection_sp->Initialize(g_properties);
114 m_collection_sp->AppendProperty(ConstString("thread"),
115 ConstString("Settings specify to threads."),
116 true,
117 Thread::GetGlobalProperties()->GetValueProperties());
118 }
119 else
120 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
121}
122
123ProcessProperties::~ProcessProperties()
124{
125}
126
127bool
128ProcessProperties::GetDisableMemoryCache() const
129{
130 const uint32_t idx = ePropertyDisableMemCache;
131 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
132}
133
134Args
135ProcessProperties::GetExtraStartupCommands () const
136{
137 Args args;
138 const uint32_t idx = ePropertyExtraStartCommand;
139 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
140 return args;
141}
142
143void
144ProcessProperties::SetExtraStartupCommands (const Args &args)
145{
146 const uint32_t idx = ePropertyExtraStartCommand;
147 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
148}
149
Greg Clayton2e7f3132012-10-18 22:40:37 +0000150FileSpec
151ProcessProperties::GetPythonOSPluginPath () const
152{
153 const uint32_t idx = ePropertyPythonOSPluginPath;
154 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
155}
156
157void
158ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
159{
160 const uint32_t idx = ePropertyPythonOSPluginPath;
161 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
162}
163
Greg Clayton24bc5d92011-03-30 18:16:51 +0000164void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000165ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000166{
167 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +0000168 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +0000169 s.Printf (" pid = %llu\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000170
171 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +0000172 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000173
174 if (m_executable)
175 {
176 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
177 s.PutCString (" file = ");
178 m_executable.Dump(&s);
179 s.EOL();
180 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000181 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000182 if (argc > 0)
183 {
184 for (uint32_t i=0; i<argc; i++)
185 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000186 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +0000187 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000188 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000189 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000190 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000191 }
192 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000193
194 const uint32_t envc = m_environment.GetArgumentCount();
195 if (envc > 0)
196 {
197 for (uint32_t i=0; i<envc; i++)
198 {
199 const char *env = m_environment.GetArgumentAtIndex(i);
200 if (i < 10)
201 s.Printf (" env[%u] = %s\n", i, env);
202 else
203 s.Printf ("env[%u] = %s\n", i, env);
204 }
205 }
206
Greg Claytonff39f742011-04-01 00:29:43 +0000207 if (m_arch.IsValid())
208 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
209
Greg Claytonb72d0f02011-04-12 05:54:46 +0000210 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000211 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000212 cstr = platform->GetUserName (m_uid);
213 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000214 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000215 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000216 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000217 cstr = platform->GetGroupName (m_gid);
218 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000219 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000220 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000221 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000222 cstr = platform->GetUserName (m_euid);
223 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000224 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000225 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000226 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000227 cstr = platform->GetGroupName (m_egid);
228 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000229 }
230}
231
232void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000233ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000234{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000235 const char *label;
236 if (show_args || verbose)
237 label = "ARGUMENTS";
238 else
239 label = "NAME";
240
Greg Claytonff39f742011-04-01 00:29:43 +0000241 if (verbose)
242 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000243 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000244 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
245 }
246 else
247 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000248 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000249 s.PutCString ("====== ====== ========== ======= ============================\n");
250 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000251}
252
253void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000254ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000255{
256 if (m_pid != LLDB_INVALID_PROCESS_ID)
257 {
258 const char *cstr;
Greg Claytond9919d32011-12-01 23:28:38 +0000259 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000260
Greg Clayton24bc5d92011-03-30 18:16:51 +0000261
Greg Claytonff39f742011-04-01 00:29:43 +0000262 if (verbose)
263 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000264 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000265 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
266 s.Printf ("%-10s ", cstr);
267 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000268 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000269
Greg Claytonb72d0f02011-04-12 05:54:46 +0000270 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000271 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
272 s.Printf ("%-10s ", cstr);
273 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000274 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000275
Greg Claytonb72d0f02011-04-12 05:54:46 +0000276 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000277 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
278 s.Printf ("%-10s ", cstr);
279 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000280 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000281
Greg Claytonb72d0f02011-04-12 05:54:46 +0000282 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000283 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
284 s.Printf ("%-10s ", cstr);
285 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000286 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000287 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
288 }
289 else
290 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000291 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000292 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000293 (int)m_arch.GetTriple().getArchName().size(),
294 m_arch.GetTriple().getArchName().data());
295 }
296
Greg Claytonb72d0f02011-04-12 05:54:46 +0000297 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000298 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000299 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000300 if (argc > 0)
301 {
302 for (uint32_t i=0; i<argc; i++)
303 {
304 if (i > 0)
305 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000306 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000307 }
308 }
309 }
310 else
311 {
312 s.PutCString (GetName());
313 }
314
315 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000316 }
317}
318
Greg Claytonb72d0f02011-04-12 05:54:46 +0000319
320void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000321ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000322{
323 m_arguments.SetArguments (argv);
324
325 // Is the first argument the executable?
326 if (first_arg_is_executable)
327 {
328 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
329 if (first_arg)
330 {
331 // Yes the first argument is an executable, set it as the executable
332 // in the launch options. Don't resolve the file path as the path
333 // could be a remote platform path
334 const bool resolve = false;
335 m_executable.SetFile(first_arg, resolve);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000336 }
337 }
338}
339void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000340ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000341{
342 // Copy all arguments
343 m_arguments = args;
344
345 // Is the first argument the executable?
346 if (first_arg_is_executable)
347 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000348 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000349 if (first_arg)
350 {
351 // Yes the first argument is an executable, set it as the executable
352 // in the launch options. Don't resolve the file path as the path
353 // could be a remote platform path
354 const bool resolve = false;
355 m_executable.SetFile(first_arg, resolve);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000356 }
357 }
358}
359
Greg Claytonabb33022011-11-08 02:43:13 +0000360void
Greg Clayton464c6162011-11-17 22:14:31 +0000361ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000362{
363 // If notthing was specified, then check the process for any default
364 // settings that were set with "settings set"
365 if (m_file_actions.empty())
366 {
Greg Claytonabb33022011-11-08 02:43:13 +0000367 if (m_flags.Test(eLaunchFlagDisableSTDIO))
368 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000369 AppendSuppressFileAction (STDIN_FILENO , true, false);
370 AppendSuppressFileAction (STDOUT_FILENO, false, true);
371 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000372 }
373 else
374 {
375 // Check for any values that might have gotten set with any of:
376 // (lldb) settings set target.input-path
377 // (lldb) settings set target.output-path
378 // (lldb) settings set target.error-path
Greg Clayton73844aa2012-08-22 17:17:09 +0000379 FileSpec in_path;
380 FileSpec out_path;
381 FileSpec err_path;
Greg Claytonabb33022011-11-08 02:43:13 +0000382 if (target)
383 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000384 in_path = target->GetStandardInputPath();
385 out_path = target->GetStandardOutputPath();
386 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000387 }
388
Greg Clayton73844aa2012-08-22 17:17:09 +0000389 if (in_path || out_path || err_path)
390 {
391 char path[PATH_MAX];
392 if (in_path && in_path.GetPath(path, sizeof(path)))
393 AppendOpenFileAction(STDIN_FILENO, path, true, false);
394
395 if (out_path && out_path.GetPath(path, sizeof(path)))
396 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
397
398 if (err_path && err_path.GetPath(path, sizeof(path)))
399 AppendOpenFileAction(STDERR_FILENO, path, false, true);
400 }
401 else if (default_to_use_pty)
Greg Clayton464c6162011-11-17 22:14:31 +0000402 {
403 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000404 {
Greg Clayton73844aa2012-08-22 17:17:09 +0000405 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
406 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
407 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
408 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000409 }
410 }
Greg Claytonabb33022011-11-08 02:43:13 +0000411 }
412 }
413}
414
Greg Clayton527154d2011-11-15 03:53:30 +0000415
416bool
Greg Clayton97471182012-04-14 01:42:46 +0000417ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
418 bool localhost,
419 bool will_debug,
420 bool first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000421{
422 error.Clear();
423
424 if (GetFlags().Test (eLaunchFlagLaunchInShell))
425 {
426 const char *shell_executable = GetShell();
427 if (shell_executable)
428 {
429 char shell_resolved_path[PATH_MAX];
430
431 if (localhost)
432 {
433 FileSpec shell_filespec (shell_executable, true);
434
435 if (!shell_filespec.Exists())
436 {
437 // Resolve the path in case we just got "bash", "sh" or "tcsh"
438 if (!shell_filespec.ResolveExecutableLocation ())
439 {
440 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
441 return false;
442 }
443 }
444 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
445 shell_executable = shell_resolved_path;
446 }
447
Greg Clayton0c8446c2012-10-17 22:57:12 +0000448 const char **argv = GetArguments().GetConstArgumentVector ();
449 if (argv == NULL || argv[0] == NULL)
450 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000451 Args shell_arguments;
452 std::string safe_arg;
453 shell_arguments.AppendArgument (shell_executable);
Greg Clayton527154d2011-11-15 03:53:30 +0000454 shell_arguments.AppendArgument ("-c");
Greg Clayton97471182012-04-14 01:42:46 +0000455 StreamString shell_command;
456 if (will_debug)
Greg Clayton527154d2011-11-15 03:53:30 +0000457 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000458 // Add a modified PATH environment variable in case argv[0]
459 // is a relative path
460 const char *argv0 = argv[0];
461 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
462 {
463 // We have a relative path to our executable which may not work if
464 // we just try to run "a.out" (without it being converted to "./a.out")
465 const char *working_dir = GetWorkingDirectory();
466 std::string new_path("PATH=");
467 const size_t empty_path_len = new_path.size();
468
469 if (working_dir && working_dir[0])
470 {
471 new_path += working_dir;
472 }
473 else
474 {
475 char current_working_dir[PATH_MAX];
476 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
477 if (cwd && cwd[0])
478 new_path += cwd;
479 }
480 const char *curr_path = getenv("PATH");
481 if (curr_path)
482 {
483 if (new_path.size() > empty_path_len)
484 new_path += ':';
485 new_path += curr_path;
486 }
487 new_path += ' ';
488 shell_command.PutCString(new_path.c_str());
489 }
490
Greg Clayton97471182012-04-14 01:42:46 +0000491 shell_command.PutCString ("exec");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000492
493#if defined(__APPLE__)
494 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Clayton97471182012-04-14 01:42:46 +0000495 if (GetArchitecture().IsValid())
496 {
497 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton0c8446c2012-10-17 22:57:12 +0000498 // Set the resume count to 2:
Greg Clayton97471182012-04-14 01:42:46 +0000499 // 1 - stop in shell
500 // 2 - stop in /usr/bin/arch
501 // 3 - then we will stop in our program
502 SetResumeCount(2);
503 }
504 else
505 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000506 // Set the resume count to 1:
Greg Clayton97471182012-04-14 01:42:46 +0000507 // 1 - stop in shell
508 // 2 - then we will stop in our program
509 SetResumeCount(1);
510 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000511#else
512 // Set the resume count to 1:
513 // 1 - stop in shell
514 // 2 - then we will stop in our program
515 SetResumeCount(1);
516#endif
Greg Clayton527154d2011-11-15 03:53:30 +0000517 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000518
519 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000520 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000521 // There should only be one argument that is the shell command itself to be used as is
522 if (argv[0] && !argv[1])
523 shell_command.Printf("%s", argv[0]);
Greg Clayton97471182012-04-14 01:42:46 +0000524 else
Greg Clayton0c8446c2012-10-17 22:57:12 +0000525 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000526 }
Greg Clayton97471182012-04-14 01:42:46 +0000527 else
528 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000529 for (size_t i=0; argv[i] != NULL; ++i)
530 {
531 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
532 shell_command.Printf(" %s", arg);
533 }
Greg Clayton97471182012-04-14 01:42:46 +0000534 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000535 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000536 m_executable.SetFile(shell_executable, false);
537 m_arguments = shell_arguments;
538 return true;
539 }
540 else
541 {
542 error.SetErrorString ("invalid shell path");
543 }
544 }
545 else
546 {
547 error.SetErrorString ("not launching in shell");
548 }
549 return false;
550}
551
552
Greg Clayton24bc5d92011-03-30 18:16:51 +0000553bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000554ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
555{
556 if ((read || write) && fd >= 0 && path && path[0])
557 {
558 m_action = eFileActionOpen;
559 m_fd = fd;
560 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000561 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000562 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000563 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000564 else
Greg Clayton527154d2011-11-15 03:53:30 +0000565 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000566 m_path.assign (path);
567 return true;
568 }
569 else
570 {
571 Clear();
572 }
573 return false;
574}
575
576bool
577ProcessLaunchInfo::FileAction::Close (int fd)
578{
579 Clear();
580 if (fd >= 0)
581 {
582 m_action = eFileActionClose;
583 m_fd = fd;
584 }
585 return m_fd >= 0;
586}
587
588
589bool
590ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
591{
592 Clear();
593 if (fd >= 0 && dup_fd >= 0)
594 {
595 m_action = eFileActionDuplicate;
596 m_fd = fd;
597 m_arg = dup_fd;
598 }
599 return m_fd >= 0;
600}
601
602
603
604bool
605ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
606 const FileAction *info,
607 Log *log,
608 Error& error)
609{
610 if (info == NULL)
611 return false;
612
613 switch (info->m_action)
614 {
615 case eFileActionNone:
616 error.Clear();
617 break;
618
619 case eFileActionClose:
620 if (info->m_fd == -1)
621 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
622 else
623 {
624 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
625 eErrorTypePOSIX);
626 if (log && (error.Fail() || log))
627 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
628 file_actions, info->m_fd);
629 }
630 break;
631
632 case eFileActionDuplicate:
633 if (info->m_fd == -1)
634 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
635 else if (info->m_arg == -1)
636 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
637 else
638 {
639 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
640 eErrorTypePOSIX);
641 if (log && (error.Fail() || log))
642 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
643 file_actions, info->m_fd, info->m_arg);
644 }
645 break;
646
647 case eFileActionOpen:
648 if (info->m_fd == -1)
649 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
650 else
651 {
652 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000653
Greg Claytonb72d0f02011-04-12 05:54:46 +0000654 mode_t mode = 0;
655
Greg Clayton527154d2011-11-15 03:53:30 +0000656 if (oflag & O_CREAT)
657 mode = 0640;
658
Greg Claytonb72d0f02011-04-12 05:54:46 +0000659 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
660 info->m_fd,
661 info->m_path.c_str(),
662 oflag,
663 mode),
664 eErrorTypePOSIX);
665 if (error.Fail() || log)
666 error.PutToLog(log,
667 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
668 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
669 }
670 break;
671
672 default:
673 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
674 break;
675 }
676 return error.Success();
677}
678
679Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000680ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000681{
682 Error error;
683 char short_option = (char) m_getopt_table[option_idx].val;
684
685 switch (short_option)
686 {
687 case 's': // Stop at program entry point
688 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
689 break;
690
Greg Claytonb72d0f02011-04-12 05:54:46 +0000691 case 'i': // STDIN for read only
692 {
693 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000694 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000695 launch_info.AppendFileAction (action);
696 }
697 break;
698
699 case 'o': // Open STDOUT for write only
700 {
701 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000702 if (action.Open (STDOUT_FILENO, option_arg, false, true))
703 launch_info.AppendFileAction (action);
704 }
705 break;
706
707 case 'e': // STDERR for write only
708 {
709 ProcessLaunchInfo::FileAction action;
710 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000711 launch_info.AppendFileAction (action);
712 }
713 break;
714
Greg Clayton95ec1682012-03-06 04:01:04 +0000715
Greg Claytonb72d0f02011-04-12 05:54:46 +0000716 case 'p': // Process plug-in name
717 launch_info.SetProcessPluginName (option_arg);
718 break;
719
720 case 'n': // Disable STDIO
721 {
722 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000723 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000724 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000725 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000726 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000727 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000728 launch_info.AppendFileAction (action);
729 }
730 break;
731
732 case 'w':
733 launch_info.SetWorkingDirectory (option_arg);
734 break;
735
736 case 't': // Open process in new terminal window
737 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
738 break;
739
740 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000741 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
742 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000743 break;
744
745 case 'A':
746 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
747 break;
748
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000749 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000750 if (option_arg && option_arg[0])
751 launch_info.SetShell (option_arg);
752 else
753 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000754 break;
755
Greg Claytonb72d0f02011-04-12 05:54:46 +0000756 case 'v':
757 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
758 break;
759
760 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000761 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000762 break;
763
764 }
765 return error;
766}
767
768OptionDefinition
769ProcessLaunchCommandOptions::g_option_table[] =
770{
771{ 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."},
772{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
773{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
774{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
775{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
776{ 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."},
Greg Clayton527154d2011-11-15 03:53:30 +0000777{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypePath, "Run the process in a shell (not supported on all platforms)."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000778
779{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
780{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
781{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
782
783{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
784
785{ 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."},
786
787{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
788};
789
790
791
792bool
793ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000794{
795 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
796 return true;
797 const char *match_name = m_match_info.GetName();
798 if (!match_name)
799 return true;
800
801 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
802}
803
804bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000805ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000806{
807 if (!NameMatches (proc_info.GetName()))
808 return false;
809
810 if (m_match_info.ProcessIDIsValid() &&
811 m_match_info.GetProcessID() != proc_info.GetProcessID())
812 return false;
813
814 if (m_match_info.ParentProcessIDIsValid() &&
815 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
816 return false;
817
Greg Claytonb72d0f02011-04-12 05:54:46 +0000818 if (m_match_info.UserIDIsValid () &&
819 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000820 return false;
821
Greg Claytonb72d0f02011-04-12 05:54:46 +0000822 if (m_match_info.GroupIDIsValid () &&
823 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000824 return false;
825
826 if (m_match_info.EffectiveUserIDIsValid () &&
827 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
828 return false;
829
830 if (m_match_info.EffectiveGroupIDIsValid () &&
831 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
832 return false;
833
834 if (m_match_info.GetArchitecture().IsValid() &&
835 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
836 return false;
837 return true;
838}
839
840bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000841ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000842{
843 if (m_name_match_type != eNameMatchIgnore)
844 return false;
845
846 if (m_match_info.ProcessIDIsValid())
847 return false;
848
849 if (m_match_info.ParentProcessIDIsValid())
850 return false;
851
Greg Claytonb72d0f02011-04-12 05:54:46 +0000852 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000853 return false;
854
Greg Claytonb72d0f02011-04-12 05:54:46 +0000855 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000856 return false;
857
858 if (m_match_info.EffectiveUserIDIsValid ())
859 return false;
860
861 if (m_match_info.EffectiveGroupIDIsValid ())
862 return false;
863
864 if (m_match_info.GetArchitecture().IsValid())
865 return false;
866
867 if (m_match_all_users)
868 return false;
869
870 return true;
871
872}
873
874void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000875ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000876{
877 m_match_info.Clear();
878 m_name_match_type = eNameMatchIgnore;
879 m_match_all_users = false;
880}
Greg Claytonfd119992011-01-07 06:08:19 +0000881
Greg Clayton46c9a352012-02-09 06:16:32 +0000882ProcessSP
883Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000884{
Greg Clayton46c9a352012-02-09 06:16:32 +0000885 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000886 ProcessCreateInstance create_callback = NULL;
887 if (plugin_name)
888 {
889 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
890 if (create_callback)
891 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000892 process_sp = create_callback(target, listener, crash_file_path);
893 if (process_sp)
894 {
895 if (!process_sp->CanDebug(target, true))
896 process_sp.reset();
897 }
Chris Lattner24943d22010-06-08 16:52:24 +0000898 }
899 }
900 else
901 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000902 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000903 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000904 process_sp = create_callback(target, listener, crash_file_path);
905 if (process_sp)
906 {
907 if (!process_sp->CanDebug(target, false))
908 process_sp.reset();
909 else
910 break;
911 }
Chris Lattner24943d22010-06-08 16:52:24 +0000912 }
913 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000914 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000915}
916
Jim Ingham5a15e692012-02-16 06:50:00 +0000917ConstString &
918Process::GetStaticBroadcasterClass ()
919{
920 static ConstString class_name ("lldb.process");
921 return class_name;
922}
Chris Lattner24943d22010-06-08 16:52:24 +0000923
924//----------------------------------------------------------------------
925// Process constructor
926//----------------------------------------------------------------------
927Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +0000928 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +0000929 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000930 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +0000931 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000932 m_public_state (eStateUnloaded),
933 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000934 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
935 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000936 m_private_state_listener ("lldb.process.internal_state_listener"),
937 m_private_state_control_wait(),
938 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000939 m_mod_id (),
Chris Lattner24943d22010-06-08 16:52:24 +0000940 m_thread_index_id (0),
941 m_exit_status (-1),
942 m_exit_string (),
943 m_thread_list (this),
944 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000945 m_image_tokens (),
946 m_listener (listener),
947 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000948 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000949 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000950 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000951 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000952 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000953 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000954 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000955 m_stderr_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000956 m_memory_cache (*this),
957 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +0000958 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000959 m_next_event_action_ap(),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000960 m_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +0000961 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +0000962 m_finalize_called(false),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000963 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +0000964{
Jim Ingham5a15e692012-02-16 06:50:00 +0000965 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +0000966
Greg Claytone005f2c2010-11-06 01:53:30 +0000967 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000968 if (log)
969 log->Printf ("%p Process::Process()", this);
970
Greg Clayton49ce6822010-10-31 03:01:06 +0000971 SetEventName (eBroadcastBitStateChanged, "state-changed");
972 SetEventName (eBroadcastBitInterrupt, "interrupt");
973 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
974 SetEventName (eBroadcastBitSTDERR, "stderr-available");
975
Chris Lattner24943d22010-06-08 16:52:24 +0000976 listener.StartListeningForEvents (this,
977 eBroadcastBitStateChanged |
978 eBroadcastBitInterrupt |
979 eBroadcastBitSTDOUT |
980 eBroadcastBitSTDERR);
981
982 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +0000983 eBroadcastBitStateChanged |
984 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +0000985
986 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
987 eBroadcastInternalStateControlStop |
988 eBroadcastInternalStateControlPause |
989 eBroadcastInternalStateControlResume);
990}
991
992//----------------------------------------------------------------------
993// Destructor
994//----------------------------------------------------------------------
995Process::~Process()
996{
Greg Claytone005f2c2010-11-06 01:53:30 +0000997 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000998 if (log)
999 log->Printf ("%p Process::~Process()", this);
1000 StopPrivateStateThread();
1001}
1002
Greg Clayton73844aa2012-08-22 17:17:09 +00001003const ProcessPropertiesSP &
1004Process::GetGlobalProperties()
1005{
1006 static ProcessPropertiesSP g_settings_sp;
1007 if (!g_settings_sp)
1008 g_settings_sp.reset (new ProcessProperties (true));
1009 return g_settings_sp;
1010}
1011
Chris Lattner24943d22010-06-08 16:52:24 +00001012void
1013Process::Finalize()
1014{
Greg Claytonffa43a62011-11-17 04:46:02 +00001015 switch (GetPrivateState())
1016 {
1017 case eStateConnected:
1018 case eStateAttaching:
1019 case eStateLaunching:
1020 case eStateStopped:
1021 case eStateRunning:
1022 case eStateStepping:
1023 case eStateCrashed:
1024 case eStateSuspended:
1025 if (GetShouldDetach())
1026 Detach();
1027 else
1028 Destroy();
1029 break;
1030
1031 case eStateInvalid:
1032 case eStateUnloaded:
1033 case eStateDetached:
1034 case eStateExited:
1035 break;
1036 }
1037
Greg Clayton2f57db02011-10-01 00:45:15 +00001038 // Clear our broadcaster before we proceed with destroying
1039 Broadcaster::Clear();
1040
Chris Lattner24943d22010-06-08 16:52:24 +00001041 // Do any cleanup needed prior to being destructed... Subclasses
1042 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001043
1044 // We need to destroy the loader before the derived Process class gets destroyed
1045 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001046 m_dynamic_checkers_ap.reset();
1047 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001048 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001049 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001050 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001051 std::vector<Notifications> empty_notifications;
1052 m_notifications.swap(empty_notifications);
1053 m_image_tokens.clear();
1054 m_memory_cache.Clear();
1055 m_allocated_memory_cache.Clear();
1056 m_language_runtimes.clear();
1057 m_next_event_action_ap.reset();
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001058 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001059}
1060
1061void
1062Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1063{
1064 m_notifications.push_back(callbacks);
1065 if (callbacks.initialize != NULL)
1066 callbacks.initialize (callbacks.baton, this);
1067}
1068
1069bool
1070Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1071{
1072 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1073 for (pos = m_notifications.begin(); pos != end; ++pos)
1074 {
1075 if (pos->baton == callbacks.baton &&
1076 pos->initialize == callbacks.initialize &&
1077 pos->process_state_changed == callbacks.process_state_changed)
1078 {
1079 m_notifications.erase(pos);
1080 return true;
1081 }
1082 }
1083 return false;
1084}
1085
1086void
1087Process::SynchronouslyNotifyStateChanged (StateType state)
1088{
1089 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1090 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1091 {
1092 if (notification_pos->process_state_changed)
1093 notification_pos->process_state_changed (notification_pos->baton, this, state);
1094 }
1095}
1096
1097// FIXME: We need to do some work on events before the general Listener sees them.
1098// For instance if we are continuing from a breakpoint, we need to ensure that we do
1099// the little "insert real insn, step & stop" trick. But we can't do that when the
1100// event is delivered by the broadcaster - since that is done on the thread that is
1101// waiting for new events, so if we needed more than one event for our handling, we would
1102// stall. So instead we do it when we fetch the event off of the queue.
1103//
1104
1105StateType
1106Process::GetNextEvent (EventSP &event_sp)
1107{
1108 StateType state = eStateInvalid;
1109
1110 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1111 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1112
1113 return state;
1114}
1115
1116
1117StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001118Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001119{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001120 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1121 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1122 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001123 if (event_sp_ptr)
1124 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001125 StateType state = GetState();
1126 // If we are exited or detached, we won't ever get back to any
1127 // other valid state...
1128 if (state == eStateDetached || state == eStateExited)
1129 return state;
1130
1131 while (state != eStateInvalid)
1132 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001133 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001134 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001135 if (event_sp_ptr && event_sp)
1136 *event_sp_ptr = event_sp;
1137
Jim Ingham21f37ad2011-08-09 02:12:22 +00001138 switch (state)
1139 {
1140 case eStateCrashed:
1141 case eStateDetached:
1142 case eStateExited:
1143 case eStateUnloaded:
1144 return state;
1145 case eStateStopped:
1146 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1147 continue;
1148 else
1149 return state;
1150 default:
1151 continue;
1152 }
1153 }
1154 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001155}
1156
1157
1158StateType
1159Process::WaitForState
1160(
1161 const TimeValue *timeout,
1162 const StateType *match_states, const uint32_t num_match_states
1163)
1164{
1165 EventSP event_sp;
1166 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001167 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001168 while (state != eStateInvalid)
1169 {
Greg Claytond8c62532010-10-07 04:19:01 +00001170 // If we are exited or detached, we won't ever get back to any
1171 // other valid state...
1172 if (state == eStateDetached || state == eStateExited)
1173 return state;
1174
Chris Lattner24943d22010-06-08 16:52:24 +00001175 state = WaitForStateChangedEvents (timeout, event_sp);
1176
1177 for (i=0; i<num_match_states; ++i)
1178 {
1179 if (match_states[i] == state)
1180 return state;
1181 }
1182 }
1183 return state;
1184}
1185
Jim Ingham63e24d72010-10-11 23:53:14 +00001186bool
1187Process::HijackProcessEvents (Listener *listener)
1188{
1189 if (listener != NULL)
1190 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001191 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001192 }
1193 else
1194 return false;
1195}
1196
1197void
1198Process::RestoreProcessEvents ()
1199{
1200 RestoreBroadcaster();
1201}
1202
Jim Inghamf9f40c22011-02-08 05:20:59 +00001203bool
1204Process::HijackPrivateProcessEvents (Listener *listener)
1205{
1206 if (listener != NULL)
1207 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001208 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001209 }
1210 else
1211 return false;
1212}
1213
1214void
1215Process::RestorePrivateProcessEvents ()
1216{
1217 m_private_state_broadcaster.RestoreBroadcaster();
1218}
1219
Chris Lattner24943d22010-06-08 16:52:24 +00001220StateType
1221Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1222{
Greg Claytone005f2c2010-11-06 01:53:30 +00001223 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001224
1225 if (log)
1226 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1227
1228 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001229 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1230 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001231 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001232 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001233 {
1234 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1235 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1236 else if (log)
1237 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1238 }
Chris Lattner24943d22010-06-08 16:52:24 +00001239
1240 if (log)
1241 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1242 __FUNCTION__,
1243 timeout,
1244 StateAsCString(state));
1245 return state;
1246}
1247
1248Event *
1249Process::PeekAtStateChangedEvents ()
1250{
Greg Claytone005f2c2010-11-06 01:53:30 +00001251 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001252
1253 if (log)
1254 log->Printf ("Process::%s...", __FUNCTION__);
1255
1256 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001257 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1258 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001259 if (log)
1260 {
1261 if (event_ptr)
1262 {
1263 log->Printf ("Process::%s (event_ptr) => %s",
1264 __FUNCTION__,
1265 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1266 }
1267 else
1268 {
1269 log->Printf ("Process::%s no events found",
1270 __FUNCTION__);
1271 }
1272 }
1273 return event_ptr;
1274}
1275
1276StateType
1277Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1278{
Greg Claytone005f2c2010-11-06 01:53:30 +00001279 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001280
1281 if (log)
1282 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1283
1284 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001285 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1286 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001287 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001288 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001289 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1290 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001291
1292 // This is a bit of a hack, but when we wait here we could very well return
1293 // to the command-line, and that could disable the log, which would render the
1294 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001295 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001296 {
1297 if (state == eStateInvalid)
1298 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1299 else
1300 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1301 }
Chris Lattner24943d22010-06-08 16:52:24 +00001302 return state;
1303}
1304
1305bool
1306Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1307{
Greg Claytone005f2c2010-11-06 01:53:30 +00001308 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001309
1310 if (log)
1311 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1312
1313 if (control_only)
1314 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1315 else
1316 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1317}
1318
1319bool
1320Process::IsRunning () const
1321{
1322 return StateIsRunningState (m_public_state.GetValue());
1323}
1324
1325int
1326Process::GetExitStatus ()
1327{
1328 if (m_public_state.GetValue() == eStateExited)
1329 return m_exit_status;
1330 return -1;
1331}
1332
Greg Clayton638351a2010-12-04 00:10:17 +00001333
Chris Lattner24943d22010-06-08 16:52:24 +00001334const char *
1335Process::GetExitDescription ()
1336{
1337 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1338 return m_exit_string.c_str();
1339 return NULL;
1340}
1341
Greg Clayton72e1c782011-01-22 23:43:18 +00001342bool
Chris Lattner24943d22010-06-08 16:52:24 +00001343Process::SetExitStatus (int status, const char *cstr)
1344{
Greg Clayton68ca8232011-01-25 02:58:48 +00001345 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1346 if (log)
1347 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1348 status, status,
1349 cstr ? "\"" : "",
1350 cstr ? cstr : "NULL",
1351 cstr ? "\"" : "");
1352
Greg Clayton72e1c782011-01-22 23:43:18 +00001353 // We were already in the exited state
1354 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001355 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001356 if (log)
1357 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001358 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001359 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001360
1361 m_exit_status = status;
1362 if (cstr)
1363 m_exit_string = cstr;
1364 else
1365 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001366
Greg Clayton72e1c782011-01-22 23:43:18 +00001367 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001368
Greg Clayton72e1c782011-01-22 23:43:18 +00001369 SetPrivateState (eStateExited);
1370 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001371}
1372
1373// This static callback can be used to watch for local child processes on
1374// the current host. The the child process exits, the process will be
1375// found in the global target list (we want to be completely sure that the
1376// lldb_private::Process doesn't go away before we can deliver the signal.
1377bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001378Process::SetProcessExitStatus (void *callback_baton,
1379 lldb::pid_t pid,
1380 bool exited,
1381 int signo, // Zero for no signal
1382 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001383)
1384{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001385 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1386 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00001387 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001388 callback_baton,
1389 pid,
1390 exited,
1391 signo,
1392 exit_status);
1393
1394 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001395 {
Greg Clayton63094e02010-06-23 01:19:29 +00001396 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001397 if (target_sp)
1398 {
1399 ProcessSP process_sp (target_sp->GetProcessSP());
1400 if (process_sp)
1401 {
1402 const char *signal_cstr = NULL;
1403 if (signo)
1404 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1405
1406 process_sp->SetExitStatus (exit_status, signal_cstr);
1407 }
1408 }
1409 return true;
1410 }
1411 return false;
1412}
1413
1414
Greg Clayton37f962e2011-08-22 02:49:39 +00001415void
1416Process::UpdateThreadListIfNeeded ()
1417{
1418 const uint32_t stop_id = GetStopID();
1419 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1420 {
Greg Clayton20206082011-11-17 01:23:07 +00001421 const StateType state = GetPrivateState();
1422 if (StateIsStoppedState (state, true))
1423 {
1424 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001425 // m_thread_list does have its own mutex, but we need to
1426 // hold onto the mutex between the call to UpdateThreadList(...)
1427 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001428 ThreadList new_thread_list(this);
1429 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001430 // thread list, but only update if "true" is returned
1431 if (UpdateThreadList (m_thread_list, new_thread_list))
1432 {
1433 OperatingSystem *os = GetOperatingSystem ();
1434 if (os)
1435 os->UpdateThreadList (m_thread_list, new_thread_list);
1436 m_thread_list.Update (new_thread_list);
1437 m_thread_list.SetStopID (stop_id);
1438 }
Greg Clayton20206082011-11-17 01:23:07 +00001439 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001440 }
1441}
1442
Chris Lattner24943d22010-06-08 16:52:24 +00001443uint32_t
1444Process::GetNextThreadIndexID ()
1445{
1446 return ++m_thread_index_id;
1447}
1448
1449StateType
1450Process::GetState()
1451{
1452 // If any other threads access this we will need a mutex for it
1453 return m_public_state.GetValue ();
1454}
1455
1456void
1457Process::SetPublicState (StateType new_state)
1458{
Greg Clayton68ca8232011-01-25 02:58:48 +00001459 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001460 if (log)
1461 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001462 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001463 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001464
1465 // On the transition from Run to Stopped, we unlock the writer end of the
1466 // run lock. The lock gets locked in Resume, which is the public API
1467 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001468 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1469 {
Sean Callanana3772862012-06-02 01:16:20 +00001470 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001471 {
Sean Callanana3772862012-06-02 01:16:20 +00001472 if (log)
1473 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1474 m_run_lock.WriteUnlock();
1475 }
1476 else
1477 {
1478 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1479 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1480 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001481 {
Sean Callanana3772862012-06-02 01:16:20 +00001482 if (new_state_is_stopped)
1483 {
1484 if (log)
1485 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1486 m_run_lock.WriteUnlock();
1487 }
Greg Claytona894fe72012-04-05 16:12:35 +00001488 }
Greg Claytona894fe72012-04-05 16:12:35 +00001489 }
1490 }
Chris Lattner24943d22010-06-08 16:52:24 +00001491}
1492
Jim Ingham027aaa72012-04-19 01:40:33 +00001493Error
1494Process::Resume ()
1495{
1496 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1497 if (log)
1498 log->Printf("Process::Resume -- locking run lock");
1499 if (!m_run_lock.WriteTryLock())
1500 {
1501 Error error("Resume request failed - process still running.");
1502 if (log)
1503 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1504 return error;
1505 }
1506 return PrivateResume();
1507}
1508
Chris Lattner24943d22010-06-08 16:52:24 +00001509StateType
1510Process::GetPrivateState ()
1511{
1512 return m_private_state.GetValue();
1513}
1514
1515void
1516Process::SetPrivateState (StateType new_state)
1517{
Greg Clayton68ca8232011-01-25 02:58:48 +00001518 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001519 bool state_changed = false;
1520
1521 if (log)
1522 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1523
1524 Mutex::Locker locker(m_private_state.GetMutex());
1525
1526 const StateType old_state = m_private_state.GetValueNoLock ();
1527 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001528 // This code is left commented out in case we ever need to control
1529 // the private process state with another run lock. Right now it doesn't
1530 // seem like we need to do this, but if we ever do, we can uncomment and
1531 // use this code.
1532// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1533// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1534// if (old_state_is_stopped != new_state_is_stopped)
1535// {
1536// if (new_state_is_stopped)
1537// m_private_run_lock.WriteUnlock();
1538// else
1539// m_private_run_lock.WriteLock();
1540// }
1541
Chris Lattner24943d22010-06-08 16:52:24 +00001542 if (state_changed)
1543 {
1544 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001545 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001546 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001547 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001548 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001549 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001550 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001551 }
1552 // Use our target to get a shared pointer to ourselves...
1553 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1554 }
1555 else
1556 {
1557 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001558 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001559 }
1560}
1561
Jim Ingham0296fe72011-11-08 03:00:11 +00001562void
1563Process::SetRunningUserExpression (bool on)
1564{
1565 m_mod_id.SetRunningUserExpression (on);
1566}
1567
Chris Lattner24943d22010-06-08 16:52:24 +00001568addr_t
1569Process::GetImageInfoAddress()
1570{
1571 return LLDB_INVALID_ADDRESS;
1572}
1573
Greg Clayton0baa3942010-11-04 01:54:29 +00001574//----------------------------------------------------------------------
1575// LoadImage
1576//
1577// This function provides a default implementation that works for most
1578// unix variants. Any Process subclasses that need to do shared library
1579// loading differently should override LoadImage and UnloadImage and
1580// do what is needed.
1581//----------------------------------------------------------------------
1582uint32_t
1583Process::LoadImage (const FileSpec &image_spec, Error &error)
1584{
Greg Clayton77d40712012-04-18 00:05:19 +00001585 char path[PATH_MAX];
1586 image_spec.GetPath(path, sizeof(path));
1587
Greg Clayton0baa3942010-11-04 01:54:29 +00001588 DynamicLoader *loader = GetDynamicLoader();
1589 if (loader)
1590 {
1591 error = loader->CanLoadImage();
1592 if (error.Fail())
1593 return LLDB_INVALID_IMAGE_TOKEN;
1594 }
1595
1596 if (error.Success())
1597 {
1598 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001599
1600 if (thread_sp)
1601 {
1602 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1603
1604 if (frame_sp)
1605 {
1606 ExecutionContext exe_ctx;
1607 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001608 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001609 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001610 expr.Printf("dlopen (\"%s\", 2)", path);
1611 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001612 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001613 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chenb14ec342011-09-09 00:01:43 +00001614 error = result_valobj_sp->GetError();
1615 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001616 {
1617 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001618 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001619 {
1620 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1621 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1622 {
1623 uint32_t image_token = m_image_tokens.size();
1624 m_image_tokens.push_back (image_ptr);
1625 return image_token;
1626 }
1627 }
1628 }
1629 }
1630 }
1631 }
Greg Clayton77d40712012-04-18 00:05:19 +00001632 if (!error.AsCString())
1633 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001634 return LLDB_INVALID_IMAGE_TOKEN;
1635}
1636
1637//----------------------------------------------------------------------
1638// UnloadImage
1639//
1640// This function provides a default implementation that works for most
1641// unix variants. Any Process subclasses that need to do shared library
1642// loading differently should override LoadImage and UnloadImage and
1643// do what is needed.
1644//----------------------------------------------------------------------
1645Error
1646Process::UnloadImage (uint32_t image_token)
1647{
1648 Error error;
1649 if (image_token < m_image_tokens.size())
1650 {
1651 const addr_t image_addr = m_image_tokens[image_token];
1652 if (image_addr == LLDB_INVALID_ADDRESS)
1653 {
1654 error.SetErrorString("image already unloaded");
1655 }
1656 else
1657 {
1658 DynamicLoader *loader = GetDynamicLoader();
1659 if (loader)
1660 error = loader->CanLoadImage();
1661
1662 if (error.Success())
1663 {
1664 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001665
1666 if (thread_sp)
1667 {
1668 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1669
1670 if (frame_sp)
1671 {
1672 ExecutionContext exe_ctx;
1673 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001674 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001675 StreamString expr;
1676 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1677 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001678 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001679 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +00001680 if (result_valobj_sp->GetError().Success())
1681 {
1682 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001683 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001684 {
1685 if (scalar.UInt(1))
1686 {
1687 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1688 }
1689 else
1690 {
1691 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1692 }
1693 }
1694 }
1695 else
1696 {
1697 error = result_valobj_sp->GetError();
1698 }
1699 }
1700 }
1701 }
1702 }
1703 }
1704 else
1705 {
1706 error.SetErrorString("invalid image token");
1707 }
1708 return error;
1709}
1710
Greg Clayton75906e42011-05-11 18:39:18 +00001711const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001712Process::GetABI()
1713{
Greg Clayton75906e42011-05-11 18:39:18 +00001714 if (!m_abi_sp)
1715 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1716 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001717}
1718
Jim Ingham642036f2010-09-23 02:01:19 +00001719LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001720Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001721{
1722 LanguageRuntimeCollection::iterator pos;
1723 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001724 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001725 {
Jim Inghame3117662012-03-10 00:22:19 +00001726 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001727
Jim Inghame3117662012-03-10 00:22:19 +00001728 m_language_runtimes[language] = runtime_sp;
1729 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001730 }
1731 else
1732 return (*pos).second.get();
1733}
1734
1735CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001736Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001737{
Jim Inghame3117662012-03-10 00:22:19 +00001738 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001739 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1740 return static_cast<CPPLanguageRuntime *> (runtime);
1741 return NULL;
1742}
1743
1744ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001745Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001746{
Jim Inghame3117662012-03-10 00:22:19 +00001747 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001748 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1749 return static_cast<ObjCLanguageRuntime *> (runtime);
1750 return NULL;
1751}
1752
Enrico Granata6b1763b2012-05-21 16:51:35 +00001753bool
1754Process::IsPossibleDynamicValue (ValueObject& in_value)
1755{
1756 if (in_value.IsDynamic())
1757 return false;
1758 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1759
1760 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1761 {
1762 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1763 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1764 }
1765
1766 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1767 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1768 return true;
1769
1770 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1771 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1772}
1773
Chris Lattner24943d22010-06-08 16:52:24 +00001774BreakpointSiteList &
1775Process::GetBreakpointSiteList()
1776{
1777 return m_breakpoint_site_list;
1778}
1779
1780const BreakpointSiteList &
1781Process::GetBreakpointSiteList() const
1782{
1783 return m_breakpoint_site_list;
1784}
1785
1786
1787void
1788Process::DisableAllBreakpointSites ()
1789{
1790 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001791 size_t num_sites = m_breakpoint_site_list.GetSize();
1792 for (size_t i = 0; i < num_sites; i++)
1793 {
1794 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1795 }
Chris Lattner24943d22010-06-08 16:52:24 +00001796}
1797
1798Error
1799Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1800{
1801 Error error (DisableBreakpointSiteByID (break_id));
1802
1803 if (error.Success())
1804 m_breakpoint_site_list.Remove(break_id);
1805
1806 return error;
1807}
1808
1809Error
1810Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1811{
1812 Error error;
1813 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1814 if (bp_site_sp)
1815 {
1816 if (bp_site_sp->IsEnabled())
1817 error = DisableBreakpoint (bp_site_sp.get());
1818 }
1819 else
1820 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001821 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001822 }
1823
1824 return error;
1825}
1826
1827Error
1828Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1829{
1830 Error error;
1831 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1832 if (bp_site_sp)
1833 {
1834 if (!bp_site_sp->IsEnabled())
1835 error = EnableBreakpoint (bp_site_sp.get());
1836 }
1837 else
1838 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001839 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001840 }
1841 return error;
1842}
1843
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001844lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001845Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001846{
Greg Clayton265ab332011-05-19 18:17:41 +00001847 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001848 if (load_addr != LLDB_INVALID_ADDRESS)
1849 {
1850 BreakpointSiteSP bp_site_sp;
1851
1852 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1853 // create a new breakpoint site and add it.
1854
1855 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1856
1857 if (bp_site_sp)
1858 {
1859 bp_site_sp->AddOwner (owner);
1860 owner->SetBreakpointSite (bp_site_sp);
1861 return bp_site_sp->GetID();
1862 }
1863 else
1864 {
1865 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1866 if (bp_site_sp)
1867 {
1868 if (EnableBreakpoint (bp_site_sp.get()).Success())
1869 {
1870 owner->SetBreakpointSite (bp_site_sp);
1871 return m_breakpoint_site_list.Add (bp_site_sp);
1872 }
1873 }
1874 }
1875 }
1876 // We failed to enable the breakpoint
1877 return LLDB_INVALID_BREAK_ID;
1878
1879}
1880
1881void
1882Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1883{
1884 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1885 if (num_owners == 0)
1886 {
1887 DisableBreakpoint(bp_site_sp.get());
1888 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1889 }
1890}
1891
1892
1893size_t
1894Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1895{
1896 size_t bytes_removed = 0;
1897 addr_t intersect_addr;
1898 size_t intersect_size;
1899 size_t opcode_offset;
1900 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001901 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001902 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001903
Jim Ingham82820f92011-06-29 19:42:28 +00001904 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001905 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001906 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001907 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001908 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001909 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001910 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001911 {
1912 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1913 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001914 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001915 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001916 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001917 }
Chris Lattner24943d22010-06-08 16:52:24 +00001918 }
1919 }
1920 }
1921 return bytes_removed;
1922}
1923
1924
Greg Claytonb1888f22011-03-19 01:12:21 +00001925
1926size_t
1927Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1928{
1929 PlatformSP platform_sp (m_target.GetPlatform());
1930 if (platform_sp)
1931 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1932 return 0;
1933}
1934
Chris Lattner24943d22010-06-08 16:52:24 +00001935Error
1936Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1937{
1938 Error error;
1939 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001940 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001941 const addr_t bp_addr = bp_site->GetLoadAddress();
1942 if (log)
1943 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1944 if (bp_site->IsEnabled())
1945 {
1946 if (log)
1947 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1948 return error;
1949 }
1950
1951 if (bp_addr == LLDB_INVALID_ADDRESS)
1952 {
1953 error.SetErrorString("BreakpointSite contains an invalid load address.");
1954 return error;
1955 }
1956 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1957 // trap for the breakpoint site
1958 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1959
1960 if (bp_opcode_size == 0)
1961 {
Greg Clayton9c236732011-10-26 00:56:27 +00001962 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001963 }
1964 else
1965 {
1966 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1967
1968 if (bp_opcode_bytes == NULL)
1969 {
1970 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1971 return error;
1972 }
1973
1974 // Save the original opcode by reading it
1975 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1976 {
1977 // Write a software breakpoint in place of the original opcode
1978 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1979 {
1980 uint8_t verify_bp_opcode_bytes[64];
1981 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1982 {
1983 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1984 {
1985 bp_site->SetEnabled(true);
1986 bp_site->SetType (BreakpointSite::eSoftware);
1987 if (log)
1988 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1989 bp_site->GetID(),
1990 (uint64_t)bp_addr);
1991 }
1992 else
Greg Clayton9c236732011-10-26 00:56:27 +00001993 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00001994 }
1995 else
1996 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1997 }
1998 else
1999 error.SetErrorString("Unable to write breakpoint trap to memory.");
2000 }
2001 else
2002 error.SetErrorString("Unable to read memory at breakpoint address.");
2003 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002004 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00002005 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2006 bp_site->GetID(),
2007 (uint64_t)bp_addr,
2008 error.AsCString());
2009 return error;
2010}
2011
2012Error
2013Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2014{
2015 Error error;
2016 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002017 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002018 addr_t bp_addr = bp_site->GetLoadAddress();
2019 lldb::user_id_t breakID = bp_site->GetID();
2020 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002021 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002022
2023 if (bp_site->IsHardware())
2024 {
2025 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2026 }
2027 else if (bp_site->IsEnabled())
2028 {
2029 const size_t break_op_size = bp_site->GetByteSize();
2030 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2031 if (break_op_size > 0)
2032 {
2033 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002034 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002035 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002036 bool break_op_found = false;
2037
2038 // Read the breakpoint opcode
2039 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2040 {
2041 bool verify = false;
2042 // Make sure we have the a breakpoint opcode exists at this address
2043 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2044 {
2045 break_op_found = true;
2046 // We found a valid breakpoint opcode at this address, now restore
2047 // the saved opcode.
2048 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2049 {
2050 verify = true;
2051 }
2052 else
2053 error.SetErrorString("Memory write failed when restoring original opcode.");
2054 }
2055 else
2056 {
2057 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2058 // Set verify to true and so we can check if the original opcode has already been restored
2059 verify = true;
2060 }
2061
2062 if (verify)
2063 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002064 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002065 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002066 // Verify that our original opcode made it back to the inferior
2067 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2068 {
2069 // compare the memory we just read with the original opcode
2070 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2071 {
2072 // SUCCESS
2073 bp_site->SetEnabled(false);
2074 if (log)
2075 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2076 return error;
2077 }
2078 else
2079 {
2080 if (break_op_found)
2081 error.SetErrorString("Failed to restore original opcode.");
2082 }
2083 }
2084 else
2085 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2086 }
2087 }
2088 else
2089 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2090 }
2091 }
2092 else
2093 {
2094 if (log)
2095 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2096 return error;
2097 }
2098
2099 if (log)
2100 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2101 bp_site->GetID(),
2102 (uint64_t)bp_addr,
2103 error.AsCString());
2104 return error;
2105
2106}
2107
Greg Claytonfd119992011-01-07 06:08:19 +00002108// Uncomment to verify memory caching works after making changes to caching code
2109//#define VERIFY_MEMORY_READS
2110
Sean Callananf90b5f32012-06-07 22:26:42 +00002111size_t
2112Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2113{
2114 if (!GetDisableMemoryCache())
2115 {
Greg Claytonfd119992011-01-07 06:08:19 +00002116#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002117 // Memory caching is enabled, with debug verification
2118
2119 if (buf && size)
2120 {
2121 // Uncomment the line below to make sure memory caching is working.
2122 // I ran this through the test suite and got no assertions, so I am
2123 // pretty confident this is working well. If any changes are made to
2124 // memory caching, uncomment the line below and test your changes!
2125
2126 // Verify all memory reads by using the cache first, then redundantly
2127 // reading the same memory from the inferior and comparing to make sure
2128 // everything is exactly the same.
2129 std::string verify_buf (size, '\0');
2130 assert (verify_buf.size() == size);
2131 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2132 Error verify_error;
2133 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2134 assert (cache_bytes_read == verify_bytes_read);
2135 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2136 assert (verify_error.Success() == error.Success());
2137 return cache_bytes_read;
2138 }
2139 return 0;
2140#else // !defined(VERIFY_MEMORY_READS)
2141 // Memory caching is enabled, without debug verification
2142
2143 return m_memory_cache.Read (addr, buf, size, error);
2144#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002145 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002146 else
2147 {
2148 // Memory caching is disabled
2149
2150 return ReadMemoryFromInferior (addr, buf, size, error);
2151 }
Greg Claytonfd119992011-01-07 06:08:19 +00002152}
Greg Claytonfd119992011-01-07 06:08:19 +00002153
Greg Claytondd29b972012-05-18 23:20:01 +00002154size_t
2155Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2156{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002157 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002158 out_str.clear();
2159 addr_t curr_addr = addr;
2160 while (1)
2161 {
2162 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2163 if (length == 0)
2164 break;
2165 out_str.append(buf, length);
2166 // If we got "length - 1" bytes, we didn't get the whole C string, we
2167 // need to read some more characters
2168 if (length == sizeof(buf) - 1)
2169 curr_addr += length;
2170 else
2171 break;
2172 }
2173 return out_str.size();
2174}
2175
Greg Claytonfd119992011-01-07 06:08:19 +00002176
2177size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002178Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002179{
2180 size_t total_cstr_len = 0;
2181 if (dst && dst_max_len)
2182 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002183 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002184 // NULL out everything just to be safe
2185 memset (dst, 0, dst_max_len);
2186 Error error;
2187 addr_t curr_addr = addr;
2188 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2189 size_t bytes_left = dst_max_len - 1;
2190 char *curr_dst = dst;
2191
2192 while (bytes_left > 0)
2193 {
2194 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2195 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2196 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2197
2198 if (bytes_read == 0)
2199 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002200 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002201 dst[total_cstr_len] = '\0';
2202 break;
2203 }
2204 const size_t len = strlen(curr_dst);
2205
2206 total_cstr_len += len;
2207
2208 if (len < bytes_to_read)
2209 break;
2210
2211 curr_dst += bytes_read;
2212 curr_addr += bytes_read;
2213 bytes_left -= bytes_read;
2214 }
2215 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002216 else
2217 {
2218 if (dst == NULL)
2219 result_error.SetErrorString("invalid arguments");
2220 else
2221 result_error.Clear();
2222 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002223 return total_cstr_len;
2224}
2225
2226size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002227Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2228{
Chris Lattner24943d22010-06-08 16:52:24 +00002229 if (buf == NULL || size == 0)
2230 return 0;
2231
2232 size_t bytes_read = 0;
2233 uint8_t *bytes = (uint8_t *)buf;
2234
2235 while (bytes_read < size)
2236 {
2237 const size_t curr_size = size - bytes_read;
2238 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2239 bytes + bytes_read,
2240 curr_size,
2241 error);
2242 bytes_read += curr_bytes_read;
2243 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2244 break;
2245 }
2246
2247 // Replace any software breakpoint opcodes that fall into this range back
2248 // into "buf" before we return
2249 if (bytes_read > 0)
2250 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2251 return bytes_read;
2252}
2253
Greg Claytonf72fdee2010-12-16 20:01:20 +00002254uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002255Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002256{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002257 Scalar scalar;
2258 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2259 return scalar.ULongLong(fail_value);
2260 return fail_value;
2261}
2262
2263addr_t
2264Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2265{
2266 Scalar scalar;
2267 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2268 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2269 return LLDB_INVALID_ADDRESS;
2270}
2271
2272
2273bool
2274Process::WritePointerToMemory (lldb::addr_t vm_addr,
2275 lldb::addr_t ptr_value,
2276 Error &error)
2277{
2278 Scalar scalar;
2279 const uint32_t addr_byte_size = GetAddressByteSize();
2280 if (addr_byte_size <= 4)
2281 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002282 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002283 scalar = ptr_value;
2284 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002285}
2286
Chris Lattner24943d22010-06-08 16:52:24 +00002287size_t
2288Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2289{
2290 size_t bytes_written = 0;
2291 const uint8_t *bytes = (const uint8_t *)buf;
2292
2293 while (bytes_written < size)
2294 {
2295 const size_t curr_size = size - bytes_written;
2296 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2297 bytes + bytes_written,
2298 curr_size,
2299 error);
2300 bytes_written += curr_bytes_written;
2301 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2302 break;
2303 }
2304 return bytes_written;
2305}
2306
2307size_t
2308Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2309{
Greg Claytonfd119992011-01-07 06:08:19 +00002310#if defined (ENABLE_MEMORY_CACHING)
2311 m_memory_cache.Flush (addr, size);
2312#endif
2313
Chris Lattner24943d22010-06-08 16:52:24 +00002314 if (buf == NULL || size == 0)
2315 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002316
Jim Ingham21f37ad2011-08-09 02:12:22 +00002317 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002318
Chris Lattner24943d22010-06-08 16:52:24 +00002319 // We need to write any data that would go where any current software traps
2320 // (enabled software breakpoints) any software traps (breakpoints) that we
2321 // may have placed in our tasks memory.
2322
2323 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2324 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2325
2326 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002327 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002328
2329 BreakpointSiteList::collection::const_iterator pos;
2330 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002331 addr_t intersect_addr = 0;
2332 size_t intersect_size = 0;
2333 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002334 const uint8_t *ubuf = (const uint8_t *)buf;
2335
2336 for (pos = iter; pos != end; ++pos)
2337 {
2338 BreakpointSiteSP bp;
2339 bp = pos->second;
2340
2341 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2342 assert(addr <= intersect_addr && intersect_addr < addr + size);
2343 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2344 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2345
2346 // Check for bytes before this breakpoint
2347 const addr_t curr_addr = addr + bytes_written;
2348 if (intersect_addr > curr_addr)
2349 {
2350 // There are some bytes before this breakpoint that we need to
2351 // just write to memory
2352 size_t curr_size = intersect_addr - curr_addr;
2353 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2354 ubuf + bytes_written,
2355 curr_size,
2356 error);
2357 bytes_written += curr_bytes_written;
2358 if (curr_bytes_written != curr_size)
2359 {
2360 // We weren't able to write all of the requested bytes, we
2361 // are done looping and will return the number of bytes that
2362 // we have written so far.
2363 break;
2364 }
2365 }
2366
2367 // Now write any bytes that would cover up any software breakpoints
2368 // directly into the breakpoint opcode buffer
2369 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2370 bytes_written += intersect_size;
2371 }
2372
2373 // Write any remaining bytes after the last breakpoint if we have any left
2374 if (bytes_written < size)
2375 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2376 ubuf + bytes_written,
2377 size - bytes_written,
2378 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002379
Chris Lattner24943d22010-06-08 16:52:24 +00002380 return bytes_written;
2381}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002382
2383size_t
2384Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2385{
2386 if (byte_size == UINT32_MAX)
2387 byte_size = scalar.GetByteSize();
2388 if (byte_size > 0)
2389 {
2390 uint8_t buf[32];
2391 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2392 if (mem_size > 0)
2393 return WriteMemory(addr, buf, mem_size, error);
2394 else
2395 error.SetErrorString ("failed to get scalar as memory data");
2396 }
2397 else
2398 {
2399 error.SetErrorString ("invalid scalar value");
2400 }
2401 return 0;
2402}
2403
2404size_t
2405Process::ReadScalarIntegerFromMemory (addr_t addr,
2406 uint32_t byte_size,
2407 bool is_signed,
2408 Scalar &scalar,
2409 Error &error)
2410{
2411 uint64_t uval;
2412
2413 if (byte_size <= sizeof(uval))
2414 {
2415 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2416 if (bytes_read == byte_size)
2417 {
2418 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2419 uint32_t offset = 0;
2420 if (byte_size <= 4)
2421 scalar = data.GetMaxU32 (&offset, byte_size);
2422 else
2423 scalar = data.GetMaxU64 (&offset, byte_size);
2424
2425 if (is_signed)
2426 scalar.SignExtend(byte_size * 8);
2427 return bytes_read;
2428 }
2429 }
2430 else
2431 {
2432 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2433 }
2434 return 0;
2435}
2436
Greg Clayton613b8732011-05-17 03:37:42 +00002437#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002438addr_t
2439Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2440{
Jim Inghame6bd1422011-06-20 17:32:44 +00002441 if (GetPrivateState() != eStateStopped)
2442 return LLDB_INVALID_ADDRESS;
2443
Greg Clayton613b8732011-05-17 03:37:42 +00002444#if defined (USE_ALLOCATE_MEMORY_CACHE)
2445 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2446#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002447 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2448 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2449 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002450 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002451 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002452 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002453 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002454 m_mod_id.GetStopID(),
2455 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002456 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002457#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002458}
2459
Sean Callanan6cf6c472011-09-20 23:01:51 +00002460bool
2461Process::CanJIT ()
2462{
Sean Callanan04200f62012-02-14 22:50:38 +00002463 if (m_can_jit == eCanJITDontKnow)
2464 {
2465 Error err;
2466
2467 uint64_t allocated_memory = AllocateMemory(8,
2468 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2469 err);
2470
2471 if (err.Success())
2472 m_can_jit = eCanJITYes;
2473 else
2474 m_can_jit = eCanJITNo;
2475
2476 DeallocateMemory (allocated_memory);
2477 }
2478
Sean Callanan6cf6c472011-09-20 23:01:51 +00002479 return m_can_jit == eCanJITYes;
2480}
2481
2482void
2483Process::SetCanJIT (bool can_jit)
2484{
2485 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2486}
2487
Chris Lattner24943d22010-06-08 16:52:24 +00002488Error
2489Process::DeallocateMemory (addr_t ptr)
2490{
Greg Clayton613b8732011-05-17 03:37:42 +00002491 Error error;
2492#if defined (USE_ALLOCATE_MEMORY_CACHE)
2493 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2494 {
2495 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2496 }
2497#else
2498 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002499
2500 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2501 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002502 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002503 ptr,
2504 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002505 m_mod_id.GetStopID(),
2506 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002507#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002508 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002509}
2510
Greg Claytonb5a8f142012-02-05 02:38:54 +00002511ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002512Process::ReadModuleFromMemory (const FileSpec& file_spec,
2513 lldb::addr_t header_addr,
2514 bool add_image_to_target,
2515 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002516{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002517 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002518 if (module_sp)
2519 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002520 Error error;
2521 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2522 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002523 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002524 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002525 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002526 m_target.GetImages().Append(module_sp);
2527 if (load_sections_in_target)
2528 {
2529 bool changed = false;
2530 module_sp->SetLoadAddress (m_target, 0, changed);
2531 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002532 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002533 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002534 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002535 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002536 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002537}
Chris Lattner24943d22010-06-08 16:52:24 +00002538
2539Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002540Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002541{
2542 Error error;
2543 error.SetErrorString("watchpoints are not supported");
2544 return error;
2545}
2546
2547Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002548Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002549{
2550 Error error;
2551 error.SetErrorString("watchpoints are not supported");
2552 return error;
2553}
2554
2555StateType
2556Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2557{
2558 StateType state;
2559 // Now wait for the process to launch and return control to us, and then
2560 // call DidLaunch:
2561 while (1)
2562 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002563 event_sp.reset();
2564 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2565
Greg Clayton20206082011-11-17 01:23:07 +00002566 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002567 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002568
2569 // If state is invalid, then we timed out
2570 if (state == eStateInvalid)
2571 break;
2572
2573 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002574 HandlePrivateEvent (event_sp);
2575 }
2576 return state;
2577}
2578
2579Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002580Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002581{
2582 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002583 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002584 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002585 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002586 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002587
Greg Clayton5beb99d2011-08-11 02:48:45 +00002588 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002589 if (exe_module)
2590 {
Greg Clayton180546b2011-04-30 01:09:13 +00002591 char local_exec_file_path[PATH_MAX];
2592 char platform_exec_file_path[PATH_MAX];
2593 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2594 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002595 if (exe_module->GetFileSpec().Exists())
2596 {
Greg Claytona2f74232011-02-24 22:24:29 +00002597 if (PrivateStateThreadIsValid ())
2598 PausePrivateStateThread ();
2599
Chris Lattner24943d22010-06-08 16:52:24 +00002600 error = WillLaunch (exe_module);
2601 if (error.Success())
2602 {
Greg Claytond8c62532010-10-07 04:19:01 +00002603 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002604 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002605
Greg Clayton777c6b72012-09-04 20:29:05 +00002606 if (m_run_lock.WriteTryLock())
2607 {
2608 // Now launch using these arguments.
2609 error = DoLaunch (exe_module, launch_info);
2610 }
2611 else
2612 {
2613 // This shouldn't happen
2614 error.SetErrorString("failed to acquire process run lock");
2615 }
Chris Lattner24943d22010-06-08 16:52:24 +00002616
2617 if (error.Fail())
2618 {
2619 if (GetID() != LLDB_INVALID_PROCESS_ID)
2620 {
2621 SetID (LLDB_INVALID_PROCESS_ID);
2622 const char *error_string = error.AsCString();
2623 if (error_string == NULL)
2624 error_string = "launch failed";
2625 SetExitStatus (-1, error_string);
2626 }
2627 }
2628 else
2629 {
2630 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002631 TimeValue timeout_time;
2632 timeout_time = TimeValue::Now();
2633 timeout_time.OffsetWithSeconds(10);
2634 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002635
Greg Clayton49859592011-06-22 01:42:17 +00002636 if (state == eStateInvalid || event_sp.get() == NULL)
2637 {
2638 // We were able to launch the process, but we failed to
2639 // catch the initial stop.
2640 SetExitStatus (0, "failed to catch stop after launch");
2641 Destroy();
2642 }
2643 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002644 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002645
Chris Lattner24943d22010-06-08 16:52:24 +00002646 DidLaunch ();
2647
Greg Clayton9ce95382012-02-13 23:10:39 +00002648 DynamicLoader *dyld = GetDynamicLoader ();
2649 if (dyld)
2650 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002651
Greg Clayton37f962e2011-08-22 02:49:39 +00002652 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002653 // This delays passing the stopped event to listeners till DidLaunch gets
2654 // a chance to complete...
2655 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002656
2657 if (PrivateStateThreadIsValid ())
2658 ResumePrivateStateThread ();
2659 else
2660 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002661 }
2662 else if (state == eStateExited)
2663 {
2664 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2665 // not likely to work, and return an invalid pid.
2666 HandlePrivateEvent (event_sp);
2667 }
2668 }
2669 }
2670 }
2671 else
2672 {
Greg Clayton9c236732011-10-26 00:56:27 +00002673 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002674 }
2675 }
2676 return error;
2677}
2678
Greg Clayton46c9a352012-02-09 06:16:32 +00002679
2680Error
2681Process::LoadCore ()
2682{
2683 Error error = DoLoadCore();
2684 if (error.Success())
2685 {
2686 if (PrivateStateThreadIsValid ())
2687 ResumePrivateStateThread ();
2688 else
2689 StartPrivateStateThread ();
2690
Greg Clayton9ce95382012-02-13 23:10:39 +00002691 DynamicLoader *dyld = GetDynamicLoader ();
2692 if (dyld)
2693 dyld->DidAttach();
2694
2695 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002696 // We successfully loaded a core file, now pretend we stopped so we can
2697 // show all of the threads in the core file and explore the crashed
2698 // state.
2699 SetPrivateState (eStateStopped);
2700
2701 }
2702 return error;
2703}
2704
Greg Clayton9ce95382012-02-13 23:10:39 +00002705DynamicLoader *
2706Process::GetDynamicLoader ()
2707{
2708 if (m_dyld_ap.get() == NULL)
2709 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2710 return m_dyld_ap.get();
2711}
Greg Clayton46c9a352012-02-09 06:16:32 +00002712
2713
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002714Process::NextEventAction::EventActionResult
2715Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002716{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002717 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2718 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002719 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002720 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002721 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002722 return eEventActionRetry;
2723
2724 case eStateStopped:
2725 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002726 {
2727 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002728 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002729 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2730 if (m_exec_count > 0)
2731 {
2732 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002733 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002734 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002735 return eEventActionRetry;
2736 }
2737 else
2738 {
2739 m_process->CompleteAttach ();
2740 return eEventActionSuccess;
2741 }
2742 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002743 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002744
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002745 default:
2746 case eStateExited:
2747 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002748 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002749 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002750
2751 m_exit_string.assign ("No valid Process");
2752 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002753}
Chris Lattner24943d22010-06-08 16:52:24 +00002754
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002755Process::NextEventAction::EventActionResult
2756Process::AttachCompletionHandler::HandleBeingInterrupted()
2757{
2758 return eEventActionSuccess;
2759}
2760
2761const char *
2762Process::AttachCompletionHandler::GetExitString ()
2763{
2764 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002765}
2766
2767Error
Greg Clayton527154d2011-11-15 03:53:30 +00002768Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002769{
Chris Lattner24943d22010-06-08 16:52:24 +00002770 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002771 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002772 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002773 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002774
Greg Clayton527154d2011-11-15 03:53:30 +00002775 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002776 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002777 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002778 {
Greg Clayton527154d2011-11-15 03:53:30 +00002779 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002780
Greg Clayton527154d2011-11-15 03:53:30 +00002781 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002782 {
Greg Clayton527154d2011-11-15 03:53:30 +00002783 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2784
2785 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002786 {
Greg Clayton527154d2011-11-15 03:53:30 +00002787 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2788 if (error.Success())
2789 {
Greg Claytond34a3b22012-10-12 16:10:12 +00002790 if (m_run_lock.WriteTryLock())
2791 {
2792 m_should_detach = true;
2793 SetPublicState (eStateAttaching);
2794 // Now attach using these arguments.
2795 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2796 }
2797 else
2798 {
2799 // This shouldn't happen
2800 error.SetErrorString("failed to acquire process run lock");
2801 }
Greg Claytonffa43a62011-11-17 04:46:02 +00002802
Greg Clayton527154d2011-11-15 03:53:30 +00002803 if (error.Fail())
2804 {
2805 if (GetID() != LLDB_INVALID_PROCESS_ID)
2806 {
2807 SetID (LLDB_INVALID_PROCESS_ID);
2808 if (error.AsCString() == NULL)
2809 error.SetErrorString("attach failed");
2810
2811 SetExitStatus(-1, error.AsCString());
2812 }
2813 }
2814 else
2815 {
2816 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2817 StartPrivateStateThread();
2818 }
2819 return error;
2820 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002821 }
Greg Clayton527154d2011-11-15 03:53:30 +00002822 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002823 {
Greg Clayton527154d2011-11-15 03:53:30 +00002824 ProcessInstanceInfoList process_infos;
2825 PlatformSP platform_sp (m_target.GetPlatform ());
2826
2827 if (platform_sp)
2828 {
2829 ProcessInstanceInfoMatch match_info;
2830 match_info.GetProcessInfo() = attach_info;
2831 match_info.SetNameMatchType (eNameMatchEquals);
2832 platform_sp->FindProcesses (match_info, process_infos);
2833 const uint32_t num_matches = process_infos.GetSize();
2834 if (num_matches == 1)
2835 {
2836 attach_pid = process_infos.GetProcessIDAtIndex(0);
2837 // Fall through and attach using the above process ID
2838 }
2839 else
2840 {
2841 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2842 if (num_matches > 1)
2843 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2844 else
2845 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2846 }
2847 }
2848 else
2849 {
2850 error.SetErrorString ("invalid platform, can't find processes by name");
2851 return error;
2852 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002853 }
Chris Lattner24943d22010-06-08 16:52:24 +00002854 }
2855 else
Greg Clayton527154d2011-11-15 03:53:30 +00002856 {
2857 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002858 }
2859 }
Greg Clayton527154d2011-11-15 03:53:30 +00002860
2861 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002862 {
Greg Clayton527154d2011-11-15 03:53:30 +00002863 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002864 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002865 {
Greg Clayton527154d2011-11-15 03:53:30 +00002866
Greg Claytond34a3b22012-10-12 16:10:12 +00002867 if (m_run_lock.WriteTryLock())
2868 {
2869 // Now attach using these arguments.
2870 m_should_detach = true;
2871 SetPublicState (eStateAttaching);
2872 error = DoAttachToProcessWithID (attach_pid, attach_info);
2873 }
2874 else
2875 {
2876 // This shouldn't happen
2877 error.SetErrorString("failed to acquire process run lock");
2878 }
2879
Greg Clayton527154d2011-11-15 03:53:30 +00002880 if (error.Success())
2881 {
2882
2883 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2884 StartPrivateStateThread();
2885 }
2886 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002887 {
2888 if (GetID() != LLDB_INVALID_PROCESS_ID)
2889 {
2890 SetID (LLDB_INVALID_PROCESS_ID);
2891 const char *error_string = error.AsCString();
2892 if (error_string == NULL)
2893 error_string = "attach failed";
2894
2895 SetExitStatus(-1, error_string);
2896 }
2897 }
Chris Lattner24943d22010-06-08 16:52:24 +00002898 }
2899 }
2900 return error;
2901}
2902
Greg Clayton75c703d2011-02-16 04:46:07 +00002903void
2904Process::CompleteAttach ()
2905{
2906 // Let the process subclass figure out at much as it can about the process
2907 // before we go looking for a dynamic loader plug-in.
2908 DidAttach();
2909
Jim Ingham0d7f7772011-09-15 01:10:17 +00002910 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2911 // the same as the one we've already set, switch architectures.
2912 PlatformSP platform_sp (m_target.GetPlatform ());
2913 assert (platform_sp.get());
2914 if (platform_sp)
2915 {
Greg Claytonb170aee2012-05-08 01:45:38 +00002916 const ArchSpec &target_arch = m_target.GetArchitecture();
2917 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2918 {
2919 ArchSpec platform_arch;
2920 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2921 if (platform_sp)
2922 {
2923 m_target.SetPlatform (platform_sp);
2924 m_target.SetArchitecture(platform_arch);
2925 }
2926 }
2927 else
2928 {
2929 ProcessInstanceInfo process_info;
2930 platform_sp->GetProcessInfo (GetID(), process_info);
2931 const ArchSpec &process_arch = process_info.GetArchitecture();
2932 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2933 m_target.SetArchitecture (process_arch);
2934 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00002935 }
2936
2937 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002938 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00002939 DynamicLoader *dyld = GetDynamicLoader ();
2940 if (dyld)
2941 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00002942
Greg Clayton37f962e2011-08-22 02:49:39 +00002943 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002944 // Figure out which one is the executable, and set that in our target:
Jim Ingham93367902012-05-30 02:19:25 +00002945 ModuleList &target_modules = m_target.GetImages();
2946 Mutex::Locker modules_locker(target_modules.GetMutex());
2947 size_t num_modules = target_modules.GetSize();
2948 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00002949
Greg Clayton75c703d2011-02-16 04:46:07 +00002950 for (int i = 0; i < num_modules; i++)
2951 {
Jim Ingham93367902012-05-30 02:19:25 +00002952 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002953 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002954 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002955 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00002956 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00002957 break;
2958 }
2959 }
Jim Ingham93367902012-05-30 02:19:25 +00002960 if (new_executable_module_sp)
2961 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00002962}
2963
Chris Lattner24943d22010-06-08 16:52:24 +00002964Error
Jason Molendafac2e622012-09-29 04:02:01 +00002965Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00002966{
Greg Claytone71e2582011-02-04 01:58:07 +00002967 m_abi_sp.reset();
2968 m_process_input_reader.reset();
2969
2970 // Find the process and its architecture. Make sure it matches the architecture
2971 // of the current Target, and if not adjust it.
2972
Jason Molendafac2e622012-09-29 04:02:01 +00002973 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00002974 if (error.Success())
2975 {
Greg Claytona2f74232011-02-24 22:24:29 +00002976 if (GetID() != LLDB_INVALID_PROCESS_ID)
2977 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002978 EventSP event_sp;
2979 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2980
2981 if (state == eStateStopped || state == eStateCrashed)
2982 {
2983 // If we attached and actually have a process on the other end, then
2984 // this ended up being the equivalent of an attach.
2985 CompleteAttach ();
2986
2987 // This delays passing the stopped event to listeners till
2988 // CompleteAttach gets a chance to complete...
2989 HandlePrivateEvent (event_sp);
2990
2991 }
Greg Claytona2f74232011-02-24 22:24:29 +00002992 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002993
2994 if (PrivateStateThreadIsValid ())
2995 ResumePrivateStateThread ();
2996 else
2997 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002998 }
2999 return error;
3000}
3001
3002
3003Error
Jim Ingham027aaa72012-04-19 01:40:33 +00003004Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00003005{
Jim Inghame1a654b2012-09-06 19:24:17 +00003006 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00003007 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00003008 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00003009 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00003010 StateAsCString(m_public_state.GetValue()),
3011 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00003012
3013 Error error (WillResume());
3014 // Tell the process it is about to resume before the thread list
3015 if (error.Success())
3016 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003017 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003018 // can let all of our threads know that they are about to be
3019 // resumed. Threads will each be called with
3020 // Thread::WillResume(StateType) where StateType contains the state
3021 // that they are supposed to have when the process is resumed
3022 // (suspended/running/stepping). Threads should also check
3023 // their resume signal in lldb::Thread::GetResumeSignal()
3024 // to see if they are suppoed to start back up with a signal.
3025 if (m_thread_list.WillResume())
3026 {
Jim Ingham1831e782012-04-07 00:00:41 +00003027 // Last thing, do the PreResumeActions.
3028 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003029 {
Jim Ingham1831e782012-04-07 00:00:41 +00003030 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3031 }
3032 else
3033 {
3034 m_mod_id.BumpResumeID();
3035 error = DoResume();
3036 if (error.Success())
3037 {
3038 DidResume();
3039 m_thread_list.DidResume();
3040 if (log)
3041 log->Printf ("Process thinks the process has resumed.");
3042 }
Chris Lattner24943d22010-06-08 16:52:24 +00003043 }
3044 }
3045 else
3046 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003047 // Somebody wanted to run without running. So generate a continue & a stopped event,
3048 // and let the world handle them.
3049 if (log)
3050 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3051
3052 SetPrivateState(eStateRunning);
3053 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003054 }
3055 }
Jim Inghamac959662011-01-24 06:34:17 +00003056 else if (log)
3057 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003058 return error;
3059}
3060
3061Error
3062Process::Halt ()
3063{
Jim Ingham43892562012-06-06 00:29:30 +00003064 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3065 // we could just straightaway get another event. It just narrows the window...
3066 m_currently_handling_event.WaitForValueEqualTo(false);
3067
3068
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003069 // Pause our private state thread so we can ensure no one else eats
3070 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003071 Listener halt_listener ("lldb.process.halt_listener");
3072 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003073
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003074 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003075 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003076
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003077 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003078 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003079
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003080 bool caused_stop = false;
3081
3082 // Ask the process subclass to actually halt our process
3083 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003084 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003085 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003086 if (m_public_state.GetValue() == eStateAttaching)
3087 {
3088 SetExitStatus(SIGKILL, "Cancelled async attach.");
3089 Destroy ();
3090 }
3091 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003092 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003093 // If "caused_stop" is true, then DoHalt stopped the process. If
3094 // "caused_stop" is false, the process was already stopped.
3095 // If the DoHalt caused the process to stop, then we want to catch
3096 // this event and set the interrupted bool to true before we pass
3097 // this along so clients know that the process was interrupted by
3098 // a halt command.
3099 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003100 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003101 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003102 TimeValue timeout_time;
3103 timeout_time = TimeValue::Now();
3104 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003105 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3106 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003107
Jim Inghamf9f40c22011-02-08 05:20:59 +00003108 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003109 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003110 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003111 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003112 }
3113 else
3114 {
Greg Clayton20206082011-11-17 01:23:07 +00003115 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003116 {
3117 // We caused the process to interrupt itself, so mark this
3118 // as such in the stop event so clients can tell an interrupted
3119 // process from a natural stop
3120 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3121 }
3122 else
3123 {
3124 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3125 if (log)
3126 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3127 error.SetErrorString ("Did not get stopped event after halt.");
3128 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003129 }
3130 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003131 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003132 }
3133 }
Chris Lattner24943d22010-06-08 16:52:24 +00003134 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003135 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003136 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003137
3138 // Post any event we might have consumed. If all goes well, we will have
3139 // stopped the process, intercepted the event and set the interrupted
3140 // bool in the event. Post it to the private event queue and that will end up
3141 // correctly setting the state.
3142 if (event_sp)
3143 m_private_state_broadcaster.BroadcastEvent(event_sp);
3144
Chris Lattner24943d22010-06-08 16:52:24 +00003145 return error;
3146}
3147
3148Error
3149Process::Detach ()
3150{
3151 Error error (WillDetach());
3152
3153 if (error.Success())
3154 {
3155 DisableAllBreakpointSites();
3156 error = DoDetach();
3157 if (error.Success())
3158 {
3159 DidDetach();
3160 StopPrivateStateThread();
3161 }
3162 }
3163 return error;
3164}
3165
3166Error
3167Process::Destroy ()
3168{
3169 Error error (WillDestroy());
3170 if (error.Success())
3171 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003172 EventSP exit_event_sp;
Jim Inghamf4928de2012-05-23 15:46:31 +00003173 if (m_public_state.GetValue() == eStateRunning)
3174 {
Greg Clayton38ae5b92012-09-05 00:37:58 +00003175 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003176 if (log)
3177 log->Printf("Process::Destroy() About to halt.");
Jim Inghamf4928de2012-05-23 15:46:31 +00003178 error = Halt();
3179 if (error.Success())
3180 {
3181 // Consume the halt event.
Jim Inghamf4928de2012-05-23 15:46:31 +00003182 TimeValue timeout (TimeValue::Now());
Jim Ingham43892562012-06-06 00:29:30 +00003183 timeout.OffsetWithSeconds(1);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003184 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3185 if (state != eStateExited)
3186 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3187
Jim Inghamf4928de2012-05-23 15:46:31 +00003188 if (state != eStateStopped)
3189 {
Jim Inghamf4928de2012-05-23 15:46:31 +00003190 if (log)
3191 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Ingham43892562012-06-06 00:29:30 +00003192 // If we really couldn't stop the process then we should just error out here, but if the
3193 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3194 StateType private_state = m_private_state.GetValue();
3195 if (private_state != eStateStopped && private_state != eStateExited)
3196 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003197 // If we exited when we were waiting for a process to stop, then
3198 // forward the event here so we don't lose the event
Jim Ingham43892562012-06-06 00:29:30 +00003199 return error;
3200 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003201 }
3202 }
3203 else
3204 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003205 if (log)
3206 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3207 return error;
Jim Inghamf4928de2012-05-23 15:46:31 +00003208 }
3209 }
Jim Ingham43892562012-06-06 00:29:30 +00003210
3211 if (m_public_state.GetValue() != eStateRunning)
3212 {
3213 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3214 // kill it, we don't want it hitting a breakpoint...
3215 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3216 // we're not going to have much luck doing this now.
3217 m_thread_list.DiscardThreadPlans();
3218 DisableAllBreakpointSites();
3219 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003220
Chris Lattner24943d22010-06-08 16:52:24 +00003221 error = DoDestroy();
3222 if (error.Success())
3223 {
3224 DidDestroy();
3225 StopPrivateStateThread();
3226 }
Caroline Tice861efb32010-11-16 05:07:41 +00003227 m_stdio_communication.StopReadThread();
3228 m_stdio_communication.Disconnect();
3229 if (m_process_input_reader && m_process_input_reader->IsActive())
3230 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3231 if (m_process_input_reader)
3232 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003233
3234 // If we exited when we were waiting for a process to stop, then
3235 // forward the event here so we don't lose the event
3236 if (exit_event_sp)
3237 {
3238 // Directly broadcast our exited event because we shut down our
3239 // private state thread above
3240 BroadcastEvent(exit_event_sp);
3241 }
3242
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003243 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3244 // the last events through the event system, in which case we might strand the write lock. Unlock
3245 // it here so when we do to tear down the process we don't get an error destroying the lock.
3246 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003247 }
3248 return error;
3249}
3250
3251Error
3252Process::Signal (int signal)
3253{
3254 Error error (WillSignal());
3255 if (error.Success())
3256 {
3257 error = DoSignal(signal);
3258 if (error.Success())
3259 DidSignal();
3260 }
3261 return error;
3262}
3263
Greg Clayton395fc332011-02-15 21:59:32 +00003264lldb::ByteOrder
3265Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003266{
Greg Clayton395fc332011-02-15 21:59:32 +00003267 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003268}
3269
3270uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003271Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003272{
Greg Clayton395fc332011-02-15 21:59:32 +00003273 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003274}
3275
Greg Clayton395fc332011-02-15 21:59:32 +00003276
Chris Lattner24943d22010-06-08 16:52:24 +00003277bool
3278Process::ShouldBroadcastEvent (Event *event_ptr)
3279{
3280 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3281 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00003282 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003283
3284 switch (state)
3285 {
Greg Claytone71e2582011-02-04 01:58:07 +00003286 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003287 case eStateAttaching:
3288 case eStateLaunching:
3289 case eStateDetached:
3290 case eStateExited:
3291 case eStateUnloaded:
3292 // These events indicate changes in the state of the debugging session, always report them.
3293 return_value = true;
3294 break;
3295 case eStateInvalid:
3296 // We stopped for no apparent reason, don't report it.
3297 return_value = false;
3298 break;
3299 case eStateRunning:
3300 case eStateStepping:
3301 // If we've started the target running, we handle the cases where we
3302 // are already running and where there is a transition from stopped to
3303 // running differently.
3304 // running -> running: Automatically suppress extra running events
3305 // stopped -> running: Report except when there is one or more no votes
3306 // and no yes votes.
3307 SynchronouslyNotifyStateChanged (state);
3308 switch (m_public_state.GetValue())
3309 {
3310 case eStateRunning:
3311 case eStateStepping:
3312 // We always suppress multiple runnings with no PUBLIC stop in between.
3313 return_value = false;
3314 break;
3315 default:
3316 // TODO: make this work correctly. For now always report
3317 // run if we aren't running so we don't miss any runnning
3318 // events. If I run the lldb/test/thread/a.out file and
3319 // break at main.cpp:58, run and hit the breakpoints on
3320 // multiple threads, then somehow during the stepping over
3321 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003322
3323 // This is a transition from stop to run.
3324 switch (m_thread_list.ShouldReportRun (event_ptr))
3325 {
Greg Clayton4a379b12012-07-17 03:23:13 +00003326 default:
Chris Lattner24943d22010-06-08 16:52:24 +00003327 case eVoteYes:
3328 case eVoteNoOpinion:
3329 return_value = true;
3330 break;
3331 case eVoteNo:
3332 return_value = false;
3333 break;
3334 }
3335 break;
3336 }
3337 break;
3338 case eStateStopped:
3339 case eStateCrashed:
3340 case eStateSuspended:
3341 {
3342 // We've stopped. First see if we're going to restart the target.
3343 // If we are going to stop, then we always broadcast the event.
3344 // 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 +00003345 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003346
3347 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003348 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003349 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003350 if (log)
3351 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003352 return true;
3353 }
3354 else
3355 {
Chris Lattner24943d22010-06-08 16:52:24 +00003356
3357 if (m_thread_list.ShouldStop (event_ptr) == false)
3358 {
Jim Ingham8290bba2012-09-05 21:13:56 +00003359 // ShouldStop may have restarted the target already. If so, don't
3360 // resume it twice.
3361 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00003362 switch (m_thread_list.ShouldReportStop (event_ptr))
3363 {
3364 case eVoteYes:
3365 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003366 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003367 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003368 case eVoteNo:
3369 return_value = false;
3370 break;
3371 }
3372
3373 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003374 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham8290bba2012-09-05 21:13:56 +00003375 if (!was_restarted)
3376 PrivateResume ();
Chris Lattner24943d22010-06-08 16:52:24 +00003377 }
3378 else
3379 {
3380 return_value = true;
3381 SynchronouslyNotifyStateChanged (state);
3382 }
3383 }
3384 }
3385 }
3386
3387 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003388 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003389 return return_value;
3390}
3391
Chris Lattner24943d22010-06-08 16:52:24 +00003392
3393bool
Jim Ingham1831e782012-04-07 00:00:41 +00003394Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003395{
Greg Claytone005f2c2010-11-06 01:53:30 +00003396 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003397
Greg Claytonb72d0f02011-04-12 05:54:46 +00003398 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003399 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003400 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3401
Jim Ingham1831e782012-04-07 00:00:41 +00003402 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003403 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003404
3405 // Create a thread that watches our internal state and controls which
3406 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003407 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003408 if (already_running)
3409 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3410 else
3411 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003412
3413 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003414 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003415 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3416 if (success)
3417 {
3418 ResumePrivateStateThread();
3419 return true;
3420 }
3421 else
3422 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003423}
3424
3425void
3426Process::PausePrivateStateThread ()
3427{
3428 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3429}
3430
3431void
3432Process::ResumePrivateStateThread ()
3433{
3434 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3435}
3436
3437void
3438Process::StopPrivateStateThread ()
3439{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003440 if (PrivateStateThreadIsValid ())
3441 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003442 else
3443 {
3444 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3445 if (log)
3446 printf ("Went to stop the private state thread, but it was already invalid.");
3447 }
Chris Lattner24943d22010-06-08 16:52:24 +00003448}
3449
3450void
3451Process::ControlPrivateStateThread (uint32_t signal)
3452{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003453 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003454
3455 assert (signal == eBroadcastInternalStateControlStop ||
3456 signal == eBroadcastInternalStateControlPause ||
3457 signal == eBroadcastInternalStateControlResume);
3458
3459 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003460 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003461
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003462 // Signal the private state thread. First we should copy this is case the
3463 // thread starts exiting since the private state thread will NULL this out
3464 // when it exits
3465 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003466 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003467 {
3468 TimeValue timeout_time;
3469 bool timed_out;
3470
3471 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3472
3473 timeout_time = TimeValue::Now();
3474 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003475 if (log)
3476 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003477 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3478 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3479
3480 if (signal == eBroadcastInternalStateControlStop)
3481 {
3482 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003483 {
3484 Error error;
3485 Host::ThreadCancel (private_state_thread, &error);
3486 if (log)
3487 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3488 }
3489 else
3490 {
3491 if (log)
3492 log->Printf ("The control event killed the private state thread without having to cancel.");
3493 }
Chris Lattner24943d22010-06-08 16:52:24 +00003494
3495 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003496 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003497 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003498 }
3499 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003500 else
3501 {
3502 if (log)
3503 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3504 }
Chris Lattner24943d22010-06-08 16:52:24 +00003505}
3506
3507void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003508Process::SendAsyncInterrupt ()
3509{
3510 if (PrivateStateThreadIsValid())
3511 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3512 else
3513 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3514}
3515
3516void
Chris Lattner24943d22010-06-08 16:52:24 +00003517Process::HandlePrivateEvent (EventSP &event_sp)
3518{
Greg Claytone005f2c2010-11-06 01:53:30 +00003519 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003520 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003521
Greg Clayton68ca8232011-01-25 02:58:48 +00003522 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003523
3524 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003525 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003526 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003527 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003528 switch (action_result)
3529 {
3530 case NextEventAction::eEventActionSuccess:
3531 SetNextEventAction(NULL);
3532 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003533
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003534 case NextEventAction::eEventActionRetry:
3535 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003536
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003537 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003538 // Handle Exiting Here. If we already got an exited event,
3539 // we should just propagate it. Otherwise, swallow this event,
3540 // and set our state to exit so the next event will kill us.
3541 if (new_state != eStateExited)
3542 {
3543 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003544 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003545 SetNextEventAction(NULL);
3546 return;
3547 }
3548 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003549 break;
3550 }
3551 }
3552
Chris Lattner24943d22010-06-08 16:52:24 +00003553 // See if we should broadcast this state to external clients?
3554 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003555
3556 if (should_broadcast)
3557 {
3558 if (log)
3559 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003560 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003561 __FUNCTION__,
3562 GetID(),
3563 StateAsCString(new_state),
3564 StateAsCString (GetState ()),
3565 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003566 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003567 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003568 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003569 PushProcessInputReader ();
3570 else
3571 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003572
Chris Lattner24943d22010-06-08 16:52:24 +00003573 BroadcastEvent (event_sp);
3574 }
3575 else
3576 {
3577 if (log)
3578 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003579 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003580 __FUNCTION__,
3581 GetID(),
3582 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003583 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003584 }
3585 }
Jim Ingham43892562012-06-06 00:29:30 +00003586 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003587}
3588
3589void *
3590Process::PrivateStateThread (void *arg)
3591{
3592 Process *proc = static_cast<Process*> (arg);
3593 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003594 return result;
3595}
3596
3597void *
3598Process::RunPrivateStateThread ()
3599{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003600 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003601 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003602
Greg Claytone005f2c2010-11-06 01:53:30 +00003603 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003604 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003605 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003606
3607 bool exit_now = false;
3608 while (!exit_now)
3609 {
3610 EventSP event_sp;
3611 WaitForEventsPrivate (NULL, event_sp, control_only);
3612 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3613 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003614 if (log)
3615 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3616
Chris Lattner24943d22010-06-08 16:52:24 +00003617 switch (event_sp->GetType())
3618 {
3619 case eBroadcastInternalStateControlStop:
3620 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003621 break; // doing any internal state managment below
3622
3623 case eBroadcastInternalStateControlPause:
3624 control_only = true;
3625 break;
3626
3627 case eBroadcastInternalStateControlResume:
3628 control_only = false;
3629 break;
3630 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003631
Chris Lattner24943d22010-06-08 16:52:24 +00003632 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003633 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003634 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003635 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3636 {
3637 if (m_public_state.GetValue() == eStateAttaching)
3638 {
3639 if (log)
3640 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3641 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3642 }
3643 else
3644 {
3645 if (log)
3646 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3647 Halt();
3648 }
3649 continue;
3650 }
Chris Lattner24943d22010-06-08 16:52:24 +00003651
3652 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3653
3654 if (internal_state != eStateInvalid)
3655 {
3656 HandlePrivateEvent (event_sp);
3657 }
3658
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003659 if (internal_state == eStateInvalid ||
3660 internal_state == eStateExited ||
3661 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003662 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003663 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003664 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003665
Chris Lattner24943d22010-06-08 16:52:24 +00003666 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003667 }
Chris Lattner24943d22010-06-08 16:52:24 +00003668 }
3669
Caroline Tice926060e2010-10-29 21:48:37 +00003670 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003671 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003672 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003673
Greg Claytona4881d02011-01-22 07:12:45 +00003674 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3675 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003676 return NULL;
3677}
3678
Chris Lattner24943d22010-06-08 16:52:24 +00003679//------------------------------------------------------------------
3680// Process Event Data
3681//------------------------------------------------------------------
3682
3683Process::ProcessEventData::ProcessEventData () :
3684 EventData (),
3685 m_process_sp (),
3686 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003687 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003688 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003689 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003690{
3691}
3692
3693Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3694 EventData (),
3695 m_process_sp (process_sp),
3696 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003697 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003698 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003699 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003700{
3701}
3702
3703Process::ProcessEventData::~ProcessEventData()
3704{
3705}
3706
3707const ConstString &
3708Process::ProcessEventData::GetFlavorString ()
3709{
3710 static ConstString g_flavor ("Process::ProcessEventData");
3711 return g_flavor;
3712}
3713
3714const ConstString &
3715Process::ProcessEventData::GetFlavor () const
3716{
3717 return ProcessEventData::GetFlavorString ();
3718}
3719
Chris Lattner24943d22010-06-08 16:52:24 +00003720void
3721Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3722{
3723 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003724 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3725 // the public event queue, then other times when we're pretending that this is where we stopped at the
3726 // end of expression evaluation. m_update_state is used to distinguish these
3727 // three cases; it is 0 when we're just pulling it off for private handling,
3728 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003729
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003730 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003731 return;
3732
3733 m_process_sp->SetPublicState (m_state);
3734
3735 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3736 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003737 {
3738 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003739 uint32_t num_threads = curr_thread_list.GetSize();
3740 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003741
Jim Ingham21f37ad2011-08-09 02:12:22 +00003742 // The actions might change one of the thread's stop_info's opinions about whether we should
3743 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003744
3745 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3746 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3747 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3748 // 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
3749 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003750 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003751 for (idx = 0; idx < num_threads; ++idx)
3752 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3753
Jim Ingham21f37ad2011-08-09 02:12:22 +00003754 bool still_should_stop = true;
3755
Chris Lattner24943d22010-06-08 16:52:24 +00003756 for (idx = 0; idx < num_threads; ++idx)
3757 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003758 curr_thread_list = m_process_sp->GetThreadList();
3759 if (curr_thread_list.GetSize() != num_threads)
3760 {
3761 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003762 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003763 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 +00003764 break;
3765 }
3766
3767 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3768
3769 if (thread_sp->GetIndexID() != thread_index_array[idx])
3770 {
3771 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003772 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003773 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003774 idx,
3775 thread_index_array[idx],
3776 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003777 break;
3778 }
3779
Jim Ingham6297a3a2010-10-20 00:39:53 +00003780 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00003781 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00003782 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003783 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003784 // The stop action might restart the target. If it does, then we want to mark that in the
3785 // event so that whoever is receiving it will know to wait for the running event and reflect
3786 // that state appropriately.
3787 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003788
3789 // FIXME: we might have run.
3790 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003791 {
3792 SetRestarted (true);
3793 break;
3794 }
3795 else if (!stop_info_sp->ShouldStop(event_ptr))
3796 {
3797 still_should_stop = false;
3798 }
Chris Lattner24943d22010-06-08 16:52:24 +00003799 }
3800 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003801
Jim Ingham21f37ad2011-08-09 02:12:22 +00003802
3803 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003804 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003805 if (!still_should_stop)
3806 {
3807 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003808 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00003809 // Use the public resume method here, since this is just
3810 // extending a public resume.
Jim Ingham21f37ad2011-08-09 02:12:22 +00003811 m_process_sp->Resume();
3812 }
3813 else
3814 {
3815 // If we didn't restart, run the Stop Hooks here:
3816 // They might also restart the target, so watch for that.
3817 m_process_sp->GetTarget().RunStopHooks();
3818 if (m_process_sp->GetPrivateState() == eStateRunning)
3819 SetRestarted(true);
3820 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003821 }
3822
Chris Lattner24943d22010-06-08 16:52:24 +00003823 }
3824}
3825
3826void
3827Process::ProcessEventData::Dump (Stream *s) const
3828{
3829 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003830 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003831
Greg Claytonb72d0f02011-04-12 05:54:46 +00003832 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003833}
3834
3835const Process::ProcessEventData *
3836Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3837{
3838 if (event_ptr)
3839 {
3840 const EventData *event_data = event_ptr->GetData();
3841 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3842 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3843 }
3844 return NULL;
3845}
3846
3847ProcessSP
3848Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3849{
3850 ProcessSP process_sp;
3851 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3852 if (data)
3853 process_sp = data->GetProcessSP();
3854 return process_sp;
3855}
3856
3857StateType
3858Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3859{
3860 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3861 if (data == NULL)
3862 return eStateInvalid;
3863 else
3864 return data->GetState();
3865}
3866
3867bool
3868Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3869{
3870 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3871 if (data == NULL)
3872 return false;
3873 else
3874 return data->GetRestarted();
3875}
3876
3877void
3878Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3879{
3880 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3881 if (data != NULL)
3882 data->SetRestarted(new_value);
3883}
3884
3885bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003886Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3887{
3888 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3889 if (data == NULL)
3890 return false;
3891 else
3892 return data->GetInterrupted ();
3893}
3894
3895void
3896Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3897{
3898 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3899 if (data != NULL)
3900 data->SetInterrupted(new_value);
3901}
3902
3903bool
Chris Lattner24943d22010-06-08 16:52:24 +00003904Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3905{
3906 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3907 if (data)
3908 {
3909 data->SetUpdateStateOnRemoval();
3910 return true;
3911 }
3912 return false;
3913}
3914
Greg Clayton289afcb2012-02-18 05:35:26 +00003915lldb::TargetSP
3916Process::CalculateTarget ()
3917{
3918 return m_target.shared_from_this();
3919}
3920
Chris Lattner24943d22010-06-08 16:52:24 +00003921void
Greg Claytona830adb2010-10-04 01:05:56 +00003922Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003923{
Greg Clayton567e7f32011-09-22 04:58:26 +00003924 exe_ctx.SetTargetPtr (&m_target);
3925 exe_ctx.SetProcessPtr (this);
3926 exe_ctx.SetThreadPtr(NULL);
3927 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003928}
3929
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003930//uint32_t
3931//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3932//{
3933// return 0;
3934//}
3935//
3936//ArchSpec
3937//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3938//{
3939// return Host::GetArchSpecForExistingProcess (pid);
3940//}
3941//
3942//ArchSpec
3943//Process::GetArchSpecForExistingProcess (const char *process_name)
3944//{
3945// return Host::GetArchSpecForExistingProcess (process_name);
3946//}
3947//
Caroline Tice861efb32010-11-16 05:07:41 +00003948void
3949Process::AppendSTDOUT (const char * s, size_t len)
3950{
Greg Clayton20d338f2010-11-18 05:57:03 +00003951 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003952 m_stdout_data.append (s, len);
Greg Claytonb3781332010-12-05 19:16:56 +00003953 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003954}
3955
3956void
Greg Claytonbd06ff42011-11-13 04:45:22 +00003957Process::AppendSTDERR (const char * s, size_t len)
3958{
3959 Mutex::Locker locker (m_stdio_communication_mutex);
3960 m_stderr_data.append (s, len);
3961 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3962}
3963
3964//------------------------------------------------------------------
3965// Process STDIO
3966//------------------------------------------------------------------
3967
3968size_t
3969Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3970{
3971 Mutex::Locker locker(m_stdio_communication_mutex);
3972 size_t bytes_available = m_stdout_data.size();
3973 if (bytes_available > 0)
3974 {
3975 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3976 if (log)
Greg Clayton851e30e2012-09-18 18:04:04 +00003977 log->Printf ("Process::GetSTDOUT (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00003978 if (bytes_available > buf_size)
3979 {
3980 memcpy(buf, m_stdout_data.c_str(), buf_size);
3981 m_stdout_data.erase(0, buf_size);
3982 bytes_available = buf_size;
3983 }
3984 else
3985 {
3986 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3987 m_stdout_data.clear();
3988 }
3989 }
3990 return bytes_available;
3991}
3992
3993
3994size_t
3995Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3996{
3997 Mutex::Locker locker(m_stdio_communication_mutex);
3998 size_t bytes_available = m_stderr_data.size();
3999 if (bytes_available > 0)
4000 {
4001 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4002 if (log)
Greg Clayton851e30e2012-09-18 18:04:04 +00004003 log->Printf ("Process::GetSTDERR (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004004 if (bytes_available > buf_size)
4005 {
4006 memcpy(buf, m_stderr_data.c_str(), buf_size);
4007 m_stderr_data.erase(0, buf_size);
4008 bytes_available = buf_size;
4009 }
4010 else
4011 {
4012 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4013 m_stderr_data.clear();
4014 }
4015 }
4016 return bytes_available;
4017}
4018
4019void
Caroline Tice861efb32010-11-16 05:07:41 +00004020Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4021{
4022 Process *process = (Process *) baton;
4023 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4024}
4025
4026size_t
4027Process::ProcessInputReaderCallback (void *baton,
4028 InputReader &reader,
4029 lldb::InputReaderAction notification,
4030 const char *bytes,
4031 size_t bytes_len)
4032{
4033 Process *process = (Process *) baton;
4034
4035 switch (notification)
4036 {
4037 case eInputReaderActivate:
4038 break;
4039
4040 case eInputReaderDeactivate:
4041 break;
4042
4043 case eInputReaderReactivate:
4044 break;
4045
Caroline Tice4a348082011-05-02 20:41:46 +00004046 case eInputReaderAsynchronousOutputWritten:
4047 break;
4048
Caroline Tice861efb32010-11-16 05:07:41 +00004049 case eInputReaderGotToken:
4050 {
4051 Error error;
4052 process->PutSTDIN (bytes, bytes_len, error);
4053 }
4054 break;
4055
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004056 case eInputReaderInterrupt:
4057 process->Halt ();
4058 break;
4059
4060 case eInputReaderEndOfFile:
4061 process->AppendSTDOUT ("^D", 2);
4062 break;
4063
Caroline Tice861efb32010-11-16 05:07:41 +00004064 case eInputReaderDone:
4065 break;
4066
4067 }
4068
4069 return bytes_len;
4070}
4071
4072void
4073Process::ResetProcessInputReader ()
4074{
4075 m_process_input_reader.reset();
4076}
4077
4078void
Greg Clayton464c6162011-11-17 22:14:31 +00004079Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004080{
4081 // First set up the Read Thread for reading/handling process I/O
4082
4083 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4084
4085 if (conn_ap.get())
4086 {
4087 m_stdio_communication.SetConnection (conn_ap.release());
4088 if (m_stdio_communication.IsConnected())
4089 {
4090 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4091 m_stdio_communication.StartReadThread();
4092
4093 // Now read thread is set up, set up input reader.
4094
4095 if (!m_process_input_reader.get())
4096 {
4097 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4098 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4099 this,
4100 eInputReaderGranularityByte,
4101 NULL,
4102 NULL,
4103 false));
4104
4105 if (err.Fail())
4106 m_process_input_reader.reset();
4107 }
4108 }
4109 }
4110}
4111
4112void
4113Process::PushProcessInputReader ()
4114{
4115 if (m_process_input_reader && !m_process_input_reader->IsActive())
4116 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4117}
4118
4119void
4120Process::PopProcessInputReader ()
4121{
4122 if (m_process_input_reader && m_process_input_reader->IsActive())
4123 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4124}
4125
Greg Claytond284b662011-02-18 01:44:25 +00004126// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004127void
Caroline Tice2a456812011-03-10 22:14:10 +00004128Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004129{
Greg Clayton73844aa2012-08-22 17:17:09 +00004130// static std::vector<OptionEnumValueElement> g_plugins;
4131//
4132// int i=0;
4133// const char *name;
4134// OptionEnumValueElement option_enum;
4135// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4136// {
4137// if (name)
4138// {
4139// option_enum.value = i;
4140// option_enum.string_value = name;
4141// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4142// g_plugins.push_back (option_enum);
4143// }
4144// ++i;
4145// }
4146// option_enum.value = 0;
4147// option_enum.string_value = NULL;
4148// option_enum.usage = NULL;
4149// g_plugins.push_back (option_enum);
4150//
4151// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4152// {
4153// if (::strcmp (name, "plugin") == 0)
4154// {
4155// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4156// break;
4157// }
4158// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004159//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004160 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004161}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004162
Greg Clayton990de7b2010-11-18 23:32:35 +00004163void
Caroline Tice2a456812011-03-10 22:14:10 +00004164Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004165{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004166 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004167}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004168
Greg Clayton427f2902010-12-14 02:59:59 +00004169ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004170Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004171 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004172 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004173 bool run_others,
Jim Ingham360f53f2010-11-30 02:22:11 +00004174 bool discard_on_error,
Jim Ingham47beabb2012-10-16 21:41:58 +00004175 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004176 Stream &errors)
4177{
4178 ExecutionResults return_value = eExecutionSetupError;
4179
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004180 if (thread_plan_sp.get() == NULL)
4181 {
4182 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004183 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004184 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004185
4186 if (exe_ctx.GetProcessPtr() != this)
4187 {
4188 errors.Printf("RunThreadPlan called on wrong process.");
4189 return eExecutionSetupError;
4190 }
4191
4192 Thread *thread = exe_ctx.GetThreadPtr();
4193 if (thread == NULL)
4194 {
4195 errors.Printf("RunThreadPlan called with invalid thread.");
4196 return eExecutionSetupError;
4197 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004198
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004199 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4200 // For that to be true the plan can't be private - since private plans suppress themselves in the
4201 // GetCompletedPlan call.
4202
4203 bool orig_plan_private = thread_plan_sp->GetPrivate();
4204 thread_plan_sp->SetPrivate(false);
4205
Jim Inghamac959662011-01-24 06:34:17 +00004206 if (m_private_state.GetValue() != eStateStopped)
4207 {
4208 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004209 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004210 }
4211
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004212 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004213 const uint32_t thread_idx_id = thread->GetIndexID();
4214 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004215
4216 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4217 // so we should arrange to reset them as well.
4218
Greg Clayton567e7f32011-09-22 04:58:26 +00004219 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004220
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004221 uint32_t selected_tid;
4222 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004223 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004224 {
4225 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004226 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004227 }
4228 else
4229 {
4230 selected_tid = LLDB_INVALID_THREAD_ID;
4231 }
4232
Jim Ingham1831e782012-04-07 00:00:41 +00004233 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004234 lldb::StateType old_state;
4235 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004236
Jim Inghamd21d98b2012-04-10 01:21:57 +00004237 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004238 if (Host::GetCurrentThread() == m_private_state_thread)
4239 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004240 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4241 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004242 // 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 +00004243 // we are fielding public events here.
4244 if (log)
4245 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4246
4247
Jim Ingham1831e782012-04-07 00:00:41 +00004248 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004249
4250 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4251 // returning control here.
4252 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4253 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4254 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4255 // do just what we want.
4256 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4257 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4258 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4259 old_state = m_public_state.GetValue();
4260 m_public_state.SetValueNoLock(eStateStopped);
4261
4262 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004263 StartPrivateStateThread(true);
4264 }
4265
4266 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004267
Jim Ingham6ae318c2011-01-23 21:14:08 +00004268 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004269
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004270 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004271
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004272 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004273 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4274 // restored on exit to the function.
4275 //
4276 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4277 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004278
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004279 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004280
Jim Ingham360f53f2010-11-30 02:22:11 +00004281 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004282 {
4283 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004284 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4285 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4286 thread->GetIndexID(),
4287 thread->GetID(),
4288 s.GetData());
4289 }
4290
4291 bool got_event;
4292 lldb::EventSP event_sp;
4293 lldb::StateType stop_state = lldb::eStateInvalid;
4294
4295 TimeValue* timeout_ptr = NULL;
4296 TimeValue real_timeout;
4297
4298 bool first_timeout = true;
4299 bool do_resume = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004300 const uint64_t default_one_thread_timeout_usec = 250000;
4301 uint64_t computed_timeout = 0;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004302
4303 while (1)
4304 {
4305 // We usually want to resume the process if we get to the top of the loop.
4306 // The only exception is if we get two running events with no intervening
4307 // stop, which can happen, we will just wait for then next stop event.
4308
4309 if (do_resume)
4310 {
4311 // Do the initial resume and wait for the running event before going further.
4312
4313 Error resume_error = PrivateResume ();
4314 if (!resume_error.Success())
4315 {
4316 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4317 return_value = eExecutionSetupError;
4318 break;
4319 }
4320
4321 real_timeout = TimeValue::Now();
4322 real_timeout.OffsetWithMicroSeconds(500000);
4323 timeout_ptr = &real_timeout;
4324
4325 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4326 if (!got_event)
4327 {
4328 if (log)
4329 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4330
4331 errors.Printf("Didn't get any event after initial resume, exiting.");
4332 return_value = eExecutionSetupError;
4333 break;
4334 }
4335
4336 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4337 if (stop_state != eStateRunning)
4338 {
4339 if (log)
Jim Ingham47beabb2012-10-16 21:41:58 +00004340 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4341 "initial resume, got %s instead.",
4342 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004343
Jim Ingham47beabb2012-10-16 21:41:58 +00004344 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4345 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004346 return_value = eExecutionSetupError;
4347 break;
4348 }
4349
4350 if (log)
4351 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4352 // We need to call the function synchronously, so spin waiting for it to return.
4353 // If we get interrupted while executing, we're going to lose our context, and
4354 // won't be able to gather the result at this point.
4355 // We set the timeout AFTER the resume, since the resume takes some time and we
4356 // don't want to charge that to the timeout.
4357
Jim Ingham47beabb2012-10-16 21:41:58 +00004358 if (first_timeout)
4359 {
4360 if (run_others)
4361 {
4362 // If we are running all threads then we take half the time to run all threads, bounded by
4363 // .25 sec.
4364 if (timeout_usec == 0)
4365 computed_timeout = default_one_thread_timeout_usec;
4366 else
4367 {
4368 computed_timeout = timeout_usec / 2;
4369 if (computed_timeout > default_one_thread_timeout_usec)
4370 {
4371 computed_timeout = default_one_thread_timeout_usec;
4372 }
4373 timeout_usec -= computed_timeout;
4374 }
4375 }
4376 else
4377 {
4378 computed_timeout = timeout_usec;
4379 }
4380 }
4381 else
4382 {
4383 computed_timeout = timeout_usec;
4384 }
4385
4386 if (computed_timeout != 0)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004387 {
Enrico Granata6cca9692012-07-16 23:10:35 +00004388 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004389 real_timeout = TimeValue::Now();
Jim Ingham47beabb2012-10-16 21:41:58 +00004390 real_timeout.OffsetWithMicroSeconds(computed_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004391
4392 timeout_ptr = &real_timeout;
4393 }
Enrico Granata6cca9692012-07-16 23:10:35 +00004394 else
4395 {
Jim Ingham47beabb2012-10-16 21:41:58 +00004396 timeout_ptr = NULL;
Enrico Granata6cca9692012-07-16 23:10:35 +00004397 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004398 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004399 else
4400 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004401 if (log)
4402 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4403 do_resume = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004404 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004405
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004406 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004407 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004408
Jim Inghamf9f40c22011-02-08 05:20:59 +00004409 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004410 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004411 if (timeout_ptr)
4412 {
4413 StreamString s;
4414 s.Printf ("about to wait - timeout is:\n ");
4415 timeout_ptr->Dump (&s, 120);
4416 s.Printf ("\nNow is:\n ");
4417 TimeValue::Now().Dump (&s, 120);
4418 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4419 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004420 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004421 {
4422 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4423 }
4424 }
4425
4426 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4427
4428 if (got_event)
4429 {
4430 if (event_sp.get())
4431 {
4432 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004433 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004434 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004435 Halt();
4436 keep_going = false;
4437 return_value = eExecutionInterrupted;
4438 errors.Printf ("Execution halted by user interrupt.");
4439 if (log)
4440 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4441 }
4442 else
4443 {
4444 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4445 if (log)
4446 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4447
4448 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004449 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004450 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004451 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004452 // Yay, we're done. Now make sure that our thread plan actually completed.
4453 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4454 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004455 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004456 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004457 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004458 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4459 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004460 }
4461 else
4462 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004463 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4464 StopReason stop_reason = eStopReasonInvalid;
4465 if (stop_info_sp)
4466 stop_reason = stop_info_sp->GetStopReason();
4467 if (stop_reason == eStopReasonPlanComplete)
4468 {
4469 if (log)
4470 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4471 // Now mark this plan as private so it doesn't get reported as the stop reason
4472 // after this point.
4473 if (thread_plan_sp)
4474 thread_plan_sp->SetPrivate (orig_plan_private);
4475 return_value = eExecutionCompleted;
4476 }
4477 else
4478 {
4479 if (log)
4480 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004481
Jim Ingham5d90ade2012-07-27 23:57:19 +00004482 return_value = eExecutionInterrupted;
4483 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004484 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004485 }
4486 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004487
Jim Ingham5d90ade2012-07-27 23:57:19 +00004488 case lldb::eStateCrashed:
4489 if (log)
4490 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4491 return_value = eExecutionInterrupted;
4492 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004493
Jim Ingham5d90ade2012-07-27 23:57:19 +00004494 case lldb::eStateRunning:
4495 do_resume = false;
4496 keep_going = true;
4497 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004498
Jim Ingham5d90ade2012-07-27 23:57:19 +00004499 default:
4500 if (log)
4501 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4502
4503 if (stop_state == eStateExited)
4504 event_to_broadcast_sp = event_sp;
4505
Sean Callanan96abc622012-08-08 17:35:10 +00004506 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00004507 return_value = eExecutionInterrupted;
4508 break;
4509 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004510 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004511
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004512 if (keep_going)
4513 continue;
4514 else
4515 break;
4516 }
4517 else
4518 {
4519 if (log)
4520 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4521 return_value = eExecutionInterrupted;
4522 break;
4523 }
4524 }
4525 else
4526 {
4527 // If we didn't get an event that means we've timed out...
4528 // We will interrupt the process here. Depending on what we were asked to do we will
4529 // either exit, or try with all threads running for the same timeout.
4530 // Not really sure what to do if Halt fails here...
4531
4532 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00004533 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004534 {
4535 if (first_timeout)
Jim Ingham47beabb2012-10-16 21:41:58 +00004536 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %lld timed out, "
4537 "trying for %d usec with all threads enabled.",
4538 computed_timeout, timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004539 else
4540 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00004541 "and timeout: %d timed out, abandoning execution.",
4542 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004543 }
4544 else
4545 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004546 "abandoning execution.",
4547 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004548 }
4549
4550 Error halt_error = Halt();
4551 if (halt_error.Success())
4552 {
4553 if (log)
4554 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4555
4556 // If halt succeeds, it always produces a stopped event. Wait for that:
4557
4558 real_timeout = TimeValue::Now();
4559 real_timeout.OffsetWithMicroSeconds(500000);
4560
4561 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4562
4563 if (got_event)
4564 {
4565 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4566 if (log)
4567 {
4568 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4569 if (stop_state == lldb::eStateStopped
4570 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4571 log->PutCString (" Event was the Halt interruption event.");
4572 }
4573
4574 if (stop_state == lldb::eStateStopped)
4575 {
4576 // Between the time we initiated the Halt and the time we delivered it, the process could have
4577 // already finished its job. Check that here:
4578
4579 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4580 {
4581 if (log)
4582 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4583 "Exiting wait loop.");
4584 return_value = eExecutionCompleted;
4585 break;
4586 }
4587
Jim Ingham47beabb2012-10-16 21:41:58 +00004588 if (!run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004589 {
4590 if (log)
4591 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4592 return_value = eExecutionInterrupted;
4593 break;
4594 }
4595
4596 if (first_timeout)
4597 {
4598 // Set all the other threads to run, and return to the top of the loop, which will continue;
4599 first_timeout = false;
4600 thread_plan_sp->SetStopOthers (false);
4601 if (log)
4602 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4603
4604 continue;
4605 }
4606 else
4607 {
4608 // Running all threads failed, so return Interrupted.
4609 if (log)
4610 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4611 return_value = eExecutionInterrupted;
4612 break;
4613 }
4614 }
4615 }
4616 else
4617 { if (log)
4618 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4619 "I'm getting out of here passing Interrupted.");
4620 return_value = eExecutionInterrupted;
4621 break;
4622 }
4623 }
4624 else
4625 {
4626 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4627 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4628 if (log)
4629 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.",
4630 halt_error.AsCString());
4631 real_timeout = TimeValue::Now();
4632 real_timeout.OffsetWithMicroSeconds(500000);
4633 timeout_ptr = &real_timeout;
4634 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4635 if (!got_event || event_sp.get() == NULL)
4636 {
4637 // This is not going anywhere, bag out.
4638 if (log)
4639 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4640 return_value = eExecutionInterrupted;
4641 break;
4642 }
4643 else
4644 {
4645 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4646 if (log)
4647 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4648 if (stop_state == lldb::eStateStopped)
4649 {
4650 // Between the time we initiated the Halt and the time we delivered it, the process could have
4651 // already finished its job. Check that here:
4652
4653 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4654 {
4655 if (log)
4656 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4657 "Exiting wait loop.");
4658 return_value = eExecutionCompleted;
4659 break;
4660 }
4661
4662 if (first_timeout)
4663 {
4664 // Set all the other threads to run, and return to the top of the loop, which will continue;
4665 first_timeout = false;
4666 thread_plan_sp->SetStopOthers (false);
4667 if (log)
4668 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4669
4670 continue;
4671 }
4672 else
4673 {
4674 // Running all threads failed, so return Interrupted.
4675 if (log)
4676 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4677 return_value = eExecutionInterrupted;
4678 break;
4679 }
4680 }
4681 else
4682 {
4683 if (log)
4684 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4685 " a stopped event, instead got %s.", StateAsCString(stop_state));
4686 return_value = eExecutionInterrupted;
4687 break;
4688 }
4689 }
4690 }
4691
4692 }
4693
4694 } // END WAIT LOOP
4695
4696 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4697 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4698 {
4699 StopPrivateStateThread();
4700 Error error;
4701 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00004702 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004703 {
4704 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4705 }
4706 m_public_state.SetValueNoLock(old_state);
4707
4708 }
4709
4710
4711 // Now do some processing on the results of the run:
4712 if (return_value == eExecutionInterrupted)
4713 {
4714 if (log)
4715 {
4716 StreamString s;
4717 if (event_sp)
4718 event_sp->Dump (&s);
4719 else
4720 {
4721 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4722 }
4723
4724 StreamString ts;
4725
4726 const char *event_explanation = NULL;
4727
4728 do
4729 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004730 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004731 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004732 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004733 break;
4734 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004735 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004736 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004737 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004738 break;
4739 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004740 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004741 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004742 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4743
4744 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004745 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004746 event_explanation = "<no event data>";
4747 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004748 }
4749
Jim Ingham5d90ade2012-07-27 23:57:19 +00004750 Process *process = event_data->GetProcessSP().get();
4751
4752 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004753 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004754 event_explanation = "<no process>";
4755 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004756 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004757
4758 ThreadList &thread_list = process->GetThreadList();
4759
4760 uint32_t num_threads = thread_list.GetSize();
4761 uint32_t thread_index;
4762
4763 ts.Printf("<%u threads> ", num_threads);
4764
4765 for (thread_index = 0;
4766 thread_index < num_threads;
4767 ++thread_index)
4768 {
4769 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4770
4771 if (!thread)
4772 {
4773 ts.Printf("<?> ");
4774 continue;
4775 }
4776
4777 ts.Printf("<0x%4.4llx ", thread->GetID());
4778 RegisterContext *register_context = thread->GetRegisterContext().get();
4779
4780 if (register_context)
4781 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4782 else
4783 ts.Printf("[ip unknown] ");
4784
4785 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4786 if (stop_info_sp)
4787 {
4788 const char *stop_desc = stop_info_sp->GetDescription();
4789 if (stop_desc)
4790 ts.PutCString (stop_desc);
4791 }
4792 ts.Printf(">");
4793 }
4794
4795 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004796 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004797 } while (0);
4798
Jim Ingham5d90ade2012-07-27 23:57:19 +00004799 if (event_explanation)
4800 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004801 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00004802 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4803 }
4804
4805 if (discard_on_error && thread_plan_sp)
4806 {
4807 if (log)
4808 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4809 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4810 thread_plan_sp->SetPrivate (orig_plan_private);
4811 }
4812 else
4813 {
4814 if (log)
4815 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004816 }
4817 }
4818 else if (return_value == eExecutionSetupError)
4819 {
4820 if (log)
4821 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004822
4823 if (discard_on_error && thread_plan_sp)
4824 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004825 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004826 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004827 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004828 }
4829 else
4830 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004831 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004832 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004833 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004834 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4835 return_value = eExecutionCompleted;
4836 }
4837 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4838 {
4839 if (log)
4840 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4841 return_value = eExecutionDiscarded;
4842 }
4843 else
4844 {
4845 if (log)
4846 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4847 if (discard_on_error && thread_plan_sp)
4848 {
4849 if (log)
4850 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4851 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4852 thread_plan_sp->SetPrivate (orig_plan_private);
4853 }
4854 }
4855 }
4856
4857 // Thread we ran the function in may have gone away because we ran the target
4858 // Check that it's still there, and if it is put it back in the context. Also restore the
4859 // frame in the context if it is still present.
4860 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4861 if (thread)
4862 {
4863 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4864 }
4865
4866 // Also restore the current process'es selected frame & thread, since this function calling may
4867 // be done behind the user's back.
4868
4869 if (selected_tid != LLDB_INVALID_THREAD_ID)
4870 {
4871 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4872 {
4873 // We were able to restore the selected thread, now restore the frame:
4874 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4875 if (old_frame_sp)
4876 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00004877 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004878 }
4879 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004880
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004881 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00004882
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004883 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004884 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004885 if (log)
4886 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4887 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00004888 }
4889
4890 return return_value;
4891}
4892
4893const char *
4894Process::ExecutionResultAsCString (ExecutionResults result)
4895{
4896 const char *result_name;
4897
4898 switch (result)
4899 {
Greg Claytonb3448432011-03-24 21:19:54 +00004900 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004901 result_name = "eExecutionCompleted";
4902 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004903 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00004904 result_name = "eExecutionDiscarded";
4905 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004906 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004907 result_name = "eExecutionInterrupted";
4908 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004909 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00004910 result_name = "eExecutionSetupError";
4911 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004912 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00004913 result_name = "eExecutionTimedOut";
4914 break;
4915 }
4916 return result_name;
4917}
4918
Greg Claytonabe0fed2011-04-18 08:33:37 +00004919void
4920Process::GetStatus (Stream &strm)
4921{
4922 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00004923 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00004924 {
4925 if (state == eStateExited)
4926 {
4927 int exit_status = GetExitStatus();
4928 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00004929 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00004930 GetID(),
4931 exit_status,
4932 exit_status,
4933 exit_description ? exit_description : "");
4934 }
4935 else
4936 {
4937 if (state == eStateConnected)
4938 strm.Printf ("Connected to remote target.\n");
4939 else
Greg Clayton444e35b2011-10-19 18:09:39 +00004940 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00004941 }
4942 }
4943 else
4944 {
Greg Clayton444e35b2011-10-19 18:09:39 +00004945 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004946 }
4947}
4948
4949size_t
4950Process::GetThreadStatus (Stream &strm,
4951 bool only_threads_with_stop_reason,
4952 uint32_t start_frame,
4953 uint32_t num_frames,
4954 uint32_t num_frames_with_source)
4955{
4956 size_t num_thread_infos_dumped = 0;
4957
Jim Inghamb9950592012-09-10 20:50:15 +00004958 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004959 const size_t num_threads = GetThreadList().GetSize();
4960 for (uint32_t i = 0; i < num_threads; i++)
4961 {
4962 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4963 if (thread)
4964 {
4965 if (only_threads_with_stop_reason)
4966 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00004967 StopInfoSP stop_info_sp = thread->GetStopInfo();
4968 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00004969 continue;
4970 }
4971 thread->GetStatus (strm,
4972 start_frame,
4973 num_frames,
4974 num_frames_with_source);
4975 ++num_thread_infos_dumped;
4976 }
4977 }
4978 return num_thread_infos_dumped;
4979}
4980
Greg Clayton76113302012-02-22 04:37:26 +00004981void
4982Process::AddInvalidMemoryRegion (const LoadRange &region)
4983{
4984 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4985}
4986
4987bool
4988Process::RemoveInvalidMemoryRange (const LoadRange &region)
4989{
4990 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4991}
4992
Jim Ingham1831e782012-04-07 00:00:41 +00004993void
4994Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4995{
4996 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4997}
4998
4999bool
5000Process::RunPreResumeActions ()
5001{
5002 bool result = true;
5003 while (!m_pre_resume_actions.empty())
5004 {
5005 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5006 m_pre_resume_actions.pop_back();
5007 bool this_result = action.callback (action.baton);
5008 if (result == true) result = this_result;
5009 }
5010 return result;
5011}
5012
5013void
5014Process::ClearPreResumeActions ()
5015{
5016 m_pre_resume_actions.clear();
5017}
Greg Clayton76113302012-02-22 04:37:26 +00005018
Greg Claytoncf5927e2012-05-18 02:38:05 +00005019void
5020Process::Flush ()
5021{
5022 m_thread_list.Flush();
5023}