blob: 02f78d4df567571d552068a220e1c8a656def7f8 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
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 Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000021#include "lldb/Core/Module.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
23#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000024#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000025#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Host/Host.h"
27#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000028#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000029#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000030#include "lldb/Target/LanguageRuntime.h"
31#include "lldb/Target/CPPLanguageRuntime.h"
32#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000033#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000035#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-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 Ingham076b3042012-04-10 01:21:57 +000040#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041
42using namespace lldb;
43using namespace lldb_private;
44
Greg Clayton67cc0632012-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 Claytonc9d645d2012-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 Clayton67cc0632012-08-22 17:17:09 +000098 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
99};
100
101enum {
102 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000103 ePropertyExtraStartCommand,
104 ePropertyPythonOSPluginPath
Greg Clayton67cc0632012-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 Claytonc9d645d2012-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 Clayton32e0a752011-03-30 18:16:51 +0000164void
Greg Clayton8b82f082011-04-12 05:54:46 +0000165ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000166{
167 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000168 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +0000169 s.Printf (" pid = %llu\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000170
171 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +0000172 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000181 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000182 if (argc > 0)
183 {
184 for (uint32_t i=0; i<argc; i++)
185 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000186 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000187 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000188 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000189 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000190 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000191 }
192 }
Greg Clayton8b82f082011-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 Clayton95bf0fd2011-04-01 00:29:43 +0000207 if (m_arch.IsValid())
208 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
209
Greg Clayton8b82f082011-04-12 05:54:46 +0000210 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000211 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000212 cstr = platform->GetUserName (m_uid);
213 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000214 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000215 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000216 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000217 cstr = platform->GetGroupName (m_gid);
218 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000219 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000220 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000221 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000222 cstr = platform->GetUserName (m_euid);
223 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000224 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000225 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000226 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000227 cstr = platform->GetGroupName (m_egid);
228 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000229 }
230}
231
232void
Greg Clayton8b82f082011-04-12 05:54:46 +0000233ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000234{
Greg Clayton8b82f082011-04-12 05:54:46 +0000235 const char *label;
236 if (show_args || verbose)
237 label = "ARGUMENTS";
238 else
239 label = "NAME";
240
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000241 if (verbose)
242 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000243 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000244 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
245 }
246 else
247 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000248 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000249 s.PutCString ("====== ====== ========== ======= ============================\n");
250 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000251}
252
253void
Greg Clayton8b82f082011-04-12 05:54:46 +0000254ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000255{
256 if (m_pid != LLDB_INVALID_PROCESS_ID)
257 {
258 const char *cstr;
Greg Clayton61e7a582011-12-01 23:28:38 +0000259 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000260
Greg Clayton32e0a752011-03-30 18:16:51 +0000261
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000262 if (verbose)
263 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000264 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000268 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000269
Greg Clayton8b82f082011-04-12 05:54:46 +0000270 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000274 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000275
Greg Clayton8b82f082011-04-12 05:54:46 +0000276 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000280 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000281
Greg Clayton8b82f082011-04-12 05:54:46 +0000282 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000286 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000287 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
288 }
289 else
290 {
Jason Molendafd54b362011-09-20 21:44:10 +0000291 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000292 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000293 (int)m_arch.GetTriple().getArchName().size(),
294 m_arch.GetTriple().getArchName().data());
295 }
296
Greg Clayton8b82f082011-04-12 05:54:46 +0000297 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000298 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000299 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000306 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000307 }
308 }
309 }
310 else
311 {
312 s.PutCString (GetName());
313 }
314
315 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000316 }
317}
318
Greg Clayton8b82f082011-04-12 05:54:46 +0000319
320void
Greg Clayton45392552012-10-17 22:57:12 +0000321ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton982c9762011-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 Clayton982c9762011-11-03 21:22:33 +0000336 }
337 }
338}
339void
Greg Clayton45392552012-10-17 22:57:12 +0000340ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Clayton8b82f082011-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 Clayton982c9762011-11-03 21:22:33 +0000348 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-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 Clayton8b82f082011-04-12 05:54:46 +0000356 }
357 }
358}
359
Greg Clayton1d885962011-11-08 02:43:13 +0000360void
Greg Claytonee95ed52011-11-17 22:14:31 +0000361ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-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 Clayton1d885962011-11-08 02:43:13 +0000367 if (m_flags.Test(eLaunchFlagDisableSTDIO))
368 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000369 AppendSuppressFileAction (STDIN_FILENO , true, false);
370 AppendSuppressFileAction (STDOUT_FILENO, false, true);
371 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-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 Clayton67cc0632012-08-22 17:17:09 +0000379 FileSpec in_path;
380 FileSpec out_path;
381 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000382 if (target)
383 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000384 in_path = target->GetStandardInputPath();
385 out_path = target->GetStandardOutputPath();
386 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000387 }
388
Greg Clayton67cc0632012-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 Claytonee95ed52011-11-17 22:14:31 +0000402 {
403 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000404 {
Greg Clayton67cc0632012-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 Clayton1d885962011-11-08 02:43:13 +0000409 }
410 }
Greg Clayton1d885962011-11-08 02:43:13 +0000411 }
412 }
413}
414
Greg Clayton144f3a92011-11-15 03:53:30 +0000415
416bool
Greg Claytond1cf11a2012-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 Clayton144f3a92011-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 Clayton45392552012-10-17 22:57:12 +0000448 const char **argv = GetArguments().GetConstArgumentVector ();
449 if (argv == NULL || argv[0] == NULL)
450 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000451 Args shell_arguments;
452 std::string safe_arg;
453 shell_arguments.AppendArgument (shell_executable);
Greg Clayton144f3a92011-11-15 03:53:30 +0000454 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000455 StreamString shell_command;
456 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000457 {
Greg Clayton45392552012-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 Claytond1cf11a2012-04-14 01:42:46 +0000491 shell_command.PutCString ("exec");
Greg Clayton45392552012-10-17 22:57:12 +0000492
493#if defined(__APPLE__)
494 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Claytond1cf11a2012-04-14 01:42:46 +0000495 if (GetArchitecture().IsValid())
496 {
497 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton45392552012-10-17 22:57:12 +0000498 // Set the resume count to 2:
Greg Claytond1cf11a2012-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 Clayton45392552012-10-17 22:57:12 +0000506 // Set the resume count to 1:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000507 // 1 - stop in shell
508 // 2 - then we will stop in our program
509 SetResumeCount(1);
510 }
Greg Clayton45392552012-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 Clayton144f3a92011-11-15 03:53:30 +0000517 }
Greg Clayton45392552012-10-17 22:57:12 +0000518
519 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000520 {
Greg Clayton45392552012-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 Claytond1cf11a2012-04-14 01:42:46 +0000524 else
Greg Clayton45392552012-10-17 22:57:12 +0000525 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000526 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000527 else
528 {
Greg Clayton45392552012-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 Claytond1cf11a2012-04-14 01:42:46 +0000534 }
Greg Clayton45392552012-10-17 22:57:12 +0000535 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton144f3a92011-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 Clayton32e0a752011-03-30 18:16:51 +0000553bool
Greg Clayton8b82f082011-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 Clayton144f3a92011-11-15 03:53:30 +0000561 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000562 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000563 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000564 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000565 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-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 Clayton144f3a92011-11-15 03:53:30 +0000653
Greg Clayton8b82f082011-04-12 05:54:46 +0000654 mode_t mode = 0;
655
Greg Clayton144f3a92011-11-15 03:53:30 +0000656 if (oflag & O_CREAT)
657 mode = 0640;
658
Greg Clayton8b82f082011-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 Claytonf6b8b582011-04-13 00:18:08 +0000680ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-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 Clayton8b82f082011-04-12 05:54:46 +0000691 case 'i': // STDIN for read only
692 {
693 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000694 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-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 Clayton9845a8d2012-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 Clayton8b82f082011-04-12 05:54:46 +0000711 launch_info.AppendFileAction (action);
712 }
713 break;
714
Greg Clayton9845a8d2012-03-06 04:01:04 +0000715
Greg Clayton8b82f082011-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 Clayton9845a8d2012-03-06 04:01:04 +0000723 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000724 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000725 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000726 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000727 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-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 Clayton70512312012-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 Clayton8b82f082011-04-12 05:54:46 +0000743 break;
744
745 case 'A':
746 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
747 break;
748
Greg Clayton982c9762011-11-03 21:22:33 +0000749 case 'c':
Greg Clayton144f3a92011-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 Clayton982c9762011-11-03 21:22:33 +0000754 break;
755
Greg Clayton8b82f082011-04-12 05:54:46 +0000756 case 'v':
757 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
758 break;
759
760 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000761 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-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."},
Sean Callanan31542552012-10-24 01:12:14 +0000774{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000775{ 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."},
Sean Callanan31542552012-10-24 01:12:14 +0000777{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000778
Sean Callanan31542552012-10-24 01:12:14 +0000779{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
780{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
781{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000782
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 Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000805ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000818 if (m_match_info.UserIDIsValid () &&
819 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000820 return false;
821
Greg Clayton8b82f082011-04-12 05:54:46 +0000822 if (m_match_info.GroupIDIsValid () &&
823 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000841ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000852 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000853 return false;
854
Greg Clayton8b82f082011-04-12 05:54:46 +0000855 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000875ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-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 Clayton58be07b2011-01-07 06:08:19 +0000881
Greg Claytonc3776bf2012-02-09 06:16:32 +0000882ProcessSP
883Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000885 ProcessSP process_sp;
Chris Lattner30fdc8d2010-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 Claytonc3776bf2012-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 Lattner30fdc8d2010-06-08 16:52:24 +0000898 }
899 }
900 else
901 {
Greg Claytonc982c762010-07-09 20:39:50 +0000902 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903 {
Greg Claytonc3776bf2012-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 Lattner30fdc8d2010-06-08 16:52:24 +0000912 }
913 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000914 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000915}
916
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000917ConstString &
918Process::GetStaticBroadcasterClass ()
919{
920 static ConstString class_name ("lldb.process");
921 return class_name;
922}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000923
924//----------------------------------------------------------------------
925// Process constructor
926//----------------------------------------------------------------------
927Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000928 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000929 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000930 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000931 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000932 m_public_state (eStateUnloaded),
933 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-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 Lattner30fdc8d2010-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 Ingham4b536182011-08-09 02:12:22 +0000939 m_mod_id (),
Chris Lattner30fdc8d2010-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 Clayton3af9ea52010-11-18 05:57:03 +0000945 m_image_tokens (),
946 m_listener (listener),
947 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000948 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000949 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000950 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000951 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000952 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000953 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000954 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000955 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000956 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
957 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000958 m_memory_cache (*this),
959 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000960 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000961 m_next_event_action_ap(),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000962 m_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000963 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000964 m_finalize_called(false),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000965 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000966{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000967 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000968
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000969 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000970 if (log)
971 log->Printf ("%p Process::Process()", this);
972
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000973 SetEventName (eBroadcastBitStateChanged, "state-changed");
974 SetEventName (eBroadcastBitInterrupt, "interrupt");
975 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
976 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000977 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000978
Greg Clayton35a4cc52012-10-29 20:52:08 +0000979 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
980 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
981 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
982
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000983 listener.StartListeningForEvents (this,
984 eBroadcastBitStateChanged |
985 eBroadcastBitInterrupt |
986 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000987 eBroadcastBitSTDERR |
988 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989
990 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000991 eBroadcastBitStateChanged |
992 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993
994 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
995 eBroadcastInternalStateControlStop |
996 eBroadcastInternalStateControlPause |
997 eBroadcastInternalStateControlResume);
998}
999
1000//----------------------------------------------------------------------
1001// Destructor
1002//----------------------------------------------------------------------
1003Process::~Process()
1004{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001005 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006 if (log)
1007 log->Printf ("%p Process::~Process()", this);
1008 StopPrivateStateThread();
1009}
1010
Greg Clayton67cc0632012-08-22 17:17:09 +00001011const ProcessPropertiesSP &
1012Process::GetGlobalProperties()
1013{
1014 static ProcessPropertiesSP g_settings_sp;
1015 if (!g_settings_sp)
1016 g_settings_sp.reset (new ProcessProperties (true));
1017 return g_settings_sp;
1018}
1019
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020void
1021Process::Finalize()
1022{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001023 switch (GetPrivateState())
1024 {
1025 case eStateConnected:
1026 case eStateAttaching:
1027 case eStateLaunching:
1028 case eStateStopped:
1029 case eStateRunning:
1030 case eStateStepping:
1031 case eStateCrashed:
1032 case eStateSuspended:
1033 if (GetShouldDetach())
1034 Detach();
1035 else
1036 Destroy();
1037 break;
1038
1039 case eStateInvalid:
1040 case eStateUnloaded:
1041 case eStateDetached:
1042 case eStateExited:
1043 break;
1044 }
1045
Greg Clayton1ed54f52011-10-01 00:45:15 +00001046 // Clear our broadcaster before we proceed with destroying
1047 Broadcaster::Clear();
1048
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001049 // Do any cleanup needed prior to being destructed... Subclasses
1050 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001051
1052 // We need to destroy the loader before the derived Process class gets destroyed
1053 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001054 m_dynamic_checkers_ap.reset();
1055 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001056 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001057 m_dyld_ap.reset();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001058 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +00001059 std::vector<Notifications> empty_notifications;
1060 m_notifications.swap(empty_notifications);
1061 m_image_tokens.clear();
1062 m_memory_cache.Clear();
1063 m_allocated_memory_cache.Clear();
1064 m_language_runtimes.clear();
1065 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001066//#ifdef LLDB_CONFIGURATION_DEBUG
1067// StreamFile s(stdout, false);
1068// EventSP event_sp;
1069// while (m_private_state_listener.GetNextEvent(event_sp))
1070// {
1071// event_sp->Dump (&s);
1072// s.EOL();
1073// }
1074//#endif
1075 // We have to be very careful here as the m_private_state_listener might
1076 // contain events that have ProcessSP values in them which can keep this
1077 // process around forever. These events need to be cleared out.
1078 m_private_state_listener.Clear();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001079 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080}
1081
1082void
1083Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1084{
1085 m_notifications.push_back(callbacks);
1086 if (callbacks.initialize != NULL)
1087 callbacks.initialize (callbacks.baton, this);
1088}
1089
1090bool
1091Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1092{
1093 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1094 for (pos = m_notifications.begin(); pos != end; ++pos)
1095 {
1096 if (pos->baton == callbacks.baton &&
1097 pos->initialize == callbacks.initialize &&
1098 pos->process_state_changed == callbacks.process_state_changed)
1099 {
1100 m_notifications.erase(pos);
1101 return true;
1102 }
1103 }
1104 return false;
1105}
1106
1107void
1108Process::SynchronouslyNotifyStateChanged (StateType state)
1109{
1110 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1111 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1112 {
1113 if (notification_pos->process_state_changed)
1114 notification_pos->process_state_changed (notification_pos->baton, this, state);
1115 }
1116}
1117
1118// FIXME: We need to do some work on events before the general Listener sees them.
1119// For instance if we are continuing from a breakpoint, we need to ensure that we do
1120// the little "insert real insn, step & stop" trick. But we can't do that when the
1121// event is delivered by the broadcaster - since that is done on the thread that is
1122// waiting for new events, so if we needed more than one event for our handling, we would
1123// stall. So instead we do it when we fetch the event off of the queue.
1124//
1125
1126StateType
1127Process::GetNextEvent (EventSP &event_sp)
1128{
1129 StateType state = eStateInvalid;
1130
1131 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1132 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1133
1134 return state;
1135}
1136
1137
1138StateType
Greg Clayton85fb1b92012-09-11 02:33:37 +00001139Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140{
Jim Ingham4b536182011-08-09 02:12:22 +00001141 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1142 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1143 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001144 if (event_sp_ptr)
1145 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001146 StateType state = GetState();
1147 // If we are exited or detached, we won't ever get back to any
1148 // other valid state...
1149 if (state == eStateDetached || state == eStateExited)
1150 return state;
1151
1152 while (state != eStateInvalid)
1153 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001154 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001155 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001156 if (event_sp_ptr && event_sp)
1157 *event_sp_ptr = event_sp;
1158
Jim Ingham4b536182011-08-09 02:12:22 +00001159 switch (state)
1160 {
1161 case eStateCrashed:
1162 case eStateDetached:
1163 case eStateExited:
1164 case eStateUnloaded:
1165 return state;
1166 case eStateStopped:
1167 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1168 continue;
1169 else
1170 return state;
1171 default:
1172 continue;
1173 }
1174 }
1175 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001176}
1177
1178
1179StateType
1180Process::WaitForState
1181(
1182 const TimeValue *timeout,
1183 const StateType *match_states, const uint32_t num_match_states
1184)
1185{
1186 EventSP event_sp;
1187 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001188 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189 while (state != eStateInvalid)
1190 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001191 // If we are exited or detached, we won't ever get back to any
1192 // other valid state...
1193 if (state == eStateDetached || state == eStateExited)
1194 return state;
1195
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001196 state = WaitForStateChangedEvents (timeout, event_sp);
1197
1198 for (i=0; i<num_match_states; ++i)
1199 {
1200 if (match_states[i] == state)
1201 return state;
1202 }
1203 }
1204 return state;
1205}
1206
Jim Ingham30f9b212010-10-11 23:53:14 +00001207bool
1208Process::HijackProcessEvents (Listener *listener)
1209{
1210 if (listener != NULL)
1211 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001212 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001213 }
1214 else
1215 return false;
1216}
1217
1218void
1219Process::RestoreProcessEvents ()
1220{
1221 RestoreBroadcaster();
1222}
1223
Jim Ingham0f16e732011-02-08 05:20:59 +00001224bool
1225Process::HijackPrivateProcessEvents (Listener *listener)
1226{
1227 if (listener != NULL)
1228 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001229 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001230 }
1231 else
1232 return false;
1233}
1234
1235void
1236Process::RestorePrivateProcessEvents ()
1237{
1238 m_private_state_broadcaster.RestoreBroadcaster();
1239}
1240
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001241StateType
1242Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1243{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001244 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001245
1246 if (log)
1247 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1248
1249 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001250 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1251 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001252 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001253 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001254 {
1255 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1256 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1257 else if (log)
1258 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1259 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001260
1261 if (log)
1262 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1263 __FUNCTION__,
1264 timeout,
1265 StateAsCString(state));
1266 return state;
1267}
1268
1269Event *
1270Process::PeekAtStateChangedEvents ()
1271{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001272 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001273
1274 if (log)
1275 log->Printf ("Process::%s...", __FUNCTION__);
1276
1277 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001278 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1279 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001280 if (log)
1281 {
1282 if (event_ptr)
1283 {
1284 log->Printf ("Process::%s (event_ptr) => %s",
1285 __FUNCTION__,
1286 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1287 }
1288 else
1289 {
1290 log->Printf ("Process::%s no events found",
1291 __FUNCTION__);
1292 }
1293 }
1294 return event_ptr;
1295}
1296
1297StateType
1298Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1299{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001300 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001301
1302 if (log)
1303 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1304
1305 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001306 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1307 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001308 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001309 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001310 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1311 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001312
1313 // This is a bit of a hack, but when we wait here we could very well return
1314 // to the command-line, and that could disable the log, which would render the
1315 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001316 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001317 {
1318 if (state == eStateInvalid)
1319 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1320 else
1321 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1322 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001323 return state;
1324}
1325
1326bool
1327Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1328{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001329 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001330
1331 if (log)
1332 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1333
1334 if (control_only)
1335 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1336 else
1337 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1338}
1339
1340bool
1341Process::IsRunning () const
1342{
1343 return StateIsRunningState (m_public_state.GetValue());
1344}
1345
1346int
1347Process::GetExitStatus ()
1348{
1349 if (m_public_state.GetValue() == eStateExited)
1350 return m_exit_status;
1351 return -1;
1352}
1353
Greg Clayton85851dd2010-12-04 00:10:17 +00001354
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355const char *
1356Process::GetExitDescription ()
1357{
1358 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1359 return m_exit_string.c_str();
1360 return NULL;
1361}
1362
Greg Clayton6779606a2011-01-22 23:43:18 +00001363bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364Process::SetExitStatus (int status, const char *cstr)
1365{
Greg Clayton414f5d32011-01-25 02:58:48 +00001366 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1367 if (log)
1368 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1369 status, status,
1370 cstr ? "\"" : "",
1371 cstr ? cstr : "NULL",
1372 cstr ? "\"" : "");
1373
Greg Clayton6779606a2011-01-22 23:43:18 +00001374 // We were already in the exited state
1375 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001376 {
Greg Clayton385d6032011-01-26 23:47:29 +00001377 if (log)
1378 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001379 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001380 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001381
1382 m_exit_status = status;
1383 if (cstr)
1384 m_exit_string = cstr;
1385 else
1386 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387
Greg Clayton6779606a2011-01-22 23:43:18 +00001388 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001389
Greg Clayton6779606a2011-01-22 23:43:18 +00001390 SetPrivateState (eStateExited);
1391 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001392}
1393
1394// This static callback can be used to watch for local child processes on
1395// the current host. The the child process exits, the process will be
1396// found in the global target list (we want to be completely sure that the
1397// lldb_private::Process doesn't go away before we can deliver the signal.
1398bool
Greg Claytone4e45922011-11-16 05:37:56 +00001399Process::SetProcessExitStatus (void *callback_baton,
1400 lldb::pid_t pid,
1401 bool exited,
1402 int signo, // Zero for no signal
1403 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001404)
1405{
Greg Claytone4e45922011-11-16 05:37:56 +00001406 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1407 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00001408 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001409 callback_baton,
1410 pid,
1411 exited,
1412 signo,
1413 exit_status);
1414
1415 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416 {
Greg Clayton66111032010-06-23 01:19:29 +00001417 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001418 if (target_sp)
1419 {
1420 ProcessSP process_sp (target_sp->GetProcessSP());
1421 if (process_sp)
1422 {
1423 const char *signal_cstr = NULL;
1424 if (signo)
1425 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1426
1427 process_sp->SetExitStatus (exit_status, signal_cstr);
1428 }
1429 }
1430 return true;
1431 }
1432 return false;
1433}
1434
1435
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001436void
1437Process::UpdateThreadListIfNeeded ()
1438{
1439 const uint32_t stop_id = GetStopID();
1440 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1441 {
Greg Clayton2637f822011-11-17 01:23:07 +00001442 const StateType state = GetPrivateState();
1443 if (StateIsStoppedState (state, true))
1444 {
1445 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001446 // m_thread_list does have its own mutex, but we need to
1447 // hold onto the mutex between the call to UpdateThreadList(...)
1448 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton2637f822011-11-17 01:23:07 +00001449 ThreadList new_thread_list(this);
1450 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001451 // thread list, but only update if "true" is returned
1452 if (UpdateThreadList (m_thread_list, new_thread_list))
1453 {
1454 OperatingSystem *os = GetOperatingSystem ();
1455 if (os)
1456 os->UpdateThreadList (m_thread_list, new_thread_list);
1457 m_thread_list.Update (new_thread_list);
1458 m_thread_list.SetStopID (stop_id);
1459 }
Greg Clayton2637f822011-11-17 01:23:07 +00001460 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001461 }
1462}
1463
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001464uint32_t
1465Process::GetNextThreadIndexID ()
1466{
1467 return ++m_thread_index_id;
1468}
1469
1470StateType
1471Process::GetState()
1472{
1473 // If any other threads access this we will need a mutex for it
1474 return m_public_state.GetValue ();
1475}
1476
1477void
1478Process::SetPublicState (StateType new_state)
1479{
Greg Clayton414f5d32011-01-25 02:58:48 +00001480 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001481 if (log)
1482 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001483 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001484 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001485
1486 // On the transition from Run to Stopped, we unlock the writer end of the
1487 // run lock. The lock gets locked in Resume, which is the public API
1488 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001489 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1490 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001491 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001492 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001493 if (log)
1494 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1495 m_run_lock.WriteUnlock();
1496 }
1497 else
1498 {
1499 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1500 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1501 if (old_state_is_stopped != new_state_is_stopped)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001502 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001503 if (new_state_is_stopped)
1504 {
1505 if (log)
1506 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1507 m_run_lock.WriteUnlock();
1508 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001509 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001510 }
1511 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001512}
1513
Jim Ingham3b8285d2012-04-19 01:40:33 +00001514Error
1515Process::Resume ()
1516{
1517 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1518 if (log)
1519 log->Printf("Process::Resume -- locking run lock");
1520 if (!m_run_lock.WriteTryLock())
1521 {
1522 Error error("Resume request failed - process still running.");
1523 if (log)
1524 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1525 return error;
1526 }
1527 return PrivateResume();
1528}
1529
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001530StateType
1531Process::GetPrivateState ()
1532{
1533 return m_private_state.GetValue();
1534}
1535
1536void
1537Process::SetPrivateState (StateType new_state)
1538{
Greg Clayton414f5d32011-01-25 02:58:48 +00001539 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001540 bool state_changed = false;
1541
1542 if (log)
1543 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1544
1545 Mutex::Locker locker(m_private_state.GetMutex());
1546
1547 const StateType old_state = m_private_state.GetValueNoLock ();
1548 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001549 // This code is left commented out in case we ever need to control
1550 // the private process state with another run lock. Right now it doesn't
1551 // seem like we need to do this, but if we ever do, we can uncomment and
1552 // use this code.
1553// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1554// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1555// if (old_state_is_stopped != new_state_is_stopped)
1556// {
1557// if (new_state_is_stopped)
1558// m_private_run_lock.WriteUnlock();
1559// else
1560// m_private_run_lock.WriteLock();
1561// }
1562
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001563 if (state_changed)
1564 {
1565 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001566 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001567 {
Jim Ingham4b536182011-08-09 02:12:22 +00001568 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001569 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001570 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001571 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001572 }
1573 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001574 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1575 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1576 else
1577 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001578 }
1579 else
1580 {
1581 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001582 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001583 }
1584}
1585
Jim Ingham0faa43f2011-11-08 03:00:11 +00001586void
1587Process::SetRunningUserExpression (bool on)
1588{
1589 m_mod_id.SetRunningUserExpression (on);
1590}
1591
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001592addr_t
1593Process::GetImageInfoAddress()
1594{
1595 return LLDB_INVALID_ADDRESS;
1596}
1597
Greg Clayton8f343b02010-11-04 01:54:29 +00001598//----------------------------------------------------------------------
1599// LoadImage
1600//
1601// This function provides a default implementation that works for most
1602// unix variants. Any Process subclasses that need to do shared library
1603// loading differently should override LoadImage and UnloadImage and
1604// do what is needed.
1605//----------------------------------------------------------------------
1606uint32_t
1607Process::LoadImage (const FileSpec &image_spec, Error &error)
1608{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001609 char path[PATH_MAX];
1610 image_spec.GetPath(path, sizeof(path));
1611
Greg Clayton8f343b02010-11-04 01:54:29 +00001612 DynamicLoader *loader = GetDynamicLoader();
1613 if (loader)
1614 {
1615 error = loader->CanLoadImage();
1616 if (error.Fail())
1617 return LLDB_INVALID_IMAGE_TOKEN;
1618 }
1619
1620 if (error.Success())
1621 {
1622 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001623
1624 if (thread_sp)
1625 {
1626 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1627
1628 if (frame_sp)
1629 {
1630 ExecutionContext exe_ctx;
1631 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001632 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001633 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001634 expr.Printf("dlopen (\"%s\", 2)", path);
1635 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001636 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001637 ClangUserExpression::Evaluate (exe_ctx,
1638 eExecutionPolicyAlways,
1639 lldb::eLanguageTypeUnknown,
1640 ClangUserExpression::eResultTypeAny,
1641 unwind_on_error,
1642 expr.GetData(),
1643 prefix,
1644 result_valobj_sp,
1645 true,
1646 ClangUserExpression::kDefaultTimeout);
Johnny Chene92aa432011-09-09 00:01:43 +00001647 error = result_valobj_sp->GetError();
1648 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001649 {
1650 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001651 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001652 {
1653 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1654 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1655 {
1656 uint32_t image_token = m_image_tokens.size();
1657 m_image_tokens.push_back (image_ptr);
1658 return image_token;
1659 }
1660 }
1661 }
1662 }
1663 }
1664 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001665 if (!error.AsCString())
1666 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001667 return LLDB_INVALID_IMAGE_TOKEN;
1668}
1669
1670//----------------------------------------------------------------------
1671// UnloadImage
1672//
1673// This function provides a default implementation that works for most
1674// unix variants. Any Process subclasses that need to do shared library
1675// loading differently should override LoadImage and UnloadImage and
1676// do what is needed.
1677//----------------------------------------------------------------------
1678Error
1679Process::UnloadImage (uint32_t image_token)
1680{
1681 Error error;
1682 if (image_token < m_image_tokens.size())
1683 {
1684 const addr_t image_addr = m_image_tokens[image_token];
1685 if (image_addr == LLDB_INVALID_ADDRESS)
1686 {
1687 error.SetErrorString("image already unloaded");
1688 }
1689 else
1690 {
1691 DynamicLoader *loader = GetDynamicLoader();
1692 if (loader)
1693 error = loader->CanLoadImage();
1694
1695 if (error.Success())
1696 {
1697 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001698
1699 if (thread_sp)
1700 {
1701 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1702
1703 if (frame_sp)
1704 {
1705 ExecutionContext exe_ctx;
1706 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001707 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001708 StreamString expr;
1709 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1710 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001711 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001712 ClangUserExpression::Evaluate (exe_ctx,
1713 eExecutionPolicyAlways,
1714 lldb::eLanguageTypeUnknown,
1715 ClangUserExpression::eResultTypeAny,
1716 unwind_on_error,
1717 expr.GetData(),
1718 prefix,
1719 result_valobj_sp,
1720 true,
1721 ClangUserExpression::kDefaultTimeout);
Greg Clayton8f343b02010-11-04 01:54:29 +00001722 if (result_valobj_sp->GetError().Success())
1723 {
1724 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001725 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001726 {
1727 if (scalar.UInt(1))
1728 {
1729 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1730 }
1731 else
1732 {
1733 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1734 }
1735 }
1736 }
1737 else
1738 {
1739 error = result_valobj_sp->GetError();
1740 }
1741 }
1742 }
1743 }
1744 }
1745 }
1746 else
1747 {
1748 error.SetErrorString("invalid image token");
1749 }
1750 return error;
1751}
1752
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001753const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001754Process::GetABI()
1755{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001756 if (!m_abi_sp)
1757 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1758 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001759}
1760
Jim Ingham22777012010-09-23 02:01:19 +00001761LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001762Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001763{
1764 LanguageRuntimeCollection::iterator pos;
1765 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001766 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001767 {
Jim Inghamab175242012-03-10 00:22:19 +00001768 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001769
Jim Inghamab175242012-03-10 00:22:19 +00001770 m_language_runtimes[language] = runtime_sp;
1771 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001772 }
1773 else
1774 return (*pos).second.get();
1775}
1776
1777CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001778Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001779{
Jim Inghamab175242012-03-10 00:22:19 +00001780 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001781 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1782 return static_cast<CPPLanguageRuntime *> (runtime);
1783 return NULL;
1784}
1785
1786ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001787Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001788{
Jim Inghamab175242012-03-10 00:22:19 +00001789 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001790 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1791 return static_cast<ObjCLanguageRuntime *> (runtime);
1792 return NULL;
1793}
1794
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001795bool
1796Process::IsPossibleDynamicValue (ValueObject& in_value)
1797{
1798 if (in_value.IsDynamic())
1799 return false;
1800 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1801
1802 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1803 {
1804 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1805 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1806 }
1807
1808 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1809 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1810 return true;
1811
1812 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1813 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1814}
1815
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001816BreakpointSiteList &
1817Process::GetBreakpointSiteList()
1818{
1819 return m_breakpoint_site_list;
1820}
1821
1822const BreakpointSiteList &
1823Process::GetBreakpointSiteList() const
1824{
1825 return m_breakpoint_site_list;
1826}
1827
1828
1829void
1830Process::DisableAllBreakpointSites ()
1831{
1832 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham43c555d2012-07-04 00:35:43 +00001833 size_t num_sites = m_breakpoint_site_list.GetSize();
1834 for (size_t i = 0; i < num_sites; i++)
1835 {
1836 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1837 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001838}
1839
1840Error
1841Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1842{
1843 Error error (DisableBreakpointSiteByID (break_id));
1844
1845 if (error.Success())
1846 m_breakpoint_site_list.Remove(break_id);
1847
1848 return error;
1849}
1850
1851Error
1852Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1853{
1854 Error error;
1855 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1856 if (bp_site_sp)
1857 {
1858 if (bp_site_sp->IsEnabled())
1859 error = DisableBreakpoint (bp_site_sp.get());
1860 }
1861 else
1862 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001863 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864 }
1865
1866 return error;
1867}
1868
1869Error
1870Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1871{
1872 Error error;
1873 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1874 if (bp_site_sp)
1875 {
1876 if (!bp_site_sp->IsEnabled())
1877 error = EnableBreakpoint (bp_site_sp.get());
1878 }
1879 else
1880 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001881 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001882 }
1883 return error;
1884}
1885
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001886lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001887Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001888{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001889 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001890 if (load_addr != LLDB_INVALID_ADDRESS)
1891 {
1892 BreakpointSiteSP bp_site_sp;
1893
1894 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1895 // create a new breakpoint site and add it.
1896
1897 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1898
1899 if (bp_site_sp)
1900 {
1901 bp_site_sp->AddOwner (owner);
1902 owner->SetBreakpointSite (bp_site_sp);
1903 return bp_site_sp->GetID();
1904 }
1905 else
1906 {
1907 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1908 if (bp_site_sp)
1909 {
1910 if (EnableBreakpoint (bp_site_sp.get()).Success())
1911 {
1912 owner->SetBreakpointSite (bp_site_sp);
1913 return m_breakpoint_site_list.Add (bp_site_sp);
1914 }
1915 }
1916 }
1917 }
1918 // We failed to enable the breakpoint
1919 return LLDB_INVALID_BREAK_ID;
1920
1921}
1922
1923void
1924Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1925{
1926 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1927 if (num_owners == 0)
1928 {
1929 DisableBreakpoint(bp_site_sp.get());
1930 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1931 }
1932}
1933
1934
1935size_t
1936Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1937{
1938 size_t bytes_removed = 0;
1939 addr_t intersect_addr;
1940 size_t intersect_size;
1941 size_t opcode_offset;
1942 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001943 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001944 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001945
Jim Ingham20c77192011-06-29 19:42:28 +00001946 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001947 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001948 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001949 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001950 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001951 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001952 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001953 {
1954 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1955 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001956 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001957 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001958 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001959 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001960 }
1961 }
1962 }
1963 return bytes_removed;
1964}
1965
1966
Greg Claytonded470d2011-03-19 01:12:21 +00001967
1968size_t
1969Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1970{
1971 PlatformSP platform_sp (m_target.GetPlatform());
1972 if (platform_sp)
1973 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1974 return 0;
1975}
1976
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001977Error
1978Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1979{
1980 Error error;
1981 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001982 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001983 const addr_t bp_addr = bp_site->GetLoadAddress();
1984 if (log)
1985 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1986 if (bp_site->IsEnabled())
1987 {
1988 if (log)
1989 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1990 return error;
1991 }
1992
1993 if (bp_addr == LLDB_INVALID_ADDRESS)
1994 {
1995 error.SetErrorString("BreakpointSite contains an invalid load address.");
1996 return error;
1997 }
1998 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1999 // trap for the breakpoint site
2000 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2001
2002 if (bp_opcode_size == 0)
2003 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002004 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002005 }
2006 else
2007 {
2008 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2009
2010 if (bp_opcode_bytes == NULL)
2011 {
2012 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2013 return error;
2014 }
2015
2016 // Save the original opcode by reading it
2017 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2018 {
2019 // Write a software breakpoint in place of the original opcode
2020 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2021 {
2022 uint8_t verify_bp_opcode_bytes[64];
2023 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2024 {
2025 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2026 {
2027 bp_site->SetEnabled(true);
2028 bp_site->SetType (BreakpointSite::eSoftware);
2029 if (log)
2030 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
2031 bp_site->GetID(),
2032 (uint64_t)bp_addr);
2033 }
2034 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002035 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002036 }
2037 else
2038 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2039 }
2040 else
2041 error.SetErrorString("Unable to write breakpoint trap to memory.");
2042 }
2043 else
2044 error.SetErrorString("Unable to read memory at breakpoint address.");
2045 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002046 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002047 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2048 bp_site->GetID(),
2049 (uint64_t)bp_addr,
2050 error.AsCString());
2051 return error;
2052}
2053
2054Error
2055Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2056{
2057 Error error;
2058 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002059 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002060 addr_t bp_addr = bp_site->GetLoadAddress();
2061 lldb::user_id_t breakID = bp_site->GetID();
2062 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002063 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002064
2065 if (bp_site->IsHardware())
2066 {
2067 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2068 }
2069 else if (bp_site->IsEnabled())
2070 {
2071 const size_t break_op_size = bp_site->GetByteSize();
2072 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2073 if (break_op_size > 0)
2074 {
2075 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002076 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002077 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002078 bool break_op_found = false;
2079
2080 // Read the breakpoint opcode
2081 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2082 {
2083 bool verify = false;
2084 // Make sure we have the a breakpoint opcode exists at this address
2085 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2086 {
2087 break_op_found = true;
2088 // We found a valid breakpoint opcode at this address, now restore
2089 // the saved opcode.
2090 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2091 {
2092 verify = true;
2093 }
2094 else
2095 error.SetErrorString("Memory write failed when restoring original opcode.");
2096 }
2097 else
2098 {
2099 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2100 // Set verify to true and so we can check if the original opcode has already been restored
2101 verify = true;
2102 }
2103
2104 if (verify)
2105 {
Greg Claytonc982c762010-07-09 20:39:50 +00002106 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002107 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108 // Verify that our original opcode made it back to the inferior
2109 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2110 {
2111 // compare the memory we just read with the original opcode
2112 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2113 {
2114 // SUCCESS
2115 bp_site->SetEnabled(false);
2116 if (log)
2117 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2118 return error;
2119 }
2120 else
2121 {
2122 if (break_op_found)
2123 error.SetErrorString("Failed to restore original opcode.");
2124 }
2125 }
2126 else
2127 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2128 }
2129 }
2130 else
2131 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2132 }
2133 }
2134 else
2135 {
2136 if (log)
2137 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2138 return error;
2139 }
2140
2141 if (log)
2142 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2143 bp_site->GetID(),
2144 (uint64_t)bp_addr,
2145 error.AsCString());
2146 return error;
2147
2148}
2149
Greg Clayton58be07b2011-01-07 06:08:19 +00002150// Uncomment to verify memory caching works after making changes to caching code
2151//#define VERIFY_MEMORY_READS
2152
Sean Callanan64c0cf22012-06-07 22:26:42 +00002153size_t
2154Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2155{
2156 if (!GetDisableMemoryCache())
2157 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002158#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002159 // Memory caching is enabled, with debug verification
2160
2161 if (buf && size)
2162 {
2163 // Uncomment the line below to make sure memory caching is working.
2164 // I ran this through the test suite and got no assertions, so I am
2165 // pretty confident this is working well. If any changes are made to
2166 // memory caching, uncomment the line below and test your changes!
2167
2168 // Verify all memory reads by using the cache first, then redundantly
2169 // reading the same memory from the inferior and comparing to make sure
2170 // everything is exactly the same.
2171 std::string verify_buf (size, '\0');
2172 assert (verify_buf.size() == size);
2173 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2174 Error verify_error;
2175 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2176 assert (cache_bytes_read == verify_bytes_read);
2177 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2178 assert (verify_error.Success() == error.Success());
2179 return cache_bytes_read;
2180 }
2181 return 0;
2182#else // !defined(VERIFY_MEMORY_READS)
2183 // Memory caching is enabled, without debug verification
2184
2185 return m_memory_cache.Read (addr, buf, size, error);
2186#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002187 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002188 else
2189 {
2190 // Memory caching is disabled
2191
2192 return ReadMemoryFromInferior (addr, buf, size, error);
2193 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002194}
Greg Clayton58be07b2011-01-07 06:08:19 +00002195
Greg Clayton4c82d422012-05-18 23:20:01 +00002196size_t
2197Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2198{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002199 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002200 out_str.clear();
2201 addr_t curr_addr = addr;
2202 while (1)
2203 {
2204 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2205 if (length == 0)
2206 break;
2207 out_str.append(buf, length);
2208 // If we got "length - 1" bytes, we didn't get the whole C string, we
2209 // need to read some more characters
2210 if (length == sizeof(buf) - 1)
2211 curr_addr += length;
2212 else
2213 break;
2214 }
2215 return out_str.size();
2216}
2217
Greg Clayton58be07b2011-01-07 06:08:19 +00002218
2219size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002220Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002221{
2222 size_t total_cstr_len = 0;
2223 if (dst && dst_max_len)
2224 {
Greg Claytone91b7952011-12-15 03:14:23 +00002225 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002226 // NULL out everything just to be safe
2227 memset (dst, 0, dst_max_len);
2228 Error error;
2229 addr_t curr_addr = addr;
2230 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2231 size_t bytes_left = dst_max_len - 1;
2232 char *curr_dst = dst;
2233
2234 while (bytes_left > 0)
2235 {
2236 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2237 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2238 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2239
2240 if (bytes_read == 0)
2241 {
Greg Claytone91b7952011-12-15 03:14:23 +00002242 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002243 dst[total_cstr_len] = '\0';
2244 break;
2245 }
2246 const size_t len = strlen(curr_dst);
2247
2248 total_cstr_len += len;
2249
2250 if (len < bytes_to_read)
2251 break;
2252
2253 curr_dst += bytes_read;
2254 curr_addr += bytes_read;
2255 bytes_left -= bytes_read;
2256 }
2257 }
Greg Claytone91b7952011-12-15 03:14:23 +00002258 else
2259 {
2260 if (dst == NULL)
2261 result_error.SetErrorString("invalid arguments");
2262 else
2263 result_error.Clear();
2264 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002265 return total_cstr_len;
2266}
2267
2268size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002269Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2270{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002271 if (buf == NULL || size == 0)
2272 return 0;
2273
2274 size_t bytes_read = 0;
2275 uint8_t *bytes = (uint8_t *)buf;
2276
2277 while (bytes_read < size)
2278 {
2279 const size_t curr_size = size - bytes_read;
2280 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2281 bytes + bytes_read,
2282 curr_size,
2283 error);
2284 bytes_read += curr_bytes_read;
2285 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2286 break;
2287 }
2288
2289 // Replace any software breakpoint opcodes that fall into this range back
2290 // into "buf" before we return
2291 if (bytes_read > 0)
2292 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2293 return bytes_read;
2294}
2295
Greg Clayton58a4c462010-12-16 20:01:20 +00002296uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002297Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002298{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002299 Scalar scalar;
2300 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2301 return scalar.ULongLong(fail_value);
2302 return fail_value;
2303}
2304
2305addr_t
2306Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2307{
2308 Scalar scalar;
2309 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2310 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2311 return LLDB_INVALID_ADDRESS;
2312}
2313
2314
2315bool
2316Process::WritePointerToMemory (lldb::addr_t vm_addr,
2317 lldb::addr_t ptr_value,
2318 Error &error)
2319{
2320 Scalar scalar;
2321 const uint32_t addr_byte_size = GetAddressByteSize();
2322 if (addr_byte_size <= 4)
2323 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002324 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002325 scalar = ptr_value;
2326 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002327}
2328
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002329size_t
2330Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2331{
2332 size_t bytes_written = 0;
2333 const uint8_t *bytes = (const uint8_t *)buf;
2334
2335 while (bytes_written < size)
2336 {
2337 const size_t curr_size = size - bytes_written;
2338 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2339 bytes + bytes_written,
2340 curr_size,
2341 error);
2342 bytes_written += curr_bytes_written;
2343 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2344 break;
2345 }
2346 return bytes_written;
2347}
2348
2349size_t
2350Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2351{
Greg Clayton58be07b2011-01-07 06:08:19 +00002352#if defined (ENABLE_MEMORY_CACHING)
2353 m_memory_cache.Flush (addr, size);
2354#endif
2355
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356 if (buf == NULL || size == 0)
2357 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002358
Jim Ingham4b536182011-08-09 02:12:22 +00002359 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002360
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361 // We need to write any data that would go where any current software traps
2362 // (enabled software breakpoints) any software traps (breakpoints) that we
2363 // may have placed in our tasks memory.
2364
2365 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2366 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2367
2368 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002369 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370
2371 BreakpointSiteList::collection::const_iterator pos;
2372 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002373 addr_t intersect_addr = 0;
2374 size_t intersect_size = 0;
2375 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376 const uint8_t *ubuf = (const uint8_t *)buf;
2377
2378 for (pos = iter; pos != end; ++pos)
2379 {
2380 BreakpointSiteSP bp;
2381 bp = pos->second;
2382
2383 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2384 assert(addr <= intersect_addr && intersect_addr < addr + size);
2385 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2386 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2387
2388 // Check for bytes before this breakpoint
2389 const addr_t curr_addr = addr + bytes_written;
2390 if (intersect_addr > curr_addr)
2391 {
2392 // There are some bytes before this breakpoint that we need to
2393 // just write to memory
2394 size_t curr_size = intersect_addr - curr_addr;
2395 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2396 ubuf + bytes_written,
2397 curr_size,
2398 error);
2399 bytes_written += curr_bytes_written;
2400 if (curr_bytes_written != curr_size)
2401 {
2402 // We weren't able to write all of the requested bytes, we
2403 // are done looping and will return the number of bytes that
2404 // we have written so far.
2405 break;
2406 }
2407 }
2408
2409 // Now write any bytes that would cover up any software breakpoints
2410 // directly into the breakpoint opcode buffer
2411 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2412 bytes_written += intersect_size;
2413 }
2414
2415 // Write any remaining bytes after the last breakpoint if we have any left
2416 if (bytes_written < size)
2417 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2418 ubuf + bytes_written,
2419 size - bytes_written,
2420 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002421
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422 return bytes_written;
2423}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002424
2425size_t
2426Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2427{
2428 if (byte_size == UINT32_MAX)
2429 byte_size = scalar.GetByteSize();
2430 if (byte_size > 0)
2431 {
2432 uint8_t buf[32];
2433 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2434 if (mem_size > 0)
2435 return WriteMemory(addr, buf, mem_size, error);
2436 else
2437 error.SetErrorString ("failed to get scalar as memory data");
2438 }
2439 else
2440 {
2441 error.SetErrorString ("invalid scalar value");
2442 }
2443 return 0;
2444}
2445
2446size_t
2447Process::ReadScalarIntegerFromMemory (addr_t addr,
2448 uint32_t byte_size,
2449 bool is_signed,
2450 Scalar &scalar,
2451 Error &error)
2452{
2453 uint64_t uval;
2454
2455 if (byte_size <= sizeof(uval))
2456 {
2457 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2458 if (bytes_read == byte_size)
2459 {
2460 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2461 uint32_t offset = 0;
2462 if (byte_size <= 4)
2463 scalar = data.GetMaxU32 (&offset, byte_size);
2464 else
2465 scalar = data.GetMaxU64 (&offset, byte_size);
2466
2467 if (is_signed)
2468 scalar.SignExtend(byte_size * 8);
2469 return bytes_read;
2470 }
2471 }
2472 else
2473 {
2474 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2475 }
2476 return 0;
2477}
2478
Greg Claytond495c532011-05-17 03:37:42 +00002479#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480addr_t
2481Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2482{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002483 if (GetPrivateState() != eStateStopped)
2484 return LLDB_INVALID_ADDRESS;
2485
Greg Claytond495c532011-05-17 03:37:42 +00002486#if defined (USE_ALLOCATE_MEMORY_CACHE)
2487 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2488#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002489 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2490 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2491 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002492 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002493 size,
Greg Claytond495c532011-05-17 03:37:42 +00002494 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002495 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002496 m_mod_id.GetStopID(),
2497 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002498 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002499#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500}
2501
Sean Callanan90539452011-09-20 23:01:51 +00002502bool
2503Process::CanJIT ()
2504{
Sean Callanana7b443a2012-02-14 22:50:38 +00002505 if (m_can_jit == eCanJITDontKnow)
2506 {
2507 Error err;
2508
2509 uint64_t allocated_memory = AllocateMemory(8,
2510 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2511 err);
2512
2513 if (err.Success())
2514 m_can_jit = eCanJITYes;
2515 else
2516 m_can_jit = eCanJITNo;
2517
2518 DeallocateMemory (allocated_memory);
2519 }
2520
Sean Callanan90539452011-09-20 23:01:51 +00002521 return m_can_jit == eCanJITYes;
2522}
2523
2524void
2525Process::SetCanJIT (bool can_jit)
2526{
2527 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2528}
2529
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002530Error
2531Process::DeallocateMemory (addr_t ptr)
2532{
Greg Claytond495c532011-05-17 03:37:42 +00002533 Error error;
2534#if defined (USE_ALLOCATE_MEMORY_CACHE)
2535 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2536 {
2537 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2538 }
2539#else
2540 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002541
2542 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2543 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002544 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002545 ptr,
2546 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002547 m_mod_id.GetStopID(),
2548 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002549#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002550 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002551}
2552
Han Ming Ongc811d382012-11-17 00:33:14 +00002553
Greg Claytonc9660542012-02-05 02:38:54 +00002554ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002555Process::ReadModuleFromMemory (const FileSpec& file_spec,
2556 lldb::addr_t header_addr,
2557 bool add_image_to_target,
2558 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002559{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002560 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002561 if (module_sp)
2562 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002563 Error error;
2564 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2565 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002566 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002567 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002568 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002569 m_target.GetImages().Append(module_sp);
2570 if (load_sections_in_target)
2571 {
2572 bool changed = false;
2573 module_sp->SetLoadAddress (m_target, 0, changed);
2574 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002575 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002576 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002577 }
Greg Claytonc9660542012-02-05 02:38:54 +00002578 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002579 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002580}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002581
2582Error
Johnny Chen01a67862011-10-14 00:42:25 +00002583Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002584{
2585 Error error;
2586 error.SetErrorString("watchpoints are not supported");
2587 return error;
2588}
2589
2590Error
Johnny Chen01a67862011-10-14 00:42:25 +00002591Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002592{
2593 Error error;
2594 error.SetErrorString("watchpoints are not supported");
2595 return error;
2596}
2597
2598StateType
2599Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2600{
2601 StateType state;
2602 // Now wait for the process to launch and return control to us, and then
2603 // call DidLaunch:
2604 while (1)
2605 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002606 event_sp.reset();
2607 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2608
Greg Clayton2637f822011-11-17 01:23:07 +00002609 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002610 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002611
2612 // If state is invalid, then we timed out
2613 if (state == eStateInvalid)
2614 break;
2615
2616 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002617 HandlePrivateEvent (event_sp);
2618 }
2619 return state;
2620}
2621
2622Error
Greg Clayton982c9762011-11-03 21:22:33 +00002623Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002624{
2625 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002626 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002627 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002628 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002629 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002630
Greg Claytonaa149cb2011-08-11 02:48:45 +00002631 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002632 if (exe_module)
2633 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002634 char local_exec_file_path[PATH_MAX];
2635 char platform_exec_file_path[PATH_MAX];
2636 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2637 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002638 if (exe_module->GetFileSpec().Exists())
2639 {
Greg Clayton71337622011-02-24 22:24:29 +00002640 if (PrivateStateThreadIsValid ())
2641 PausePrivateStateThread ();
2642
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002643 error = WillLaunch (exe_module);
2644 if (error.Success())
2645 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002646 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002647 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002648
Greg Clayton69fd4be2012-09-04 20:29:05 +00002649 if (m_run_lock.WriteTryLock())
2650 {
2651 // Now launch using these arguments.
2652 error = DoLaunch (exe_module, launch_info);
2653 }
2654 else
2655 {
2656 // This shouldn't happen
2657 error.SetErrorString("failed to acquire process run lock");
2658 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002659
2660 if (error.Fail())
2661 {
2662 if (GetID() != LLDB_INVALID_PROCESS_ID)
2663 {
2664 SetID (LLDB_INVALID_PROCESS_ID);
2665 const char *error_string = error.AsCString();
2666 if (error_string == NULL)
2667 error_string = "launch failed";
2668 SetExitStatus (-1, error_string);
2669 }
2670 }
2671 else
2672 {
2673 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002674 TimeValue timeout_time;
2675 timeout_time = TimeValue::Now();
2676 timeout_time.OffsetWithSeconds(10);
2677 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002678
Greg Clayton1a38ea72011-06-22 01:42:17 +00002679 if (state == eStateInvalid || event_sp.get() == NULL)
2680 {
2681 // We were able to launch the process, but we failed to
2682 // catch the initial stop.
2683 SetExitStatus (0, "failed to catch stop after launch");
2684 Destroy();
2685 }
2686 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002687 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002688
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002689 DidLaunch ();
2690
Greg Claytonc859e2d2012-02-13 23:10:39 +00002691 DynamicLoader *dyld = GetDynamicLoader ();
2692 if (dyld)
2693 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002694
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002695 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002696 // This delays passing the stopped event to listeners till DidLaunch gets
2697 // a chance to complete...
2698 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002699
2700 if (PrivateStateThreadIsValid ())
2701 ResumePrivateStateThread ();
2702 else
2703 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002704 }
2705 else if (state == eStateExited)
2706 {
2707 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2708 // not likely to work, and return an invalid pid.
2709 HandlePrivateEvent (event_sp);
2710 }
2711 }
2712 }
2713 }
2714 else
2715 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002716 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717 }
2718 }
2719 return error;
2720}
2721
Greg Claytonc3776bf2012-02-09 06:16:32 +00002722
2723Error
2724Process::LoadCore ()
2725{
2726 Error error = DoLoadCore();
2727 if (error.Success())
2728 {
2729 if (PrivateStateThreadIsValid ())
2730 ResumePrivateStateThread ();
2731 else
2732 StartPrivateStateThread ();
2733
Greg Claytonc859e2d2012-02-13 23:10:39 +00002734 DynamicLoader *dyld = GetDynamicLoader ();
2735 if (dyld)
2736 dyld->DidAttach();
2737
2738 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002739 // We successfully loaded a core file, now pretend we stopped so we can
2740 // show all of the threads in the core file and explore the crashed
2741 // state.
2742 SetPrivateState (eStateStopped);
2743
2744 }
2745 return error;
2746}
2747
Greg Claytonc859e2d2012-02-13 23:10:39 +00002748DynamicLoader *
2749Process::GetDynamicLoader ()
2750{
2751 if (m_dyld_ap.get() == NULL)
2752 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2753 return m_dyld_ap.get();
2754}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002755
2756
Jim Inghambb3a2832011-01-29 01:49:25 +00002757Process::NextEventAction::EventActionResult
2758Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002759{
Jim Inghambb3a2832011-01-29 01:49:25 +00002760 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2761 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002762 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002763 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002764 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002765 return eEventActionRetry;
2766
2767 case eStateStopped:
2768 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002769 {
2770 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002771 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002772 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2773 if (m_exec_count > 0)
2774 {
2775 --m_exec_count;
Jim Ingham3b8285d2012-04-19 01:40:33 +00002776 m_process->PrivateResume ();
Jim Ingham04e0a222012-05-23 15:46:31 +00002777 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Claytonc9ed4782011-11-12 02:10:56 +00002778 return eEventActionRetry;
2779 }
2780 else
2781 {
2782 m_process->CompleteAttach ();
2783 return eEventActionSuccess;
2784 }
2785 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002786 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002787
Greg Clayton513c26c2011-01-29 07:10:55 +00002788 default:
2789 case eStateExited:
2790 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002791 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002792 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002793
2794 m_exit_string.assign ("No valid Process");
2795 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002796}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002797
Jim Inghambb3a2832011-01-29 01:49:25 +00002798Process::NextEventAction::EventActionResult
2799Process::AttachCompletionHandler::HandleBeingInterrupted()
2800{
2801 return eEventActionSuccess;
2802}
2803
2804const char *
2805Process::AttachCompletionHandler::GetExitString ()
2806{
2807 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002808}
2809
2810Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002811Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002812{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002814 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002815 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002816 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002817
Greg Clayton144f3a92011-11-15 03:53:30 +00002818 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002819 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002820 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002821 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002822 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002823
Greg Clayton144f3a92011-11-15 03:53:30 +00002824 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002825 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002826 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2827
2828 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002829 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002830 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2831 if (error.Success())
2832 {
Greg Clayton926cce72012-10-12 16:10:12 +00002833 if (m_run_lock.WriteTryLock())
2834 {
2835 m_should_detach = true;
2836 SetPublicState (eStateAttaching);
2837 // Now attach using these arguments.
2838 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2839 }
2840 else
2841 {
2842 // This shouldn't happen
2843 error.SetErrorString("failed to acquire process run lock");
2844 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00002845
Greg Clayton144f3a92011-11-15 03:53:30 +00002846 if (error.Fail())
2847 {
2848 if (GetID() != LLDB_INVALID_PROCESS_ID)
2849 {
2850 SetID (LLDB_INVALID_PROCESS_ID);
2851 if (error.AsCString() == NULL)
2852 error.SetErrorString("attach failed");
2853
2854 SetExitStatus(-1, error.AsCString());
2855 }
2856 }
2857 else
2858 {
2859 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2860 StartPrivateStateThread();
2861 }
2862 return error;
2863 }
Greg Claytone996fd32011-03-08 22:40:15 +00002864 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002865 else
Greg Claytone996fd32011-03-08 22:40:15 +00002866 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002867 ProcessInstanceInfoList process_infos;
2868 PlatformSP platform_sp (m_target.GetPlatform ());
2869
2870 if (platform_sp)
2871 {
2872 ProcessInstanceInfoMatch match_info;
2873 match_info.GetProcessInfo() = attach_info;
2874 match_info.SetNameMatchType (eNameMatchEquals);
2875 platform_sp->FindProcesses (match_info, process_infos);
2876 const uint32_t num_matches = process_infos.GetSize();
2877 if (num_matches == 1)
2878 {
2879 attach_pid = process_infos.GetProcessIDAtIndex(0);
2880 // Fall through and attach using the above process ID
2881 }
2882 else
2883 {
2884 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2885 if (num_matches > 1)
2886 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2887 else
2888 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2889 }
2890 }
2891 else
2892 {
2893 error.SetErrorString ("invalid platform, can't find processes by name");
2894 return error;
2895 }
Greg Claytone996fd32011-03-08 22:40:15 +00002896 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002897 }
2898 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002899 {
2900 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002901 }
2902 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002903
2904 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002905 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002906 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002907 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002908 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002909
Greg Clayton926cce72012-10-12 16:10:12 +00002910 if (m_run_lock.WriteTryLock())
2911 {
2912 // Now attach using these arguments.
2913 m_should_detach = true;
2914 SetPublicState (eStateAttaching);
2915 error = DoAttachToProcessWithID (attach_pid, attach_info);
2916 }
2917 else
2918 {
2919 // This shouldn't happen
2920 error.SetErrorString("failed to acquire process run lock");
2921 }
2922
Greg Clayton144f3a92011-11-15 03:53:30 +00002923 if (error.Success())
2924 {
2925
2926 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2927 StartPrivateStateThread();
2928 }
2929 else
Greg Claytone996fd32011-03-08 22:40:15 +00002930 {
2931 if (GetID() != LLDB_INVALID_PROCESS_ID)
2932 {
2933 SetID (LLDB_INVALID_PROCESS_ID);
2934 const char *error_string = error.AsCString();
2935 if (error_string == NULL)
2936 error_string = "attach failed";
2937
2938 SetExitStatus(-1, error_string);
2939 }
2940 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002941 }
2942 }
2943 return error;
2944}
2945
Greg Clayton93d3c8332011-02-16 04:46:07 +00002946void
2947Process::CompleteAttach ()
2948{
2949 // Let the process subclass figure out at much as it can about the process
2950 // before we go looking for a dynamic loader plug-in.
2951 DidAttach();
2952
Jim Ingham4299fdb2011-09-15 01:10:17 +00002953 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2954 // the same as the one we've already set, switch architectures.
2955 PlatformSP platform_sp (m_target.GetPlatform ());
2956 assert (platform_sp.get());
2957 if (platform_sp)
2958 {
Greg Clayton70512312012-05-08 01:45:38 +00002959 const ArchSpec &target_arch = m_target.GetArchitecture();
2960 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2961 {
2962 ArchSpec platform_arch;
2963 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2964 if (platform_sp)
2965 {
2966 m_target.SetPlatform (platform_sp);
2967 m_target.SetArchitecture(platform_arch);
2968 }
2969 }
2970 else
2971 {
2972 ProcessInstanceInfo process_info;
2973 platform_sp->GetProcessInfo (GetID(), process_info);
2974 const ArchSpec &process_arch = process_info.GetArchitecture();
2975 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2976 m_target.SetArchitecture (process_arch);
2977 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00002978 }
2979
2980 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002981 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002982 DynamicLoader *dyld = GetDynamicLoader ();
2983 if (dyld)
2984 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002985
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002986 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002987 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00002988 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002989 Mutex::Locker modules_locker(target_modules.GetMutex());
2990 size_t num_modules = target_modules.GetSize();
2991 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002992
Greg Clayton93d3c8332011-02-16 04:46:07 +00002993 for (int i = 0; i < num_modules; i++)
2994 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002995 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002996 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002997 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002998 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002999 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003000 break;
3001 }
3002 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003003 if (new_executable_module_sp)
3004 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003005}
3006
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003007Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003008Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003009{
Greg Claytonb766a732011-02-04 01:58:07 +00003010 m_abi_sp.reset();
3011 m_process_input_reader.reset();
3012
3013 // Find the process and its architecture. Make sure it matches the architecture
3014 // of the current Target, and if not adjust it.
3015
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003016 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003017 if (error.Success())
3018 {
Greg Clayton71337622011-02-24 22:24:29 +00003019 if (GetID() != LLDB_INVALID_PROCESS_ID)
3020 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003021 EventSP event_sp;
3022 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3023
3024 if (state == eStateStopped || state == eStateCrashed)
3025 {
3026 // If we attached and actually have a process on the other end, then
3027 // this ended up being the equivalent of an attach.
3028 CompleteAttach ();
3029
3030 // This delays passing the stopped event to listeners till
3031 // CompleteAttach gets a chance to complete...
3032 HandlePrivateEvent (event_sp);
3033
3034 }
Greg Clayton71337622011-02-24 22:24:29 +00003035 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003036
3037 if (PrivateStateThreadIsValid ())
3038 ResumePrivateStateThread ();
3039 else
3040 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003041 }
3042 return error;
3043}
3044
3045
3046Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003047Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003048{
Jim Ingham46ef1802012-09-06 19:24:17 +00003049 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00003051 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003052 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003053 StateAsCString(m_public_state.GetValue()),
3054 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003055
3056 Error error (WillResume());
3057 // Tell the process it is about to resume before the thread list
3058 if (error.Success())
3059 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003060 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061 // can let all of our threads know that they are about to be
3062 // resumed. Threads will each be called with
3063 // Thread::WillResume(StateType) where StateType contains the state
3064 // that they are supposed to have when the process is resumed
3065 // (suspended/running/stepping). Threads should also check
3066 // their resume signal in lldb::Thread::GetResumeSignal()
3067 // to see if they are suppoed to start back up with a signal.
3068 if (m_thread_list.WillResume())
3069 {
Jim Ingham372787f2012-04-07 00:00:41 +00003070 // Last thing, do the PreResumeActions.
3071 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003072 {
Jim Ingham372787f2012-04-07 00:00:41 +00003073 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3074 }
3075 else
3076 {
3077 m_mod_id.BumpResumeID();
3078 error = DoResume();
3079 if (error.Success())
3080 {
3081 DidResume();
3082 m_thread_list.DidResume();
3083 if (log)
3084 log->Printf ("Process thinks the process has resumed.");
3085 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003086 }
3087 }
3088 else
3089 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003090 // Somebody wanted to run without running. So generate a continue & a stopped event,
3091 // and let the world handle them.
3092 if (log)
3093 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3094
3095 SetPrivateState(eStateRunning);
3096 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003097 }
3098 }
Jim Ingham444586b2011-01-24 06:34:17 +00003099 else if (log)
3100 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003101 return error;
3102}
3103
3104Error
3105Process::Halt ()
3106{
Jim Inghamaacc3182012-06-06 00:29:30 +00003107 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3108 // we could just straightaway get another event. It just narrows the window...
3109 m_currently_handling_event.WaitForValueEqualTo(false);
3110
3111
Jim Inghambb3a2832011-01-29 01:49:25 +00003112 // Pause our private state thread so we can ensure no one else eats
3113 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003114 Listener halt_listener ("lldb.process.halt_listener");
3115 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003116
Jim Inghambb3a2832011-01-29 01:49:25 +00003117 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003118 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003119
Greg Clayton513c26c2011-01-29 07:10:55 +00003120 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003121 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003122
Greg Clayton513c26c2011-01-29 07:10:55 +00003123 bool caused_stop = false;
3124
3125 // Ask the process subclass to actually halt our process
3126 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003127 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003128 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003129 if (m_public_state.GetValue() == eStateAttaching)
3130 {
3131 SetExitStatus(SIGKILL, "Cancelled async attach.");
3132 Destroy ();
3133 }
3134 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003135 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003136 // If "caused_stop" is true, then DoHalt stopped the process. If
3137 // "caused_stop" is false, the process was already stopped.
3138 // If the DoHalt caused the process to stop, then we want to catch
3139 // this event and set the interrupted bool to true before we pass
3140 // this along so clients know that the process was interrupted by
3141 // a halt command.
3142 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003143 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003144 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003145 TimeValue timeout_time;
3146 timeout_time = TimeValue::Now();
3147 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003148 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3149 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003150
Jim Ingham0f16e732011-02-08 05:20:59 +00003151 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003152 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003153 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003154 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003155 }
3156 else
3157 {
Greg Clayton2637f822011-11-17 01:23:07 +00003158 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003159 {
3160 // We caused the process to interrupt itself, so mark this
3161 // as such in the stop event so clients can tell an interrupted
3162 // process from a natural stop
3163 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3164 }
3165 else
3166 {
3167 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3168 if (log)
3169 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3170 error.SetErrorString ("Did not get stopped event after halt.");
3171 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003172 }
3173 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003174 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003175 }
3176 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003177 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003178 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003179 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003180
3181 // Post any event we might have consumed. If all goes well, we will have
3182 // stopped the process, intercepted the event and set the interrupted
3183 // bool in the event. Post it to the private event queue and that will end up
3184 // correctly setting the state.
3185 if (event_sp)
3186 m_private_state_broadcaster.BroadcastEvent(event_sp);
3187
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003188 return error;
3189}
3190
3191Error
3192Process::Detach ()
3193{
3194 Error error (WillDetach());
3195
3196 if (error.Success())
3197 {
3198 DisableAllBreakpointSites();
3199 error = DoDetach();
3200 if (error.Success())
3201 {
3202 DidDetach();
3203 StopPrivateStateThread();
3204 }
3205 }
3206 return error;
3207}
3208
3209Error
3210Process::Destroy ()
3211{
3212 Error error (WillDestroy());
3213 if (error.Success())
3214 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003215 EventSP exit_event_sp;
Jim Ingham04e0a222012-05-23 15:46:31 +00003216 if (m_public_state.GetValue() == eStateRunning)
3217 {
Greg Claytona28d2032012-09-05 00:37:58 +00003218 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003219 if (log)
3220 log->Printf("Process::Destroy() About to halt.");
Jim Ingham04e0a222012-05-23 15:46:31 +00003221 error = Halt();
3222 if (error.Success())
3223 {
3224 // Consume the halt event.
Jim Ingham04e0a222012-05-23 15:46:31 +00003225 TimeValue timeout (TimeValue::Now());
Jim Inghamaacc3182012-06-06 00:29:30 +00003226 timeout.OffsetWithSeconds(1);
Greg Clayton85fb1b92012-09-11 02:33:37 +00003227 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3228 if (state != eStateExited)
3229 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3230
Jim Ingham04e0a222012-05-23 15:46:31 +00003231 if (state != eStateStopped)
3232 {
Jim Ingham04e0a222012-05-23 15:46:31 +00003233 if (log)
3234 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Inghamaacc3182012-06-06 00:29:30 +00003235 // If we really couldn't stop the process then we should just error out here, but if the
3236 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3237 StateType private_state = m_private_state.GetValue();
3238 if (private_state != eStateStopped && private_state != eStateExited)
3239 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003240 // If we exited when we were waiting for a process to stop, then
3241 // forward the event here so we don't lose the event
Jim Inghamaacc3182012-06-06 00:29:30 +00003242 return error;
3243 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003244 }
3245 }
3246 else
3247 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003248 if (log)
3249 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3250 return error;
Jim Ingham04e0a222012-05-23 15:46:31 +00003251 }
3252 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003253
3254 if (m_public_state.GetValue() != eStateRunning)
3255 {
3256 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3257 // kill it, we don't want it hitting a breakpoint...
3258 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3259 // we're not going to have much luck doing this now.
3260 m_thread_list.DiscardThreadPlans();
3261 DisableAllBreakpointSites();
3262 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003263
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003264 error = DoDestroy();
3265 if (error.Success())
3266 {
3267 DidDestroy();
3268 StopPrivateStateThread();
3269 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003270 m_stdio_communication.StopReadThread();
3271 m_stdio_communication.Disconnect();
3272 if (m_process_input_reader && m_process_input_reader->IsActive())
3273 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3274 if (m_process_input_reader)
3275 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003276
3277 // If we exited when we were waiting for a process to stop, then
3278 // forward the event here so we don't lose the event
3279 if (exit_event_sp)
3280 {
3281 // Directly broadcast our exited event because we shut down our
3282 // private state thread above
3283 BroadcastEvent(exit_event_sp);
3284 }
3285
Jim Inghamb1e2e842012-04-12 18:49:31 +00003286 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3287 // the last events through the event system, in which case we might strand the write lock. Unlock
3288 // it here so when we do to tear down the process we don't get an error destroying the lock.
3289 m_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003290 }
3291 return error;
3292}
3293
3294Error
3295Process::Signal (int signal)
3296{
3297 Error error (WillSignal());
3298 if (error.Success())
3299 {
3300 error = DoSignal(signal);
3301 if (error.Success())
3302 DidSignal();
3303 }
3304 return error;
3305}
3306
Greg Clayton514487e2011-02-15 21:59:32 +00003307lldb::ByteOrder
3308Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003309{
Greg Clayton514487e2011-02-15 21:59:32 +00003310 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003311}
3312
3313uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003314Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003315{
Greg Clayton514487e2011-02-15 21:59:32 +00003316 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003317}
3318
Greg Clayton514487e2011-02-15 21:59:32 +00003319
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003320bool
3321Process::ShouldBroadcastEvent (Event *event_ptr)
3322{
3323 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3324 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003325 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003326
3327 switch (state)
3328 {
Greg Claytonb766a732011-02-04 01:58:07 +00003329 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003330 case eStateAttaching:
3331 case eStateLaunching:
3332 case eStateDetached:
3333 case eStateExited:
3334 case eStateUnloaded:
3335 // These events indicate changes in the state of the debugging session, always report them.
3336 return_value = true;
3337 break;
3338 case eStateInvalid:
3339 // We stopped for no apparent reason, don't report it.
3340 return_value = false;
3341 break;
3342 case eStateRunning:
3343 case eStateStepping:
3344 // If we've started the target running, we handle the cases where we
3345 // are already running and where there is a transition from stopped to
3346 // running differently.
3347 // running -> running: Automatically suppress extra running events
3348 // stopped -> running: Report except when there is one or more no votes
3349 // and no yes votes.
3350 SynchronouslyNotifyStateChanged (state);
3351 switch (m_public_state.GetValue())
3352 {
3353 case eStateRunning:
3354 case eStateStepping:
3355 // We always suppress multiple runnings with no PUBLIC stop in between.
3356 return_value = false;
3357 break;
3358 default:
3359 // TODO: make this work correctly. For now always report
3360 // run if we aren't running so we don't miss any runnning
3361 // events. If I run the lldb/test/thread/a.out file and
3362 // break at main.cpp:58, run and hit the breakpoints on
3363 // multiple threads, then somehow during the stepping over
3364 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365
3366 // This is a transition from stop to run.
3367 switch (m_thread_list.ShouldReportRun (event_ptr))
3368 {
Greg Clayton23f59502012-07-17 03:23:13 +00003369 default:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370 case eVoteYes:
3371 case eVoteNoOpinion:
3372 return_value = true;
3373 break;
3374 case eVoteNo:
3375 return_value = false;
3376 break;
3377 }
3378 break;
3379 }
3380 break;
3381 case eStateStopped:
3382 case eStateCrashed:
3383 case eStateSuspended:
3384 {
3385 // We've stopped. First see if we're going to restart the target.
3386 // If we are going to stop, then we always broadcast the event.
3387 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00003388 // If no thread has an opinion, we don't report it.
Jim Inghamcb4ca112012-05-16 01:32:14 +00003389
3390 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003391 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003392 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003393 if (log)
3394 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003395 return true;
3396 }
3397 else
3398 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003399
3400 if (m_thread_list.ShouldStop (event_ptr) == false)
3401 {
Jim Inghamcb95f342012-09-05 21:13:56 +00003402 // ShouldStop may have restarted the target already. If so, don't
3403 // resume it twice.
3404 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003405 switch (m_thread_list.ShouldReportStop (event_ptr))
3406 {
3407 case eVoteYes:
3408 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003409 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003410 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003411 case eVoteNo:
3412 return_value = false;
3413 break;
3414 }
3415
3416 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003417 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Inghamcb95f342012-09-05 21:13:56 +00003418 if (!was_restarted)
3419 PrivateResume ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003420 }
3421 else
3422 {
3423 return_value = true;
3424 SynchronouslyNotifyStateChanged (state);
3425 }
3426 }
3427 }
3428 }
3429
3430 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003431 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003432 return return_value;
3433}
3434
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003435
3436bool
Jim Ingham372787f2012-04-07 00:00:41 +00003437Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003438{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003439 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003440
Greg Clayton8b82f082011-04-12 05:54:46 +00003441 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003442 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003443 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3444
Jim Ingham372787f2012-04-07 00:00:41 +00003445 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003446 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003447
3448 // Create a thread that watches our internal state and controls which
3449 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003450 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003451 if (already_running)
3452 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3453 else
3454 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003455
3456 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003457 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003458 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3459 if (success)
3460 {
3461 ResumePrivateStateThread();
3462 return true;
3463 }
3464 else
3465 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003466}
3467
3468void
3469Process::PausePrivateStateThread ()
3470{
3471 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3472}
3473
3474void
3475Process::ResumePrivateStateThread ()
3476{
3477 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3478}
3479
3480void
3481Process::StopPrivateStateThread ()
3482{
Greg Clayton8b82f082011-04-12 05:54:46 +00003483 if (PrivateStateThreadIsValid ())
3484 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003485 else
3486 {
3487 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3488 if (log)
3489 printf ("Went to stop the private state thread, but it was already invalid.");
3490 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003491}
3492
3493void
3494Process::ControlPrivateStateThread (uint32_t signal)
3495{
Jim Inghamb1e2e842012-04-12 18:49:31 +00003496 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003497
3498 assert (signal == eBroadcastInternalStateControlStop ||
3499 signal == eBroadcastInternalStateControlPause ||
3500 signal == eBroadcastInternalStateControlResume);
3501
3502 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003503 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003504
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003505 // Signal the private state thread. First we should copy this is case the
3506 // thread starts exiting since the private state thread will NULL this out
3507 // when it exits
3508 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003509 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003510 {
3511 TimeValue timeout_time;
3512 bool timed_out;
3513
3514 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3515
3516 timeout_time = TimeValue::Now();
3517 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003518 if (log)
3519 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003520 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3521 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3522
3523 if (signal == eBroadcastInternalStateControlStop)
3524 {
3525 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003526 {
3527 Error error;
3528 Host::ThreadCancel (private_state_thread, &error);
3529 if (log)
3530 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3531 }
3532 else
3533 {
3534 if (log)
3535 log->Printf ("The control event killed the private state thread without having to cancel.");
3536 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003537
3538 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003539 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003540 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003541 }
3542 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003543 else
3544 {
3545 if (log)
3546 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3547 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003548}
3549
3550void
Jim Inghamcfc09352012-07-27 23:57:19 +00003551Process::SendAsyncInterrupt ()
3552{
3553 if (PrivateStateThreadIsValid())
3554 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3555 else
3556 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3557}
3558
3559void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003560Process::HandlePrivateEvent (EventSP &event_sp)
3561{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003562 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003563 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003564
Greg Clayton414f5d32011-01-25 02:58:48 +00003565 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003566
3567 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003568 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003569 {
Jim Ingham754ab982011-01-29 04:05:41 +00003570 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003571 switch (action_result)
3572 {
3573 case NextEventAction::eEventActionSuccess:
3574 SetNextEventAction(NULL);
3575 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003576
Jim Inghambb3a2832011-01-29 01:49:25 +00003577 case NextEventAction::eEventActionRetry:
3578 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003579
Jim Inghambb3a2832011-01-29 01:49:25 +00003580 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003581 // Handle Exiting Here. If we already got an exited event,
3582 // we should just propagate it. Otherwise, swallow this event,
3583 // and set our state to exit so the next event will kill us.
3584 if (new_state != eStateExited)
3585 {
3586 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003587 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003588 SetNextEventAction(NULL);
3589 return;
3590 }
3591 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003592 break;
3593 }
3594 }
3595
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003596 // See if we should broadcast this state to external clients?
3597 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003598
3599 if (should_broadcast)
3600 {
3601 if (log)
3602 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003603 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003604 __FUNCTION__,
3605 GetID(),
3606 StateAsCString(new_state),
3607 StateAsCString (GetState ()),
3608 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003609 }
Jim Ingham9575d842011-03-11 03:53:59 +00003610 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003611 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003612 PushProcessInputReader ();
3613 else
3614 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003615
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003616 BroadcastEvent (event_sp);
3617 }
3618 else
3619 {
3620 if (log)
3621 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003622 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003623 __FUNCTION__,
3624 GetID(),
3625 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003626 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003627 }
3628 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003629 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003630}
3631
3632void *
3633Process::PrivateStateThread (void *arg)
3634{
3635 Process *proc = static_cast<Process*> (arg);
3636 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003637 return result;
3638}
3639
3640void *
3641Process::RunPrivateStateThread ()
3642{
Jim Ingham076b3042012-04-10 01:21:57 +00003643 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003644 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003645
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003646 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003647 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003648 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003649
3650 bool exit_now = false;
3651 while (!exit_now)
3652 {
3653 EventSP event_sp;
3654 WaitForEventsPrivate (NULL, event_sp, control_only);
3655 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3656 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003657 if (log)
3658 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3659
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003660 switch (event_sp->GetType())
3661 {
3662 case eBroadcastInternalStateControlStop:
3663 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003664 break; // doing any internal state managment below
3665
3666 case eBroadcastInternalStateControlPause:
3667 control_only = true;
3668 break;
3669
3670 case eBroadcastInternalStateControlResume:
3671 control_only = false;
3672 break;
3673 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003674
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003675 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003676 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003677 }
Jim Inghamcfc09352012-07-27 23:57:19 +00003678 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3679 {
3680 if (m_public_state.GetValue() == eStateAttaching)
3681 {
3682 if (log)
3683 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3684 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3685 }
3686 else
3687 {
3688 if (log)
3689 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3690 Halt();
3691 }
3692 continue;
3693 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003694
3695 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3696
3697 if (internal_state != eStateInvalid)
3698 {
3699 HandlePrivateEvent (event_sp);
3700 }
3701
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003702 if (internal_state == eStateInvalid ||
3703 internal_state == eStateExited ||
3704 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003705 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003706 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003707 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003708
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003709 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003710 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003711 }
3712
Caroline Tice20ad3c42010-10-29 21:48:37 +00003713 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003714 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003715 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003716
Greg Clayton6ed95942011-01-22 07:12:45 +00003717 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3718 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003719 return NULL;
3720}
3721
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003722//------------------------------------------------------------------
3723// Process Event Data
3724//------------------------------------------------------------------
3725
3726Process::ProcessEventData::ProcessEventData () :
3727 EventData (),
3728 m_process_sp (),
3729 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003730 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003731 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003732 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003733{
3734}
3735
3736Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3737 EventData (),
3738 m_process_sp (process_sp),
3739 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003740 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003741 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003742 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003743{
3744}
3745
3746Process::ProcessEventData::~ProcessEventData()
3747{
3748}
3749
3750const ConstString &
3751Process::ProcessEventData::GetFlavorString ()
3752{
3753 static ConstString g_flavor ("Process::ProcessEventData");
3754 return g_flavor;
3755}
3756
3757const ConstString &
3758Process::ProcessEventData::GetFlavor () const
3759{
3760 return ProcessEventData::GetFlavorString ();
3761}
3762
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003763void
3764Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3765{
3766 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003767 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3768 // the public event queue, then other times when we're pretending that this is where we stopped at the
3769 // end of expression evaluation. m_update_state is used to distinguish these
3770 // three cases; it is 0 when we're just pulling it off for private handling,
3771 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003772
Jim Inghama8604692011-05-22 21:45:01 +00003773 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003774 return;
3775
3776 m_process_sp->SetPublicState (m_state);
3777
3778 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3779 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003780 {
3781 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003782 uint32_t num_threads = curr_thread_list.GetSize();
3783 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003784
Jim Ingham4b536182011-08-09 02:12:22 +00003785 // The actions might change one of the thread's stop_info's opinions about whether we should
3786 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003787
3788 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3789 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3790 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3791 // 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
3792 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003793 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003794 for (idx = 0; idx < num_threads; ++idx)
3795 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3796
Jim Ingham4b536182011-08-09 02:12:22 +00003797 bool still_should_stop = true;
3798
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003799 for (idx = 0; idx < num_threads; ++idx)
3800 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003801 curr_thread_list = m_process_sp->GetThreadList();
3802 if (curr_thread_list.GetSize() != num_threads)
3803 {
3804 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003805 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003806 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003807 break;
3808 }
3809
3810 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3811
3812 if (thread_sp->GetIndexID() != thread_index_array[idx])
3813 {
3814 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003815 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003816 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003817 idx,
3818 thread_index_array[idx],
3819 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003820 break;
3821 }
3822
Jim Inghamb15bfc72010-10-20 00:39:53 +00003823 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00003824 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003825 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003826 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003827 // The stop action might restart the target. If it does, then we want to mark that in the
3828 // event so that whoever is receiving it will know to wait for the running event and reflect
3829 // that state appropriately.
3830 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003831
3832 // FIXME: we might have run.
3833 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003834 {
3835 SetRestarted (true);
3836 break;
3837 }
3838 else if (!stop_info_sp->ShouldStop(event_ptr))
3839 {
3840 still_should_stop = false;
3841 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003842 }
3843 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003844
Jim Ingham4b536182011-08-09 02:12:22 +00003845
3846 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003847 {
Jim Ingham4b536182011-08-09 02:12:22 +00003848 if (!still_should_stop)
3849 {
3850 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003851 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00003852 // Use the public resume method here, since this is just
3853 // extending a public resume.
Jim Ingham4b536182011-08-09 02:12:22 +00003854 m_process_sp->Resume();
3855 }
3856 else
3857 {
3858 // If we didn't restart, run the Stop Hooks here:
3859 // They might also restart the target, so watch for that.
3860 m_process_sp->GetTarget().RunStopHooks();
3861 if (m_process_sp->GetPrivateState() == eStateRunning)
3862 SetRestarted(true);
3863 }
Jim Ingham9575d842011-03-11 03:53:59 +00003864 }
3865
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003866 }
3867}
3868
3869void
3870Process::ProcessEventData::Dump (Stream *s) const
3871{
3872 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003873 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003874
Greg Clayton8b82f082011-04-12 05:54:46 +00003875 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003876}
3877
3878const Process::ProcessEventData *
3879Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3880{
3881 if (event_ptr)
3882 {
3883 const EventData *event_data = event_ptr->GetData();
3884 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3885 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3886 }
3887 return NULL;
3888}
3889
3890ProcessSP
3891Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3892{
3893 ProcessSP process_sp;
3894 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3895 if (data)
3896 process_sp = data->GetProcessSP();
3897 return process_sp;
3898}
3899
3900StateType
3901Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3902{
3903 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3904 if (data == NULL)
3905 return eStateInvalid;
3906 else
3907 return data->GetState();
3908}
3909
3910bool
3911Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3912{
3913 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3914 if (data == NULL)
3915 return false;
3916 else
3917 return data->GetRestarted();
3918}
3919
3920void
3921Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3922{
3923 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3924 if (data != NULL)
3925 data->SetRestarted(new_value);
3926}
3927
3928bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003929Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3930{
3931 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3932 if (data == NULL)
3933 return false;
3934 else
3935 return data->GetInterrupted ();
3936}
3937
3938void
3939Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3940{
3941 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3942 if (data != NULL)
3943 data->SetInterrupted(new_value);
3944}
3945
3946bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003947Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3948{
3949 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3950 if (data)
3951 {
3952 data->SetUpdateStateOnRemoval();
3953 return true;
3954 }
3955 return false;
3956}
3957
Greg Claytond9e416c2012-02-18 05:35:26 +00003958lldb::TargetSP
3959Process::CalculateTarget ()
3960{
3961 return m_target.shared_from_this();
3962}
3963
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003964void
Greg Clayton0603aa92010-10-04 01:05:56 +00003965Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003966{
Greg Claytonc14ee322011-09-22 04:58:26 +00003967 exe_ctx.SetTargetPtr (&m_target);
3968 exe_ctx.SetProcessPtr (this);
3969 exe_ctx.SetThreadPtr(NULL);
3970 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003971}
3972
Greg Claytone996fd32011-03-08 22:40:15 +00003973//uint32_t
3974//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3975//{
3976// return 0;
3977//}
3978//
3979//ArchSpec
3980//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3981//{
3982// return Host::GetArchSpecForExistingProcess (pid);
3983//}
3984//
3985//ArchSpec
3986//Process::GetArchSpecForExistingProcess (const char *process_name)
3987//{
3988// return Host::GetArchSpecForExistingProcess (process_name);
3989//}
3990//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003991void
3992Process::AppendSTDOUT (const char * s, size_t len)
3993{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003994 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003995 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00003996 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003997}
3998
3999void
Greg Clayton93e86192011-11-13 04:45:22 +00004000Process::AppendSTDERR (const char * s, size_t len)
4001{
4002 Mutex::Locker locker (m_stdio_communication_mutex);
4003 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004004 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004005}
4006
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004007void
4008Process::BroadcastAsyncProfileData(const char *s, size_t len)
4009{
4010 Mutex::Locker locker (m_profile_data_comm_mutex);
4011 m_profile_data.append (s, len);
4012 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4013}
4014
4015size_t
4016Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4017{
4018 Mutex::Locker locker(m_profile_data_comm_mutex);
4019 size_t bytes_available = m_profile_data.size();
4020 if (bytes_available > 0)
4021 {
4022 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4023 if (log)
4024 log->Printf ("Process::GetProfileData (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
4025 if (bytes_available > buf_size)
4026 {
4027 memcpy(buf, m_profile_data.c_str(), buf_size);
4028 m_profile_data.erase(0, buf_size);
4029 bytes_available = buf_size;
4030 }
4031 else
4032 {
4033 memcpy(buf, m_profile_data.c_str(), bytes_available);
4034 m_profile_data.clear();
4035 }
4036 }
4037 return bytes_available;
4038}
4039
4040
Greg Clayton93e86192011-11-13 04:45:22 +00004041//------------------------------------------------------------------
4042// Process STDIO
4043//------------------------------------------------------------------
4044
4045size_t
4046Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4047{
4048 Mutex::Locker locker(m_stdio_communication_mutex);
4049 size_t bytes_available = m_stdout_data.size();
4050 if (bytes_available > 0)
4051 {
4052 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4053 if (log)
Greg Clayton43e0af02012-09-18 18:04:04 +00004054 log->Printf ("Process::GetSTDOUT (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004055 if (bytes_available > buf_size)
4056 {
4057 memcpy(buf, m_stdout_data.c_str(), buf_size);
4058 m_stdout_data.erase(0, buf_size);
4059 bytes_available = buf_size;
4060 }
4061 else
4062 {
4063 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4064 m_stdout_data.clear();
4065 }
4066 }
4067 return bytes_available;
4068}
4069
4070
4071size_t
4072Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4073{
4074 Mutex::Locker locker(m_stdio_communication_mutex);
4075 size_t bytes_available = m_stderr_data.size();
4076 if (bytes_available > 0)
4077 {
4078 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4079 if (log)
Greg Clayton43e0af02012-09-18 18:04:04 +00004080 log->Printf ("Process::GetSTDERR (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004081 if (bytes_available > buf_size)
4082 {
4083 memcpy(buf, m_stderr_data.c_str(), buf_size);
4084 m_stderr_data.erase(0, buf_size);
4085 bytes_available = buf_size;
4086 }
4087 else
4088 {
4089 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4090 m_stderr_data.clear();
4091 }
4092 }
4093 return bytes_available;
4094}
4095
4096void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004097Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4098{
4099 Process *process = (Process *) baton;
4100 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4101}
4102
4103size_t
4104Process::ProcessInputReaderCallback (void *baton,
4105 InputReader &reader,
4106 lldb::InputReaderAction notification,
4107 const char *bytes,
4108 size_t bytes_len)
4109{
4110 Process *process = (Process *) baton;
4111
4112 switch (notification)
4113 {
4114 case eInputReaderActivate:
4115 break;
4116
4117 case eInputReaderDeactivate:
4118 break;
4119
4120 case eInputReaderReactivate:
4121 break;
4122
Caroline Tice969ed3d2011-05-02 20:41:46 +00004123 case eInputReaderAsynchronousOutputWritten:
4124 break;
4125
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004126 case eInputReaderGotToken:
4127 {
4128 Error error;
4129 process->PutSTDIN (bytes, bytes_len, error);
4130 }
4131 break;
4132
Caroline Ticeefed6132010-11-19 20:47:54 +00004133 case eInputReaderInterrupt:
4134 process->Halt ();
4135 break;
4136
4137 case eInputReaderEndOfFile:
4138 process->AppendSTDOUT ("^D", 2);
4139 break;
4140
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004141 case eInputReaderDone:
4142 break;
4143
4144 }
4145
4146 return bytes_len;
4147}
4148
4149void
4150Process::ResetProcessInputReader ()
4151{
4152 m_process_input_reader.reset();
4153}
4154
4155void
Greg Claytonee95ed52011-11-17 22:14:31 +00004156Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004157{
4158 // First set up the Read Thread for reading/handling process I/O
4159
4160 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4161
4162 if (conn_ap.get())
4163 {
4164 m_stdio_communication.SetConnection (conn_ap.release());
4165 if (m_stdio_communication.IsConnected())
4166 {
4167 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4168 m_stdio_communication.StartReadThread();
4169
4170 // Now read thread is set up, set up input reader.
4171
4172 if (!m_process_input_reader.get())
4173 {
4174 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4175 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4176 this,
4177 eInputReaderGranularityByte,
4178 NULL,
4179 NULL,
4180 false));
4181
4182 if (err.Fail())
4183 m_process_input_reader.reset();
4184 }
4185 }
4186 }
4187}
4188
4189void
4190Process::PushProcessInputReader ()
4191{
4192 if (m_process_input_reader && !m_process_input_reader->IsActive())
4193 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4194}
4195
4196void
4197Process::PopProcessInputReader ()
4198{
4199 if (m_process_input_reader && m_process_input_reader->IsActive())
4200 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4201}
4202
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004203// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004204void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004205Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004206{
Greg Clayton67cc0632012-08-22 17:17:09 +00004207// static std::vector<OptionEnumValueElement> g_plugins;
4208//
4209// int i=0;
4210// const char *name;
4211// OptionEnumValueElement option_enum;
4212// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4213// {
4214// if (name)
4215// {
4216// option_enum.value = i;
4217// option_enum.string_value = name;
4218// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4219// g_plugins.push_back (option_enum);
4220// }
4221// ++i;
4222// }
4223// option_enum.value = 0;
4224// option_enum.string_value = NULL;
4225// option_enum.usage = NULL;
4226// g_plugins.push_back (option_enum);
4227//
4228// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4229// {
4230// if (::strcmp (name, "plugin") == 0)
4231// {
4232// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4233// break;
4234// }
4235// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004236//
Greg Clayton6920b522012-08-22 18:39:03 +00004237 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004238}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004239
Greg Clayton99d0faf2010-11-18 23:32:35 +00004240void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004241Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004242{
Greg Clayton6920b522012-08-22 18:39:03 +00004243 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004244}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004245
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004246ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004247Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004248 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00004249 bool stop_others,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004250 bool run_others,
Jim Inghamf48169b2010-11-30 02:22:11 +00004251 bool discard_on_error,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004252 uint32_t timeout_usec,
Jim Inghamf48169b2010-11-30 02:22:11 +00004253 Stream &errors)
4254{
4255 ExecutionResults return_value = eExecutionSetupError;
4256
Jim Ingham77787032011-01-20 02:03:18 +00004257 if (thread_plan_sp.get() == NULL)
4258 {
4259 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004260 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004261 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004262
4263 if (exe_ctx.GetProcessPtr() != this)
4264 {
4265 errors.Printf("RunThreadPlan called on wrong process.");
4266 return eExecutionSetupError;
4267 }
4268
4269 Thread *thread = exe_ctx.GetThreadPtr();
4270 if (thread == NULL)
4271 {
4272 errors.Printf("RunThreadPlan called with invalid thread.");
4273 return eExecutionSetupError;
4274 }
Jim Ingham77787032011-01-20 02:03:18 +00004275
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004276 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4277 // For that to be true the plan can't be private - since private plans suppress themselves in the
4278 // GetCompletedPlan call.
4279
4280 bool orig_plan_private = thread_plan_sp->GetPrivate();
4281 thread_plan_sp->SetPrivate(false);
4282
Jim Ingham444586b2011-01-24 06:34:17 +00004283 if (m_private_state.GetValue() != eStateStopped)
4284 {
4285 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004286 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004287 }
4288
Jim Ingham66243842011-08-13 00:56:10 +00004289 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004290 const uint32_t thread_idx_id = thread->GetIndexID();
4291 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004292
4293 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4294 // so we should arrange to reset them as well.
4295
Greg Claytonc14ee322011-09-22 04:58:26 +00004296 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004297
Jim Ingham66243842011-08-13 00:56:10 +00004298 uint32_t selected_tid;
4299 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004300 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004301 {
4302 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004303 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004304 }
4305 else
4306 {
4307 selected_tid = LLDB_INVALID_THREAD_ID;
4308 }
4309
Jim Ingham372787f2012-04-07 00:00:41 +00004310 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004311 lldb::StateType old_state;
4312 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004313
Jim Ingham076b3042012-04-10 01:21:57 +00004314 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004315 if (Host::GetCurrentThread() == m_private_state_thread)
4316 {
Jim Ingham076b3042012-04-10 01:21:57 +00004317 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4318 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004319 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Ingham076b3042012-04-10 01:21:57 +00004320 // we are fielding public events here.
4321 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004322 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
Jim Ingham076b3042012-04-10 01:21:57 +00004323
4324
Jim Ingham372787f2012-04-07 00:00:41 +00004325 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004326
4327 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4328 // returning control here.
4329 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4330 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4331 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4332 // do just what we want.
4333 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4334 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4335 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4336 old_state = m_public_state.GetValue();
4337 m_public_state.SetValueNoLock(eStateStopped);
4338
4339 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004340 StartPrivateStateThread(true);
4341 }
4342
4343 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004344
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004345 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004346
Sean Callanana46ec452012-07-11 21:31:24 +00004347 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004348
Jim Ingham77787032011-01-20 02:03:18 +00004349 {
Sean Callanana46ec452012-07-11 21:31:24 +00004350 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4351 // restored on exit to the function.
4352 //
4353 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4354 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004355
Sean Callanana46ec452012-07-11 21:31:24 +00004356 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004357
Jim Inghamf48169b2010-11-30 02:22:11 +00004358 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004359 {
4360 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004361 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4362 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4363 thread->GetIndexID(),
4364 thread->GetID(),
4365 s.GetData());
4366 }
4367
4368 bool got_event;
4369 lldb::EventSP event_sp;
4370 lldb::StateType stop_state = lldb::eStateInvalid;
4371
4372 TimeValue* timeout_ptr = NULL;
4373 TimeValue real_timeout;
4374
4375 bool first_timeout = true;
4376 bool do_resume = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004377 const uint64_t default_one_thread_timeout_usec = 250000;
4378 uint64_t computed_timeout = 0;
Sean Callanana46ec452012-07-11 21:31:24 +00004379
Jim Ingham8559a352012-11-26 23:52:18 +00004380 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4381 // So don't call return anywhere within it.
4382
Sean Callanana46ec452012-07-11 21:31:24 +00004383 while (1)
4384 {
4385 // We usually want to resume the process if we get to the top of the loop.
4386 // The only exception is if we get two running events with no intervening
4387 // stop, which can happen, we will just wait for then next stop event.
4388
4389 if (do_resume)
4390 {
4391 // Do the initial resume and wait for the running event before going further.
4392
4393 Error resume_error = PrivateResume ();
4394 if (!resume_error.Success())
4395 {
4396 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4397 return_value = eExecutionSetupError;
4398 break;
4399 }
4400
4401 real_timeout = TimeValue::Now();
4402 real_timeout.OffsetWithMicroSeconds(500000);
4403 timeout_ptr = &real_timeout;
4404
4405 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4406 if (!got_event)
4407 {
4408 if (log)
4409 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4410
4411 errors.Printf("Didn't get any event after initial resume, exiting.");
4412 return_value = eExecutionSetupError;
4413 break;
4414 }
4415
4416 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4417 if (stop_state != eStateRunning)
4418 {
4419 if (log)
Jim Ingham35e1bda2012-10-16 21:41:58 +00004420 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4421 "initial resume, got %s instead.",
4422 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004423
Jim Ingham35e1bda2012-10-16 21:41:58 +00004424 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4425 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004426 return_value = eExecutionSetupError;
4427 break;
4428 }
4429
4430 if (log)
4431 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4432 // We need to call the function synchronously, so spin waiting for it to return.
4433 // If we get interrupted while executing, we're going to lose our context, and
4434 // won't be able to gather the result at this point.
4435 // We set the timeout AFTER the resume, since the resume takes some time and we
4436 // don't want to charge that to the timeout.
4437
Jim Ingham35e1bda2012-10-16 21:41:58 +00004438 if (first_timeout)
4439 {
4440 if (run_others)
4441 {
4442 // If we are running all threads then we take half the time to run all threads, bounded by
4443 // .25 sec.
4444 if (timeout_usec == 0)
4445 computed_timeout = default_one_thread_timeout_usec;
4446 else
4447 {
4448 computed_timeout = timeout_usec / 2;
4449 if (computed_timeout > default_one_thread_timeout_usec)
4450 {
4451 computed_timeout = default_one_thread_timeout_usec;
4452 }
4453 timeout_usec -= computed_timeout;
4454 }
4455 }
4456 else
4457 {
4458 computed_timeout = timeout_usec;
4459 }
4460 }
4461 else
4462 {
4463 computed_timeout = timeout_usec;
4464 }
4465
4466 if (computed_timeout != 0)
Sean Callanana46ec452012-07-11 21:31:24 +00004467 {
Enrico Granata3372f582012-07-16 23:10:35 +00004468 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanana46ec452012-07-11 21:31:24 +00004469 real_timeout = TimeValue::Now();
Jim Ingham35e1bda2012-10-16 21:41:58 +00004470 real_timeout.OffsetWithMicroSeconds(computed_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00004471
4472 timeout_ptr = &real_timeout;
4473 }
Enrico Granata3372f582012-07-16 23:10:35 +00004474 else
4475 {
Jim Ingham35e1bda2012-10-16 21:41:58 +00004476 timeout_ptr = NULL;
Enrico Granata3372f582012-07-16 23:10:35 +00004477 }
Sean Callanana46ec452012-07-11 21:31:24 +00004478 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004479 else
4480 {
Sean Callanana46ec452012-07-11 21:31:24 +00004481 if (log)
4482 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4483 do_resume = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00004484 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004485
Sean Callanana46ec452012-07-11 21:31:24 +00004486 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00004487 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00004488
Jim Ingham0f16e732011-02-08 05:20:59 +00004489 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004490 {
Sean Callanana46ec452012-07-11 21:31:24 +00004491 if (timeout_ptr)
4492 {
4493 StreamString s;
4494 s.Printf ("about to wait - timeout is:\n ");
4495 timeout_ptr->Dump (&s, 120);
4496 s.Printf ("\nNow is:\n ");
4497 TimeValue::Now().Dump (&s, 120);
4498 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4499 }
Jim Ingham20829ac2011-08-09 22:24:33 +00004500 else
Sean Callanana46ec452012-07-11 21:31:24 +00004501 {
4502 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4503 }
4504 }
4505
4506 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4507
4508 if (got_event)
4509 {
4510 if (event_sp.get())
4511 {
4512 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00004513 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004514 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004515 Halt();
4516 keep_going = false;
4517 return_value = eExecutionInterrupted;
4518 errors.Printf ("Execution halted by user interrupt.");
4519 if (log)
4520 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4521 }
4522 else
4523 {
4524 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4525 if (log)
4526 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4527
4528 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00004529 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004530 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00004531 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004532 // Yay, we're done. Now make sure that our thread plan actually completed.
4533 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4534 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004535 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004536 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00004537 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00004538 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4539 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00004540 }
4541 else
4542 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004543 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4544 StopReason stop_reason = eStopReasonInvalid;
4545 if (stop_info_sp)
4546 stop_reason = stop_info_sp->GetStopReason();
4547 if (stop_reason == eStopReasonPlanComplete)
4548 {
4549 if (log)
4550 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4551 // Now mark this plan as private so it doesn't get reported as the stop reason
4552 // after this point.
4553 if (thread_plan_sp)
4554 thread_plan_sp->SetPrivate (orig_plan_private);
4555 return_value = eExecutionCompleted;
4556 }
4557 else
4558 {
4559 if (log)
4560 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanana46ec452012-07-11 21:31:24 +00004561
Jim Inghamcfc09352012-07-27 23:57:19 +00004562 return_value = eExecutionInterrupted;
4563 }
Sean Callanana46ec452012-07-11 21:31:24 +00004564 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004565 }
4566 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004567
Jim Inghamcfc09352012-07-27 23:57:19 +00004568 case lldb::eStateCrashed:
4569 if (log)
4570 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4571 return_value = eExecutionInterrupted;
4572 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004573
Jim Inghamcfc09352012-07-27 23:57:19 +00004574 case lldb::eStateRunning:
4575 do_resume = false;
4576 keep_going = true;
4577 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004578
Jim Inghamcfc09352012-07-27 23:57:19 +00004579 default:
4580 if (log)
4581 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4582
4583 if (stop_state == eStateExited)
4584 event_to_broadcast_sp = event_sp;
4585
Sean Callananbf154da2012-08-08 17:35:10 +00004586 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00004587 return_value = eExecutionInterrupted;
4588 break;
4589 }
Sean Callanana46ec452012-07-11 21:31:24 +00004590 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004591
Sean Callanana46ec452012-07-11 21:31:24 +00004592 if (keep_going)
4593 continue;
4594 else
4595 break;
4596 }
4597 else
4598 {
4599 if (log)
4600 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4601 return_value = eExecutionInterrupted;
4602 break;
4603 }
4604 }
4605 else
4606 {
4607 // If we didn't get an event that means we've timed out...
4608 // We will interrupt the process here. Depending on what we were asked to do we will
4609 // either exit, or try with all threads running for the same timeout.
4610 // Not really sure what to do if Halt fails here...
4611
4612 if (log) {
Jim Ingham35e1bda2012-10-16 21:41:58 +00004613 if (run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00004614 {
4615 if (first_timeout)
Jim Ingham35e1bda2012-10-16 21:41:58 +00004616 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %lld timed out, "
4617 "trying for %d usec with all threads enabled.",
4618 computed_timeout, timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004619 else
4620 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham35e1bda2012-10-16 21:41:58 +00004621 "and timeout: %d timed out, abandoning execution.",
4622 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004623 }
4624 else
4625 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00004626 "abandoning execution.",
4627 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004628 }
4629
4630 Error halt_error = Halt();
4631 if (halt_error.Success())
4632 {
4633 if (log)
4634 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4635
4636 // If halt succeeds, it always produces a stopped event. Wait for that:
4637
4638 real_timeout = TimeValue::Now();
4639 real_timeout.OffsetWithMicroSeconds(500000);
4640
4641 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4642
4643 if (got_event)
4644 {
4645 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4646 if (log)
4647 {
4648 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4649 if (stop_state == lldb::eStateStopped
4650 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4651 log->PutCString (" Event was the Halt interruption event.");
4652 }
4653
4654 if (stop_state == lldb::eStateStopped)
4655 {
4656 // Between the time we initiated the Halt and the time we delivered it, the process could have
4657 // already finished its job. Check that here:
4658
4659 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4660 {
4661 if (log)
4662 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4663 "Exiting wait loop.");
4664 return_value = eExecutionCompleted;
4665 break;
4666 }
4667
Jim Ingham35e1bda2012-10-16 21:41:58 +00004668 if (!run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00004669 {
4670 if (log)
4671 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4672 return_value = eExecutionInterrupted;
4673 break;
4674 }
4675
4676 if (first_timeout)
4677 {
4678 // Set all the other threads to run, and return to the top of the loop, which will continue;
4679 first_timeout = false;
4680 thread_plan_sp->SetStopOthers (false);
4681 if (log)
4682 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4683
4684 continue;
4685 }
4686 else
4687 {
4688 // Running all threads failed, so return Interrupted.
4689 if (log)
4690 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4691 return_value = eExecutionInterrupted;
4692 break;
4693 }
4694 }
4695 }
4696 else
4697 { if (log)
4698 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4699 "I'm getting out of here passing Interrupted.");
4700 return_value = eExecutionInterrupted;
4701 break;
4702 }
4703 }
4704 else
4705 {
4706 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4707 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4708 if (log)
4709 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.",
4710 halt_error.AsCString());
4711 real_timeout = TimeValue::Now();
4712 real_timeout.OffsetWithMicroSeconds(500000);
4713 timeout_ptr = &real_timeout;
4714 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4715 if (!got_event || event_sp.get() == NULL)
4716 {
4717 // This is not going anywhere, bag out.
4718 if (log)
4719 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4720 return_value = eExecutionInterrupted;
4721 break;
4722 }
4723 else
4724 {
4725 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4726 if (log)
4727 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4728 if (stop_state == lldb::eStateStopped)
4729 {
4730 // Between the time we initiated the Halt and the time we delivered it, the process could have
4731 // already finished its job. Check that here:
4732
4733 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4734 {
4735 if (log)
4736 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4737 "Exiting wait loop.");
4738 return_value = eExecutionCompleted;
4739 break;
4740 }
4741
4742 if (first_timeout)
4743 {
4744 // Set all the other threads to run, and return to the top of the loop, which will continue;
4745 first_timeout = false;
4746 thread_plan_sp->SetStopOthers (false);
4747 if (log)
4748 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4749
4750 continue;
4751 }
4752 else
4753 {
4754 // Running all threads failed, so return Interrupted.
4755 if (log)
4756 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4757 return_value = eExecutionInterrupted;
4758 break;
4759 }
4760 }
4761 else
4762 {
4763 if (log)
4764 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4765 " a stopped event, instead got %s.", StateAsCString(stop_state));
4766 return_value = eExecutionInterrupted;
4767 break;
4768 }
4769 }
4770 }
4771
4772 }
4773
4774 } // END WAIT LOOP
4775
4776 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4777 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4778 {
4779 StopPrivateStateThread();
4780 Error error;
4781 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00004782 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004783 {
4784 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4785 }
4786 m_public_state.SetValueNoLock(old_state);
4787
4788 }
4789
Jim Ingham8559a352012-11-26 23:52:18 +00004790 // Restore the thread state if we are going to discard the plan execution.
4791
4792 if (return_value == eExecutionCompleted || discard_on_error)
4793 {
4794 thread_plan_sp->RestoreThreadState();
4795 }
Sean Callanana46ec452012-07-11 21:31:24 +00004796
4797 // Now do some processing on the results of the run:
4798 if (return_value == eExecutionInterrupted)
4799 {
4800 if (log)
4801 {
4802 StreamString s;
4803 if (event_sp)
4804 event_sp->Dump (&s);
4805 else
4806 {
4807 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4808 }
4809
4810 StreamString ts;
4811
4812 const char *event_explanation = NULL;
4813
4814 do
4815 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004816 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004817 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004818 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00004819 break;
4820 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004821 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004822 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004823 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00004824 break;
4825 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004826 else
Sean Callanana46ec452012-07-11 21:31:24 +00004827 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004828 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4829
4830 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00004831 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004832 event_explanation = "<no event data>";
4833 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004834 }
4835
Jim Inghamcfc09352012-07-27 23:57:19 +00004836 Process *process = event_data->GetProcessSP().get();
4837
4838 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00004839 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004840 event_explanation = "<no process>";
4841 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004842 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004843
4844 ThreadList &thread_list = process->GetThreadList();
4845
4846 uint32_t num_threads = thread_list.GetSize();
4847 uint32_t thread_index;
4848
4849 ts.Printf("<%u threads> ", num_threads);
4850
4851 for (thread_index = 0;
4852 thread_index < num_threads;
4853 ++thread_index)
4854 {
4855 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4856
4857 if (!thread)
4858 {
4859 ts.Printf("<?> ");
4860 continue;
4861 }
4862
4863 ts.Printf("<0x%4.4llx ", thread->GetID());
4864 RegisterContext *register_context = thread->GetRegisterContext().get();
4865
4866 if (register_context)
4867 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4868 else
4869 ts.Printf("[ip unknown] ");
4870
4871 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4872 if (stop_info_sp)
4873 {
4874 const char *stop_desc = stop_info_sp->GetDescription();
4875 if (stop_desc)
4876 ts.PutCString (stop_desc);
4877 }
4878 ts.Printf(">");
4879 }
4880
4881 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00004882 }
Sean Callanana46ec452012-07-11 21:31:24 +00004883 } while (0);
4884
Jim Inghamcfc09352012-07-27 23:57:19 +00004885 if (event_explanation)
4886 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00004887 else
Jim Inghamcfc09352012-07-27 23:57:19 +00004888 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4889 }
4890
4891 if (discard_on_error && thread_plan_sp)
4892 {
4893 if (log)
4894 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4895 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4896 thread_plan_sp->SetPrivate (orig_plan_private);
4897 }
4898 else
4899 {
4900 if (log)
4901 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00004902 }
4903 }
4904 else if (return_value == eExecutionSetupError)
4905 {
4906 if (log)
4907 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004908
4909 if (discard_on_error && thread_plan_sp)
4910 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004911 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004912 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004913 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004914 }
4915 else
4916 {
Sean Callanana46ec452012-07-11 21:31:24 +00004917 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004918 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004919 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00004920 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4921 return_value = eExecutionCompleted;
4922 }
4923 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4924 {
4925 if (log)
4926 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4927 return_value = eExecutionDiscarded;
4928 }
4929 else
4930 {
4931 if (log)
4932 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4933 if (discard_on_error && thread_plan_sp)
4934 {
4935 if (log)
4936 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4937 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4938 thread_plan_sp->SetPrivate (orig_plan_private);
4939 }
4940 }
4941 }
4942
4943 // Thread we ran the function in may have gone away because we ran the target
4944 // Check that it's still there, and if it is put it back in the context. Also restore the
4945 // frame in the context if it is still present.
4946 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4947 if (thread)
4948 {
4949 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4950 }
4951
4952 // Also restore the current process'es selected frame & thread, since this function calling may
4953 // be done behind the user's back.
4954
4955 if (selected_tid != LLDB_INVALID_THREAD_ID)
4956 {
4957 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4958 {
4959 // We were able to restore the selected thread, now restore the frame:
4960 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4961 if (old_frame_sp)
4962 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004963 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004964 }
4965 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004966
Sean Callanana46ec452012-07-11 21:31:24 +00004967 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00004968
Sean Callanana46ec452012-07-11 21:31:24 +00004969 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004970 {
Sean Callanana46ec452012-07-11 21:31:24 +00004971 if (log)
4972 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4973 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004974 }
4975
4976 return return_value;
4977}
4978
4979const char *
4980Process::ExecutionResultAsCString (ExecutionResults result)
4981{
4982 const char *result_name;
4983
4984 switch (result)
4985 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004986 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004987 result_name = "eExecutionCompleted";
4988 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004989 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004990 result_name = "eExecutionDiscarded";
4991 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004992 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004993 result_name = "eExecutionInterrupted";
4994 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004995 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004996 result_name = "eExecutionSetupError";
4997 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004998 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004999 result_name = "eExecutionTimedOut";
5000 break;
5001 }
5002 return result_name;
5003}
5004
Greg Clayton7260f622011-04-18 08:33:37 +00005005void
5006Process::GetStatus (Stream &strm)
5007{
5008 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005009 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005010 {
5011 if (state == eStateExited)
5012 {
5013 int exit_status = GetExitStatus();
5014 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00005015 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005016 GetID(),
5017 exit_status,
5018 exit_status,
5019 exit_description ? exit_description : "");
5020 }
5021 else
5022 {
5023 if (state == eStateConnected)
5024 strm.Printf ("Connected to remote target.\n");
5025 else
Greg Clayton81c22f62011-10-19 18:09:39 +00005026 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005027 }
5028 }
5029 else
5030 {
Greg Clayton81c22f62011-10-19 18:09:39 +00005031 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005032 }
5033}
5034
5035size_t
5036Process::GetThreadStatus (Stream &strm,
5037 bool only_threads_with_stop_reason,
5038 uint32_t start_frame,
5039 uint32_t num_frames,
5040 uint32_t num_frames_with_source)
5041{
5042 size_t num_thread_infos_dumped = 0;
5043
Jim Ingham41f2b942012-09-10 20:50:15 +00005044 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005045 const size_t num_threads = GetThreadList().GetSize();
5046 for (uint32_t i = 0; i < num_threads; i++)
5047 {
5048 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5049 if (thread)
5050 {
5051 if (only_threads_with_stop_reason)
5052 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005053 StopInfoSP stop_info_sp = thread->GetStopInfo();
5054 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005055 continue;
5056 }
5057 thread->GetStatus (strm,
5058 start_frame,
5059 num_frames,
5060 num_frames_with_source);
5061 ++num_thread_infos_dumped;
5062 }
5063 }
5064 return num_thread_infos_dumped;
5065}
5066
Greg Claytona9f40ad2012-02-22 04:37:26 +00005067void
5068Process::AddInvalidMemoryRegion (const LoadRange &region)
5069{
5070 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5071}
5072
5073bool
5074Process::RemoveInvalidMemoryRange (const LoadRange &region)
5075{
5076 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5077}
5078
Jim Ingham372787f2012-04-07 00:00:41 +00005079void
5080Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5081{
5082 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5083}
5084
5085bool
5086Process::RunPreResumeActions ()
5087{
5088 bool result = true;
5089 while (!m_pre_resume_actions.empty())
5090 {
5091 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5092 m_pre_resume_actions.pop_back();
5093 bool this_result = action.callback (action.baton);
5094 if (result == true) result = this_result;
5095 }
5096 return result;
5097}
5098
5099void
5100Process::ClearPreResumeActions ()
5101{
5102 m_pre_resume_actions.clear();
5103}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005104
Greg Claytonfa559e52012-05-18 02:38:05 +00005105void
5106Process::Flush ()
5107{
5108 m_thread_list.Flush();
5109}