blob: ee6fd27ae62b25d2021f2ffd91b6f59d2862849f [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 (),
Greg Claytond495c532011-05-17 03:37:42 +0000956 m_memory_cache (*this),
957 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000958 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000959 m_next_event_action_ap(),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000960 m_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000961 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000962 m_finalize_called(false),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000963 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000965 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000966
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000967 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968 if (log)
969 log->Printf ("%p Process::Process()", this);
970
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000971 SetEventName (eBroadcastBitStateChanged, "state-changed");
972 SetEventName (eBroadcastBitInterrupt, "interrupt");
973 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
974 SetEventName (eBroadcastBitSTDERR, "stderr-available");
975
Greg Clayton35a4cc52012-10-29 20:52:08 +0000976 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
977 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
978 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
979
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980 listener.StartListeningForEvents (this,
981 eBroadcastBitStateChanged |
982 eBroadcastBitInterrupt |
983 eBroadcastBitSTDOUT |
984 eBroadcastBitSTDERR);
985
986 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000987 eBroadcastBitStateChanged |
988 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989
990 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
991 eBroadcastInternalStateControlStop |
992 eBroadcastInternalStateControlPause |
993 eBroadcastInternalStateControlResume);
994}
995
996//----------------------------------------------------------------------
997// Destructor
998//----------------------------------------------------------------------
999Process::~Process()
1000{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001001 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002 if (log)
1003 log->Printf ("%p Process::~Process()", this);
1004 StopPrivateStateThread();
1005}
1006
Greg Clayton67cc0632012-08-22 17:17:09 +00001007const ProcessPropertiesSP &
1008Process::GetGlobalProperties()
1009{
1010 static ProcessPropertiesSP g_settings_sp;
1011 if (!g_settings_sp)
1012 g_settings_sp.reset (new ProcessProperties (true));
1013 return g_settings_sp;
1014}
1015
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016void
1017Process::Finalize()
1018{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001019 switch (GetPrivateState())
1020 {
1021 case eStateConnected:
1022 case eStateAttaching:
1023 case eStateLaunching:
1024 case eStateStopped:
1025 case eStateRunning:
1026 case eStateStepping:
1027 case eStateCrashed:
1028 case eStateSuspended:
1029 if (GetShouldDetach())
1030 Detach();
1031 else
1032 Destroy();
1033 break;
1034
1035 case eStateInvalid:
1036 case eStateUnloaded:
1037 case eStateDetached:
1038 case eStateExited:
1039 break;
1040 }
1041
Greg Clayton1ed54f52011-10-01 00:45:15 +00001042 // Clear our broadcaster before we proceed with destroying
1043 Broadcaster::Clear();
1044
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045 // Do any cleanup needed prior to being destructed... Subclasses
1046 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001047
1048 // We need to destroy the loader before the derived Process class gets destroyed
1049 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001050 m_dynamic_checkers_ap.reset();
1051 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001052 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001053 m_dyld_ap.reset();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001054 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +00001055 std::vector<Notifications> empty_notifications;
1056 m_notifications.swap(empty_notifications);
1057 m_image_tokens.clear();
1058 m_memory_cache.Clear();
1059 m_allocated_memory_cache.Clear();
1060 m_language_runtimes.clear();
1061 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001062//#ifdef LLDB_CONFIGURATION_DEBUG
1063// StreamFile s(stdout, false);
1064// EventSP event_sp;
1065// while (m_private_state_listener.GetNextEvent(event_sp))
1066// {
1067// event_sp->Dump (&s);
1068// s.EOL();
1069// }
1070//#endif
1071 // We have to be very careful here as the m_private_state_listener might
1072 // contain events that have ProcessSP values in them which can keep this
1073 // process around forever. These events need to be cleared out.
1074 m_private_state_listener.Clear();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001075 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076}
1077
1078void
1079Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1080{
1081 m_notifications.push_back(callbacks);
1082 if (callbacks.initialize != NULL)
1083 callbacks.initialize (callbacks.baton, this);
1084}
1085
1086bool
1087Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1088{
1089 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1090 for (pos = m_notifications.begin(); pos != end; ++pos)
1091 {
1092 if (pos->baton == callbacks.baton &&
1093 pos->initialize == callbacks.initialize &&
1094 pos->process_state_changed == callbacks.process_state_changed)
1095 {
1096 m_notifications.erase(pos);
1097 return true;
1098 }
1099 }
1100 return false;
1101}
1102
1103void
1104Process::SynchronouslyNotifyStateChanged (StateType state)
1105{
1106 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1107 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1108 {
1109 if (notification_pos->process_state_changed)
1110 notification_pos->process_state_changed (notification_pos->baton, this, state);
1111 }
1112}
1113
1114// FIXME: We need to do some work on events before the general Listener sees them.
1115// For instance if we are continuing from a breakpoint, we need to ensure that we do
1116// the little "insert real insn, step & stop" trick. But we can't do that when the
1117// event is delivered by the broadcaster - since that is done on the thread that is
1118// waiting for new events, so if we needed more than one event for our handling, we would
1119// stall. So instead we do it when we fetch the event off of the queue.
1120//
1121
1122StateType
1123Process::GetNextEvent (EventSP &event_sp)
1124{
1125 StateType state = eStateInvalid;
1126
1127 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1128 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1129
1130 return state;
1131}
1132
1133
1134StateType
Greg Clayton85fb1b92012-09-11 02:33:37 +00001135Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001136{
Jim Ingham4b536182011-08-09 02:12:22 +00001137 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1138 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1139 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001140 if (event_sp_ptr)
1141 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001142 StateType state = GetState();
1143 // If we are exited or detached, we won't ever get back to any
1144 // other valid state...
1145 if (state == eStateDetached || state == eStateExited)
1146 return state;
1147
1148 while (state != eStateInvalid)
1149 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001150 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001151 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001152 if (event_sp_ptr && event_sp)
1153 *event_sp_ptr = event_sp;
1154
Jim Ingham4b536182011-08-09 02:12:22 +00001155 switch (state)
1156 {
1157 case eStateCrashed:
1158 case eStateDetached:
1159 case eStateExited:
1160 case eStateUnloaded:
1161 return state;
1162 case eStateStopped:
1163 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1164 continue;
1165 else
1166 return state;
1167 default:
1168 continue;
1169 }
1170 }
1171 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001172}
1173
1174
1175StateType
1176Process::WaitForState
1177(
1178 const TimeValue *timeout,
1179 const StateType *match_states, const uint32_t num_match_states
1180)
1181{
1182 EventSP event_sp;
1183 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001184 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001185 while (state != eStateInvalid)
1186 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001187 // If we are exited or detached, we won't ever get back to any
1188 // other valid state...
1189 if (state == eStateDetached || state == eStateExited)
1190 return state;
1191
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192 state = WaitForStateChangedEvents (timeout, event_sp);
1193
1194 for (i=0; i<num_match_states; ++i)
1195 {
1196 if (match_states[i] == state)
1197 return state;
1198 }
1199 }
1200 return state;
1201}
1202
Jim Ingham30f9b212010-10-11 23:53:14 +00001203bool
1204Process::HijackProcessEvents (Listener *listener)
1205{
1206 if (listener != NULL)
1207 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001208 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001209 }
1210 else
1211 return false;
1212}
1213
1214void
1215Process::RestoreProcessEvents ()
1216{
1217 RestoreBroadcaster();
1218}
1219
Jim Ingham0f16e732011-02-08 05:20:59 +00001220bool
1221Process::HijackPrivateProcessEvents (Listener *listener)
1222{
1223 if (listener != NULL)
1224 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001225 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001226 }
1227 else
1228 return false;
1229}
1230
1231void
1232Process::RestorePrivateProcessEvents ()
1233{
1234 m_private_state_broadcaster.RestoreBroadcaster();
1235}
1236
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001237StateType
1238Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1239{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001240 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001241
1242 if (log)
1243 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1244
1245 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001246 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1247 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001248 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001249 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001250 {
1251 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1252 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1253 else if (log)
1254 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1255 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001256
1257 if (log)
1258 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1259 __FUNCTION__,
1260 timeout,
1261 StateAsCString(state));
1262 return state;
1263}
1264
1265Event *
1266Process::PeekAtStateChangedEvents ()
1267{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001268 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001269
1270 if (log)
1271 log->Printf ("Process::%s...", __FUNCTION__);
1272
1273 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001274 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1275 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001276 if (log)
1277 {
1278 if (event_ptr)
1279 {
1280 log->Printf ("Process::%s (event_ptr) => %s",
1281 __FUNCTION__,
1282 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1283 }
1284 else
1285 {
1286 log->Printf ("Process::%s no events found",
1287 __FUNCTION__);
1288 }
1289 }
1290 return event_ptr;
1291}
1292
1293StateType
1294Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1295{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001296 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001297
1298 if (log)
1299 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1300
1301 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001302 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1303 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001304 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001305 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001306 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1307 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001308
1309 // This is a bit of a hack, but when we wait here we could very well return
1310 // to the command-line, and that could disable the log, which would render the
1311 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001312 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001313 {
1314 if (state == eStateInvalid)
1315 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1316 else
1317 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1318 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001319 return state;
1320}
1321
1322bool
1323Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1324{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001325 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001326
1327 if (log)
1328 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1329
1330 if (control_only)
1331 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1332 else
1333 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1334}
1335
1336bool
1337Process::IsRunning () const
1338{
1339 return StateIsRunningState (m_public_state.GetValue());
1340}
1341
1342int
1343Process::GetExitStatus ()
1344{
1345 if (m_public_state.GetValue() == eStateExited)
1346 return m_exit_status;
1347 return -1;
1348}
1349
Greg Clayton85851dd2010-12-04 00:10:17 +00001350
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001351const char *
1352Process::GetExitDescription ()
1353{
1354 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1355 return m_exit_string.c_str();
1356 return NULL;
1357}
1358
Greg Clayton6779606a2011-01-22 23:43:18 +00001359bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001360Process::SetExitStatus (int status, const char *cstr)
1361{
Greg Clayton414f5d32011-01-25 02:58:48 +00001362 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1363 if (log)
1364 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1365 status, status,
1366 cstr ? "\"" : "",
1367 cstr ? cstr : "NULL",
1368 cstr ? "\"" : "");
1369
Greg Clayton6779606a2011-01-22 23:43:18 +00001370 // We were already in the exited state
1371 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001372 {
Greg Clayton385d6032011-01-26 23:47:29 +00001373 if (log)
1374 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001375 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001376 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001377
1378 m_exit_status = status;
1379 if (cstr)
1380 m_exit_string = cstr;
1381 else
1382 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001383
Greg Clayton6779606a2011-01-22 23:43:18 +00001384 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001385
Greg Clayton6779606a2011-01-22 23:43:18 +00001386 SetPrivateState (eStateExited);
1387 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001388}
1389
1390// This static callback can be used to watch for local child processes on
1391// the current host. The the child process exits, the process will be
1392// found in the global target list (we want to be completely sure that the
1393// lldb_private::Process doesn't go away before we can deliver the signal.
1394bool
Greg Claytone4e45922011-11-16 05:37:56 +00001395Process::SetProcessExitStatus (void *callback_baton,
1396 lldb::pid_t pid,
1397 bool exited,
1398 int signo, // Zero for no signal
1399 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400)
1401{
Greg Claytone4e45922011-11-16 05:37:56 +00001402 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1403 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00001404 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001405 callback_baton,
1406 pid,
1407 exited,
1408 signo,
1409 exit_status);
1410
1411 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001412 {
Greg Clayton66111032010-06-23 01:19:29 +00001413 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001414 if (target_sp)
1415 {
1416 ProcessSP process_sp (target_sp->GetProcessSP());
1417 if (process_sp)
1418 {
1419 const char *signal_cstr = NULL;
1420 if (signo)
1421 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1422
1423 process_sp->SetExitStatus (exit_status, signal_cstr);
1424 }
1425 }
1426 return true;
1427 }
1428 return false;
1429}
1430
1431
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001432void
1433Process::UpdateThreadListIfNeeded ()
1434{
1435 const uint32_t stop_id = GetStopID();
1436 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1437 {
Greg Clayton2637f822011-11-17 01:23:07 +00001438 const StateType state = GetPrivateState();
1439 if (StateIsStoppedState (state, true))
1440 {
1441 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001442 // m_thread_list does have its own mutex, but we need to
1443 // hold onto the mutex between the call to UpdateThreadList(...)
1444 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton2637f822011-11-17 01:23:07 +00001445 ThreadList new_thread_list(this);
1446 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001447 // thread list, but only update if "true" is returned
1448 if (UpdateThreadList (m_thread_list, new_thread_list))
1449 {
1450 OperatingSystem *os = GetOperatingSystem ();
1451 if (os)
1452 os->UpdateThreadList (m_thread_list, new_thread_list);
1453 m_thread_list.Update (new_thread_list);
1454 m_thread_list.SetStopID (stop_id);
1455 }
Greg Clayton2637f822011-11-17 01:23:07 +00001456 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001457 }
1458}
1459
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001460uint32_t
1461Process::GetNextThreadIndexID ()
1462{
1463 return ++m_thread_index_id;
1464}
1465
1466StateType
1467Process::GetState()
1468{
1469 // If any other threads access this we will need a mutex for it
1470 return m_public_state.GetValue ();
1471}
1472
1473void
1474Process::SetPublicState (StateType new_state)
1475{
Greg Clayton414f5d32011-01-25 02:58:48 +00001476 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001477 if (log)
1478 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001479 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001480 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001481
1482 // On the transition from Run to Stopped, we unlock the writer end of the
1483 // run lock. The lock gets locked in Resume, which is the public API
1484 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001485 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1486 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001487 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001488 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001489 if (log)
1490 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1491 m_run_lock.WriteUnlock();
1492 }
1493 else
1494 {
1495 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1496 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1497 if (old_state_is_stopped != new_state_is_stopped)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001498 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001499 if (new_state_is_stopped)
1500 {
1501 if (log)
1502 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1503 m_run_lock.WriteUnlock();
1504 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001505 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001506 }
1507 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001508}
1509
Jim Ingham3b8285d2012-04-19 01:40:33 +00001510Error
1511Process::Resume ()
1512{
1513 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1514 if (log)
1515 log->Printf("Process::Resume -- locking run lock");
1516 if (!m_run_lock.WriteTryLock())
1517 {
1518 Error error("Resume request failed - process still running.");
1519 if (log)
1520 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1521 return error;
1522 }
1523 return PrivateResume();
1524}
1525
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001526StateType
1527Process::GetPrivateState ()
1528{
1529 return m_private_state.GetValue();
1530}
1531
1532void
1533Process::SetPrivateState (StateType new_state)
1534{
Greg Clayton414f5d32011-01-25 02:58:48 +00001535 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001536 bool state_changed = false;
1537
1538 if (log)
1539 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1540
1541 Mutex::Locker locker(m_private_state.GetMutex());
1542
1543 const StateType old_state = m_private_state.GetValueNoLock ();
1544 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001545 // This code is left commented out in case we ever need to control
1546 // the private process state with another run lock. Right now it doesn't
1547 // seem like we need to do this, but if we ever do, we can uncomment and
1548 // use this code.
1549// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1550// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1551// if (old_state_is_stopped != new_state_is_stopped)
1552// {
1553// if (new_state_is_stopped)
1554// m_private_run_lock.WriteUnlock();
1555// else
1556// m_private_run_lock.WriteLock();
1557// }
1558
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001559 if (state_changed)
1560 {
1561 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001562 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001563 {
Jim Ingham4b536182011-08-09 02:12:22 +00001564 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001565 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001566 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001567 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001568 }
1569 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001570 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1571 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1572 else
1573 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001574 }
1575 else
1576 {
1577 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001578 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001579 }
1580}
1581
Jim Ingham0faa43f2011-11-08 03:00:11 +00001582void
1583Process::SetRunningUserExpression (bool on)
1584{
1585 m_mod_id.SetRunningUserExpression (on);
1586}
1587
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001588addr_t
1589Process::GetImageInfoAddress()
1590{
1591 return LLDB_INVALID_ADDRESS;
1592}
1593
Greg Clayton8f343b02010-11-04 01:54:29 +00001594//----------------------------------------------------------------------
1595// LoadImage
1596//
1597// This function provides a default implementation that works for most
1598// unix variants. Any Process subclasses that need to do shared library
1599// loading differently should override LoadImage and UnloadImage and
1600// do what is needed.
1601//----------------------------------------------------------------------
1602uint32_t
1603Process::LoadImage (const FileSpec &image_spec, Error &error)
1604{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001605 char path[PATH_MAX];
1606 image_spec.GetPath(path, sizeof(path));
1607
Greg Clayton8f343b02010-11-04 01:54:29 +00001608 DynamicLoader *loader = GetDynamicLoader();
1609 if (loader)
1610 {
1611 error = loader->CanLoadImage();
1612 if (error.Fail())
1613 return LLDB_INVALID_IMAGE_TOKEN;
1614 }
1615
1616 if (error.Success())
1617 {
1618 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001619
1620 if (thread_sp)
1621 {
1622 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1623
1624 if (frame_sp)
1625 {
1626 ExecutionContext exe_ctx;
1627 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001628 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001629 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001630 expr.Printf("dlopen (\"%s\", 2)", path);
1631 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001632 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001633 ClangUserExpression::Evaluate (exe_ctx,
1634 eExecutionPolicyAlways,
1635 lldb::eLanguageTypeUnknown,
1636 ClangUserExpression::eResultTypeAny,
1637 unwind_on_error,
1638 expr.GetData(),
1639 prefix,
1640 result_valobj_sp,
1641 true,
1642 ClangUserExpression::kDefaultTimeout);
Johnny Chene92aa432011-09-09 00:01:43 +00001643 error = result_valobj_sp->GetError();
1644 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001645 {
1646 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001647 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001648 {
1649 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1650 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1651 {
1652 uint32_t image_token = m_image_tokens.size();
1653 m_image_tokens.push_back (image_ptr);
1654 return image_token;
1655 }
1656 }
1657 }
1658 }
1659 }
1660 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001661 if (!error.AsCString())
1662 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001663 return LLDB_INVALID_IMAGE_TOKEN;
1664}
1665
1666//----------------------------------------------------------------------
1667// UnloadImage
1668//
1669// This function provides a default implementation that works for most
1670// unix variants. Any Process subclasses that need to do shared library
1671// loading differently should override LoadImage and UnloadImage and
1672// do what is needed.
1673//----------------------------------------------------------------------
1674Error
1675Process::UnloadImage (uint32_t image_token)
1676{
1677 Error error;
1678 if (image_token < m_image_tokens.size())
1679 {
1680 const addr_t image_addr = m_image_tokens[image_token];
1681 if (image_addr == LLDB_INVALID_ADDRESS)
1682 {
1683 error.SetErrorString("image already unloaded");
1684 }
1685 else
1686 {
1687 DynamicLoader *loader = GetDynamicLoader();
1688 if (loader)
1689 error = loader->CanLoadImage();
1690
1691 if (error.Success())
1692 {
1693 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001694
1695 if (thread_sp)
1696 {
1697 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1698
1699 if (frame_sp)
1700 {
1701 ExecutionContext exe_ctx;
1702 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001703 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001704 StreamString expr;
1705 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1706 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001707 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001708 ClangUserExpression::Evaluate (exe_ctx,
1709 eExecutionPolicyAlways,
1710 lldb::eLanguageTypeUnknown,
1711 ClangUserExpression::eResultTypeAny,
1712 unwind_on_error,
1713 expr.GetData(),
1714 prefix,
1715 result_valobj_sp,
1716 true,
1717 ClangUserExpression::kDefaultTimeout);
Greg Clayton8f343b02010-11-04 01:54:29 +00001718 if (result_valobj_sp->GetError().Success())
1719 {
1720 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001721 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001722 {
1723 if (scalar.UInt(1))
1724 {
1725 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1726 }
1727 else
1728 {
1729 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1730 }
1731 }
1732 }
1733 else
1734 {
1735 error = result_valobj_sp->GetError();
1736 }
1737 }
1738 }
1739 }
1740 }
1741 }
1742 else
1743 {
1744 error.SetErrorString("invalid image token");
1745 }
1746 return error;
1747}
1748
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001749const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001750Process::GetABI()
1751{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001752 if (!m_abi_sp)
1753 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1754 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001755}
1756
Jim Ingham22777012010-09-23 02:01:19 +00001757LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001758Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001759{
1760 LanguageRuntimeCollection::iterator pos;
1761 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001762 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001763 {
Jim Inghamab175242012-03-10 00:22:19 +00001764 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001765
Jim Inghamab175242012-03-10 00:22:19 +00001766 m_language_runtimes[language] = runtime_sp;
1767 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001768 }
1769 else
1770 return (*pos).second.get();
1771}
1772
1773CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001774Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001775{
Jim Inghamab175242012-03-10 00:22:19 +00001776 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001777 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1778 return static_cast<CPPLanguageRuntime *> (runtime);
1779 return NULL;
1780}
1781
1782ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001783Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001784{
Jim Inghamab175242012-03-10 00:22:19 +00001785 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001786 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1787 return static_cast<ObjCLanguageRuntime *> (runtime);
1788 return NULL;
1789}
1790
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001791bool
1792Process::IsPossibleDynamicValue (ValueObject& in_value)
1793{
1794 if (in_value.IsDynamic())
1795 return false;
1796 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1797
1798 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1799 {
1800 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1801 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1802 }
1803
1804 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1805 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1806 return true;
1807
1808 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1809 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1810}
1811
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001812BreakpointSiteList &
1813Process::GetBreakpointSiteList()
1814{
1815 return m_breakpoint_site_list;
1816}
1817
1818const BreakpointSiteList &
1819Process::GetBreakpointSiteList() const
1820{
1821 return m_breakpoint_site_list;
1822}
1823
1824
1825void
1826Process::DisableAllBreakpointSites ()
1827{
1828 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham43c555d2012-07-04 00:35:43 +00001829 size_t num_sites = m_breakpoint_site_list.GetSize();
1830 for (size_t i = 0; i < num_sites; i++)
1831 {
1832 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1833 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001834}
1835
1836Error
1837Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1838{
1839 Error error (DisableBreakpointSiteByID (break_id));
1840
1841 if (error.Success())
1842 m_breakpoint_site_list.Remove(break_id);
1843
1844 return error;
1845}
1846
1847Error
1848Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1849{
1850 Error error;
1851 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1852 if (bp_site_sp)
1853 {
1854 if (bp_site_sp->IsEnabled())
1855 error = DisableBreakpoint (bp_site_sp.get());
1856 }
1857 else
1858 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001859 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001860 }
1861
1862 return error;
1863}
1864
1865Error
1866Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1867{
1868 Error error;
1869 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1870 if (bp_site_sp)
1871 {
1872 if (!bp_site_sp->IsEnabled())
1873 error = EnableBreakpoint (bp_site_sp.get());
1874 }
1875 else
1876 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001877 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001878 }
1879 return error;
1880}
1881
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001882lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001883Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001884{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001885 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001886 if (load_addr != LLDB_INVALID_ADDRESS)
1887 {
1888 BreakpointSiteSP bp_site_sp;
1889
1890 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1891 // create a new breakpoint site and add it.
1892
1893 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1894
1895 if (bp_site_sp)
1896 {
1897 bp_site_sp->AddOwner (owner);
1898 owner->SetBreakpointSite (bp_site_sp);
1899 return bp_site_sp->GetID();
1900 }
1901 else
1902 {
1903 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1904 if (bp_site_sp)
1905 {
1906 if (EnableBreakpoint (bp_site_sp.get()).Success())
1907 {
1908 owner->SetBreakpointSite (bp_site_sp);
1909 return m_breakpoint_site_list.Add (bp_site_sp);
1910 }
1911 }
1912 }
1913 }
1914 // We failed to enable the breakpoint
1915 return LLDB_INVALID_BREAK_ID;
1916
1917}
1918
1919void
1920Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1921{
1922 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1923 if (num_owners == 0)
1924 {
1925 DisableBreakpoint(bp_site_sp.get());
1926 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1927 }
1928}
1929
1930
1931size_t
1932Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1933{
1934 size_t bytes_removed = 0;
1935 addr_t intersect_addr;
1936 size_t intersect_size;
1937 size_t opcode_offset;
1938 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001939 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001940 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001941
Jim Ingham20c77192011-06-29 19:42:28 +00001942 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001943 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001944 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001945 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001946 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001947 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001948 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001949 {
1950 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1951 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001952 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001953 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001954 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001955 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001956 }
1957 }
1958 }
1959 return bytes_removed;
1960}
1961
1962
Greg Claytonded470d2011-03-19 01:12:21 +00001963
1964size_t
1965Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1966{
1967 PlatformSP platform_sp (m_target.GetPlatform());
1968 if (platform_sp)
1969 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1970 return 0;
1971}
1972
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001973Error
1974Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1975{
1976 Error error;
1977 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001978 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001979 const addr_t bp_addr = bp_site->GetLoadAddress();
1980 if (log)
1981 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1982 if (bp_site->IsEnabled())
1983 {
1984 if (log)
1985 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1986 return error;
1987 }
1988
1989 if (bp_addr == LLDB_INVALID_ADDRESS)
1990 {
1991 error.SetErrorString("BreakpointSite contains an invalid load address.");
1992 return error;
1993 }
1994 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1995 // trap for the breakpoint site
1996 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1997
1998 if (bp_opcode_size == 0)
1999 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002000 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002001 }
2002 else
2003 {
2004 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2005
2006 if (bp_opcode_bytes == NULL)
2007 {
2008 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2009 return error;
2010 }
2011
2012 // Save the original opcode by reading it
2013 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2014 {
2015 // Write a software breakpoint in place of the original opcode
2016 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2017 {
2018 uint8_t verify_bp_opcode_bytes[64];
2019 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2020 {
2021 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2022 {
2023 bp_site->SetEnabled(true);
2024 bp_site->SetType (BreakpointSite::eSoftware);
2025 if (log)
2026 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
2027 bp_site->GetID(),
2028 (uint64_t)bp_addr);
2029 }
2030 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002031 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002032 }
2033 else
2034 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2035 }
2036 else
2037 error.SetErrorString("Unable to write breakpoint trap to memory.");
2038 }
2039 else
2040 error.SetErrorString("Unable to read memory at breakpoint address.");
2041 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002042 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002043 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2044 bp_site->GetID(),
2045 (uint64_t)bp_addr,
2046 error.AsCString());
2047 return error;
2048}
2049
2050Error
2051Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2052{
2053 Error error;
2054 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002055 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002056 addr_t bp_addr = bp_site->GetLoadAddress();
2057 lldb::user_id_t breakID = bp_site->GetID();
2058 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002059 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002060
2061 if (bp_site->IsHardware())
2062 {
2063 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2064 }
2065 else if (bp_site->IsEnabled())
2066 {
2067 const size_t break_op_size = bp_site->GetByteSize();
2068 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2069 if (break_op_size > 0)
2070 {
2071 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002072 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002073 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074 bool break_op_found = false;
2075
2076 // Read the breakpoint opcode
2077 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2078 {
2079 bool verify = false;
2080 // Make sure we have the a breakpoint opcode exists at this address
2081 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2082 {
2083 break_op_found = true;
2084 // We found a valid breakpoint opcode at this address, now restore
2085 // the saved opcode.
2086 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2087 {
2088 verify = true;
2089 }
2090 else
2091 error.SetErrorString("Memory write failed when restoring original opcode.");
2092 }
2093 else
2094 {
2095 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2096 // Set verify to true and so we can check if the original opcode has already been restored
2097 verify = true;
2098 }
2099
2100 if (verify)
2101 {
Greg Claytonc982c762010-07-09 20:39:50 +00002102 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002103 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002104 // Verify that our original opcode made it back to the inferior
2105 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2106 {
2107 // compare the memory we just read with the original opcode
2108 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2109 {
2110 // SUCCESS
2111 bp_site->SetEnabled(false);
2112 if (log)
2113 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2114 return error;
2115 }
2116 else
2117 {
2118 if (break_op_found)
2119 error.SetErrorString("Failed to restore original opcode.");
2120 }
2121 }
2122 else
2123 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2124 }
2125 }
2126 else
2127 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2128 }
2129 }
2130 else
2131 {
2132 if (log)
2133 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2134 return error;
2135 }
2136
2137 if (log)
2138 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2139 bp_site->GetID(),
2140 (uint64_t)bp_addr,
2141 error.AsCString());
2142 return error;
2143
2144}
2145
Greg Clayton58be07b2011-01-07 06:08:19 +00002146// Uncomment to verify memory caching works after making changes to caching code
2147//#define VERIFY_MEMORY_READS
2148
Sean Callanan64c0cf22012-06-07 22:26:42 +00002149size_t
2150Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2151{
2152 if (!GetDisableMemoryCache())
2153 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002154#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002155 // Memory caching is enabled, with debug verification
2156
2157 if (buf && size)
2158 {
2159 // Uncomment the line below to make sure memory caching is working.
2160 // I ran this through the test suite and got no assertions, so I am
2161 // pretty confident this is working well. If any changes are made to
2162 // memory caching, uncomment the line below and test your changes!
2163
2164 // Verify all memory reads by using the cache first, then redundantly
2165 // reading the same memory from the inferior and comparing to make sure
2166 // everything is exactly the same.
2167 std::string verify_buf (size, '\0');
2168 assert (verify_buf.size() == size);
2169 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2170 Error verify_error;
2171 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2172 assert (cache_bytes_read == verify_bytes_read);
2173 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2174 assert (verify_error.Success() == error.Success());
2175 return cache_bytes_read;
2176 }
2177 return 0;
2178#else // !defined(VERIFY_MEMORY_READS)
2179 // Memory caching is enabled, without debug verification
2180
2181 return m_memory_cache.Read (addr, buf, size, error);
2182#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002183 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002184 else
2185 {
2186 // Memory caching is disabled
2187
2188 return ReadMemoryFromInferior (addr, buf, size, error);
2189 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002190}
Greg Clayton58be07b2011-01-07 06:08:19 +00002191
Greg Clayton4c82d422012-05-18 23:20:01 +00002192size_t
2193Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2194{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002195 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002196 out_str.clear();
2197 addr_t curr_addr = addr;
2198 while (1)
2199 {
2200 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2201 if (length == 0)
2202 break;
2203 out_str.append(buf, length);
2204 // If we got "length - 1" bytes, we didn't get the whole C string, we
2205 // need to read some more characters
2206 if (length == sizeof(buf) - 1)
2207 curr_addr += length;
2208 else
2209 break;
2210 }
2211 return out_str.size();
2212}
2213
Greg Clayton58be07b2011-01-07 06:08:19 +00002214
2215size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002216Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002217{
2218 size_t total_cstr_len = 0;
2219 if (dst && dst_max_len)
2220 {
Greg Claytone91b7952011-12-15 03:14:23 +00002221 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002222 // NULL out everything just to be safe
2223 memset (dst, 0, dst_max_len);
2224 Error error;
2225 addr_t curr_addr = addr;
2226 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2227 size_t bytes_left = dst_max_len - 1;
2228 char *curr_dst = dst;
2229
2230 while (bytes_left > 0)
2231 {
2232 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2233 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2234 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2235
2236 if (bytes_read == 0)
2237 {
Greg Claytone91b7952011-12-15 03:14:23 +00002238 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002239 dst[total_cstr_len] = '\0';
2240 break;
2241 }
2242 const size_t len = strlen(curr_dst);
2243
2244 total_cstr_len += len;
2245
2246 if (len < bytes_to_read)
2247 break;
2248
2249 curr_dst += bytes_read;
2250 curr_addr += bytes_read;
2251 bytes_left -= bytes_read;
2252 }
2253 }
Greg Claytone91b7952011-12-15 03:14:23 +00002254 else
2255 {
2256 if (dst == NULL)
2257 result_error.SetErrorString("invalid arguments");
2258 else
2259 result_error.Clear();
2260 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002261 return total_cstr_len;
2262}
2263
2264size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002265Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2266{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002267 if (buf == NULL || size == 0)
2268 return 0;
2269
2270 size_t bytes_read = 0;
2271 uint8_t *bytes = (uint8_t *)buf;
2272
2273 while (bytes_read < size)
2274 {
2275 const size_t curr_size = size - bytes_read;
2276 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2277 bytes + bytes_read,
2278 curr_size,
2279 error);
2280 bytes_read += curr_bytes_read;
2281 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2282 break;
2283 }
2284
2285 // Replace any software breakpoint opcodes that fall into this range back
2286 // into "buf" before we return
2287 if (bytes_read > 0)
2288 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2289 return bytes_read;
2290}
2291
Greg Clayton58a4c462010-12-16 20:01:20 +00002292uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002293Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002294{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002295 Scalar scalar;
2296 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2297 return scalar.ULongLong(fail_value);
2298 return fail_value;
2299}
2300
2301addr_t
2302Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2303{
2304 Scalar scalar;
2305 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2306 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2307 return LLDB_INVALID_ADDRESS;
2308}
2309
2310
2311bool
2312Process::WritePointerToMemory (lldb::addr_t vm_addr,
2313 lldb::addr_t ptr_value,
2314 Error &error)
2315{
2316 Scalar scalar;
2317 const uint32_t addr_byte_size = GetAddressByteSize();
2318 if (addr_byte_size <= 4)
2319 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002320 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002321 scalar = ptr_value;
2322 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002323}
2324
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325size_t
2326Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2327{
2328 size_t bytes_written = 0;
2329 const uint8_t *bytes = (const uint8_t *)buf;
2330
2331 while (bytes_written < size)
2332 {
2333 const size_t curr_size = size - bytes_written;
2334 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2335 bytes + bytes_written,
2336 curr_size,
2337 error);
2338 bytes_written += curr_bytes_written;
2339 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2340 break;
2341 }
2342 return bytes_written;
2343}
2344
2345size_t
2346Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2347{
Greg Clayton58be07b2011-01-07 06:08:19 +00002348#if defined (ENABLE_MEMORY_CACHING)
2349 m_memory_cache.Flush (addr, size);
2350#endif
2351
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002352 if (buf == NULL || size == 0)
2353 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002354
Jim Ingham4b536182011-08-09 02:12:22 +00002355 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002356
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002357 // We need to write any data that would go where any current software traps
2358 // (enabled software breakpoints) any software traps (breakpoints) that we
2359 // may have placed in our tasks memory.
2360
2361 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2362 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2363
2364 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002365 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002366
2367 BreakpointSiteList::collection::const_iterator pos;
2368 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002369 addr_t intersect_addr = 0;
2370 size_t intersect_size = 0;
2371 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002372 const uint8_t *ubuf = (const uint8_t *)buf;
2373
2374 for (pos = iter; pos != end; ++pos)
2375 {
2376 BreakpointSiteSP bp;
2377 bp = pos->second;
2378
2379 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2380 assert(addr <= intersect_addr && intersect_addr < addr + size);
2381 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2382 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2383
2384 // Check for bytes before this breakpoint
2385 const addr_t curr_addr = addr + bytes_written;
2386 if (intersect_addr > curr_addr)
2387 {
2388 // There are some bytes before this breakpoint that we need to
2389 // just write to memory
2390 size_t curr_size = intersect_addr - curr_addr;
2391 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2392 ubuf + bytes_written,
2393 curr_size,
2394 error);
2395 bytes_written += curr_bytes_written;
2396 if (curr_bytes_written != curr_size)
2397 {
2398 // We weren't able to write all of the requested bytes, we
2399 // are done looping and will return the number of bytes that
2400 // we have written so far.
2401 break;
2402 }
2403 }
2404
2405 // Now write any bytes that would cover up any software breakpoints
2406 // directly into the breakpoint opcode buffer
2407 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2408 bytes_written += intersect_size;
2409 }
2410
2411 // Write any remaining bytes after the last breakpoint if we have any left
2412 if (bytes_written < size)
2413 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2414 ubuf + bytes_written,
2415 size - bytes_written,
2416 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002417
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002418 return bytes_written;
2419}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002420
2421size_t
2422Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2423{
2424 if (byte_size == UINT32_MAX)
2425 byte_size = scalar.GetByteSize();
2426 if (byte_size > 0)
2427 {
2428 uint8_t buf[32];
2429 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2430 if (mem_size > 0)
2431 return WriteMemory(addr, buf, mem_size, error);
2432 else
2433 error.SetErrorString ("failed to get scalar as memory data");
2434 }
2435 else
2436 {
2437 error.SetErrorString ("invalid scalar value");
2438 }
2439 return 0;
2440}
2441
2442size_t
2443Process::ReadScalarIntegerFromMemory (addr_t addr,
2444 uint32_t byte_size,
2445 bool is_signed,
2446 Scalar &scalar,
2447 Error &error)
2448{
2449 uint64_t uval;
2450
2451 if (byte_size <= sizeof(uval))
2452 {
2453 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2454 if (bytes_read == byte_size)
2455 {
2456 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2457 uint32_t offset = 0;
2458 if (byte_size <= 4)
2459 scalar = data.GetMaxU32 (&offset, byte_size);
2460 else
2461 scalar = data.GetMaxU64 (&offset, byte_size);
2462
2463 if (is_signed)
2464 scalar.SignExtend(byte_size * 8);
2465 return bytes_read;
2466 }
2467 }
2468 else
2469 {
2470 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2471 }
2472 return 0;
2473}
2474
Greg Claytond495c532011-05-17 03:37:42 +00002475#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002476addr_t
2477Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2478{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002479 if (GetPrivateState() != eStateStopped)
2480 return LLDB_INVALID_ADDRESS;
2481
Greg Claytond495c532011-05-17 03:37:42 +00002482#if defined (USE_ALLOCATE_MEMORY_CACHE)
2483 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2484#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002485 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2486 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2487 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002488 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 +00002489 size,
Greg Claytond495c532011-05-17 03:37:42 +00002490 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002491 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002492 m_mod_id.GetStopID(),
2493 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002494 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002495#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002496}
2497
Sean Callanan90539452011-09-20 23:01:51 +00002498bool
2499Process::CanJIT ()
2500{
Sean Callanana7b443a2012-02-14 22:50:38 +00002501 if (m_can_jit == eCanJITDontKnow)
2502 {
2503 Error err;
2504
2505 uint64_t allocated_memory = AllocateMemory(8,
2506 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2507 err);
2508
2509 if (err.Success())
2510 m_can_jit = eCanJITYes;
2511 else
2512 m_can_jit = eCanJITNo;
2513
2514 DeallocateMemory (allocated_memory);
2515 }
2516
Sean Callanan90539452011-09-20 23:01:51 +00002517 return m_can_jit == eCanJITYes;
2518}
2519
2520void
2521Process::SetCanJIT (bool can_jit)
2522{
2523 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2524}
2525
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002526Error
2527Process::DeallocateMemory (addr_t ptr)
2528{
Greg Claytond495c532011-05-17 03:37:42 +00002529 Error error;
2530#if defined (USE_ALLOCATE_MEMORY_CACHE)
2531 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2532 {
2533 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2534 }
2535#else
2536 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002537
2538 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2539 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002540 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 +00002541 ptr,
2542 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002543 m_mod_id.GetStopID(),
2544 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002545#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002546 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002547}
2548
Greg Claytonc9660542012-02-05 02:38:54 +00002549ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002550Process::ReadModuleFromMemory (const FileSpec& file_spec,
2551 lldb::addr_t header_addr,
2552 bool add_image_to_target,
2553 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002554{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002555 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002556 if (module_sp)
2557 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002558 Error error;
2559 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2560 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002561 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002562 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002563 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002564 m_target.GetImages().Append(module_sp);
2565 if (load_sections_in_target)
2566 {
2567 bool changed = false;
2568 module_sp->SetLoadAddress (m_target, 0, changed);
2569 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002570 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002571 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002572 }
Greg Claytonc9660542012-02-05 02:38:54 +00002573 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002574 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002575}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002576
2577Error
Johnny Chen01a67862011-10-14 00:42:25 +00002578Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002579{
2580 Error error;
2581 error.SetErrorString("watchpoints are not supported");
2582 return error;
2583}
2584
2585Error
Johnny Chen01a67862011-10-14 00:42:25 +00002586Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002587{
2588 Error error;
2589 error.SetErrorString("watchpoints are not supported");
2590 return error;
2591}
2592
2593StateType
2594Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2595{
2596 StateType state;
2597 // Now wait for the process to launch and return control to us, and then
2598 // call DidLaunch:
2599 while (1)
2600 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002601 event_sp.reset();
2602 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2603
Greg Clayton2637f822011-11-17 01:23:07 +00002604 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002605 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002606
2607 // If state is invalid, then we timed out
2608 if (state == eStateInvalid)
2609 break;
2610
2611 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002612 HandlePrivateEvent (event_sp);
2613 }
2614 return state;
2615}
2616
2617Error
Greg Clayton982c9762011-11-03 21:22:33 +00002618Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002619{
2620 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002621 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002622 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002623 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002624 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002625
Greg Claytonaa149cb2011-08-11 02:48:45 +00002626 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002627 if (exe_module)
2628 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002629 char local_exec_file_path[PATH_MAX];
2630 char platform_exec_file_path[PATH_MAX];
2631 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2632 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002633 if (exe_module->GetFileSpec().Exists())
2634 {
Greg Clayton71337622011-02-24 22:24:29 +00002635 if (PrivateStateThreadIsValid ())
2636 PausePrivateStateThread ();
2637
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002638 error = WillLaunch (exe_module);
2639 if (error.Success())
2640 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002641 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002642 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002643
Greg Clayton69fd4be2012-09-04 20:29:05 +00002644 if (m_run_lock.WriteTryLock())
2645 {
2646 // Now launch using these arguments.
2647 error = DoLaunch (exe_module, launch_info);
2648 }
2649 else
2650 {
2651 // This shouldn't happen
2652 error.SetErrorString("failed to acquire process run lock");
2653 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002654
2655 if (error.Fail())
2656 {
2657 if (GetID() != LLDB_INVALID_PROCESS_ID)
2658 {
2659 SetID (LLDB_INVALID_PROCESS_ID);
2660 const char *error_string = error.AsCString();
2661 if (error_string == NULL)
2662 error_string = "launch failed";
2663 SetExitStatus (-1, error_string);
2664 }
2665 }
2666 else
2667 {
2668 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002669 TimeValue timeout_time;
2670 timeout_time = TimeValue::Now();
2671 timeout_time.OffsetWithSeconds(10);
2672 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002673
Greg Clayton1a38ea72011-06-22 01:42:17 +00002674 if (state == eStateInvalid || event_sp.get() == NULL)
2675 {
2676 // We were able to launch the process, but we failed to
2677 // catch the initial stop.
2678 SetExitStatus (0, "failed to catch stop after launch");
2679 Destroy();
2680 }
2681 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002682 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002683
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002684 DidLaunch ();
2685
Greg Claytonc859e2d2012-02-13 23:10:39 +00002686 DynamicLoader *dyld = GetDynamicLoader ();
2687 if (dyld)
2688 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002689
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002690 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002691 // This delays passing the stopped event to listeners till DidLaunch gets
2692 // a chance to complete...
2693 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002694
2695 if (PrivateStateThreadIsValid ())
2696 ResumePrivateStateThread ();
2697 else
2698 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002699 }
2700 else if (state == eStateExited)
2701 {
2702 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2703 // not likely to work, and return an invalid pid.
2704 HandlePrivateEvent (event_sp);
2705 }
2706 }
2707 }
2708 }
2709 else
2710 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002711 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712 }
2713 }
2714 return error;
2715}
2716
Greg Claytonc3776bf2012-02-09 06:16:32 +00002717
2718Error
2719Process::LoadCore ()
2720{
2721 Error error = DoLoadCore();
2722 if (error.Success())
2723 {
2724 if (PrivateStateThreadIsValid ())
2725 ResumePrivateStateThread ();
2726 else
2727 StartPrivateStateThread ();
2728
Greg Claytonc859e2d2012-02-13 23:10:39 +00002729 DynamicLoader *dyld = GetDynamicLoader ();
2730 if (dyld)
2731 dyld->DidAttach();
2732
2733 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002734 // We successfully loaded a core file, now pretend we stopped so we can
2735 // show all of the threads in the core file and explore the crashed
2736 // state.
2737 SetPrivateState (eStateStopped);
2738
2739 }
2740 return error;
2741}
2742
Greg Claytonc859e2d2012-02-13 23:10:39 +00002743DynamicLoader *
2744Process::GetDynamicLoader ()
2745{
2746 if (m_dyld_ap.get() == NULL)
2747 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2748 return m_dyld_ap.get();
2749}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002750
2751
Jim Inghambb3a2832011-01-29 01:49:25 +00002752Process::NextEventAction::EventActionResult
2753Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002754{
Jim Inghambb3a2832011-01-29 01:49:25 +00002755 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2756 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002757 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002758 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002759 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002760 return eEventActionRetry;
2761
2762 case eStateStopped:
2763 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002764 {
2765 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002766 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002767 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2768 if (m_exec_count > 0)
2769 {
2770 --m_exec_count;
Jim Ingham3b8285d2012-04-19 01:40:33 +00002771 m_process->PrivateResume ();
Jim Ingham04e0a222012-05-23 15:46:31 +00002772 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Claytonc9ed4782011-11-12 02:10:56 +00002773 return eEventActionRetry;
2774 }
2775 else
2776 {
2777 m_process->CompleteAttach ();
2778 return eEventActionSuccess;
2779 }
2780 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002781 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002782
Greg Clayton513c26c2011-01-29 07:10:55 +00002783 default:
2784 case eStateExited:
2785 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002786 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002787 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002788
2789 m_exit_string.assign ("No valid Process");
2790 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002791}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002792
Jim Inghambb3a2832011-01-29 01:49:25 +00002793Process::NextEventAction::EventActionResult
2794Process::AttachCompletionHandler::HandleBeingInterrupted()
2795{
2796 return eEventActionSuccess;
2797}
2798
2799const char *
2800Process::AttachCompletionHandler::GetExitString ()
2801{
2802 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002803}
2804
2805Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002806Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002807{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002808 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002809 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002810 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002811 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002812
Greg Clayton144f3a92011-11-15 03:53:30 +00002813 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002814 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002815 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002816 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002817 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002818
Greg Clayton144f3a92011-11-15 03:53:30 +00002819 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002820 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002821 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2822
2823 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002824 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002825 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2826 if (error.Success())
2827 {
Greg Clayton926cce72012-10-12 16:10:12 +00002828 if (m_run_lock.WriteTryLock())
2829 {
2830 m_should_detach = true;
2831 SetPublicState (eStateAttaching);
2832 // Now attach using these arguments.
2833 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2834 }
2835 else
2836 {
2837 // This shouldn't happen
2838 error.SetErrorString("failed to acquire process run lock");
2839 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00002840
Greg Clayton144f3a92011-11-15 03:53:30 +00002841 if (error.Fail())
2842 {
2843 if (GetID() != LLDB_INVALID_PROCESS_ID)
2844 {
2845 SetID (LLDB_INVALID_PROCESS_ID);
2846 if (error.AsCString() == NULL)
2847 error.SetErrorString("attach failed");
2848
2849 SetExitStatus(-1, error.AsCString());
2850 }
2851 }
2852 else
2853 {
2854 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2855 StartPrivateStateThread();
2856 }
2857 return error;
2858 }
Greg Claytone996fd32011-03-08 22:40:15 +00002859 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002860 else
Greg Claytone996fd32011-03-08 22:40:15 +00002861 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002862 ProcessInstanceInfoList process_infos;
2863 PlatformSP platform_sp (m_target.GetPlatform ());
2864
2865 if (platform_sp)
2866 {
2867 ProcessInstanceInfoMatch match_info;
2868 match_info.GetProcessInfo() = attach_info;
2869 match_info.SetNameMatchType (eNameMatchEquals);
2870 platform_sp->FindProcesses (match_info, process_infos);
2871 const uint32_t num_matches = process_infos.GetSize();
2872 if (num_matches == 1)
2873 {
2874 attach_pid = process_infos.GetProcessIDAtIndex(0);
2875 // Fall through and attach using the above process ID
2876 }
2877 else
2878 {
2879 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2880 if (num_matches > 1)
2881 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2882 else
2883 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2884 }
2885 }
2886 else
2887 {
2888 error.SetErrorString ("invalid platform, can't find processes by name");
2889 return error;
2890 }
Greg Claytone996fd32011-03-08 22:40:15 +00002891 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002892 }
2893 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002894 {
2895 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002896 }
2897 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002898
2899 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002900 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002901 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002902 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002904
Greg Clayton926cce72012-10-12 16:10:12 +00002905 if (m_run_lock.WriteTryLock())
2906 {
2907 // Now attach using these arguments.
2908 m_should_detach = true;
2909 SetPublicState (eStateAttaching);
2910 error = DoAttachToProcessWithID (attach_pid, attach_info);
2911 }
2912 else
2913 {
2914 // This shouldn't happen
2915 error.SetErrorString("failed to acquire process run lock");
2916 }
2917
Greg Clayton144f3a92011-11-15 03:53:30 +00002918 if (error.Success())
2919 {
2920
2921 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2922 StartPrivateStateThread();
2923 }
2924 else
Greg Claytone996fd32011-03-08 22:40:15 +00002925 {
2926 if (GetID() != LLDB_INVALID_PROCESS_ID)
2927 {
2928 SetID (LLDB_INVALID_PROCESS_ID);
2929 const char *error_string = error.AsCString();
2930 if (error_string == NULL)
2931 error_string = "attach failed";
2932
2933 SetExitStatus(-1, error_string);
2934 }
2935 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002936 }
2937 }
2938 return error;
2939}
2940
Greg Clayton93d3c8332011-02-16 04:46:07 +00002941void
2942Process::CompleteAttach ()
2943{
2944 // Let the process subclass figure out at much as it can about the process
2945 // before we go looking for a dynamic loader plug-in.
2946 DidAttach();
2947
Jim Ingham4299fdb2011-09-15 01:10:17 +00002948 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2949 // the same as the one we've already set, switch architectures.
2950 PlatformSP platform_sp (m_target.GetPlatform ());
2951 assert (platform_sp.get());
2952 if (platform_sp)
2953 {
Greg Clayton70512312012-05-08 01:45:38 +00002954 const ArchSpec &target_arch = m_target.GetArchitecture();
2955 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2956 {
2957 ArchSpec platform_arch;
2958 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2959 if (platform_sp)
2960 {
2961 m_target.SetPlatform (platform_sp);
2962 m_target.SetArchitecture(platform_arch);
2963 }
2964 }
2965 else
2966 {
2967 ProcessInstanceInfo process_info;
2968 platform_sp->GetProcessInfo (GetID(), process_info);
2969 const ArchSpec &process_arch = process_info.GetArchitecture();
2970 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2971 m_target.SetArchitecture (process_arch);
2972 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00002973 }
2974
2975 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002976 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002977 DynamicLoader *dyld = GetDynamicLoader ();
2978 if (dyld)
2979 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002980
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002981 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002982 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00002983 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002984 Mutex::Locker modules_locker(target_modules.GetMutex());
2985 size_t num_modules = target_modules.GetSize();
2986 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002987
Greg Clayton93d3c8332011-02-16 04:46:07 +00002988 for (int i = 0; i < num_modules; i++)
2989 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002990 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002991 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002992 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002993 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002994 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002995 break;
2996 }
2997 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002998 if (new_executable_module_sp)
2999 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003000}
3001
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003002Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003003Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003004{
Greg Claytonb766a732011-02-04 01:58:07 +00003005 m_abi_sp.reset();
3006 m_process_input_reader.reset();
3007
3008 // Find the process and its architecture. Make sure it matches the architecture
3009 // of the current Target, and if not adjust it.
3010
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003011 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003012 if (error.Success())
3013 {
Greg Clayton71337622011-02-24 22:24:29 +00003014 if (GetID() != LLDB_INVALID_PROCESS_ID)
3015 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003016 EventSP event_sp;
3017 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3018
3019 if (state == eStateStopped || state == eStateCrashed)
3020 {
3021 // If we attached and actually have a process on the other end, then
3022 // this ended up being the equivalent of an attach.
3023 CompleteAttach ();
3024
3025 // This delays passing the stopped event to listeners till
3026 // CompleteAttach gets a chance to complete...
3027 HandlePrivateEvent (event_sp);
3028
3029 }
Greg Clayton71337622011-02-24 22:24:29 +00003030 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003031
3032 if (PrivateStateThreadIsValid ())
3033 ResumePrivateStateThread ();
3034 else
3035 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003036 }
3037 return error;
3038}
3039
3040
3041Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003042Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003043{
Jim Ingham46ef1802012-09-06 19:24:17 +00003044 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00003046 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003047 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003048 StateAsCString(m_public_state.GetValue()),
3049 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050
3051 Error error (WillResume());
3052 // Tell the process it is about to resume before the thread list
3053 if (error.Success())
3054 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003055 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003056 // can let all of our threads know that they are about to be
3057 // resumed. Threads will each be called with
3058 // Thread::WillResume(StateType) where StateType contains the state
3059 // that they are supposed to have when the process is resumed
3060 // (suspended/running/stepping). Threads should also check
3061 // their resume signal in lldb::Thread::GetResumeSignal()
3062 // to see if they are suppoed to start back up with a signal.
3063 if (m_thread_list.WillResume())
3064 {
Jim Ingham372787f2012-04-07 00:00:41 +00003065 // Last thing, do the PreResumeActions.
3066 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003067 {
Jim Ingham372787f2012-04-07 00:00:41 +00003068 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3069 }
3070 else
3071 {
3072 m_mod_id.BumpResumeID();
3073 error = DoResume();
3074 if (error.Success())
3075 {
3076 DidResume();
3077 m_thread_list.DidResume();
3078 if (log)
3079 log->Printf ("Process thinks the process has resumed.");
3080 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081 }
3082 }
3083 else
3084 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003085 // Somebody wanted to run without running. So generate a continue & a stopped event,
3086 // and let the world handle them.
3087 if (log)
3088 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3089
3090 SetPrivateState(eStateRunning);
3091 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003092 }
3093 }
Jim Ingham444586b2011-01-24 06:34:17 +00003094 else if (log)
3095 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003096 return error;
3097}
3098
3099Error
3100Process::Halt ()
3101{
Jim Inghamaacc3182012-06-06 00:29:30 +00003102 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3103 // we could just straightaway get another event. It just narrows the window...
3104 m_currently_handling_event.WaitForValueEqualTo(false);
3105
3106
Jim Inghambb3a2832011-01-29 01:49:25 +00003107 // Pause our private state thread so we can ensure no one else eats
3108 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003109 Listener halt_listener ("lldb.process.halt_listener");
3110 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003111
Jim Inghambb3a2832011-01-29 01:49:25 +00003112 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003113 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003114
Greg Clayton513c26c2011-01-29 07:10:55 +00003115 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003116 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003117
Greg Clayton513c26c2011-01-29 07:10:55 +00003118 bool caused_stop = false;
3119
3120 // Ask the process subclass to actually halt our process
3121 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003123 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003124 if (m_public_state.GetValue() == eStateAttaching)
3125 {
3126 SetExitStatus(SIGKILL, "Cancelled async attach.");
3127 Destroy ();
3128 }
3129 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003130 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003131 // If "caused_stop" is true, then DoHalt stopped the process. If
3132 // "caused_stop" is false, the process was already stopped.
3133 // If the DoHalt caused the process to stop, then we want to catch
3134 // this event and set the interrupted bool to true before we pass
3135 // this along so clients know that the process was interrupted by
3136 // a halt command.
3137 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003138 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003139 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003140 TimeValue timeout_time;
3141 timeout_time = TimeValue::Now();
3142 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003143 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3144 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003145
Jim Ingham0f16e732011-02-08 05:20:59 +00003146 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003147 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003148 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003149 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003150 }
3151 else
3152 {
Greg Clayton2637f822011-11-17 01:23:07 +00003153 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003154 {
3155 // We caused the process to interrupt itself, so mark this
3156 // as such in the stop event so clients can tell an interrupted
3157 // process from a natural stop
3158 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3159 }
3160 else
3161 {
3162 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3163 if (log)
3164 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3165 error.SetErrorString ("Did not get stopped event after halt.");
3166 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003167 }
3168 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003169 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003170 }
3171 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003172 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003173 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003174 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003175
3176 // Post any event we might have consumed. If all goes well, we will have
3177 // stopped the process, intercepted the event and set the interrupted
3178 // bool in the event. Post it to the private event queue and that will end up
3179 // correctly setting the state.
3180 if (event_sp)
3181 m_private_state_broadcaster.BroadcastEvent(event_sp);
3182
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003183 return error;
3184}
3185
3186Error
3187Process::Detach ()
3188{
3189 Error error (WillDetach());
3190
3191 if (error.Success())
3192 {
3193 DisableAllBreakpointSites();
3194 error = DoDetach();
3195 if (error.Success())
3196 {
3197 DidDetach();
3198 StopPrivateStateThread();
3199 }
3200 }
3201 return error;
3202}
3203
3204Error
3205Process::Destroy ()
3206{
3207 Error error (WillDestroy());
3208 if (error.Success())
3209 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003210 EventSP exit_event_sp;
Jim Ingham04e0a222012-05-23 15:46:31 +00003211 if (m_public_state.GetValue() == eStateRunning)
3212 {
Greg Claytona28d2032012-09-05 00:37:58 +00003213 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003214 if (log)
3215 log->Printf("Process::Destroy() About to halt.");
Jim Ingham04e0a222012-05-23 15:46:31 +00003216 error = Halt();
3217 if (error.Success())
3218 {
3219 // Consume the halt event.
Jim Ingham04e0a222012-05-23 15:46:31 +00003220 TimeValue timeout (TimeValue::Now());
Jim Inghamaacc3182012-06-06 00:29:30 +00003221 timeout.OffsetWithSeconds(1);
Greg Clayton85fb1b92012-09-11 02:33:37 +00003222 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3223 if (state != eStateExited)
3224 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3225
Jim Ingham04e0a222012-05-23 15:46:31 +00003226 if (state != eStateStopped)
3227 {
Jim Ingham04e0a222012-05-23 15:46:31 +00003228 if (log)
3229 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Inghamaacc3182012-06-06 00:29:30 +00003230 // If we really couldn't stop the process then we should just error out here, but if the
3231 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3232 StateType private_state = m_private_state.GetValue();
3233 if (private_state != eStateStopped && private_state != eStateExited)
3234 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003235 // If we exited when we were waiting for a process to stop, then
3236 // forward the event here so we don't lose the event
Jim Inghamaacc3182012-06-06 00:29:30 +00003237 return error;
3238 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003239 }
3240 }
3241 else
3242 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003243 if (log)
3244 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3245 return error;
Jim Ingham04e0a222012-05-23 15:46:31 +00003246 }
3247 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003248
3249 if (m_public_state.GetValue() != eStateRunning)
3250 {
3251 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3252 // kill it, we don't want it hitting a breakpoint...
3253 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3254 // we're not going to have much luck doing this now.
3255 m_thread_list.DiscardThreadPlans();
3256 DisableAllBreakpointSites();
3257 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003258
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003259 error = DoDestroy();
3260 if (error.Success())
3261 {
3262 DidDestroy();
3263 StopPrivateStateThread();
3264 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003265 m_stdio_communication.StopReadThread();
3266 m_stdio_communication.Disconnect();
3267 if (m_process_input_reader && m_process_input_reader->IsActive())
3268 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3269 if (m_process_input_reader)
3270 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003271
3272 // If we exited when we were waiting for a process to stop, then
3273 // forward the event here so we don't lose the event
3274 if (exit_event_sp)
3275 {
3276 // Directly broadcast our exited event because we shut down our
3277 // private state thread above
3278 BroadcastEvent(exit_event_sp);
3279 }
3280
Jim Inghamb1e2e842012-04-12 18:49:31 +00003281 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3282 // the last events through the event system, in which case we might strand the write lock. Unlock
3283 // it here so when we do to tear down the process we don't get an error destroying the lock.
3284 m_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003285 }
3286 return error;
3287}
3288
3289Error
3290Process::Signal (int signal)
3291{
3292 Error error (WillSignal());
3293 if (error.Success())
3294 {
3295 error = DoSignal(signal);
3296 if (error.Success())
3297 DidSignal();
3298 }
3299 return error;
3300}
3301
Greg Clayton514487e2011-02-15 21:59:32 +00003302lldb::ByteOrder
3303Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003304{
Greg Clayton514487e2011-02-15 21:59:32 +00003305 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003306}
3307
3308uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003309Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003310{
Greg Clayton514487e2011-02-15 21:59:32 +00003311 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003312}
3313
Greg Clayton514487e2011-02-15 21:59:32 +00003314
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003315bool
3316Process::ShouldBroadcastEvent (Event *event_ptr)
3317{
3318 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3319 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003320 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003321
3322 switch (state)
3323 {
Greg Claytonb766a732011-02-04 01:58:07 +00003324 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003325 case eStateAttaching:
3326 case eStateLaunching:
3327 case eStateDetached:
3328 case eStateExited:
3329 case eStateUnloaded:
3330 // These events indicate changes in the state of the debugging session, always report them.
3331 return_value = true;
3332 break;
3333 case eStateInvalid:
3334 // We stopped for no apparent reason, don't report it.
3335 return_value = false;
3336 break;
3337 case eStateRunning:
3338 case eStateStepping:
3339 // If we've started the target running, we handle the cases where we
3340 // are already running and where there is a transition from stopped to
3341 // running differently.
3342 // running -> running: Automatically suppress extra running events
3343 // stopped -> running: Report except when there is one or more no votes
3344 // and no yes votes.
3345 SynchronouslyNotifyStateChanged (state);
3346 switch (m_public_state.GetValue())
3347 {
3348 case eStateRunning:
3349 case eStateStepping:
3350 // We always suppress multiple runnings with no PUBLIC stop in between.
3351 return_value = false;
3352 break;
3353 default:
3354 // TODO: make this work correctly. For now always report
3355 // run if we aren't running so we don't miss any runnning
3356 // events. If I run the lldb/test/thread/a.out file and
3357 // break at main.cpp:58, run and hit the breakpoints on
3358 // multiple threads, then somehow during the stepping over
3359 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003360
3361 // This is a transition from stop to run.
3362 switch (m_thread_list.ShouldReportRun (event_ptr))
3363 {
Greg Clayton23f59502012-07-17 03:23:13 +00003364 default:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365 case eVoteYes:
3366 case eVoteNoOpinion:
3367 return_value = true;
3368 break;
3369 case eVoteNo:
3370 return_value = false;
3371 break;
3372 }
3373 break;
3374 }
3375 break;
3376 case eStateStopped:
3377 case eStateCrashed:
3378 case eStateSuspended:
3379 {
3380 // We've stopped. First see if we're going to restart the target.
3381 // If we are going to stop, then we always broadcast the event.
3382 // 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 +00003383 // If no thread has an opinion, we don't report it.
Jim Inghamcb4ca112012-05-16 01:32:14 +00003384
3385 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003386 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003387 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003388 if (log)
3389 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003390 return true;
3391 }
3392 else
3393 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003394
3395 if (m_thread_list.ShouldStop (event_ptr) == false)
3396 {
Jim Inghamcb95f342012-09-05 21:13:56 +00003397 // ShouldStop may have restarted the target already. If so, don't
3398 // resume it twice.
3399 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003400 switch (m_thread_list.ShouldReportStop (event_ptr))
3401 {
3402 case eVoteYes:
3403 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003404 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003405 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003406 case eVoteNo:
3407 return_value = false;
3408 break;
3409 }
3410
3411 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003412 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Inghamcb95f342012-09-05 21:13:56 +00003413 if (!was_restarted)
3414 PrivateResume ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003415 }
3416 else
3417 {
3418 return_value = true;
3419 SynchronouslyNotifyStateChanged (state);
3420 }
3421 }
3422 }
3423 }
3424
3425 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003426 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003427 return return_value;
3428}
3429
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003430
3431bool
Jim Ingham372787f2012-04-07 00:00:41 +00003432Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003433{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003434 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003435
Greg Clayton8b82f082011-04-12 05:54:46 +00003436 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003437 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003438 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3439
Jim Ingham372787f2012-04-07 00:00:41 +00003440 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003441 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003442
3443 // Create a thread that watches our internal state and controls which
3444 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003445 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003446 if (already_running)
3447 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3448 else
3449 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003450
3451 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003452 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003453 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3454 if (success)
3455 {
3456 ResumePrivateStateThread();
3457 return true;
3458 }
3459 else
3460 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003461}
3462
3463void
3464Process::PausePrivateStateThread ()
3465{
3466 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3467}
3468
3469void
3470Process::ResumePrivateStateThread ()
3471{
3472 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3473}
3474
3475void
3476Process::StopPrivateStateThread ()
3477{
Greg Clayton8b82f082011-04-12 05:54:46 +00003478 if (PrivateStateThreadIsValid ())
3479 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003480 else
3481 {
3482 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3483 if (log)
3484 printf ("Went to stop the private state thread, but it was already invalid.");
3485 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003486}
3487
3488void
3489Process::ControlPrivateStateThread (uint32_t signal)
3490{
Jim Inghamb1e2e842012-04-12 18:49:31 +00003491 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003492
3493 assert (signal == eBroadcastInternalStateControlStop ||
3494 signal == eBroadcastInternalStateControlPause ||
3495 signal == eBroadcastInternalStateControlResume);
3496
3497 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003498 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003499
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003500 // Signal the private state thread. First we should copy this is case the
3501 // thread starts exiting since the private state thread will NULL this out
3502 // when it exits
3503 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003504 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003505 {
3506 TimeValue timeout_time;
3507 bool timed_out;
3508
3509 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3510
3511 timeout_time = TimeValue::Now();
3512 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003513 if (log)
3514 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003515 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3516 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3517
3518 if (signal == eBroadcastInternalStateControlStop)
3519 {
3520 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003521 {
3522 Error error;
3523 Host::ThreadCancel (private_state_thread, &error);
3524 if (log)
3525 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3526 }
3527 else
3528 {
3529 if (log)
3530 log->Printf ("The control event killed the private state thread without having to cancel.");
3531 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003532
3533 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003534 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003535 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003536 }
3537 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003538 else
3539 {
3540 if (log)
3541 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3542 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003543}
3544
3545void
Jim Inghamcfc09352012-07-27 23:57:19 +00003546Process::SendAsyncInterrupt ()
3547{
3548 if (PrivateStateThreadIsValid())
3549 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3550 else
3551 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3552}
3553
3554void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003555Process::HandlePrivateEvent (EventSP &event_sp)
3556{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003557 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003558 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003559
Greg Clayton414f5d32011-01-25 02:58:48 +00003560 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003561
3562 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003563 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003564 {
Jim Ingham754ab982011-01-29 04:05:41 +00003565 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003566 switch (action_result)
3567 {
3568 case NextEventAction::eEventActionSuccess:
3569 SetNextEventAction(NULL);
3570 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003571
Jim Inghambb3a2832011-01-29 01:49:25 +00003572 case NextEventAction::eEventActionRetry:
3573 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003574
Jim Inghambb3a2832011-01-29 01:49:25 +00003575 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003576 // Handle Exiting Here. If we already got an exited event,
3577 // we should just propagate it. Otherwise, swallow this event,
3578 // and set our state to exit so the next event will kill us.
3579 if (new_state != eStateExited)
3580 {
3581 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003582 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003583 SetNextEventAction(NULL);
3584 return;
3585 }
3586 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003587 break;
3588 }
3589 }
3590
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003591 // See if we should broadcast this state to external clients?
3592 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003593
3594 if (should_broadcast)
3595 {
3596 if (log)
3597 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003598 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003599 __FUNCTION__,
3600 GetID(),
3601 StateAsCString(new_state),
3602 StateAsCString (GetState ()),
3603 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003604 }
Jim Ingham9575d842011-03-11 03:53:59 +00003605 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003606 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003607 PushProcessInputReader ();
3608 else
3609 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003610
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003611 BroadcastEvent (event_sp);
3612 }
3613 else
3614 {
3615 if (log)
3616 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003617 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003618 __FUNCTION__,
3619 GetID(),
3620 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003621 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003622 }
3623 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003624 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003625}
3626
3627void *
3628Process::PrivateStateThread (void *arg)
3629{
3630 Process *proc = static_cast<Process*> (arg);
3631 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003632 return result;
3633}
3634
3635void *
3636Process::RunPrivateStateThread ()
3637{
Jim Ingham076b3042012-04-10 01:21:57 +00003638 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003639 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003640
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003641 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003642 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003643 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003644
3645 bool exit_now = false;
3646 while (!exit_now)
3647 {
3648 EventSP event_sp;
3649 WaitForEventsPrivate (NULL, event_sp, control_only);
3650 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3651 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003652 if (log)
3653 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3654
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003655 switch (event_sp->GetType())
3656 {
3657 case eBroadcastInternalStateControlStop:
3658 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003659 break; // doing any internal state managment below
3660
3661 case eBroadcastInternalStateControlPause:
3662 control_only = true;
3663 break;
3664
3665 case eBroadcastInternalStateControlResume:
3666 control_only = false;
3667 break;
3668 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003669
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003670 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003671 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003672 }
Jim Inghamcfc09352012-07-27 23:57:19 +00003673 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3674 {
3675 if (m_public_state.GetValue() == eStateAttaching)
3676 {
3677 if (log)
3678 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3679 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3680 }
3681 else
3682 {
3683 if (log)
3684 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3685 Halt();
3686 }
3687 continue;
3688 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003689
3690 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3691
3692 if (internal_state != eStateInvalid)
3693 {
3694 HandlePrivateEvent (event_sp);
3695 }
3696
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003697 if (internal_state == eStateInvalid ||
3698 internal_state == eStateExited ||
3699 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003700 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003701 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003702 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 +00003703
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003704 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003705 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003706 }
3707
Caroline Tice20ad3c42010-10-29 21:48:37 +00003708 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003709 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003710 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003711
Greg Clayton6ed95942011-01-22 07:12:45 +00003712 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3713 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003714 return NULL;
3715}
3716
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003717//------------------------------------------------------------------
3718// Process Event Data
3719//------------------------------------------------------------------
3720
3721Process::ProcessEventData::ProcessEventData () :
3722 EventData (),
3723 m_process_sp (),
3724 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003725 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003726 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003727 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003728{
3729}
3730
3731Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3732 EventData (),
3733 m_process_sp (process_sp),
3734 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003735 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003736 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003737 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003738{
3739}
3740
3741Process::ProcessEventData::~ProcessEventData()
3742{
3743}
3744
3745const ConstString &
3746Process::ProcessEventData::GetFlavorString ()
3747{
3748 static ConstString g_flavor ("Process::ProcessEventData");
3749 return g_flavor;
3750}
3751
3752const ConstString &
3753Process::ProcessEventData::GetFlavor () const
3754{
3755 return ProcessEventData::GetFlavorString ();
3756}
3757
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003758void
3759Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3760{
3761 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003762 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3763 // the public event queue, then other times when we're pretending that this is where we stopped at the
3764 // end of expression evaluation. m_update_state is used to distinguish these
3765 // three cases; it is 0 when we're just pulling it off for private handling,
3766 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003767
Jim Inghama8604692011-05-22 21:45:01 +00003768 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003769 return;
3770
3771 m_process_sp->SetPublicState (m_state);
3772
3773 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3774 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003775 {
3776 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003777 uint32_t num_threads = curr_thread_list.GetSize();
3778 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003779
Jim Ingham4b536182011-08-09 02:12:22 +00003780 // The actions might change one of the thread's stop_info's opinions about whether we should
3781 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003782
3783 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3784 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3785 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3786 // 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
3787 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003788 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003789 for (idx = 0; idx < num_threads; ++idx)
3790 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3791
Jim Ingham4b536182011-08-09 02:12:22 +00003792 bool still_should_stop = true;
3793
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003794 for (idx = 0; idx < num_threads; ++idx)
3795 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003796 curr_thread_list = m_process_sp->GetThreadList();
3797 if (curr_thread_list.GetSize() != num_threads)
3798 {
3799 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003800 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003801 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 +00003802 break;
3803 }
3804
3805 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3806
3807 if (thread_sp->GetIndexID() != thread_index_array[idx])
3808 {
3809 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003810 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003811 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003812 idx,
3813 thread_index_array[idx],
3814 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003815 break;
3816 }
3817
Jim Inghamb15bfc72010-10-20 00:39:53 +00003818 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00003819 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003820 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003821 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003822 // The stop action might restart the target. If it does, then we want to mark that in the
3823 // event so that whoever is receiving it will know to wait for the running event and reflect
3824 // that state appropriately.
3825 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003826
3827 // FIXME: we might have run.
3828 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003829 {
3830 SetRestarted (true);
3831 break;
3832 }
3833 else if (!stop_info_sp->ShouldStop(event_ptr))
3834 {
3835 still_should_stop = false;
3836 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003837 }
3838 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003839
Jim Ingham4b536182011-08-09 02:12:22 +00003840
3841 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003842 {
Jim Ingham4b536182011-08-09 02:12:22 +00003843 if (!still_should_stop)
3844 {
3845 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003846 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00003847 // Use the public resume method here, since this is just
3848 // extending a public resume.
Jim Ingham4b536182011-08-09 02:12:22 +00003849 m_process_sp->Resume();
3850 }
3851 else
3852 {
3853 // If we didn't restart, run the Stop Hooks here:
3854 // They might also restart the target, so watch for that.
3855 m_process_sp->GetTarget().RunStopHooks();
3856 if (m_process_sp->GetPrivateState() == eStateRunning)
3857 SetRestarted(true);
3858 }
Jim Ingham9575d842011-03-11 03:53:59 +00003859 }
3860
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003861 }
3862}
3863
3864void
3865Process::ProcessEventData::Dump (Stream *s) const
3866{
3867 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003868 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003869
Greg Clayton8b82f082011-04-12 05:54:46 +00003870 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003871}
3872
3873const Process::ProcessEventData *
3874Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3875{
3876 if (event_ptr)
3877 {
3878 const EventData *event_data = event_ptr->GetData();
3879 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3880 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3881 }
3882 return NULL;
3883}
3884
3885ProcessSP
3886Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3887{
3888 ProcessSP process_sp;
3889 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3890 if (data)
3891 process_sp = data->GetProcessSP();
3892 return process_sp;
3893}
3894
3895StateType
3896Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3897{
3898 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3899 if (data == NULL)
3900 return eStateInvalid;
3901 else
3902 return data->GetState();
3903}
3904
3905bool
3906Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3907{
3908 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3909 if (data == NULL)
3910 return false;
3911 else
3912 return data->GetRestarted();
3913}
3914
3915void
3916Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3917{
3918 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3919 if (data != NULL)
3920 data->SetRestarted(new_value);
3921}
3922
3923bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003924Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3925{
3926 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3927 if (data == NULL)
3928 return false;
3929 else
3930 return data->GetInterrupted ();
3931}
3932
3933void
3934Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3935{
3936 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3937 if (data != NULL)
3938 data->SetInterrupted(new_value);
3939}
3940
3941bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003942Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3943{
3944 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3945 if (data)
3946 {
3947 data->SetUpdateStateOnRemoval();
3948 return true;
3949 }
3950 return false;
3951}
3952
Greg Claytond9e416c2012-02-18 05:35:26 +00003953lldb::TargetSP
3954Process::CalculateTarget ()
3955{
3956 return m_target.shared_from_this();
3957}
3958
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003959void
Greg Clayton0603aa92010-10-04 01:05:56 +00003960Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003961{
Greg Claytonc14ee322011-09-22 04:58:26 +00003962 exe_ctx.SetTargetPtr (&m_target);
3963 exe_ctx.SetProcessPtr (this);
3964 exe_ctx.SetThreadPtr(NULL);
3965 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003966}
3967
Greg Claytone996fd32011-03-08 22:40:15 +00003968//uint32_t
3969//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3970//{
3971// return 0;
3972//}
3973//
3974//ArchSpec
3975//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3976//{
3977// return Host::GetArchSpecForExistingProcess (pid);
3978//}
3979//
3980//ArchSpec
3981//Process::GetArchSpecForExistingProcess (const char *process_name)
3982//{
3983// return Host::GetArchSpecForExistingProcess (process_name);
3984//}
3985//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003986void
3987Process::AppendSTDOUT (const char * s, size_t len)
3988{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003989 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003990 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00003991 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003992}
3993
3994void
Greg Clayton93e86192011-11-13 04:45:22 +00003995Process::AppendSTDERR (const char * s, size_t len)
3996{
3997 Mutex::Locker locker (m_stdio_communication_mutex);
3998 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00003999 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004000}
4001
4002//------------------------------------------------------------------
4003// Process STDIO
4004//------------------------------------------------------------------
4005
4006size_t
4007Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4008{
4009 Mutex::Locker locker(m_stdio_communication_mutex);
4010 size_t bytes_available = m_stdout_data.size();
4011 if (bytes_available > 0)
4012 {
4013 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4014 if (log)
Greg Clayton43e0af02012-09-18 18:04:04 +00004015 log->Printf ("Process::GetSTDOUT (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004016 if (bytes_available > buf_size)
4017 {
4018 memcpy(buf, m_stdout_data.c_str(), buf_size);
4019 m_stdout_data.erase(0, buf_size);
4020 bytes_available = buf_size;
4021 }
4022 else
4023 {
4024 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4025 m_stdout_data.clear();
4026 }
4027 }
4028 return bytes_available;
4029}
4030
4031
4032size_t
4033Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4034{
4035 Mutex::Locker locker(m_stdio_communication_mutex);
4036 size_t bytes_available = m_stderr_data.size();
4037 if (bytes_available > 0)
4038 {
4039 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4040 if (log)
Greg Clayton43e0af02012-09-18 18:04:04 +00004041 log->Printf ("Process::GetSTDERR (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004042 if (bytes_available > buf_size)
4043 {
4044 memcpy(buf, m_stderr_data.c_str(), buf_size);
4045 m_stderr_data.erase(0, buf_size);
4046 bytes_available = buf_size;
4047 }
4048 else
4049 {
4050 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4051 m_stderr_data.clear();
4052 }
4053 }
4054 return bytes_available;
4055}
4056
4057void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004058Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4059{
4060 Process *process = (Process *) baton;
4061 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4062}
4063
4064size_t
4065Process::ProcessInputReaderCallback (void *baton,
4066 InputReader &reader,
4067 lldb::InputReaderAction notification,
4068 const char *bytes,
4069 size_t bytes_len)
4070{
4071 Process *process = (Process *) baton;
4072
4073 switch (notification)
4074 {
4075 case eInputReaderActivate:
4076 break;
4077
4078 case eInputReaderDeactivate:
4079 break;
4080
4081 case eInputReaderReactivate:
4082 break;
4083
Caroline Tice969ed3d2011-05-02 20:41:46 +00004084 case eInputReaderAsynchronousOutputWritten:
4085 break;
4086
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004087 case eInputReaderGotToken:
4088 {
4089 Error error;
4090 process->PutSTDIN (bytes, bytes_len, error);
4091 }
4092 break;
4093
Caroline Ticeefed6132010-11-19 20:47:54 +00004094 case eInputReaderInterrupt:
4095 process->Halt ();
4096 break;
4097
4098 case eInputReaderEndOfFile:
4099 process->AppendSTDOUT ("^D", 2);
4100 break;
4101
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004102 case eInputReaderDone:
4103 break;
4104
4105 }
4106
4107 return bytes_len;
4108}
4109
4110void
4111Process::ResetProcessInputReader ()
4112{
4113 m_process_input_reader.reset();
4114}
4115
4116void
Greg Claytonee95ed52011-11-17 22:14:31 +00004117Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004118{
4119 // First set up the Read Thread for reading/handling process I/O
4120
4121 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4122
4123 if (conn_ap.get())
4124 {
4125 m_stdio_communication.SetConnection (conn_ap.release());
4126 if (m_stdio_communication.IsConnected())
4127 {
4128 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4129 m_stdio_communication.StartReadThread();
4130
4131 // Now read thread is set up, set up input reader.
4132
4133 if (!m_process_input_reader.get())
4134 {
4135 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4136 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4137 this,
4138 eInputReaderGranularityByte,
4139 NULL,
4140 NULL,
4141 false));
4142
4143 if (err.Fail())
4144 m_process_input_reader.reset();
4145 }
4146 }
4147 }
4148}
4149
4150void
4151Process::PushProcessInputReader ()
4152{
4153 if (m_process_input_reader && !m_process_input_reader->IsActive())
4154 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4155}
4156
4157void
4158Process::PopProcessInputReader ()
4159{
4160 if (m_process_input_reader && m_process_input_reader->IsActive())
4161 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4162}
4163
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004164// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004165void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004166Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004167{
Greg Clayton67cc0632012-08-22 17:17:09 +00004168// static std::vector<OptionEnumValueElement> g_plugins;
4169//
4170// int i=0;
4171// const char *name;
4172// OptionEnumValueElement option_enum;
4173// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4174// {
4175// if (name)
4176// {
4177// option_enum.value = i;
4178// option_enum.string_value = name;
4179// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4180// g_plugins.push_back (option_enum);
4181// }
4182// ++i;
4183// }
4184// option_enum.value = 0;
4185// option_enum.string_value = NULL;
4186// option_enum.usage = NULL;
4187// g_plugins.push_back (option_enum);
4188//
4189// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4190// {
4191// if (::strcmp (name, "plugin") == 0)
4192// {
4193// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4194// break;
4195// }
4196// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004197//
Greg Clayton6920b522012-08-22 18:39:03 +00004198 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004199}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004200
Greg Clayton99d0faf2010-11-18 23:32:35 +00004201void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004202Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004203{
Greg Clayton6920b522012-08-22 18:39:03 +00004204 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004205}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004206
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004207ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004208Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004209 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00004210 bool stop_others,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004211 bool run_others,
Jim Inghamf48169b2010-11-30 02:22:11 +00004212 bool discard_on_error,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004213 uint32_t timeout_usec,
Jim Inghamf48169b2010-11-30 02:22:11 +00004214 Stream &errors)
4215{
4216 ExecutionResults return_value = eExecutionSetupError;
4217
Jim Ingham77787032011-01-20 02:03:18 +00004218 if (thread_plan_sp.get() == NULL)
4219 {
4220 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004221 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004222 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004223
4224 if (exe_ctx.GetProcessPtr() != this)
4225 {
4226 errors.Printf("RunThreadPlan called on wrong process.");
4227 return eExecutionSetupError;
4228 }
4229
4230 Thread *thread = exe_ctx.GetThreadPtr();
4231 if (thread == NULL)
4232 {
4233 errors.Printf("RunThreadPlan called with invalid thread.");
4234 return eExecutionSetupError;
4235 }
Jim Ingham77787032011-01-20 02:03:18 +00004236
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004237 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4238 // For that to be true the plan can't be private - since private plans suppress themselves in the
4239 // GetCompletedPlan call.
4240
4241 bool orig_plan_private = thread_plan_sp->GetPrivate();
4242 thread_plan_sp->SetPrivate(false);
4243
Jim Ingham444586b2011-01-24 06:34:17 +00004244 if (m_private_state.GetValue() != eStateStopped)
4245 {
4246 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004247 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004248 }
4249
Jim Ingham66243842011-08-13 00:56:10 +00004250 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004251 const uint32_t thread_idx_id = thread->GetIndexID();
4252 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004253
4254 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4255 // so we should arrange to reset them as well.
4256
Greg Claytonc14ee322011-09-22 04:58:26 +00004257 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004258
Jim Ingham66243842011-08-13 00:56:10 +00004259 uint32_t selected_tid;
4260 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004261 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004262 {
4263 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004264 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004265 }
4266 else
4267 {
4268 selected_tid = LLDB_INVALID_THREAD_ID;
4269 }
4270
Jim Ingham372787f2012-04-07 00:00:41 +00004271 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004272 lldb::StateType old_state;
4273 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004274
Jim Ingham076b3042012-04-10 01:21:57 +00004275 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004276 if (Host::GetCurrentThread() == m_private_state_thread)
4277 {
Jim Ingham076b3042012-04-10 01:21:57 +00004278 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4279 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004280 // 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 +00004281 // we are fielding public events here.
4282 if (log)
4283 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4284
4285
Jim Ingham372787f2012-04-07 00:00:41 +00004286 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004287
4288 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4289 // returning control here.
4290 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4291 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4292 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4293 // do just what we want.
4294 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4295 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4296 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4297 old_state = m_public_state.GetValue();
4298 m_public_state.SetValueNoLock(eStateStopped);
4299
4300 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004301 StartPrivateStateThread(true);
4302 }
4303
4304 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004305
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004306 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004307
Sean Callanana46ec452012-07-11 21:31:24 +00004308 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004309
Jim Ingham77787032011-01-20 02:03:18 +00004310 {
Sean Callanana46ec452012-07-11 21:31:24 +00004311 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4312 // restored on exit to the function.
4313 //
4314 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4315 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004316
Sean Callanana46ec452012-07-11 21:31:24 +00004317 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004318
Jim Inghamf48169b2010-11-30 02:22:11 +00004319 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004320 {
4321 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004322 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4323 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4324 thread->GetIndexID(),
4325 thread->GetID(),
4326 s.GetData());
4327 }
4328
4329 bool got_event;
4330 lldb::EventSP event_sp;
4331 lldb::StateType stop_state = lldb::eStateInvalid;
4332
4333 TimeValue* timeout_ptr = NULL;
4334 TimeValue real_timeout;
4335
4336 bool first_timeout = true;
4337 bool do_resume = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004338 const uint64_t default_one_thread_timeout_usec = 250000;
4339 uint64_t computed_timeout = 0;
Sean Callanana46ec452012-07-11 21:31:24 +00004340
4341 while (1)
4342 {
4343 // We usually want to resume the process if we get to the top of the loop.
4344 // The only exception is if we get two running events with no intervening
4345 // stop, which can happen, we will just wait for then next stop event.
4346
4347 if (do_resume)
4348 {
4349 // Do the initial resume and wait for the running event before going further.
4350
4351 Error resume_error = PrivateResume ();
4352 if (!resume_error.Success())
4353 {
4354 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4355 return_value = eExecutionSetupError;
4356 break;
4357 }
4358
4359 real_timeout = TimeValue::Now();
4360 real_timeout.OffsetWithMicroSeconds(500000);
4361 timeout_ptr = &real_timeout;
4362
4363 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4364 if (!got_event)
4365 {
4366 if (log)
4367 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4368
4369 errors.Printf("Didn't get any event after initial resume, exiting.");
4370 return_value = eExecutionSetupError;
4371 break;
4372 }
4373
4374 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4375 if (stop_state != eStateRunning)
4376 {
4377 if (log)
Jim Ingham35e1bda2012-10-16 21:41:58 +00004378 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4379 "initial resume, got %s instead.",
4380 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004381
Jim Ingham35e1bda2012-10-16 21:41:58 +00004382 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4383 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004384 return_value = eExecutionSetupError;
4385 break;
4386 }
4387
4388 if (log)
4389 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4390 // We need to call the function synchronously, so spin waiting for it to return.
4391 // If we get interrupted while executing, we're going to lose our context, and
4392 // won't be able to gather the result at this point.
4393 // We set the timeout AFTER the resume, since the resume takes some time and we
4394 // don't want to charge that to the timeout.
4395
Jim Ingham35e1bda2012-10-16 21:41:58 +00004396 if (first_timeout)
4397 {
4398 if (run_others)
4399 {
4400 // If we are running all threads then we take half the time to run all threads, bounded by
4401 // .25 sec.
4402 if (timeout_usec == 0)
4403 computed_timeout = default_one_thread_timeout_usec;
4404 else
4405 {
4406 computed_timeout = timeout_usec / 2;
4407 if (computed_timeout > default_one_thread_timeout_usec)
4408 {
4409 computed_timeout = default_one_thread_timeout_usec;
4410 }
4411 timeout_usec -= computed_timeout;
4412 }
4413 }
4414 else
4415 {
4416 computed_timeout = timeout_usec;
4417 }
4418 }
4419 else
4420 {
4421 computed_timeout = timeout_usec;
4422 }
4423
4424 if (computed_timeout != 0)
Sean Callanana46ec452012-07-11 21:31:24 +00004425 {
Enrico Granata3372f582012-07-16 23:10:35 +00004426 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanana46ec452012-07-11 21:31:24 +00004427 real_timeout = TimeValue::Now();
Jim Ingham35e1bda2012-10-16 21:41:58 +00004428 real_timeout.OffsetWithMicroSeconds(computed_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00004429
4430 timeout_ptr = &real_timeout;
4431 }
Enrico Granata3372f582012-07-16 23:10:35 +00004432 else
4433 {
Jim Ingham35e1bda2012-10-16 21:41:58 +00004434 timeout_ptr = NULL;
Enrico Granata3372f582012-07-16 23:10:35 +00004435 }
Sean Callanana46ec452012-07-11 21:31:24 +00004436 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004437 else
4438 {
Sean Callanana46ec452012-07-11 21:31:24 +00004439 if (log)
4440 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4441 do_resume = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00004442 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004443
Sean Callanana46ec452012-07-11 21:31:24 +00004444 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00004445 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00004446
Jim Ingham0f16e732011-02-08 05:20:59 +00004447 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004448 {
Sean Callanana46ec452012-07-11 21:31:24 +00004449 if (timeout_ptr)
4450 {
4451 StreamString s;
4452 s.Printf ("about to wait - timeout is:\n ");
4453 timeout_ptr->Dump (&s, 120);
4454 s.Printf ("\nNow is:\n ");
4455 TimeValue::Now().Dump (&s, 120);
4456 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4457 }
Jim Ingham20829ac2011-08-09 22:24:33 +00004458 else
Sean Callanana46ec452012-07-11 21:31:24 +00004459 {
4460 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4461 }
4462 }
4463
4464 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4465
4466 if (got_event)
4467 {
4468 if (event_sp.get())
4469 {
4470 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00004471 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004472 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004473 Halt();
4474 keep_going = false;
4475 return_value = eExecutionInterrupted;
4476 errors.Printf ("Execution halted by user interrupt.");
4477 if (log)
4478 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4479 }
4480 else
4481 {
4482 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4483 if (log)
4484 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4485
4486 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00004487 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004488 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00004489 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004490 // Yay, we're done. Now make sure that our thread plan actually completed.
4491 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4492 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004493 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004494 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00004495 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00004496 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4497 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00004498 }
4499 else
4500 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004501 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4502 StopReason stop_reason = eStopReasonInvalid;
4503 if (stop_info_sp)
4504 stop_reason = stop_info_sp->GetStopReason();
4505 if (stop_reason == eStopReasonPlanComplete)
4506 {
4507 if (log)
4508 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4509 // Now mark this plan as private so it doesn't get reported as the stop reason
4510 // after this point.
4511 if (thread_plan_sp)
4512 thread_plan_sp->SetPrivate (orig_plan_private);
4513 return_value = eExecutionCompleted;
4514 }
4515 else
4516 {
4517 if (log)
4518 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanana46ec452012-07-11 21:31:24 +00004519
Jim Inghamcfc09352012-07-27 23:57:19 +00004520 return_value = eExecutionInterrupted;
4521 }
Sean Callanana46ec452012-07-11 21:31:24 +00004522 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004523 }
4524 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004525
Jim Inghamcfc09352012-07-27 23:57:19 +00004526 case lldb::eStateCrashed:
4527 if (log)
4528 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4529 return_value = eExecutionInterrupted;
4530 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004531
Jim Inghamcfc09352012-07-27 23:57:19 +00004532 case lldb::eStateRunning:
4533 do_resume = false;
4534 keep_going = true;
4535 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004536
Jim Inghamcfc09352012-07-27 23:57:19 +00004537 default:
4538 if (log)
4539 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4540
4541 if (stop_state == eStateExited)
4542 event_to_broadcast_sp = event_sp;
4543
Sean Callananbf154da2012-08-08 17:35:10 +00004544 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00004545 return_value = eExecutionInterrupted;
4546 break;
4547 }
Sean Callanana46ec452012-07-11 21:31:24 +00004548 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004549
Sean Callanana46ec452012-07-11 21:31:24 +00004550 if (keep_going)
4551 continue;
4552 else
4553 break;
4554 }
4555 else
4556 {
4557 if (log)
4558 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4559 return_value = eExecutionInterrupted;
4560 break;
4561 }
4562 }
4563 else
4564 {
4565 // If we didn't get an event that means we've timed out...
4566 // We will interrupt the process here. Depending on what we were asked to do we will
4567 // either exit, or try with all threads running for the same timeout.
4568 // Not really sure what to do if Halt fails here...
4569
4570 if (log) {
Jim Ingham35e1bda2012-10-16 21:41:58 +00004571 if (run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00004572 {
4573 if (first_timeout)
Jim Ingham35e1bda2012-10-16 21:41:58 +00004574 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %lld timed out, "
4575 "trying for %d usec with all threads enabled.",
4576 computed_timeout, timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004577 else
4578 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham35e1bda2012-10-16 21:41:58 +00004579 "and timeout: %d timed out, abandoning execution.",
4580 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004581 }
4582 else
4583 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00004584 "abandoning execution.",
4585 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004586 }
4587
4588 Error halt_error = Halt();
4589 if (halt_error.Success())
4590 {
4591 if (log)
4592 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4593
4594 // If halt succeeds, it always produces a stopped event. Wait for that:
4595
4596 real_timeout = TimeValue::Now();
4597 real_timeout.OffsetWithMicroSeconds(500000);
4598
4599 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4600
4601 if (got_event)
4602 {
4603 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4604 if (log)
4605 {
4606 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4607 if (stop_state == lldb::eStateStopped
4608 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4609 log->PutCString (" Event was the Halt interruption event.");
4610 }
4611
4612 if (stop_state == lldb::eStateStopped)
4613 {
4614 // Between the time we initiated the Halt and the time we delivered it, the process could have
4615 // already finished its job. Check that here:
4616
4617 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4618 {
4619 if (log)
4620 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4621 "Exiting wait loop.");
4622 return_value = eExecutionCompleted;
4623 break;
4624 }
4625
Jim Ingham35e1bda2012-10-16 21:41:58 +00004626 if (!run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00004627 {
4628 if (log)
4629 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4630 return_value = eExecutionInterrupted;
4631 break;
4632 }
4633
4634 if (first_timeout)
4635 {
4636 // Set all the other threads to run, and return to the top of the loop, which will continue;
4637 first_timeout = false;
4638 thread_plan_sp->SetStopOthers (false);
4639 if (log)
4640 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4641
4642 continue;
4643 }
4644 else
4645 {
4646 // Running all threads failed, so return Interrupted.
4647 if (log)
4648 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4649 return_value = eExecutionInterrupted;
4650 break;
4651 }
4652 }
4653 }
4654 else
4655 { if (log)
4656 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4657 "I'm getting out of here passing Interrupted.");
4658 return_value = eExecutionInterrupted;
4659 break;
4660 }
4661 }
4662 else
4663 {
4664 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4665 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4666 if (log)
4667 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.",
4668 halt_error.AsCString());
4669 real_timeout = TimeValue::Now();
4670 real_timeout.OffsetWithMicroSeconds(500000);
4671 timeout_ptr = &real_timeout;
4672 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4673 if (!got_event || event_sp.get() == NULL)
4674 {
4675 // This is not going anywhere, bag out.
4676 if (log)
4677 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4678 return_value = eExecutionInterrupted;
4679 break;
4680 }
4681 else
4682 {
4683 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4684 if (log)
4685 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4686 if (stop_state == lldb::eStateStopped)
4687 {
4688 // Between the time we initiated the Halt and the time we delivered it, the process could have
4689 // already finished its job. Check that here:
4690
4691 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4692 {
4693 if (log)
4694 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4695 "Exiting wait loop.");
4696 return_value = eExecutionCompleted;
4697 break;
4698 }
4699
4700 if (first_timeout)
4701 {
4702 // Set all the other threads to run, and return to the top of the loop, which will continue;
4703 first_timeout = false;
4704 thread_plan_sp->SetStopOthers (false);
4705 if (log)
4706 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4707
4708 continue;
4709 }
4710 else
4711 {
4712 // Running all threads failed, so return Interrupted.
4713 if (log)
4714 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4715 return_value = eExecutionInterrupted;
4716 break;
4717 }
4718 }
4719 else
4720 {
4721 if (log)
4722 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4723 " a stopped event, instead got %s.", StateAsCString(stop_state));
4724 return_value = eExecutionInterrupted;
4725 break;
4726 }
4727 }
4728 }
4729
4730 }
4731
4732 } // END WAIT LOOP
4733
4734 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4735 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4736 {
4737 StopPrivateStateThread();
4738 Error error;
4739 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00004740 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004741 {
4742 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4743 }
4744 m_public_state.SetValueNoLock(old_state);
4745
4746 }
4747
4748
4749 // Now do some processing on the results of the run:
4750 if (return_value == eExecutionInterrupted)
4751 {
4752 if (log)
4753 {
4754 StreamString s;
4755 if (event_sp)
4756 event_sp->Dump (&s);
4757 else
4758 {
4759 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4760 }
4761
4762 StreamString ts;
4763
4764 const char *event_explanation = NULL;
4765
4766 do
4767 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004768 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004769 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004770 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00004771 break;
4772 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004773 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004774 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004775 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00004776 break;
4777 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004778 else
Sean Callanana46ec452012-07-11 21:31:24 +00004779 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004780 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4781
4782 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00004783 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004784 event_explanation = "<no event data>";
4785 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004786 }
4787
Jim Inghamcfc09352012-07-27 23:57:19 +00004788 Process *process = event_data->GetProcessSP().get();
4789
4790 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00004791 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004792 event_explanation = "<no process>";
4793 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004794 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004795
4796 ThreadList &thread_list = process->GetThreadList();
4797
4798 uint32_t num_threads = thread_list.GetSize();
4799 uint32_t thread_index;
4800
4801 ts.Printf("<%u threads> ", num_threads);
4802
4803 for (thread_index = 0;
4804 thread_index < num_threads;
4805 ++thread_index)
4806 {
4807 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4808
4809 if (!thread)
4810 {
4811 ts.Printf("<?> ");
4812 continue;
4813 }
4814
4815 ts.Printf("<0x%4.4llx ", thread->GetID());
4816 RegisterContext *register_context = thread->GetRegisterContext().get();
4817
4818 if (register_context)
4819 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4820 else
4821 ts.Printf("[ip unknown] ");
4822
4823 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4824 if (stop_info_sp)
4825 {
4826 const char *stop_desc = stop_info_sp->GetDescription();
4827 if (stop_desc)
4828 ts.PutCString (stop_desc);
4829 }
4830 ts.Printf(">");
4831 }
4832
4833 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00004834 }
Sean Callanana46ec452012-07-11 21:31:24 +00004835 } while (0);
4836
Jim Inghamcfc09352012-07-27 23:57:19 +00004837 if (event_explanation)
4838 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00004839 else
Jim Inghamcfc09352012-07-27 23:57:19 +00004840 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4841 }
4842
4843 if (discard_on_error && thread_plan_sp)
4844 {
4845 if (log)
4846 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4847 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4848 thread_plan_sp->SetPrivate (orig_plan_private);
4849 }
4850 else
4851 {
4852 if (log)
4853 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00004854 }
4855 }
4856 else if (return_value == eExecutionSetupError)
4857 {
4858 if (log)
4859 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004860
4861 if (discard_on_error && thread_plan_sp)
4862 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004863 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004864 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004865 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004866 }
4867 else
4868 {
Sean Callanana46ec452012-07-11 21:31:24 +00004869 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004870 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004871 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00004872 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4873 return_value = eExecutionCompleted;
4874 }
4875 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4876 {
4877 if (log)
4878 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4879 return_value = eExecutionDiscarded;
4880 }
4881 else
4882 {
4883 if (log)
4884 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4885 if (discard_on_error && thread_plan_sp)
4886 {
4887 if (log)
4888 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4889 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4890 thread_plan_sp->SetPrivate (orig_plan_private);
4891 }
4892 }
4893 }
4894
4895 // Thread we ran the function in may have gone away because we ran the target
4896 // Check that it's still there, and if it is put it back in the context. Also restore the
4897 // frame in the context if it is still present.
4898 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4899 if (thread)
4900 {
4901 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4902 }
4903
4904 // Also restore the current process'es selected frame & thread, since this function calling may
4905 // be done behind the user's back.
4906
4907 if (selected_tid != LLDB_INVALID_THREAD_ID)
4908 {
4909 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4910 {
4911 // We were able to restore the selected thread, now restore the frame:
4912 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4913 if (old_frame_sp)
4914 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004915 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004916 }
4917 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004918
Sean Callanana46ec452012-07-11 21:31:24 +00004919 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00004920
Sean Callanana46ec452012-07-11 21:31:24 +00004921 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004922 {
Sean Callanana46ec452012-07-11 21:31:24 +00004923 if (log)
4924 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4925 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004926 }
4927
4928 return return_value;
4929}
4930
4931const char *
4932Process::ExecutionResultAsCString (ExecutionResults result)
4933{
4934 const char *result_name;
4935
4936 switch (result)
4937 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004938 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004939 result_name = "eExecutionCompleted";
4940 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004941 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004942 result_name = "eExecutionDiscarded";
4943 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004944 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004945 result_name = "eExecutionInterrupted";
4946 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004947 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004948 result_name = "eExecutionSetupError";
4949 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004950 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004951 result_name = "eExecutionTimedOut";
4952 break;
4953 }
4954 return result_name;
4955}
4956
Greg Clayton7260f622011-04-18 08:33:37 +00004957void
4958Process::GetStatus (Stream &strm)
4959{
4960 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00004961 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00004962 {
4963 if (state == eStateExited)
4964 {
4965 int exit_status = GetExitStatus();
4966 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004967 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004968 GetID(),
4969 exit_status,
4970 exit_status,
4971 exit_description ? exit_description : "");
4972 }
4973 else
4974 {
4975 if (state == eStateConnected)
4976 strm.Printf ("Connected to remote target.\n");
4977 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004978 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004979 }
4980 }
4981 else
4982 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004983 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004984 }
4985}
4986
4987size_t
4988Process::GetThreadStatus (Stream &strm,
4989 bool only_threads_with_stop_reason,
4990 uint32_t start_frame,
4991 uint32_t num_frames,
4992 uint32_t num_frames_with_source)
4993{
4994 size_t num_thread_infos_dumped = 0;
4995
Jim Ingham41f2b942012-09-10 20:50:15 +00004996 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00004997 const size_t num_threads = GetThreadList().GetSize();
4998 for (uint32_t i = 0; i < num_threads; i++)
4999 {
5000 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5001 if (thread)
5002 {
5003 if (only_threads_with_stop_reason)
5004 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005005 StopInfoSP stop_info_sp = thread->GetStopInfo();
5006 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005007 continue;
5008 }
5009 thread->GetStatus (strm,
5010 start_frame,
5011 num_frames,
5012 num_frames_with_source);
5013 ++num_thread_infos_dumped;
5014 }
5015 }
5016 return num_thread_infos_dumped;
5017}
5018
Greg Claytona9f40ad2012-02-22 04:37:26 +00005019void
5020Process::AddInvalidMemoryRegion (const LoadRange &region)
5021{
5022 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5023}
5024
5025bool
5026Process::RemoveInvalidMemoryRange (const LoadRange &region)
5027{
5028 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5029}
5030
Jim Ingham372787f2012-04-07 00:00:41 +00005031void
5032Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5033{
5034 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5035}
5036
5037bool
5038Process::RunPreResumeActions ()
5039{
5040 bool result = true;
5041 while (!m_pre_resume_actions.empty())
5042 {
5043 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5044 m_pre_resume_actions.pop_back();
5045 bool this_result = action.callback (action.baton);
5046 if (result == true) result = this_result;
5047 }
5048 return result;
5049}
5050
5051void
5052Process::ClearPreResumeActions ()
5053{
5054 m_pre_resume_actions.clear();
5055}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005056
Greg Claytonfa559e52012-05-18 02:38:05 +00005057void
5058Process::Flush ()
5059{
5060 m_thread_list.Flush();
5061}