blob: 6ece3196ca48ef3cde5115f53ef9055c4f5c3ec6 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000021#include "lldb/Core/Module.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
23#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000024#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000025#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Host/Host.h"
27#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000028#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000029#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000030#include "lldb/Target/LanguageRuntime.h"
31#include "lldb/Target/CPPLanguageRuntime.h"
32#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000033#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000035#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Target/Target.h"
37#include "lldb/Target/TargetList.h"
38#include "lldb/Target/Thread.h"
39#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000040#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041
42using namespace lldb;
43using namespace lldb_private;
44
Greg Clayton67cc0632012-08-22 17:17:09 +000045
46// Comment out line below to disable memory caching, overriding the process setting
47// target.process.disable-memory-cache
48#define ENABLE_MEMORY_CACHING
49
50#ifdef ENABLE_MEMORY_CACHING
51#define DISABLE_MEM_CACHE_DEFAULT false
52#else
53#define DISABLE_MEM_CACHE_DEFAULT true
54#endif
55
56class ProcessOptionValueProperties : public OptionValueProperties
57{
58public:
59 ProcessOptionValueProperties (const ConstString &name) :
60 OptionValueProperties (name)
61 {
62 }
63
64 // This constructor is used when creating ProcessOptionValueProperties when it
65 // is part of a new lldb_private::Process instance. It will copy all current
66 // global property values as needed
67 ProcessOptionValueProperties (ProcessProperties *global_properties) :
68 OptionValueProperties(*global_properties->GetValueProperties())
69 {
70 }
71
72 virtual const Property *
73 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
74 {
75 // When gettings the value for a key from the process options, we will always
76 // try and grab the setting from the current process if there is one. Else we just
77 // use the one from this instance.
78 if (exe_ctx)
79 {
80 Process *process = exe_ctx->GetProcessPtr();
81 if (process)
82 {
83 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
84 if (this != instance_properties)
85 return instance_properties->ProtectedGetPropertyAtIndex (idx);
86 }
87 }
88 return ProtectedGetPropertyAtIndex (idx);
89 }
90};
91
92static PropertyDefinition
93g_properties[] =
94{
95 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
96 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used." },
Greg Claytonc9d645d2012-10-18 22:40:37 +000097 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, 0, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
Greg Clayton67cc0632012-08-22 17:17:09 +000098 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
99};
100
101enum {
102 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000103 ePropertyExtraStartCommand,
104 ePropertyPythonOSPluginPath
Greg Clayton67cc0632012-08-22 17:17:09 +0000105};
106
107ProcessProperties::ProcessProperties (bool is_global) :
108 Properties ()
109{
110 if (is_global)
111 {
112 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
113 m_collection_sp->Initialize(g_properties);
114 m_collection_sp->AppendProperty(ConstString("thread"),
115 ConstString("Settings specify to threads."),
116 true,
117 Thread::GetGlobalProperties()->GetValueProperties());
118 }
119 else
120 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
121}
122
123ProcessProperties::~ProcessProperties()
124{
125}
126
127bool
128ProcessProperties::GetDisableMemoryCache() const
129{
130 const uint32_t idx = ePropertyDisableMemCache;
131 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
132}
133
134Args
135ProcessProperties::GetExtraStartupCommands () const
136{
137 Args args;
138 const uint32_t idx = ePropertyExtraStartCommand;
139 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
140 return args;
141}
142
143void
144ProcessProperties::SetExtraStartupCommands (const Args &args)
145{
146 const uint32_t idx = ePropertyExtraStartCommand;
147 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
148}
149
Greg Claytonc9d645d2012-10-18 22:40:37 +0000150FileSpec
151ProcessProperties::GetPythonOSPluginPath () const
152{
153 const uint32_t idx = ePropertyPythonOSPluginPath;
154 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
155}
156
157void
158ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
159{
160 const uint32_t idx = ePropertyPythonOSPluginPath;
161 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
162}
163
Greg Clayton32e0a752011-03-30 18:16:51 +0000164void
Greg Clayton8b82f082011-04-12 05:54:46 +0000165ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000166{
167 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000168 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +0000169 s.Printf (" pid = %llu\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000170
171 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +0000172 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000173
174 if (m_executable)
175 {
176 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
177 s.PutCString (" file = ");
178 m_executable.Dump(&s);
179 s.EOL();
180 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000181 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000182 if (argc > 0)
183 {
184 for (uint32_t i=0; i<argc; i++)
185 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000186 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000187 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000188 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000189 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000190 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000191 }
192 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000193
194 const uint32_t envc = m_environment.GetArgumentCount();
195 if (envc > 0)
196 {
197 for (uint32_t i=0; i<envc; i++)
198 {
199 const char *env = m_environment.GetArgumentAtIndex(i);
200 if (i < 10)
201 s.Printf (" env[%u] = %s\n", i, env);
202 else
203 s.Printf ("env[%u] = %s\n", i, env);
204 }
205 }
206
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000207 if (m_arch.IsValid())
208 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
209
Greg Clayton8b82f082011-04-12 05:54:46 +0000210 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000211 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000212 cstr = platform->GetUserName (m_uid);
213 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000214 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000215 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000216 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000217 cstr = platform->GetGroupName (m_gid);
218 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000219 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000220 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000221 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000222 cstr = platform->GetUserName (m_euid);
223 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000224 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000225 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000226 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000227 cstr = platform->GetGroupName (m_egid);
228 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000229 }
230}
231
232void
Greg Clayton8b82f082011-04-12 05:54:46 +0000233ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000234{
Greg Clayton8b82f082011-04-12 05:54:46 +0000235 const char *label;
236 if (show_args || verbose)
237 label = "ARGUMENTS";
238 else
239 label = "NAME";
240
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000241 if (verbose)
242 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000243 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000244 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
245 }
246 else
247 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000248 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000249 s.PutCString ("====== ====== ========== ======= ============================\n");
250 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000251}
252
253void
Greg Clayton8b82f082011-04-12 05:54:46 +0000254ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000255{
256 if (m_pid != LLDB_INVALID_PROCESS_ID)
257 {
258 const char *cstr;
Greg Clayton61e7a582011-12-01 23:28:38 +0000259 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000260
Greg Clayton32e0a752011-03-30 18:16:51 +0000261
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000262 if (verbose)
263 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000264 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000265 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
266 s.Printf ("%-10s ", cstr);
267 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000268 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000269
Greg Clayton8b82f082011-04-12 05:54:46 +0000270 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000271 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
272 s.Printf ("%-10s ", cstr);
273 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000274 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000275
Greg Clayton8b82f082011-04-12 05:54:46 +0000276 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000277 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
278 s.Printf ("%-10s ", cstr);
279 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000280 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000281
Greg Clayton8b82f082011-04-12 05:54:46 +0000282 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000283 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
284 s.Printf ("%-10s ", cstr);
285 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000286 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000287 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
288 }
289 else
290 {
Jason Molendafd54b362011-09-20 21:44:10 +0000291 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000292 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000293 (int)m_arch.GetTriple().getArchName().size(),
294 m_arch.GetTriple().getArchName().data());
295 }
296
Greg Clayton8b82f082011-04-12 05:54:46 +0000297 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000298 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000299 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000300 if (argc > 0)
301 {
302 for (uint32_t i=0; i<argc; i++)
303 {
304 if (i > 0)
305 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000306 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000307 }
308 }
309 }
310 else
311 {
312 s.PutCString (GetName());
313 }
314
315 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000316 }
317}
318
Greg Clayton8b82f082011-04-12 05:54:46 +0000319
320void
Greg Clayton45392552012-10-17 22:57:12 +0000321ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton982c9762011-11-03 21:22:33 +0000322{
323 m_arguments.SetArguments (argv);
324
325 // Is the first argument the executable?
326 if (first_arg_is_executable)
327 {
328 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
329 if (first_arg)
330 {
331 // Yes the first argument is an executable, set it as the executable
332 // in the launch options. Don't resolve the file path as the path
333 // could be a remote platform path
334 const bool resolve = false;
335 m_executable.SetFile(first_arg, resolve);
Greg Clayton982c9762011-11-03 21:22:33 +0000336 }
337 }
338}
339void
Greg Clayton45392552012-10-17 22:57:12 +0000340ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Clayton8b82f082011-04-12 05:54:46 +0000341{
342 // Copy all arguments
343 m_arguments = args;
344
345 // Is the first argument the executable?
346 if (first_arg_is_executable)
347 {
Greg Clayton982c9762011-11-03 21:22:33 +0000348 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000349 if (first_arg)
350 {
351 // Yes the first argument is an executable, set it as the executable
352 // in the launch options. Don't resolve the file path as the path
353 // could be a remote platform path
354 const bool resolve = false;
355 m_executable.SetFile(first_arg, resolve);
Greg Clayton8b82f082011-04-12 05:54:46 +0000356 }
357 }
358}
359
Greg Clayton1d885962011-11-08 02:43:13 +0000360void
Greg Claytonee95ed52011-11-17 22:14:31 +0000361ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-11-08 02:43:13 +0000362{
363 // If notthing was specified, then check the process for any default
364 // settings that were set with "settings set"
365 if (m_file_actions.empty())
366 {
Greg Clayton1d885962011-11-08 02:43:13 +0000367 if (m_flags.Test(eLaunchFlagDisableSTDIO))
368 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000369 AppendSuppressFileAction (STDIN_FILENO , true, false);
370 AppendSuppressFileAction (STDOUT_FILENO, false, true);
371 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000372 }
373 else
374 {
375 // Check for any values that might have gotten set with any of:
376 // (lldb) settings set target.input-path
377 // (lldb) settings set target.output-path
378 // (lldb) settings set target.error-path
Greg Clayton67cc0632012-08-22 17:17:09 +0000379 FileSpec in_path;
380 FileSpec out_path;
381 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000382 if (target)
383 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000384 in_path = target->GetStandardInputPath();
385 out_path = target->GetStandardOutputPath();
386 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000387 }
388
Greg Clayton67cc0632012-08-22 17:17:09 +0000389 if (in_path || out_path || err_path)
390 {
391 char path[PATH_MAX];
392 if (in_path && in_path.GetPath(path, sizeof(path)))
393 AppendOpenFileAction(STDIN_FILENO, path, true, false);
394
395 if (out_path && out_path.GetPath(path, sizeof(path)))
396 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
397
398 if (err_path && err_path.GetPath(path, sizeof(path)))
399 AppendOpenFileAction(STDERR_FILENO, path, false, true);
400 }
401 else if (default_to_use_pty)
Greg Claytonee95ed52011-11-17 22:14:31 +0000402 {
403 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000404 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000405 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
406 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
407 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
408 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000409 }
410 }
Greg Clayton1d885962011-11-08 02:43:13 +0000411 }
412 }
413}
414
Greg Clayton144f3a92011-11-15 03:53:30 +0000415
416bool
Greg Claytond1cf11a2012-04-14 01:42:46 +0000417ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
418 bool localhost,
419 bool will_debug,
420 bool first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000421{
422 error.Clear();
423
424 if (GetFlags().Test (eLaunchFlagLaunchInShell))
425 {
426 const char *shell_executable = GetShell();
427 if (shell_executable)
428 {
429 char shell_resolved_path[PATH_MAX];
430
431 if (localhost)
432 {
433 FileSpec shell_filespec (shell_executable, true);
434
435 if (!shell_filespec.Exists())
436 {
437 // Resolve the path in case we just got "bash", "sh" or "tcsh"
438 if (!shell_filespec.ResolveExecutableLocation ())
439 {
440 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
441 return false;
442 }
443 }
444 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
445 shell_executable = shell_resolved_path;
446 }
447
Greg Clayton45392552012-10-17 22:57:12 +0000448 const char **argv = GetArguments().GetConstArgumentVector ();
449 if (argv == NULL || argv[0] == NULL)
450 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000451 Args shell_arguments;
452 std::string safe_arg;
453 shell_arguments.AppendArgument (shell_executable);
Greg Clayton144f3a92011-11-15 03:53:30 +0000454 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000455 StreamString shell_command;
456 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000457 {
Greg Clayton45392552012-10-17 22:57:12 +0000458 // Add a modified PATH environment variable in case argv[0]
459 // is a relative path
460 const char *argv0 = argv[0];
461 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
462 {
463 // We have a relative path to our executable which may not work if
464 // we just try to run "a.out" (without it being converted to "./a.out")
465 const char *working_dir = GetWorkingDirectory();
466 std::string new_path("PATH=");
467 const size_t empty_path_len = new_path.size();
468
469 if (working_dir && working_dir[0])
470 {
471 new_path += working_dir;
472 }
473 else
474 {
475 char current_working_dir[PATH_MAX];
476 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
477 if (cwd && cwd[0])
478 new_path += cwd;
479 }
480 const char *curr_path = getenv("PATH");
481 if (curr_path)
482 {
483 if (new_path.size() > empty_path_len)
484 new_path += ':';
485 new_path += curr_path;
486 }
487 new_path += ' ';
488 shell_command.PutCString(new_path.c_str());
489 }
490
Greg Claytond1cf11a2012-04-14 01:42:46 +0000491 shell_command.PutCString ("exec");
Greg Clayton45392552012-10-17 22:57:12 +0000492
493#if defined(__APPLE__)
494 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Claytond1cf11a2012-04-14 01:42:46 +0000495 if (GetArchitecture().IsValid())
496 {
497 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton45392552012-10-17 22:57:12 +0000498 // Set the resume count to 2:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000499 // 1 - stop in shell
500 // 2 - stop in /usr/bin/arch
501 // 3 - then we will stop in our program
502 SetResumeCount(2);
503 }
504 else
505 {
Greg Clayton45392552012-10-17 22:57:12 +0000506 // Set the resume count to 1:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000507 // 1 - stop in shell
508 // 2 - then we will stop in our program
509 SetResumeCount(1);
510 }
Greg Clayton45392552012-10-17 22:57:12 +0000511#else
512 // Set the resume count to 1:
513 // 1 - stop in shell
514 // 2 - then we will stop in our program
515 SetResumeCount(1);
516#endif
Greg Clayton144f3a92011-11-15 03:53:30 +0000517 }
Greg Clayton45392552012-10-17 22:57:12 +0000518
519 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000520 {
Greg Clayton45392552012-10-17 22:57:12 +0000521 // There should only be one argument that is the shell command itself to be used as is
522 if (argv[0] && !argv[1])
523 shell_command.Printf("%s", argv[0]);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000524 else
Greg Clayton45392552012-10-17 22:57:12 +0000525 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000526 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000527 else
528 {
Greg Clayton45392552012-10-17 22:57:12 +0000529 for (size_t i=0; argv[i] != NULL; ++i)
530 {
531 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
532 shell_command.Printf(" %s", arg);
533 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000534 }
Greg Clayton45392552012-10-17 22:57:12 +0000535 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton144f3a92011-11-15 03:53:30 +0000536 m_executable.SetFile(shell_executable, false);
537 m_arguments = shell_arguments;
538 return true;
539 }
540 else
541 {
542 error.SetErrorString ("invalid shell path");
543 }
544 }
545 else
546 {
547 error.SetErrorString ("not launching in shell");
548 }
549 return false;
550}
551
552
Greg Clayton32e0a752011-03-30 18:16:51 +0000553bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000554ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
555{
556 if ((read || write) && fd >= 0 && path && path[0])
557 {
558 m_action = eFileActionOpen;
559 m_fd = fd;
560 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000561 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000562 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000563 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000564 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000565 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000566 m_path.assign (path);
567 return true;
568 }
569 else
570 {
571 Clear();
572 }
573 return false;
574}
575
576bool
577ProcessLaunchInfo::FileAction::Close (int fd)
578{
579 Clear();
580 if (fd >= 0)
581 {
582 m_action = eFileActionClose;
583 m_fd = fd;
584 }
585 return m_fd >= 0;
586}
587
588
589bool
590ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
591{
592 Clear();
593 if (fd >= 0 && dup_fd >= 0)
594 {
595 m_action = eFileActionDuplicate;
596 m_fd = fd;
597 m_arg = dup_fd;
598 }
599 return m_fd >= 0;
600}
601
602
603
604bool
605ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
606 const FileAction *info,
607 Log *log,
608 Error& error)
609{
610 if (info == NULL)
611 return false;
612
613 switch (info->m_action)
614 {
615 case eFileActionNone:
616 error.Clear();
617 break;
618
619 case eFileActionClose:
620 if (info->m_fd == -1)
621 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
622 else
623 {
624 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
625 eErrorTypePOSIX);
626 if (log && (error.Fail() || log))
627 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
628 file_actions, info->m_fd);
629 }
630 break;
631
632 case eFileActionDuplicate:
633 if (info->m_fd == -1)
634 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
635 else if (info->m_arg == -1)
636 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
637 else
638 {
639 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
640 eErrorTypePOSIX);
641 if (log && (error.Fail() || log))
642 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
643 file_actions, info->m_fd, info->m_arg);
644 }
645 break;
646
647 case eFileActionOpen:
648 if (info->m_fd == -1)
649 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
650 else
651 {
652 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000653
Greg Clayton8b82f082011-04-12 05:54:46 +0000654 mode_t mode = 0;
655
Greg Clayton144f3a92011-11-15 03:53:30 +0000656 if (oflag & O_CREAT)
657 mode = 0640;
658
Greg Clayton8b82f082011-04-12 05:54:46 +0000659 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
660 info->m_fd,
661 info->m_path.c_str(),
662 oflag,
663 mode),
664 eErrorTypePOSIX);
665 if (error.Fail() || log)
666 error.PutToLog(log,
667 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
668 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
669 }
670 break;
671
672 default:
673 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
674 break;
675 }
676 return error.Success();
677}
678
679Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000680ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000681{
682 Error error;
683 char short_option = (char) m_getopt_table[option_idx].val;
684
685 switch (short_option)
686 {
687 case 's': // Stop at program entry point
688 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
689 break;
690
Greg Clayton8b82f082011-04-12 05:54:46 +0000691 case 'i': // STDIN for read only
692 {
693 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000694 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000695 launch_info.AppendFileAction (action);
696 }
697 break;
698
699 case 'o': // Open STDOUT for write only
700 {
701 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000702 if (action.Open (STDOUT_FILENO, option_arg, false, true))
703 launch_info.AppendFileAction (action);
704 }
705 break;
706
707 case 'e': // STDERR for write only
708 {
709 ProcessLaunchInfo::FileAction action;
710 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000711 launch_info.AppendFileAction (action);
712 }
713 break;
714
Greg Clayton9845a8d2012-03-06 04:01:04 +0000715
Greg Clayton8b82f082011-04-12 05:54:46 +0000716 case 'p': // Process plug-in name
717 launch_info.SetProcessPluginName (option_arg);
718 break;
719
720 case 'n': // Disable STDIO
721 {
722 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000723 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000724 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000725 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000726 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000727 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000728 launch_info.AppendFileAction (action);
729 }
730 break;
731
732 case 'w':
733 launch_info.SetWorkingDirectory (option_arg);
734 break;
735
736 case 't': // Open process in new terminal window
737 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
738 break;
739
740 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000741 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
742 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000743 break;
744
745 case 'A':
746 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
747 break;
748
Greg Clayton982c9762011-11-03 21:22:33 +0000749 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000750 if (option_arg && option_arg[0])
751 launch_info.SetShell (option_arg);
752 else
753 launch_info.SetShell ("/bin/bash");
Greg Clayton982c9762011-11-03 21:22:33 +0000754 break;
755
Greg Clayton8b82f082011-04-12 05:54:46 +0000756 case 'v':
757 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
758 break;
759
760 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000761 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000762 break;
763
764 }
765 return error;
766}
767
768OptionDefinition
769ProcessLaunchCommandOptions::g_option_table[] =
770{
771{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
772{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
773{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
Sean Callanan31542552012-10-24 01:12:14 +0000774{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000775{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
776{ LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Sean Callanan31542552012-10-24 01:12:14 +0000777{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000778
Sean Callanan31542552012-10-24 01:12:14 +0000779{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
780{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
781{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000782
783{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
784
785{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', no_argument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
786
787{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
788};
789
790
791
792bool
793ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000794{
795 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
796 return true;
797 const char *match_name = m_match_info.GetName();
798 if (!match_name)
799 return true;
800
801 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
802}
803
804bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000805ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000806{
807 if (!NameMatches (proc_info.GetName()))
808 return false;
809
810 if (m_match_info.ProcessIDIsValid() &&
811 m_match_info.GetProcessID() != proc_info.GetProcessID())
812 return false;
813
814 if (m_match_info.ParentProcessIDIsValid() &&
815 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
816 return false;
817
Greg Clayton8b82f082011-04-12 05:54:46 +0000818 if (m_match_info.UserIDIsValid () &&
819 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000820 return false;
821
Greg Clayton8b82f082011-04-12 05:54:46 +0000822 if (m_match_info.GroupIDIsValid () &&
823 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000824 return false;
825
826 if (m_match_info.EffectiveUserIDIsValid () &&
827 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
828 return false;
829
830 if (m_match_info.EffectiveGroupIDIsValid () &&
831 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
832 return false;
833
834 if (m_match_info.GetArchitecture().IsValid() &&
835 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
836 return false;
837 return true;
838}
839
840bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000841ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000842{
843 if (m_name_match_type != eNameMatchIgnore)
844 return false;
845
846 if (m_match_info.ProcessIDIsValid())
847 return false;
848
849 if (m_match_info.ParentProcessIDIsValid())
850 return false;
851
Greg Clayton8b82f082011-04-12 05:54:46 +0000852 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000853 return false;
854
Greg Clayton8b82f082011-04-12 05:54:46 +0000855 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000856 return false;
857
858 if (m_match_info.EffectiveUserIDIsValid ())
859 return false;
860
861 if (m_match_info.EffectiveGroupIDIsValid ())
862 return false;
863
864 if (m_match_info.GetArchitecture().IsValid())
865 return false;
866
867 if (m_match_all_users)
868 return false;
869
870 return true;
871
872}
873
874void
Greg Clayton8b82f082011-04-12 05:54:46 +0000875ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000876{
877 m_match_info.Clear();
878 m_name_match_type = eNameMatchIgnore;
879 m_match_all_users = false;
880}
Greg Clayton58be07b2011-01-07 06:08:19 +0000881
Greg Claytonc3776bf2012-02-09 06:16:32 +0000882ProcessSP
883Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000885 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000886 ProcessCreateInstance create_callback = NULL;
887 if (plugin_name)
888 {
889 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
890 if (create_callback)
891 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000892 process_sp = create_callback(target, listener, crash_file_path);
893 if (process_sp)
894 {
895 if (!process_sp->CanDebug(target, true))
896 process_sp.reset();
897 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000898 }
899 }
900 else
901 {
Greg Claytonc982c762010-07-09 20:39:50 +0000902 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000904 process_sp = create_callback(target, listener, crash_file_path);
905 if (process_sp)
906 {
907 if (!process_sp->CanDebug(target, false))
908 process_sp.reset();
909 else
910 break;
911 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000912 }
913 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000914 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000915}
916
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000917ConstString &
918Process::GetStaticBroadcasterClass ()
919{
920 static ConstString class_name ("lldb.process");
921 return class_name;
922}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000923
924//----------------------------------------------------------------------
925// Process constructor
926//----------------------------------------------------------------------
927Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000928 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000929 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000930 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000931 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000932 m_public_state (eStateUnloaded),
933 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000934 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
935 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936 m_private_state_listener ("lldb.process.internal_state_listener"),
937 m_private_state_control_wait(),
938 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000939 m_mod_id (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000940 m_thread_index_id (0),
941 m_exit_status (-1),
942 m_exit_string (),
943 m_thread_list (this),
944 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000945 m_image_tokens (),
946 m_listener (listener),
947 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000948 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000949 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000950 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000951 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000952 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000953 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000954 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000955 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000956 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
957 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000958 m_memory_cache (*this),
959 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000960 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000961 m_next_event_action_ap(),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000962 m_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000963 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000964 m_finalize_called(false),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000965 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000966{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000967 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000968
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000969 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000970 if (log)
971 log->Printf ("%p Process::Process()", this);
972
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000973 SetEventName (eBroadcastBitStateChanged, "state-changed");
974 SetEventName (eBroadcastBitInterrupt, "interrupt");
975 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
976 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000977 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000978
Greg Clayton35a4cc52012-10-29 20:52:08 +0000979 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
980 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
981 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
982
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000983 listener.StartListeningForEvents (this,
984 eBroadcastBitStateChanged |
985 eBroadcastBitInterrupt |
986 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000987 eBroadcastBitSTDERR |
988 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989
990 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000991 eBroadcastBitStateChanged |
992 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993
994 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
995 eBroadcastInternalStateControlStop |
996 eBroadcastInternalStateControlPause |
997 eBroadcastInternalStateControlResume);
998}
999
1000//----------------------------------------------------------------------
1001// Destructor
1002//----------------------------------------------------------------------
1003Process::~Process()
1004{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001005 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006 if (log)
1007 log->Printf ("%p Process::~Process()", this);
1008 StopPrivateStateThread();
1009}
1010
Greg Clayton67cc0632012-08-22 17:17:09 +00001011const ProcessPropertiesSP &
1012Process::GetGlobalProperties()
1013{
1014 static ProcessPropertiesSP g_settings_sp;
1015 if (!g_settings_sp)
1016 g_settings_sp.reset (new ProcessProperties (true));
1017 return g_settings_sp;
1018}
1019
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020void
1021Process::Finalize()
1022{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001023 switch (GetPrivateState())
1024 {
1025 case eStateConnected:
1026 case eStateAttaching:
1027 case eStateLaunching:
1028 case eStateStopped:
1029 case eStateRunning:
1030 case eStateStepping:
1031 case eStateCrashed:
1032 case eStateSuspended:
1033 if (GetShouldDetach())
1034 Detach();
1035 else
1036 Destroy();
1037 break;
1038
1039 case eStateInvalid:
1040 case eStateUnloaded:
1041 case eStateDetached:
1042 case eStateExited:
1043 break;
1044 }
1045
Greg Clayton1ed54f52011-10-01 00:45:15 +00001046 // Clear our broadcaster before we proceed with destroying
1047 Broadcaster::Clear();
1048
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001049 // Do any cleanup needed prior to being destructed... Subclasses
1050 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001051
1052 // We need to destroy the loader before the derived Process class gets destroyed
1053 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001054 m_dynamic_checkers_ap.reset();
1055 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001056 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001057 m_dyld_ap.reset();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001058 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +00001059 std::vector<Notifications> empty_notifications;
1060 m_notifications.swap(empty_notifications);
1061 m_image_tokens.clear();
1062 m_memory_cache.Clear();
1063 m_allocated_memory_cache.Clear();
1064 m_language_runtimes.clear();
1065 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001066//#ifdef LLDB_CONFIGURATION_DEBUG
1067// StreamFile s(stdout, false);
1068// EventSP event_sp;
1069// while (m_private_state_listener.GetNextEvent(event_sp))
1070// {
1071// event_sp->Dump (&s);
1072// s.EOL();
1073// }
1074//#endif
1075 // We have to be very careful here as the m_private_state_listener might
1076 // contain events that have ProcessSP values in them which can keep this
1077 // process around forever. These events need to be cleared out.
1078 m_private_state_listener.Clear();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001079 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001080}
1081
1082void
1083Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1084{
1085 m_notifications.push_back(callbacks);
1086 if (callbacks.initialize != NULL)
1087 callbacks.initialize (callbacks.baton, this);
1088}
1089
1090bool
1091Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1092{
1093 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1094 for (pos = m_notifications.begin(); pos != end; ++pos)
1095 {
1096 if (pos->baton == callbacks.baton &&
1097 pos->initialize == callbacks.initialize &&
1098 pos->process_state_changed == callbacks.process_state_changed)
1099 {
1100 m_notifications.erase(pos);
1101 return true;
1102 }
1103 }
1104 return false;
1105}
1106
1107void
1108Process::SynchronouslyNotifyStateChanged (StateType state)
1109{
1110 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1111 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1112 {
1113 if (notification_pos->process_state_changed)
1114 notification_pos->process_state_changed (notification_pos->baton, this, state);
1115 }
1116}
1117
1118// FIXME: We need to do some work on events before the general Listener sees them.
1119// For instance if we are continuing from a breakpoint, we need to ensure that we do
1120// the little "insert real insn, step & stop" trick. But we can't do that when the
1121// event is delivered by the broadcaster - since that is done on the thread that is
1122// waiting for new events, so if we needed more than one event for our handling, we would
1123// stall. So instead we do it when we fetch the event off of the queue.
1124//
1125
1126StateType
1127Process::GetNextEvent (EventSP &event_sp)
1128{
1129 StateType state = eStateInvalid;
1130
1131 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1132 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1133
1134 return state;
1135}
1136
1137
1138StateType
Greg Clayton85fb1b92012-09-11 02:33:37 +00001139Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140{
Jim Ingham4b536182011-08-09 02:12:22 +00001141 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1142 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1143 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001144 if (event_sp_ptr)
1145 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001146 StateType state = GetState();
1147 // If we are exited or detached, we won't ever get back to any
1148 // other valid state...
1149 if (state == eStateDetached || state == eStateExited)
1150 return state;
1151
1152 while (state != eStateInvalid)
1153 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001154 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001155 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001156 if (event_sp_ptr && event_sp)
1157 *event_sp_ptr = event_sp;
1158
Jim Ingham4b536182011-08-09 02:12:22 +00001159 switch (state)
1160 {
1161 case eStateCrashed:
1162 case eStateDetached:
1163 case eStateExited:
1164 case eStateUnloaded:
1165 return state;
1166 case eStateStopped:
1167 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1168 continue;
1169 else
1170 return state;
1171 default:
1172 continue;
1173 }
1174 }
1175 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001176}
1177
1178
1179StateType
1180Process::WaitForState
1181(
1182 const TimeValue *timeout,
1183 const StateType *match_states, const uint32_t num_match_states
1184)
1185{
1186 EventSP event_sp;
1187 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001188 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001189 while (state != eStateInvalid)
1190 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001191 // If we are exited or detached, we won't ever get back to any
1192 // other valid state...
1193 if (state == eStateDetached || state == eStateExited)
1194 return state;
1195
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001196 state = WaitForStateChangedEvents (timeout, event_sp);
1197
1198 for (i=0; i<num_match_states; ++i)
1199 {
1200 if (match_states[i] == state)
1201 return state;
1202 }
1203 }
1204 return state;
1205}
1206
Jim Ingham30f9b212010-10-11 23:53:14 +00001207bool
1208Process::HijackProcessEvents (Listener *listener)
1209{
1210 if (listener != NULL)
1211 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001212 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001213 }
1214 else
1215 return false;
1216}
1217
1218void
1219Process::RestoreProcessEvents ()
1220{
1221 RestoreBroadcaster();
1222}
1223
Jim Ingham0f16e732011-02-08 05:20:59 +00001224bool
1225Process::HijackPrivateProcessEvents (Listener *listener)
1226{
1227 if (listener != NULL)
1228 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001229 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001230 }
1231 else
1232 return false;
1233}
1234
1235void
1236Process::RestorePrivateProcessEvents ()
1237{
1238 m_private_state_broadcaster.RestoreBroadcaster();
1239}
1240
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001241StateType
1242Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1243{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001244 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001245
1246 if (log)
1247 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1248
1249 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001250 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1251 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001252 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001253 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001254 {
1255 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1256 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1257 else if (log)
1258 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1259 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001260
1261 if (log)
1262 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1263 __FUNCTION__,
1264 timeout,
1265 StateAsCString(state));
1266 return state;
1267}
1268
1269Event *
1270Process::PeekAtStateChangedEvents ()
1271{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001272 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001273
1274 if (log)
1275 log->Printf ("Process::%s...", __FUNCTION__);
1276
1277 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001278 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1279 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001280 if (log)
1281 {
1282 if (event_ptr)
1283 {
1284 log->Printf ("Process::%s (event_ptr) => %s",
1285 __FUNCTION__,
1286 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1287 }
1288 else
1289 {
1290 log->Printf ("Process::%s no events found",
1291 __FUNCTION__);
1292 }
1293 }
1294 return event_ptr;
1295}
1296
1297StateType
1298Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1299{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001300 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001301
1302 if (log)
1303 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1304
1305 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001306 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1307 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001308 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001309 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001310 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1311 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001312
1313 // This is a bit of a hack, but when we wait here we could very well return
1314 // to the command-line, and that could disable the log, which would render the
1315 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001316 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001317 {
1318 if (state == eStateInvalid)
1319 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1320 else
1321 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1322 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001323 return state;
1324}
1325
1326bool
1327Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1328{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001329 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001330
1331 if (log)
1332 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1333
1334 if (control_only)
1335 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1336 else
1337 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1338}
1339
1340bool
1341Process::IsRunning () const
1342{
1343 return StateIsRunningState (m_public_state.GetValue());
1344}
1345
1346int
1347Process::GetExitStatus ()
1348{
1349 if (m_public_state.GetValue() == eStateExited)
1350 return m_exit_status;
1351 return -1;
1352}
1353
Greg Clayton85851dd2010-12-04 00:10:17 +00001354
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355const char *
1356Process::GetExitDescription ()
1357{
1358 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1359 return m_exit_string.c_str();
1360 return NULL;
1361}
1362
Greg Clayton6779606a2011-01-22 23:43:18 +00001363bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364Process::SetExitStatus (int status, const char *cstr)
1365{
Greg Clayton414f5d32011-01-25 02:58:48 +00001366 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1367 if (log)
1368 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1369 status, status,
1370 cstr ? "\"" : "",
1371 cstr ? cstr : "NULL",
1372 cstr ? "\"" : "");
1373
Greg Clayton6779606a2011-01-22 23:43:18 +00001374 // We were already in the exited state
1375 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001376 {
Greg Clayton385d6032011-01-26 23:47:29 +00001377 if (log)
1378 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001379 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001380 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001381
1382 m_exit_status = status;
1383 if (cstr)
1384 m_exit_string = cstr;
1385 else
1386 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387
Greg Clayton6779606a2011-01-22 23:43:18 +00001388 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001389
Greg Clayton6779606a2011-01-22 23:43:18 +00001390 SetPrivateState (eStateExited);
1391 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001392}
1393
1394// This static callback can be used to watch for local child processes on
1395// the current host. The the child process exits, the process will be
1396// found in the global target list (we want to be completely sure that the
1397// lldb_private::Process doesn't go away before we can deliver the signal.
1398bool
Greg Claytone4e45922011-11-16 05:37:56 +00001399Process::SetProcessExitStatus (void *callback_baton,
1400 lldb::pid_t pid,
1401 bool exited,
1402 int signo, // Zero for no signal
1403 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001404)
1405{
Greg Claytone4e45922011-11-16 05:37:56 +00001406 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1407 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00001408 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001409 callback_baton,
1410 pid,
1411 exited,
1412 signo,
1413 exit_status);
1414
1415 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416 {
Greg Clayton66111032010-06-23 01:19:29 +00001417 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001418 if (target_sp)
1419 {
1420 ProcessSP process_sp (target_sp->GetProcessSP());
1421 if (process_sp)
1422 {
1423 const char *signal_cstr = NULL;
1424 if (signo)
1425 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1426
1427 process_sp->SetExitStatus (exit_status, signal_cstr);
1428 }
1429 }
1430 return true;
1431 }
1432 return false;
1433}
1434
1435
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001436void
1437Process::UpdateThreadListIfNeeded ()
1438{
1439 const uint32_t stop_id = GetStopID();
1440 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1441 {
Greg Clayton2637f822011-11-17 01:23:07 +00001442 const StateType state = GetPrivateState();
1443 if (StateIsStoppedState (state, true))
1444 {
1445 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001446 // m_thread_list does have its own mutex, but we need to
1447 // hold onto the mutex between the call to UpdateThreadList(...)
1448 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton2637f822011-11-17 01:23:07 +00001449 ThreadList new_thread_list(this);
1450 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001451 // thread list, but only update if "true" is returned
1452 if (UpdateThreadList (m_thread_list, new_thread_list))
1453 {
1454 OperatingSystem *os = GetOperatingSystem ();
1455 if (os)
1456 os->UpdateThreadList (m_thread_list, new_thread_list);
1457 m_thread_list.Update (new_thread_list);
1458 m_thread_list.SetStopID (stop_id);
1459 }
Greg Clayton2637f822011-11-17 01:23:07 +00001460 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001461 }
1462}
1463
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001464uint32_t
1465Process::GetNextThreadIndexID ()
1466{
1467 return ++m_thread_index_id;
1468}
1469
1470StateType
1471Process::GetState()
1472{
1473 // If any other threads access this we will need a mutex for it
1474 return m_public_state.GetValue ();
1475}
1476
1477void
1478Process::SetPublicState (StateType new_state)
1479{
Greg Clayton414f5d32011-01-25 02:58:48 +00001480 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001481 if (log)
1482 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001483 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001484 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001485
1486 // On the transition from Run to Stopped, we unlock the writer end of the
1487 // run lock. The lock gets locked in Resume, which is the public API
1488 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001489 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1490 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001491 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001492 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001493 if (log)
1494 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1495 m_run_lock.WriteUnlock();
1496 }
1497 else
1498 {
1499 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1500 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1501 if (old_state_is_stopped != new_state_is_stopped)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001502 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001503 if (new_state_is_stopped)
1504 {
1505 if (log)
1506 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1507 m_run_lock.WriteUnlock();
1508 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001509 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001510 }
1511 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001512}
1513
Jim Ingham3b8285d2012-04-19 01:40:33 +00001514Error
1515Process::Resume ()
1516{
1517 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1518 if (log)
1519 log->Printf("Process::Resume -- locking run lock");
1520 if (!m_run_lock.WriteTryLock())
1521 {
1522 Error error("Resume request failed - process still running.");
1523 if (log)
1524 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1525 return error;
1526 }
1527 return PrivateResume();
1528}
1529
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001530StateType
1531Process::GetPrivateState ()
1532{
1533 return m_private_state.GetValue();
1534}
1535
1536void
1537Process::SetPrivateState (StateType new_state)
1538{
Greg Clayton414f5d32011-01-25 02:58:48 +00001539 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001540 bool state_changed = false;
1541
1542 if (log)
1543 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1544
1545 Mutex::Locker locker(m_private_state.GetMutex());
1546
1547 const StateType old_state = m_private_state.GetValueNoLock ();
1548 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001549 // This code is left commented out in case we ever need to control
1550 // the private process state with another run lock. Right now it doesn't
1551 // seem like we need to do this, but if we ever do, we can uncomment and
1552 // use this code.
1553// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1554// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1555// if (old_state_is_stopped != new_state_is_stopped)
1556// {
1557// if (new_state_is_stopped)
1558// m_private_run_lock.WriteUnlock();
1559// else
1560// m_private_run_lock.WriteLock();
1561// }
1562
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001563 if (state_changed)
1564 {
1565 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001566 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001567 {
Jim Ingham4b536182011-08-09 02:12:22 +00001568 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001569 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001570 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001571 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001572 }
1573 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001574 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1575 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1576 else
1577 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001578 }
1579 else
1580 {
1581 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001582 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001583 }
1584}
1585
Jim Ingham0faa43f2011-11-08 03:00:11 +00001586void
1587Process::SetRunningUserExpression (bool on)
1588{
1589 m_mod_id.SetRunningUserExpression (on);
1590}
1591
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001592addr_t
1593Process::GetImageInfoAddress()
1594{
1595 return LLDB_INVALID_ADDRESS;
1596}
1597
Greg Clayton8f343b02010-11-04 01:54:29 +00001598//----------------------------------------------------------------------
1599// LoadImage
1600//
1601// This function provides a default implementation that works for most
1602// unix variants. Any Process subclasses that need to do shared library
1603// loading differently should override LoadImage and UnloadImage and
1604// do what is needed.
1605//----------------------------------------------------------------------
1606uint32_t
1607Process::LoadImage (const FileSpec &image_spec, Error &error)
1608{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001609 char path[PATH_MAX];
1610 image_spec.GetPath(path, sizeof(path));
1611
Greg Clayton8f343b02010-11-04 01:54:29 +00001612 DynamicLoader *loader = GetDynamicLoader();
1613 if (loader)
1614 {
1615 error = loader->CanLoadImage();
1616 if (error.Fail())
1617 return LLDB_INVALID_IMAGE_TOKEN;
1618 }
1619
1620 if (error.Success())
1621 {
1622 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001623
1624 if (thread_sp)
1625 {
1626 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1627
1628 if (frame_sp)
1629 {
1630 ExecutionContext exe_ctx;
1631 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001632 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001633 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001634 expr.Printf("dlopen (\"%s\", 2)", path);
1635 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001636 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001637 ClangUserExpression::Evaluate (exe_ctx,
1638 eExecutionPolicyAlways,
1639 lldb::eLanguageTypeUnknown,
1640 ClangUserExpression::eResultTypeAny,
1641 unwind_on_error,
1642 expr.GetData(),
1643 prefix,
1644 result_valobj_sp,
1645 true,
1646 ClangUserExpression::kDefaultTimeout);
Johnny Chene92aa432011-09-09 00:01:43 +00001647 error = result_valobj_sp->GetError();
1648 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001649 {
1650 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001651 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001652 {
1653 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1654 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1655 {
1656 uint32_t image_token = m_image_tokens.size();
1657 m_image_tokens.push_back (image_ptr);
1658 return image_token;
1659 }
1660 }
1661 }
1662 }
1663 }
1664 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001665 if (!error.AsCString())
1666 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001667 return LLDB_INVALID_IMAGE_TOKEN;
1668}
1669
1670//----------------------------------------------------------------------
1671// UnloadImage
1672//
1673// This function provides a default implementation that works for most
1674// unix variants. Any Process subclasses that need to do shared library
1675// loading differently should override LoadImage and UnloadImage and
1676// do what is needed.
1677//----------------------------------------------------------------------
1678Error
1679Process::UnloadImage (uint32_t image_token)
1680{
1681 Error error;
1682 if (image_token < m_image_tokens.size())
1683 {
1684 const addr_t image_addr = m_image_tokens[image_token];
1685 if (image_addr == LLDB_INVALID_ADDRESS)
1686 {
1687 error.SetErrorString("image already unloaded");
1688 }
1689 else
1690 {
1691 DynamicLoader *loader = GetDynamicLoader();
1692 if (loader)
1693 error = loader->CanLoadImage();
1694
1695 if (error.Success())
1696 {
1697 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001698
1699 if (thread_sp)
1700 {
1701 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1702
1703 if (frame_sp)
1704 {
1705 ExecutionContext exe_ctx;
1706 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001707 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001708 StreamString expr;
1709 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1710 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001711 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001712 ClangUserExpression::Evaluate (exe_ctx,
1713 eExecutionPolicyAlways,
1714 lldb::eLanguageTypeUnknown,
1715 ClangUserExpression::eResultTypeAny,
1716 unwind_on_error,
1717 expr.GetData(),
1718 prefix,
1719 result_valobj_sp,
1720 true,
1721 ClangUserExpression::kDefaultTimeout);
Greg Clayton8f343b02010-11-04 01:54:29 +00001722 if (result_valobj_sp->GetError().Success())
1723 {
1724 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001725 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001726 {
1727 if (scalar.UInt(1))
1728 {
1729 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1730 }
1731 else
1732 {
1733 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1734 }
1735 }
1736 }
1737 else
1738 {
1739 error = result_valobj_sp->GetError();
1740 }
1741 }
1742 }
1743 }
1744 }
1745 }
1746 else
1747 {
1748 error.SetErrorString("invalid image token");
1749 }
1750 return error;
1751}
1752
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001753const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001754Process::GetABI()
1755{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001756 if (!m_abi_sp)
1757 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1758 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001759}
1760
Jim Ingham22777012010-09-23 02:01:19 +00001761LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001762Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001763{
1764 LanguageRuntimeCollection::iterator pos;
1765 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001766 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001767 {
Jim Inghamab175242012-03-10 00:22:19 +00001768 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001769
Jim Inghamab175242012-03-10 00:22:19 +00001770 m_language_runtimes[language] = runtime_sp;
1771 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001772 }
1773 else
1774 return (*pos).second.get();
1775}
1776
1777CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001778Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001779{
Jim Inghamab175242012-03-10 00:22:19 +00001780 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001781 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1782 return static_cast<CPPLanguageRuntime *> (runtime);
1783 return NULL;
1784}
1785
1786ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001787Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001788{
Jim Inghamab175242012-03-10 00:22:19 +00001789 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001790 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1791 return static_cast<ObjCLanguageRuntime *> (runtime);
1792 return NULL;
1793}
1794
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001795bool
1796Process::IsPossibleDynamicValue (ValueObject& in_value)
1797{
1798 if (in_value.IsDynamic())
1799 return false;
1800 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1801
1802 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1803 {
1804 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1805 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1806 }
1807
1808 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1809 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1810 return true;
1811
1812 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1813 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1814}
1815
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001816BreakpointSiteList &
1817Process::GetBreakpointSiteList()
1818{
1819 return m_breakpoint_site_list;
1820}
1821
1822const BreakpointSiteList &
1823Process::GetBreakpointSiteList() const
1824{
1825 return m_breakpoint_site_list;
1826}
1827
1828
1829void
1830Process::DisableAllBreakpointSites ()
1831{
1832 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham43c555d2012-07-04 00:35:43 +00001833 size_t num_sites = m_breakpoint_site_list.GetSize();
1834 for (size_t i = 0; i < num_sites; i++)
1835 {
1836 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1837 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001838}
1839
1840Error
1841Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1842{
1843 Error error (DisableBreakpointSiteByID (break_id));
1844
1845 if (error.Success())
1846 m_breakpoint_site_list.Remove(break_id);
1847
1848 return error;
1849}
1850
1851Error
1852Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1853{
1854 Error error;
1855 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1856 if (bp_site_sp)
1857 {
1858 if (bp_site_sp->IsEnabled())
1859 error = DisableBreakpoint (bp_site_sp.get());
1860 }
1861 else
1862 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001863 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864 }
1865
1866 return error;
1867}
1868
1869Error
1870Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1871{
1872 Error error;
1873 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1874 if (bp_site_sp)
1875 {
1876 if (!bp_site_sp->IsEnabled())
1877 error = EnableBreakpoint (bp_site_sp.get());
1878 }
1879 else
1880 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001881 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001882 }
1883 return error;
1884}
1885
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001886lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001887Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001888{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001889 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001890 if (load_addr != LLDB_INVALID_ADDRESS)
1891 {
1892 BreakpointSiteSP bp_site_sp;
1893
1894 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1895 // create a new breakpoint site and add it.
1896
1897 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1898
1899 if (bp_site_sp)
1900 {
1901 bp_site_sp->AddOwner (owner);
1902 owner->SetBreakpointSite (bp_site_sp);
1903 return bp_site_sp->GetID();
1904 }
1905 else
1906 {
1907 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1908 if (bp_site_sp)
1909 {
1910 if (EnableBreakpoint (bp_site_sp.get()).Success())
1911 {
1912 owner->SetBreakpointSite (bp_site_sp);
1913 return m_breakpoint_site_list.Add (bp_site_sp);
1914 }
1915 }
1916 }
1917 }
1918 // We failed to enable the breakpoint
1919 return LLDB_INVALID_BREAK_ID;
1920
1921}
1922
1923void
1924Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1925{
1926 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1927 if (num_owners == 0)
1928 {
1929 DisableBreakpoint(bp_site_sp.get());
1930 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1931 }
1932}
1933
1934
1935size_t
1936Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1937{
1938 size_t bytes_removed = 0;
1939 addr_t intersect_addr;
1940 size_t intersect_size;
1941 size_t opcode_offset;
1942 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001943 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001944 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001945
Jim Ingham20c77192011-06-29 19:42:28 +00001946 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001947 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001948 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001949 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001950 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001951 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001952 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001953 {
1954 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1955 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001956 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001957 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001958 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001959 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001960 }
1961 }
1962 }
1963 return bytes_removed;
1964}
1965
1966
Greg Claytonded470d2011-03-19 01:12:21 +00001967
1968size_t
1969Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1970{
1971 PlatformSP platform_sp (m_target.GetPlatform());
1972 if (platform_sp)
1973 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1974 return 0;
1975}
1976
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001977Error
1978Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1979{
1980 Error error;
1981 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001982 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001983 const addr_t bp_addr = bp_site->GetLoadAddress();
1984 if (log)
1985 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1986 if (bp_site->IsEnabled())
1987 {
1988 if (log)
1989 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1990 return error;
1991 }
1992
1993 if (bp_addr == LLDB_INVALID_ADDRESS)
1994 {
1995 error.SetErrorString("BreakpointSite contains an invalid load address.");
1996 return error;
1997 }
1998 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1999 // trap for the breakpoint site
2000 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2001
2002 if (bp_opcode_size == 0)
2003 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002004 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002005 }
2006 else
2007 {
2008 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2009
2010 if (bp_opcode_bytes == NULL)
2011 {
2012 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2013 return error;
2014 }
2015
2016 // Save the original opcode by reading it
2017 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2018 {
2019 // Write a software breakpoint in place of the original opcode
2020 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2021 {
2022 uint8_t verify_bp_opcode_bytes[64];
2023 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2024 {
2025 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2026 {
2027 bp_site->SetEnabled(true);
2028 bp_site->SetType (BreakpointSite::eSoftware);
2029 if (log)
2030 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
2031 bp_site->GetID(),
2032 (uint64_t)bp_addr);
2033 }
2034 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002035 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002036 }
2037 else
2038 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2039 }
2040 else
2041 error.SetErrorString("Unable to write breakpoint trap to memory.");
2042 }
2043 else
2044 error.SetErrorString("Unable to read memory at breakpoint address.");
2045 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002046 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002047 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2048 bp_site->GetID(),
2049 (uint64_t)bp_addr,
2050 error.AsCString());
2051 return error;
2052}
2053
2054Error
2055Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2056{
2057 Error error;
2058 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002059 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002060 addr_t bp_addr = bp_site->GetLoadAddress();
2061 lldb::user_id_t breakID = bp_site->GetID();
2062 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002063 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002064
2065 if (bp_site->IsHardware())
2066 {
2067 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2068 }
2069 else if (bp_site->IsEnabled())
2070 {
2071 const size_t break_op_size = bp_site->GetByteSize();
2072 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2073 if (break_op_size > 0)
2074 {
2075 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002076 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002077 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002078 bool break_op_found = false;
2079
2080 // Read the breakpoint opcode
2081 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2082 {
2083 bool verify = false;
2084 // Make sure we have the a breakpoint opcode exists at this address
2085 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2086 {
2087 break_op_found = true;
2088 // We found a valid breakpoint opcode at this address, now restore
2089 // the saved opcode.
2090 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2091 {
2092 verify = true;
2093 }
2094 else
2095 error.SetErrorString("Memory write failed when restoring original opcode.");
2096 }
2097 else
2098 {
2099 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2100 // Set verify to true and so we can check if the original opcode has already been restored
2101 verify = true;
2102 }
2103
2104 if (verify)
2105 {
Greg Claytonc982c762010-07-09 20:39:50 +00002106 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002107 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108 // Verify that our original opcode made it back to the inferior
2109 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2110 {
2111 // compare the memory we just read with the original opcode
2112 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2113 {
2114 // SUCCESS
2115 bp_site->SetEnabled(false);
2116 if (log)
2117 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2118 return error;
2119 }
2120 else
2121 {
2122 if (break_op_found)
2123 error.SetErrorString("Failed to restore original opcode.");
2124 }
2125 }
2126 else
2127 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2128 }
2129 }
2130 else
2131 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2132 }
2133 }
2134 else
2135 {
2136 if (log)
2137 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2138 return error;
2139 }
2140
2141 if (log)
2142 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2143 bp_site->GetID(),
2144 (uint64_t)bp_addr,
2145 error.AsCString());
2146 return error;
2147
2148}
2149
Greg Clayton58be07b2011-01-07 06:08:19 +00002150// Uncomment to verify memory caching works after making changes to caching code
2151//#define VERIFY_MEMORY_READS
2152
Sean Callanan64c0cf22012-06-07 22:26:42 +00002153size_t
2154Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2155{
2156 if (!GetDisableMemoryCache())
2157 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002158#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002159 // Memory caching is enabled, with debug verification
2160
2161 if (buf && size)
2162 {
2163 // Uncomment the line below to make sure memory caching is working.
2164 // I ran this through the test suite and got no assertions, so I am
2165 // pretty confident this is working well. If any changes are made to
2166 // memory caching, uncomment the line below and test your changes!
2167
2168 // Verify all memory reads by using the cache first, then redundantly
2169 // reading the same memory from the inferior and comparing to make sure
2170 // everything is exactly the same.
2171 std::string verify_buf (size, '\0');
2172 assert (verify_buf.size() == size);
2173 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2174 Error verify_error;
2175 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2176 assert (cache_bytes_read == verify_bytes_read);
2177 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2178 assert (verify_error.Success() == error.Success());
2179 return cache_bytes_read;
2180 }
2181 return 0;
2182#else // !defined(VERIFY_MEMORY_READS)
2183 // Memory caching is enabled, without debug verification
2184
2185 return m_memory_cache.Read (addr, buf, size, error);
2186#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002187 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002188 else
2189 {
2190 // Memory caching is disabled
2191
2192 return ReadMemoryFromInferior (addr, buf, size, error);
2193 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002194}
Greg Clayton58be07b2011-01-07 06:08:19 +00002195
Greg Clayton4c82d422012-05-18 23:20:01 +00002196size_t
2197Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2198{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002199 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002200 out_str.clear();
2201 addr_t curr_addr = addr;
2202 while (1)
2203 {
2204 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2205 if (length == 0)
2206 break;
2207 out_str.append(buf, length);
2208 // If we got "length - 1" bytes, we didn't get the whole C string, we
2209 // need to read some more characters
2210 if (length == sizeof(buf) - 1)
2211 curr_addr += length;
2212 else
2213 break;
2214 }
2215 return out_str.size();
2216}
2217
Greg Clayton58be07b2011-01-07 06:08:19 +00002218
2219size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002220Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002221{
2222 size_t total_cstr_len = 0;
2223 if (dst && dst_max_len)
2224 {
Greg Claytone91b7952011-12-15 03:14:23 +00002225 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002226 // NULL out everything just to be safe
2227 memset (dst, 0, dst_max_len);
2228 Error error;
2229 addr_t curr_addr = addr;
2230 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2231 size_t bytes_left = dst_max_len - 1;
2232 char *curr_dst = dst;
2233
2234 while (bytes_left > 0)
2235 {
2236 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2237 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2238 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2239
2240 if (bytes_read == 0)
2241 {
Greg Claytone91b7952011-12-15 03:14:23 +00002242 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002243 dst[total_cstr_len] = '\0';
2244 break;
2245 }
2246 const size_t len = strlen(curr_dst);
2247
2248 total_cstr_len += len;
2249
2250 if (len < bytes_to_read)
2251 break;
2252
2253 curr_dst += bytes_read;
2254 curr_addr += bytes_read;
2255 bytes_left -= bytes_read;
2256 }
2257 }
Greg Claytone91b7952011-12-15 03:14:23 +00002258 else
2259 {
2260 if (dst == NULL)
2261 result_error.SetErrorString("invalid arguments");
2262 else
2263 result_error.Clear();
2264 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002265 return total_cstr_len;
2266}
2267
2268size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002269Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2270{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002271 if (buf == NULL || size == 0)
2272 return 0;
2273
2274 size_t bytes_read = 0;
2275 uint8_t *bytes = (uint8_t *)buf;
2276
2277 while (bytes_read < size)
2278 {
2279 const size_t curr_size = size - bytes_read;
2280 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2281 bytes + bytes_read,
2282 curr_size,
2283 error);
2284 bytes_read += curr_bytes_read;
2285 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2286 break;
2287 }
2288
2289 // Replace any software breakpoint opcodes that fall into this range back
2290 // into "buf" before we return
2291 if (bytes_read > 0)
2292 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2293 return bytes_read;
2294}
2295
Greg Clayton58a4c462010-12-16 20:01:20 +00002296uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002297Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002298{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002299 Scalar scalar;
2300 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2301 return scalar.ULongLong(fail_value);
2302 return fail_value;
2303}
2304
2305addr_t
2306Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2307{
2308 Scalar scalar;
2309 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2310 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2311 return LLDB_INVALID_ADDRESS;
2312}
2313
2314
2315bool
2316Process::WritePointerToMemory (lldb::addr_t vm_addr,
2317 lldb::addr_t ptr_value,
2318 Error &error)
2319{
2320 Scalar scalar;
2321 const uint32_t addr_byte_size = GetAddressByteSize();
2322 if (addr_byte_size <= 4)
2323 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002324 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002325 scalar = ptr_value;
2326 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002327}
2328
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002329size_t
2330Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2331{
2332 size_t bytes_written = 0;
2333 const uint8_t *bytes = (const uint8_t *)buf;
2334
2335 while (bytes_written < size)
2336 {
2337 const size_t curr_size = size - bytes_written;
2338 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2339 bytes + bytes_written,
2340 curr_size,
2341 error);
2342 bytes_written += curr_bytes_written;
2343 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2344 break;
2345 }
2346 return bytes_written;
2347}
2348
2349size_t
2350Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2351{
Greg Clayton58be07b2011-01-07 06:08:19 +00002352#if defined (ENABLE_MEMORY_CACHING)
2353 m_memory_cache.Flush (addr, size);
2354#endif
2355
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356 if (buf == NULL || size == 0)
2357 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002358
Jim Ingham4b536182011-08-09 02:12:22 +00002359 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002360
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361 // We need to write any data that would go where any current software traps
2362 // (enabled software breakpoints) any software traps (breakpoints) that we
2363 // may have placed in our tasks memory.
2364
2365 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2366 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2367
2368 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002369 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002370
2371 BreakpointSiteList::collection::const_iterator pos;
2372 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002373 addr_t intersect_addr = 0;
2374 size_t intersect_size = 0;
2375 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376 const uint8_t *ubuf = (const uint8_t *)buf;
2377
2378 for (pos = iter; pos != end; ++pos)
2379 {
2380 BreakpointSiteSP bp;
2381 bp = pos->second;
2382
2383 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2384 assert(addr <= intersect_addr && intersect_addr < addr + size);
2385 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2386 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2387
2388 // Check for bytes before this breakpoint
2389 const addr_t curr_addr = addr + bytes_written;
2390 if (intersect_addr > curr_addr)
2391 {
2392 // There are some bytes before this breakpoint that we need to
2393 // just write to memory
2394 size_t curr_size = intersect_addr - curr_addr;
2395 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2396 ubuf + bytes_written,
2397 curr_size,
2398 error);
2399 bytes_written += curr_bytes_written;
2400 if (curr_bytes_written != curr_size)
2401 {
2402 // We weren't able to write all of the requested bytes, we
2403 // are done looping and will return the number of bytes that
2404 // we have written so far.
2405 break;
2406 }
2407 }
2408
2409 // Now write any bytes that would cover up any software breakpoints
2410 // directly into the breakpoint opcode buffer
2411 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2412 bytes_written += intersect_size;
2413 }
2414
2415 // Write any remaining bytes after the last breakpoint if we have any left
2416 if (bytes_written < size)
2417 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2418 ubuf + bytes_written,
2419 size - bytes_written,
2420 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002421
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422 return bytes_written;
2423}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002424
2425size_t
2426Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2427{
2428 if (byte_size == UINT32_MAX)
2429 byte_size = scalar.GetByteSize();
2430 if (byte_size > 0)
2431 {
2432 uint8_t buf[32];
2433 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2434 if (mem_size > 0)
2435 return WriteMemory(addr, buf, mem_size, error);
2436 else
2437 error.SetErrorString ("failed to get scalar as memory data");
2438 }
2439 else
2440 {
2441 error.SetErrorString ("invalid scalar value");
2442 }
2443 return 0;
2444}
2445
2446size_t
2447Process::ReadScalarIntegerFromMemory (addr_t addr,
2448 uint32_t byte_size,
2449 bool is_signed,
2450 Scalar &scalar,
2451 Error &error)
2452{
2453 uint64_t uval;
2454
2455 if (byte_size <= sizeof(uval))
2456 {
2457 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2458 if (bytes_read == byte_size)
2459 {
2460 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2461 uint32_t offset = 0;
2462 if (byte_size <= 4)
2463 scalar = data.GetMaxU32 (&offset, byte_size);
2464 else
2465 scalar = data.GetMaxU64 (&offset, byte_size);
2466
2467 if (is_signed)
2468 scalar.SignExtend(byte_size * 8);
2469 return bytes_read;
2470 }
2471 }
2472 else
2473 {
2474 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2475 }
2476 return 0;
2477}
2478
Greg Claytond495c532011-05-17 03:37:42 +00002479#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002480addr_t
2481Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2482{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002483 if (GetPrivateState() != eStateStopped)
2484 return LLDB_INVALID_ADDRESS;
2485
Greg Claytond495c532011-05-17 03:37:42 +00002486#if defined (USE_ALLOCATE_MEMORY_CACHE)
2487 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2488#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002489 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2490 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2491 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002492 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002493 size,
Greg Claytond495c532011-05-17 03:37:42 +00002494 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002495 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002496 m_mod_id.GetStopID(),
2497 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002498 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002499#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500}
2501
Sean Callanan90539452011-09-20 23:01:51 +00002502bool
2503Process::CanJIT ()
2504{
Sean Callanana7b443a2012-02-14 22:50:38 +00002505 if (m_can_jit == eCanJITDontKnow)
2506 {
2507 Error err;
2508
2509 uint64_t allocated_memory = AllocateMemory(8,
2510 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2511 err);
2512
2513 if (err.Success())
2514 m_can_jit = eCanJITYes;
2515 else
2516 m_can_jit = eCanJITNo;
2517
2518 DeallocateMemory (allocated_memory);
2519 }
2520
Sean Callanan90539452011-09-20 23:01:51 +00002521 return m_can_jit == eCanJITYes;
2522}
2523
2524void
2525Process::SetCanJIT (bool can_jit)
2526{
2527 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2528}
2529
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002530Error
2531Process::DeallocateMemory (addr_t ptr)
2532{
Greg Claytond495c532011-05-17 03:37:42 +00002533 Error error;
2534#if defined (USE_ALLOCATE_MEMORY_CACHE)
2535 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2536 {
2537 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2538 }
2539#else
2540 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002541
2542 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2543 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002544 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002545 ptr,
2546 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002547 m_mod_id.GetStopID(),
2548 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002549#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002550 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002551}
2552
Han Ming Ongab3b8b22012-11-17 00:21:04 +00002553//Error
2554//Process::GetProfileData (uint64_t &elapsed_usec, uint64_t &task_used_usec, int &num_threads, uint64_t **threads_id, uint64_t **threads_used_usec, mach_vm_size_t &rprvt, mach_vm_size_t &rsize, mach_vm_size_t &vprvt, mach_vm_size_t &vsize, mach_vm_size_t &dirty_size)
2555//{
2556// return DoGetProfileData(elapsed_usec, task_used_usec, num_threads, threads_id, threads_used_usec, rprvt, rsize, vprvt, vsize, dirty_size);
2557//}
2558//
Greg Claytonc9660542012-02-05 02:38:54 +00002559ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002560Process::ReadModuleFromMemory (const FileSpec& file_spec,
2561 lldb::addr_t header_addr,
2562 bool add_image_to_target,
2563 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002564{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002565 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002566 if (module_sp)
2567 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002568 Error error;
2569 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2570 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002571 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002572 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002573 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002574 m_target.GetImages().Append(module_sp);
2575 if (load_sections_in_target)
2576 {
2577 bool changed = false;
2578 module_sp->SetLoadAddress (m_target, 0, changed);
2579 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002580 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002581 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002582 }
Greg Claytonc9660542012-02-05 02:38:54 +00002583 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002584 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002585}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002586
2587Error
Johnny Chen01a67862011-10-14 00:42:25 +00002588Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002589{
2590 Error error;
2591 error.SetErrorString("watchpoints are not supported");
2592 return error;
2593}
2594
2595Error
Johnny Chen01a67862011-10-14 00:42:25 +00002596Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002597{
2598 Error error;
2599 error.SetErrorString("watchpoints are not supported");
2600 return error;
2601}
2602
2603StateType
2604Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2605{
2606 StateType state;
2607 // Now wait for the process to launch and return control to us, and then
2608 // call DidLaunch:
2609 while (1)
2610 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002611 event_sp.reset();
2612 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2613
Greg Clayton2637f822011-11-17 01:23:07 +00002614 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002615 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002616
2617 // If state is invalid, then we timed out
2618 if (state == eStateInvalid)
2619 break;
2620
2621 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002622 HandlePrivateEvent (event_sp);
2623 }
2624 return state;
2625}
2626
2627Error
Greg Clayton982c9762011-11-03 21:22:33 +00002628Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002629{
2630 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002631 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002632 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002633 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002634 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002635
Greg Claytonaa149cb2011-08-11 02:48:45 +00002636 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002637 if (exe_module)
2638 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002639 char local_exec_file_path[PATH_MAX];
2640 char platform_exec_file_path[PATH_MAX];
2641 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2642 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002643 if (exe_module->GetFileSpec().Exists())
2644 {
Greg Clayton71337622011-02-24 22:24:29 +00002645 if (PrivateStateThreadIsValid ())
2646 PausePrivateStateThread ();
2647
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002648 error = WillLaunch (exe_module);
2649 if (error.Success())
2650 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002651 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002652 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002653
Greg Clayton69fd4be2012-09-04 20:29:05 +00002654 if (m_run_lock.WriteTryLock())
2655 {
2656 // Now launch using these arguments.
2657 error = DoLaunch (exe_module, launch_info);
2658 }
2659 else
2660 {
2661 // This shouldn't happen
2662 error.SetErrorString("failed to acquire process run lock");
2663 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002664
2665 if (error.Fail())
2666 {
2667 if (GetID() != LLDB_INVALID_PROCESS_ID)
2668 {
2669 SetID (LLDB_INVALID_PROCESS_ID);
2670 const char *error_string = error.AsCString();
2671 if (error_string == NULL)
2672 error_string = "launch failed";
2673 SetExitStatus (-1, error_string);
2674 }
2675 }
2676 else
2677 {
2678 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002679 TimeValue timeout_time;
2680 timeout_time = TimeValue::Now();
2681 timeout_time.OffsetWithSeconds(10);
2682 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002683
Greg Clayton1a38ea72011-06-22 01:42:17 +00002684 if (state == eStateInvalid || event_sp.get() == NULL)
2685 {
2686 // We were able to launch the process, but we failed to
2687 // catch the initial stop.
2688 SetExitStatus (0, "failed to catch stop after launch");
2689 Destroy();
2690 }
2691 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002692 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002693
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694 DidLaunch ();
2695
Greg Claytonc859e2d2012-02-13 23:10:39 +00002696 DynamicLoader *dyld = GetDynamicLoader ();
2697 if (dyld)
2698 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002699
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002700 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002701 // This delays passing the stopped event to listeners till DidLaunch gets
2702 // a chance to complete...
2703 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002704
2705 if (PrivateStateThreadIsValid ())
2706 ResumePrivateStateThread ();
2707 else
2708 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002709 }
2710 else if (state == eStateExited)
2711 {
2712 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2713 // not likely to work, and return an invalid pid.
2714 HandlePrivateEvent (event_sp);
2715 }
2716 }
2717 }
2718 }
2719 else
2720 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002721 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002722 }
2723 }
2724 return error;
2725}
2726
Greg Claytonc3776bf2012-02-09 06:16:32 +00002727
2728Error
2729Process::LoadCore ()
2730{
2731 Error error = DoLoadCore();
2732 if (error.Success())
2733 {
2734 if (PrivateStateThreadIsValid ())
2735 ResumePrivateStateThread ();
2736 else
2737 StartPrivateStateThread ();
2738
Greg Claytonc859e2d2012-02-13 23:10:39 +00002739 DynamicLoader *dyld = GetDynamicLoader ();
2740 if (dyld)
2741 dyld->DidAttach();
2742
2743 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002744 // We successfully loaded a core file, now pretend we stopped so we can
2745 // show all of the threads in the core file and explore the crashed
2746 // state.
2747 SetPrivateState (eStateStopped);
2748
2749 }
2750 return error;
2751}
2752
Greg Claytonc859e2d2012-02-13 23:10:39 +00002753DynamicLoader *
2754Process::GetDynamicLoader ()
2755{
2756 if (m_dyld_ap.get() == NULL)
2757 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2758 return m_dyld_ap.get();
2759}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002760
2761
Jim Inghambb3a2832011-01-29 01:49:25 +00002762Process::NextEventAction::EventActionResult
2763Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002764{
Jim Inghambb3a2832011-01-29 01:49:25 +00002765 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2766 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002767 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002768 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002769 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002770 return eEventActionRetry;
2771
2772 case eStateStopped:
2773 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002774 {
2775 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002776 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002777 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2778 if (m_exec_count > 0)
2779 {
2780 --m_exec_count;
Jim Ingham3b8285d2012-04-19 01:40:33 +00002781 m_process->PrivateResume ();
Jim Ingham04e0a222012-05-23 15:46:31 +00002782 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Claytonc9ed4782011-11-12 02:10:56 +00002783 return eEventActionRetry;
2784 }
2785 else
2786 {
2787 m_process->CompleteAttach ();
2788 return eEventActionSuccess;
2789 }
2790 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002791 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002792
Greg Clayton513c26c2011-01-29 07:10:55 +00002793 default:
2794 case eStateExited:
2795 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002796 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002797 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002798
2799 m_exit_string.assign ("No valid Process");
2800 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002801}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002802
Jim Inghambb3a2832011-01-29 01:49:25 +00002803Process::NextEventAction::EventActionResult
2804Process::AttachCompletionHandler::HandleBeingInterrupted()
2805{
2806 return eEventActionSuccess;
2807}
2808
2809const char *
2810Process::AttachCompletionHandler::GetExitString ()
2811{
2812 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813}
2814
2815Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002816Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002817{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002818 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002819 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002820 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002821 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002822
Greg Clayton144f3a92011-11-15 03:53:30 +00002823 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002824 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002825 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002826 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002827 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002828
Greg Clayton144f3a92011-11-15 03:53:30 +00002829 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002830 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002831 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2832
2833 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002834 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002835 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2836 if (error.Success())
2837 {
Greg Clayton926cce72012-10-12 16:10:12 +00002838 if (m_run_lock.WriteTryLock())
2839 {
2840 m_should_detach = true;
2841 SetPublicState (eStateAttaching);
2842 // Now attach using these arguments.
2843 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2844 }
2845 else
2846 {
2847 // This shouldn't happen
2848 error.SetErrorString("failed to acquire process run lock");
2849 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00002850
Greg Clayton144f3a92011-11-15 03:53:30 +00002851 if (error.Fail())
2852 {
2853 if (GetID() != LLDB_INVALID_PROCESS_ID)
2854 {
2855 SetID (LLDB_INVALID_PROCESS_ID);
2856 if (error.AsCString() == NULL)
2857 error.SetErrorString("attach failed");
2858
2859 SetExitStatus(-1, error.AsCString());
2860 }
2861 }
2862 else
2863 {
2864 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2865 StartPrivateStateThread();
2866 }
2867 return error;
2868 }
Greg Claytone996fd32011-03-08 22:40:15 +00002869 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002870 else
Greg Claytone996fd32011-03-08 22:40:15 +00002871 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002872 ProcessInstanceInfoList process_infos;
2873 PlatformSP platform_sp (m_target.GetPlatform ());
2874
2875 if (platform_sp)
2876 {
2877 ProcessInstanceInfoMatch match_info;
2878 match_info.GetProcessInfo() = attach_info;
2879 match_info.SetNameMatchType (eNameMatchEquals);
2880 platform_sp->FindProcesses (match_info, process_infos);
2881 const uint32_t num_matches = process_infos.GetSize();
2882 if (num_matches == 1)
2883 {
2884 attach_pid = process_infos.GetProcessIDAtIndex(0);
2885 // Fall through and attach using the above process ID
2886 }
2887 else
2888 {
2889 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2890 if (num_matches > 1)
2891 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2892 else
2893 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2894 }
2895 }
2896 else
2897 {
2898 error.SetErrorString ("invalid platform, can't find processes by name");
2899 return error;
2900 }
Greg Claytone996fd32011-03-08 22:40:15 +00002901 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002902 }
2903 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002904 {
2905 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002906 }
2907 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002908
2909 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002910 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002911 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002912 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002913 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002914
Greg Clayton926cce72012-10-12 16:10:12 +00002915 if (m_run_lock.WriteTryLock())
2916 {
2917 // Now attach using these arguments.
2918 m_should_detach = true;
2919 SetPublicState (eStateAttaching);
2920 error = DoAttachToProcessWithID (attach_pid, attach_info);
2921 }
2922 else
2923 {
2924 // This shouldn't happen
2925 error.SetErrorString("failed to acquire process run lock");
2926 }
2927
Greg Clayton144f3a92011-11-15 03:53:30 +00002928 if (error.Success())
2929 {
2930
2931 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2932 StartPrivateStateThread();
2933 }
2934 else
Greg Claytone996fd32011-03-08 22:40:15 +00002935 {
2936 if (GetID() != LLDB_INVALID_PROCESS_ID)
2937 {
2938 SetID (LLDB_INVALID_PROCESS_ID);
2939 const char *error_string = error.AsCString();
2940 if (error_string == NULL)
2941 error_string = "attach failed";
2942
2943 SetExitStatus(-1, error_string);
2944 }
2945 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946 }
2947 }
2948 return error;
2949}
2950
Greg Clayton93d3c8332011-02-16 04:46:07 +00002951void
2952Process::CompleteAttach ()
2953{
2954 // Let the process subclass figure out at much as it can about the process
2955 // before we go looking for a dynamic loader plug-in.
2956 DidAttach();
2957
Jim Ingham4299fdb2011-09-15 01:10:17 +00002958 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2959 // the same as the one we've already set, switch architectures.
2960 PlatformSP platform_sp (m_target.GetPlatform ());
2961 assert (platform_sp.get());
2962 if (platform_sp)
2963 {
Greg Clayton70512312012-05-08 01:45:38 +00002964 const ArchSpec &target_arch = m_target.GetArchitecture();
2965 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2966 {
2967 ArchSpec platform_arch;
2968 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2969 if (platform_sp)
2970 {
2971 m_target.SetPlatform (platform_sp);
2972 m_target.SetArchitecture(platform_arch);
2973 }
2974 }
2975 else
2976 {
2977 ProcessInstanceInfo process_info;
2978 platform_sp->GetProcessInfo (GetID(), process_info);
2979 const ArchSpec &process_arch = process_info.GetArchitecture();
2980 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2981 m_target.SetArchitecture (process_arch);
2982 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00002983 }
2984
2985 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002986 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002987 DynamicLoader *dyld = GetDynamicLoader ();
2988 if (dyld)
2989 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002990
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002991 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002992 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00002993 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002994 Mutex::Locker modules_locker(target_modules.GetMutex());
2995 size_t num_modules = target_modules.GetSize();
2996 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002997
Greg Clayton93d3c8332011-02-16 04:46:07 +00002998 for (int i = 0; i < num_modules; i++)
2999 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003000 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003001 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003002 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003003 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003004 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003005 break;
3006 }
3007 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003008 if (new_executable_module_sp)
3009 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003010}
3011
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003012Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003013Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003014{
Greg Claytonb766a732011-02-04 01:58:07 +00003015 m_abi_sp.reset();
3016 m_process_input_reader.reset();
3017
3018 // Find the process and its architecture. Make sure it matches the architecture
3019 // of the current Target, and if not adjust it.
3020
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003021 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003022 if (error.Success())
3023 {
Greg Clayton71337622011-02-24 22:24:29 +00003024 if (GetID() != LLDB_INVALID_PROCESS_ID)
3025 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003026 EventSP event_sp;
3027 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3028
3029 if (state == eStateStopped || state == eStateCrashed)
3030 {
3031 // If we attached and actually have a process on the other end, then
3032 // this ended up being the equivalent of an attach.
3033 CompleteAttach ();
3034
3035 // This delays passing the stopped event to listeners till
3036 // CompleteAttach gets a chance to complete...
3037 HandlePrivateEvent (event_sp);
3038
3039 }
Greg Clayton71337622011-02-24 22:24:29 +00003040 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003041
3042 if (PrivateStateThreadIsValid ())
3043 ResumePrivateStateThread ();
3044 else
3045 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003046 }
3047 return error;
3048}
3049
3050
3051Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003052Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003053{
Jim Ingham46ef1802012-09-06 19:24:17 +00003054 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003055 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00003056 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003057 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003058 StateAsCString(m_public_state.GetValue()),
3059 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003060
3061 Error error (WillResume());
3062 // Tell the process it is about to resume before the thread list
3063 if (error.Success())
3064 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003065 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003066 // can let all of our threads know that they are about to be
3067 // resumed. Threads will each be called with
3068 // Thread::WillResume(StateType) where StateType contains the state
3069 // that they are supposed to have when the process is resumed
3070 // (suspended/running/stepping). Threads should also check
3071 // their resume signal in lldb::Thread::GetResumeSignal()
3072 // to see if they are suppoed to start back up with a signal.
3073 if (m_thread_list.WillResume())
3074 {
Jim Ingham372787f2012-04-07 00:00:41 +00003075 // Last thing, do the PreResumeActions.
3076 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003077 {
Jim Ingham372787f2012-04-07 00:00:41 +00003078 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3079 }
3080 else
3081 {
3082 m_mod_id.BumpResumeID();
3083 error = DoResume();
3084 if (error.Success())
3085 {
3086 DidResume();
3087 m_thread_list.DidResume();
3088 if (log)
3089 log->Printf ("Process thinks the process has resumed.");
3090 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091 }
3092 }
3093 else
3094 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003095 // Somebody wanted to run without running. So generate a continue & a stopped event,
3096 // and let the world handle them.
3097 if (log)
3098 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3099
3100 SetPrivateState(eStateRunning);
3101 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003102 }
3103 }
Jim Ingham444586b2011-01-24 06:34:17 +00003104 else if (log)
3105 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003106 return error;
3107}
3108
3109Error
3110Process::Halt ()
3111{
Jim Inghamaacc3182012-06-06 00:29:30 +00003112 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3113 // we could just straightaway get another event. It just narrows the window...
3114 m_currently_handling_event.WaitForValueEqualTo(false);
3115
3116
Jim Inghambb3a2832011-01-29 01:49:25 +00003117 // Pause our private state thread so we can ensure no one else eats
3118 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003119 Listener halt_listener ("lldb.process.halt_listener");
3120 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003121
Jim Inghambb3a2832011-01-29 01:49:25 +00003122 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003123 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003124
Greg Clayton513c26c2011-01-29 07:10:55 +00003125 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003126 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003127
Greg Clayton513c26c2011-01-29 07:10:55 +00003128 bool caused_stop = false;
3129
3130 // Ask the process subclass to actually halt our process
3131 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003133 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003134 if (m_public_state.GetValue() == eStateAttaching)
3135 {
3136 SetExitStatus(SIGKILL, "Cancelled async attach.");
3137 Destroy ();
3138 }
3139 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003140 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003141 // If "caused_stop" is true, then DoHalt stopped the process. If
3142 // "caused_stop" is false, the process was already stopped.
3143 // If the DoHalt caused the process to stop, then we want to catch
3144 // this event and set the interrupted bool to true before we pass
3145 // this along so clients know that the process was interrupted by
3146 // a halt command.
3147 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003148 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003149 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003150 TimeValue timeout_time;
3151 timeout_time = TimeValue::Now();
3152 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003153 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3154 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003155
Jim Ingham0f16e732011-02-08 05:20:59 +00003156 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003157 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003158 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003159 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003160 }
3161 else
3162 {
Greg Clayton2637f822011-11-17 01:23:07 +00003163 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003164 {
3165 // We caused the process to interrupt itself, so mark this
3166 // as such in the stop event so clients can tell an interrupted
3167 // process from a natural stop
3168 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3169 }
3170 else
3171 {
3172 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3173 if (log)
3174 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3175 error.SetErrorString ("Did not get stopped event after halt.");
3176 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003177 }
3178 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003179 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003180 }
3181 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003182 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003183 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003184 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003185
3186 // Post any event we might have consumed. If all goes well, we will have
3187 // stopped the process, intercepted the event and set the interrupted
3188 // bool in the event. Post it to the private event queue and that will end up
3189 // correctly setting the state.
3190 if (event_sp)
3191 m_private_state_broadcaster.BroadcastEvent(event_sp);
3192
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003193 return error;
3194}
3195
3196Error
3197Process::Detach ()
3198{
3199 Error error (WillDetach());
3200
3201 if (error.Success())
3202 {
3203 DisableAllBreakpointSites();
3204 error = DoDetach();
3205 if (error.Success())
3206 {
3207 DidDetach();
3208 StopPrivateStateThread();
3209 }
3210 }
3211 return error;
3212}
3213
3214Error
3215Process::Destroy ()
3216{
3217 Error error (WillDestroy());
3218 if (error.Success())
3219 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003220 EventSP exit_event_sp;
Jim Ingham04e0a222012-05-23 15:46:31 +00003221 if (m_public_state.GetValue() == eStateRunning)
3222 {
Greg Claytona28d2032012-09-05 00:37:58 +00003223 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003224 if (log)
3225 log->Printf("Process::Destroy() About to halt.");
Jim Ingham04e0a222012-05-23 15:46:31 +00003226 error = Halt();
3227 if (error.Success())
3228 {
3229 // Consume the halt event.
Jim Ingham04e0a222012-05-23 15:46:31 +00003230 TimeValue timeout (TimeValue::Now());
Jim Inghamaacc3182012-06-06 00:29:30 +00003231 timeout.OffsetWithSeconds(1);
Greg Clayton85fb1b92012-09-11 02:33:37 +00003232 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3233 if (state != eStateExited)
3234 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3235
Jim Ingham04e0a222012-05-23 15:46:31 +00003236 if (state != eStateStopped)
3237 {
Jim Ingham04e0a222012-05-23 15:46:31 +00003238 if (log)
3239 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Inghamaacc3182012-06-06 00:29:30 +00003240 // If we really couldn't stop the process then we should just error out here, but if the
3241 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3242 StateType private_state = m_private_state.GetValue();
3243 if (private_state != eStateStopped && private_state != eStateExited)
3244 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003245 // If we exited when we were waiting for a process to stop, then
3246 // forward the event here so we don't lose the event
Jim Inghamaacc3182012-06-06 00:29:30 +00003247 return error;
3248 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003249 }
3250 }
3251 else
3252 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003253 if (log)
3254 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3255 return error;
Jim Ingham04e0a222012-05-23 15:46:31 +00003256 }
3257 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003258
3259 if (m_public_state.GetValue() != eStateRunning)
3260 {
3261 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3262 // kill it, we don't want it hitting a breakpoint...
3263 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3264 // we're not going to have much luck doing this now.
3265 m_thread_list.DiscardThreadPlans();
3266 DisableAllBreakpointSites();
3267 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003268
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003269 error = DoDestroy();
3270 if (error.Success())
3271 {
3272 DidDestroy();
3273 StopPrivateStateThread();
3274 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003275 m_stdio_communication.StopReadThread();
3276 m_stdio_communication.Disconnect();
3277 if (m_process_input_reader && m_process_input_reader->IsActive())
3278 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3279 if (m_process_input_reader)
3280 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003281
3282 // If we exited when we were waiting for a process to stop, then
3283 // forward the event here so we don't lose the event
3284 if (exit_event_sp)
3285 {
3286 // Directly broadcast our exited event because we shut down our
3287 // private state thread above
3288 BroadcastEvent(exit_event_sp);
3289 }
3290
Jim Inghamb1e2e842012-04-12 18:49:31 +00003291 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3292 // the last events through the event system, in which case we might strand the write lock. Unlock
3293 // it here so when we do to tear down the process we don't get an error destroying the lock.
3294 m_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003295 }
3296 return error;
3297}
3298
3299Error
3300Process::Signal (int signal)
3301{
3302 Error error (WillSignal());
3303 if (error.Success())
3304 {
3305 error = DoSignal(signal);
3306 if (error.Success())
3307 DidSignal();
3308 }
3309 return error;
3310}
3311
Greg Clayton514487e2011-02-15 21:59:32 +00003312lldb::ByteOrder
3313Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003314{
Greg Clayton514487e2011-02-15 21:59:32 +00003315 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003316}
3317
3318uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003319Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003320{
Greg Clayton514487e2011-02-15 21:59:32 +00003321 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003322}
3323
Greg Clayton514487e2011-02-15 21:59:32 +00003324
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003325bool
3326Process::ShouldBroadcastEvent (Event *event_ptr)
3327{
3328 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3329 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003330 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003331
3332 switch (state)
3333 {
Greg Claytonb766a732011-02-04 01:58:07 +00003334 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003335 case eStateAttaching:
3336 case eStateLaunching:
3337 case eStateDetached:
3338 case eStateExited:
3339 case eStateUnloaded:
3340 // These events indicate changes in the state of the debugging session, always report them.
3341 return_value = true;
3342 break;
3343 case eStateInvalid:
3344 // We stopped for no apparent reason, don't report it.
3345 return_value = false;
3346 break;
3347 case eStateRunning:
3348 case eStateStepping:
3349 // If we've started the target running, we handle the cases where we
3350 // are already running and where there is a transition from stopped to
3351 // running differently.
3352 // running -> running: Automatically suppress extra running events
3353 // stopped -> running: Report except when there is one or more no votes
3354 // and no yes votes.
3355 SynchronouslyNotifyStateChanged (state);
3356 switch (m_public_state.GetValue())
3357 {
3358 case eStateRunning:
3359 case eStateStepping:
3360 // We always suppress multiple runnings with no PUBLIC stop in between.
3361 return_value = false;
3362 break;
3363 default:
3364 // TODO: make this work correctly. For now always report
3365 // run if we aren't running so we don't miss any runnning
3366 // events. If I run the lldb/test/thread/a.out file and
3367 // break at main.cpp:58, run and hit the breakpoints on
3368 // multiple threads, then somehow during the stepping over
3369 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370
3371 // This is a transition from stop to run.
3372 switch (m_thread_list.ShouldReportRun (event_ptr))
3373 {
Greg Clayton23f59502012-07-17 03:23:13 +00003374 default:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003375 case eVoteYes:
3376 case eVoteNoOpinion:
3377 return_value = true;
3378 break;
3379 case eVoteNo:
3380 return_value = false;
3381 break;
3382 }
3383 break;
3384 }
3385 break;
3386 case eStateStopped:
3387 case eStateCrashed:
3388 case eStateSuspended:
3389 {
3390 // We've stopped. First see if we're going to restart the target.
3391 // If we are going to stop, then we always broadcast the event.
3392 // 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 +00003393 // If no thread has an opinion, we don't report it.
Jim Inghamcb4ca112012-05-16 01:32:14 +00003394
3395 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003396 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003397 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003398 if (log)
3399 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003400 return true;
3401 }
3402 else
3403 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003404
3405 if (m_thread_list.ShouldStop (event_ptr) == false)
3406 {
Jim Inghamcb95f342012-09-05 21:13:56 +00003407 // ShouldStop may have restarted the target already. If so, don't
3408 // resume it twice.
3409 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003410 switch (m_thread_list.ShouldReportStop (event_ptr))
3411 {
3412 case eVoteYes:
3413 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003414 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003415 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003416 case eVoteNo:
3417 return_value = false;
3418 break;
3419 }
3420
3421 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003422 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Inghamcb95f342012-09-05 21:13:56 +00003423 if (!was_restarted)
3424 PrivateResume ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003425 }
3426 else
3427 {
3428 return_value = true;
3429 SynchronouslyNotifyStateChanged (state);
3430 }
3431 }
3432 }
3433 }
3434
3435 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003436 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003437 return return_value;
3438}
3439
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003440
3441bool
Jim Ingham372787f2012-04-07 00:00:41 +00003442Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003443{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003444 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003445
Greg Clayton8b82f082011-04-12 05:54:46 +00003446 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003447 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003448 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3449
Jim Ingham372787f2012-04-07 00:00:41 +00003450 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003451 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003452
3453 // Create a thread that watches our internal state and controls which
3454 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003455 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003456 if (already_running)
3457 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3458 else
3459 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003460
3461 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003462 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003463 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3464 if (success)
3465 {
3466 ResumePrivateStateThread();
3467 return true;
3468 }
3469 else
3470 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003471}
3472
3473void
3474Process::PausePrivateStateThread ()
3475{
3476 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3477}
3478
3479void
3480Process::ResumePrivateStateThread ()
3481{
3482 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3483}
3484
3485void
3486Process::StopPrivateStateThread ()
3487{
Greg Clayton8b82f082011-04-12 05:54:46 +00003488 if (PrivateStateThreadIsValid ())
3489 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003490 else
3491 {
3492 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3493 if (log)
3494 printf ("Went to stop the private state thread, but it was already invalid.");
3495 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003496}
3497
3498void
3499Process::ControlPrivateStateThread (uint32_t signal)
3500{
Jim Inghamb1e2e842012-04-12 18:49:31 +00003501 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003502
3503 assert (signal == eBroadcastInternalStateControlStop ||
3504 signal == eBroadcastInternalStateControlPause ||
3505 signal == eBroadcastInternalStateControlResume);
3506
3507 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003508 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003509
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003510 // Signal the private state thread. First we should copy this is case the
3511 // thread starts exiting since the private state thread will NULL this out
3512 // when it exits
3513 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003514 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003515 {
3516 TimeValue timeout_time;
3517 bool timed_out;
3518
3519 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3520
3521 timeout_time = TimeValue::Now();
3522 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003523 if (log)
3524 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003525 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3526 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3527
3528 if (signal == eBroadcastInternalStateControlStop)
3529 {
3530 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003531 {
3532 Error error;
3533 Host::ThreadCancel (private_state_thread, &error);
3534 if (log)
3535 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3536 }
3537 else
3538 {
3539 if (log)
3540 log->Printf ("The control event killed the private state thread without having to cancel.");
3541 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003542
3543 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003544 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003545 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003546 }
3547 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003548 else
3549 {
3550 if (log)
3551 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3552 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003553}
3554
3555void
Jim Inghamcfc09352012-07-27 23:57:19 +00003556Process::SendAsyncInterrupt ()
3557{
3558 if (PrivateStateThreadIsValid())
3559 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3560 else
3561 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3562}
3563
3564void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003565Process::HandlePrivateEvent (EventSP &event_sp)
3566{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003567 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003568 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003569
Greg Clayton414f5d32011-01-25 02:58:48 +00003570 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003571
3572 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003573 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003574 {
Jim Ingham754ab982011-01-29 04:05:41 +00003575 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003576 switch (action_result)
3577 {
3578 case NextEventAction::eEventActionSuccess:
3579 SetNextEventAction(NULL);
3580 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003581
Jim Inghambb3a2832011-01-29 01:49:25 +00003582 case NextEventAction::eEventActionRetry:
3583 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003584
Jim Inghambb3a2832011-01-29 01:49:25 +00003585 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003586 // Handle Exiting Here. If we already got an exited event,
3587 // we should just propagate it. Otherwise, swallow this event,
3588 // and set our state to exit so the next event will kill us.
3589 if (new_state != eStateExited)
3590 {
3591 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003592 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003593 SetNextEventAction(NULL);
3594 return;
3595 }
3596 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003597 break;
3598 }
3599 }
3600
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003601 // See if we should broadcast this state to external clients?
3602 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003603
3604 if (should_broadcast)
3605 {
3606 if (log)
3607 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003608 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003609 __FUNCTION__,
3610 GetID(),
3611 StateAsCString(new_state),
3612 StateAsCString (GetState ()),
3613 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003614 }
Jim Ingham9575d842011-03-11 03:53:59 +00003615 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003616 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003617 PushProcessInputReader ();
3618 else
3619 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003620
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003621 BroadcastEvent (event_sp);
3622 }
3623 else
3624 {
3625 if (log)
3626 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003627 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003628 __FUNCTION__,
3629 GetID(),
3630 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003631 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003632 }
3633 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003634 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003635}
3636
3637void *
3638Process::PrivateStateThread (void *arg)
3639{
3640 Process *proc = static_cast<Process*> (arg);
3641 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003642 return result;
3643}
3644
3645void *
3646Process::RunPrivateStateThread ()
3647{
Jim Ingham076b3042012-04-10 01:21:57 +00003648 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003649 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003650
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003651 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003652 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003653 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003654
3655 bool exit_now = false;
3656 while (!exit_now)
3657 {
3658 EventSP event_sp;
3659 WaitForEventsPrivate (NULL, event_sp, control_only);
3660 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3661 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003662 if (log)
3663 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3664
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003665 switch (event_sp->GetType())
3666 {
3667 case eBroadcastInternalStateControlStop:
3668 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003669 break; // doing any internal state managment below
3670
3671 case eBroadcastInternalStateControlPause:
3672 control_only = true;
3673 break;
3674
3675 case eBroadcastInternalStateControlResume:
3676 control_only = false;
3677 break;
3678 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003679
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003680 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003681 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003682 }
Jim Inghamcfc09352012-07-27 23:57:19 +00003683 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3684 {
3685 if (m_public_state.GetValue() == eStateAttaching)
3686 {
3687 if (log)
3688 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3689 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3690 }
3691 else
3692 {
3693 if (log)
3694 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3695 Halt();
3696 }
3697 continue;
3698 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003699
3700 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3701
3702 if (internal_state != eStateInvalid)
3703 {
3704 HandlePrivateEvent (event_sp);
3705 }
3706
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003707 if (internal_state == eStateInvalid ||
3708 internal_state == eStateExited ||
3709 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003710 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003711 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003712 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 +00003713
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003714 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003715 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003716 }
3717
Caroline Tice20ad3c42010-10-29 21:48:37 +00003718 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003719 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003720 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003721
Greg Clayton6ed95942011-01-22 07:12:45 +00003722 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3723 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003724 return NULL;
3725}
3726
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003727//------------------------------------------------------------------
3728// Process Event Data
3729//------------------------------------------------------------------
3730
3731Process::ProcessEventData::ProcessEventData () :
3732 EventData (),
3733 m_process_sp (),
3734 m_state (eStateInvalid),
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 (const ProcessSP &process_sp, StateType state) :
3742 EventData (),
3743 m_process_sp (process_sp),
3744 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003745 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003746 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003747 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003748{
3749}
3750
3751Process::ProcessEventData::~ProcessEventData()
3752{
3753}
3754
3755const ConstString &
3756Process::ProcessEventData::GetFlavorString ()
3757{
3758 static ConstString g_flavor ("Process::ProcessEventData");
3759 return g_flavor;
3760}
3761
3762const ConstString &
3763Process::ProcessEventData::GetFlavor () const
3764{
3765 return ProcessEventData::GetFlavorString ();
3766}
3767
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003768void
3769Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3770{
3771 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003772 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3773 // the public event queue, then other times when we're pretending that this is where we stopped at the
3774 // end of expression evaluation. m_update_state is used to distinguish these
3775 // three cases; it is 0 when we're just pulling it off for private handling,
3776 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003777
Jim Inghama8604692011-05-22 21:45:01 +00003778 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003779 return;
3780
3781 m_process_sp->SetPublicState (m_state);
3782
3783 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3784 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003785 {
3786 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003787 uint32_t num_threads = curr_thread_list.GetSize();
3788 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003789
Jim Ingham4b536182011-08-09 02:12:22 +00003790 // The actions might change one of the thread's stop_info's opinions about whether we should
3791 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003792
3793 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3794 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3795 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3796 // 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
3797 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003798 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003799 for (idx = 0; idx < num_threads; ++idx)
3800 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3801
Jim Ingham4b536182011-08-09 02:12:22 +00003802 bool still_should_stop = true;
3803
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003804 for (idx = 0; idx < num_threads; ++idx)
3805 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003806 curr_thread_list = m_process_sp->GetThreadList();
3807 if (curr_thread_list.GetSize() != num_threads)
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("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003812 break;
3813 }
3814
3815 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3816
3817 if (thread_sp->GetIndexID() != thread_index_array[idx])
3818 {
3819 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003820 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003821 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003822 idx,
3823 thread_index_array[idx],
3824 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003825 break;
3826 }
3827
Jim Inghamb15bfc72010-10-20 00:39:53 +00003828 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00003829 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003830 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003831 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003832 // The stop action might restart the target. If it does, then we want to mark that in the
3833 // event so that whoever is receiving it will know to wait for the running event and reflect
3834 // that state appropriately.
3835 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003836
3837 // FIXME: we might have run.
3838 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003839 {
3840 SetRestarted (true);
3841 break;
3842 }
3843 else if (!stop_info_sp->ShouldStop(event_ptr))
3844 {
3845 still_should_stop = false;
3846 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003847 }
3848 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003849
Jim Ingham4b536182011-08-09 02:12:22 +00003850
3851 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003852 {
Jim Ingham4b536182011-08-09 02:12:22 +00003853 if (!still_should_stop)
3854 {
3855 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003856 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00003857 // Use the public resume method here, since this is just
3858 // extending a public resume.
Jim Ingham4b536182011-08-09 02:12:22 +00003859 m_process_sp->Resume();
3860 }
3861 else
3862 {
3863 // If we didn't restart, run the Stop Hooks here:
3864 // They might also restart the target, so watch for that.
3865 m_process_sp->GetTarget().RunStopHooks();
3866 if (m_process_sp->GetPrivateState() == eStateRunning)
3867 SetRestarted(true);
3868 }
Jim Ingham9575d842011-03-11 03:53:59 +00003869 }
3870
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003871 }
3872}
3873
3874void
3875Process::ProcessEventData::Dump (Stream *s) const
3876{
3877 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003878 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003879
Greg Clayton8b82f082011-04-12 05:54:46 +00003880 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003881}
3882
3883const Process::ProcessEventData *
3884Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3885{
3886 if (event_ptr)
3887 {
3888 const EventData *event_data = event_ptr->GetData();
3889 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3890 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3891 }
3892 return NULL;
3893}
3894
3895ProcessSP
3896Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3897{
3898 ProcessSP process_sp;
3899 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3900 if (data)
3901 process_sp = data->GetProcessSP();
3902 return process_sp;
3903}
3904
3905StateType
3906Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3907{
3908 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3909 if (data == NULL)
3910 return eStateInvalid;
3911 else
3912 return data->GetState();
3913}
3914
3915bool
3916Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3917{
3918 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3919 if (data == NULL)
3920 return false;
3921 else
3922 return data->GetRestarted();
3923}
3924
3925void
3926Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3927{
3928 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3929 if (data != NULL)
3930 data->SetRestarted(new_value);
3931}
3932
3933bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003934Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3935{
3936 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3937 if (data == NULL)
3938 return false;
3939 else
3940 return data->GetInterrupted ();
3941}
3942
3943void
3944Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3945{
3946 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3947 if (data != NULL)
3948 data->SetInterrupted(new_value);
3949}
3950
3951bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003952Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3953{
3954 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3955 if (data)
3956 {
3957 data->SetUpdateStateOnRemoval();
3958 return true;
3959 }
3960 return false;
3961}
3962
Greg Claytond9e416c2012-02-18 05:35:26 +00003963lldb::TargetSP
3964Process::CalculateTarget ()
3965{
3966 return m_target.shared_from_this();
3967}
3968
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003969void
Greg Clayton0603aa92010-10-04 01:05:56 +00003970Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003971{
Greg Claytonc14ee322011-09-22 04:58:26 +00003972 exe_ctx.SetTargetPtr (&m_target);
3973 exe_ctx.SetProcessPtr (this);
3974 exe_ctx.SetThreadPtr(NULL);
3975 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003976}
3977
Greg Claytone996fd32011-03-08 22:40:15 +00003978//uint32_t
3979//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3980//{
3981// return 0;
3982//}
3983//
3984//ArchSpec
3985//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3986//{
3987// return Host::GetArchSpecForExistingProcess (pid);
3988//}
3989//
3990//ArchSpec
3991//Process::GetArchSpecForExistingProcess (const char *process_name)
3992//{
3993// return Host::GetArchSpecForExistingProcess (process_name);
3994//}
3995//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003996void
3997Process::AppendSTDOUT (const char * s, size_t len)
3998{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003999 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004000 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004001 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004002}
4003
4004void
Greg Clayton93e86192011-11-13 04:45:22 +00004005Process::AppendSTDERR (const char * s, size_t len)
4006{
4007 Mutex::Locker locker (m_stdio_communication_mutex);
4008 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004009 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004010}
4011
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004012void
4013Process::BroadcastAsyncProfileData(const char *s, size_t len)
4014{
4015 Mutex::Locker locker (m_profile_data_comm_mutex);
4016 m_profile_data.append (s, len);
4017 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4018}
4019
4020size_t
4021Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4022{
4023 Mutex::Locker locker(m_profile_data_comm_mutex);
4024 size_t bytes_available = m_profile_data.size();
4025 if (bytes_available > 0)
4026 {
4027 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4028 if (log)
4029 log->Printf ("Process::GetProfileData (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
4030 if (bytes_available > buf_size)
4031 {
4032 memcpy(buf, m_profile_data.c_str(), buf_size);
4033 m_profile_data.erase(0, buf_size);
4034 bytes_available = buf_size;
4035 }
4036 else
4037 {
4038 memcpy(buf, m_profile_data.c_str(), bytes_available);
4039 m_profile_data.clear();
4040 }
4041 }
4042 return bytes_available;
4043}
4044
4045
Greg Clayton93e86192011-11-13 04:45:22 +00004046//------------------------------------------------------------------
4047// Process STDIO
4048//------------------------------------------------------------------
4049
4050size_t
4051Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4052{
4053 Mutex::Locker locker(m_stdio_communication_mutex);
4054 size_t bytes_available = m_stdout_data.size();
4055 if (bytes_available > 0)
4056 {
4057 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4058 if (log)
Greg Clayton43e0af02012-09-18 18:04:04 +00004059 log->Printf ("Process::GetSTDOUT (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004060 if (bytes_available > buf_size)
4061 {
4062 memcpy(buf, m_stdout_data.c_str(), buf_size);
4063 m_stdout_data.erase(0, buf_size);
4064 bytes_available = buf_size;
4065 }
4066 else
4067 {
4068 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4069 m_stdout_data.clear();
4070 }
4071 }
4072 return bytes_available;
4073}
4074
4075
4076size_t
4077Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4078{
4079 Mutex::Locker locker(m_stdio_communication_mutex);
4080 size_t bytes_available = m_stderr_data.size();
4081 if (bytes_available > 0)
4082 {
4083 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4084 if (log)
Greg Clayton43e0af02012-09-18 18:04:04 +00004085 log->Printf ("Process::GetSTDERR (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004086 if (bytes_available > buf_size)
4087 {
4088 memcpy(buf, m_stderr_data.c_str(), buf_size);
4089 m_stderr_data.erase(0, buf_size);
4090 bytes_available = buf_size;
4091 }
4092 else
4093 {
4094 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4095 m_stderr_data.clear();
4096 }
4097 }
4098 return bytes_available;
4099}
4100
4101void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004102Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4103{
4104 Process *process = (Process *) baton;
4105 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4106}
4107
4108size_t
4109Process::ProcessInputReaderCallback (void *baton,
4110 InputReader &reader,
4111 lldb::InputReaderAction notification,
4112 const char *bytes,
4113 size_t bytes_len)
4114{
4115 Process *process = (Process *) baton;
4116
4117 switch (notification)
4118 {
4119 case eInputReaderActivate:
4120 break;
4121
4122 case eInputReaderDeactivate:
4123 break;
4124
4125 case eInputReaderReactivate:
4126 break;
4127
Caroline Tice969ed3d2011-05-02 20:41:46 +00004128 case eInputReaderAsynchronousOutputWritten:
4129 break;
4130
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004131 case eInputReaderGotToken:
4132 {
4133 Error error;
4134 process->PutSTDIN (bytes, bytes_len, error);
4135 }
4136 break;
4137
Caroline Ticeefed6132010-11-19 20:47:54 +00004138 case eInputReaderInterrupt:
4139 process->Halt ();
4140 break;
4141
4142 case eInputReaderEndOfFile:
4143 process->AppendSTDOUT ("^D", 2);
4144 break;
4145
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004146 case eInputReaderDone:
4147 break;
4148
4149 }
4150
4151 return bytes_len;
4152}
4153
4154void
4155Process::ResetProcessInputReader ()
4156{
4157 m_process_input_reader.reset();
4158}
4159
4160void
Greg Claytonee95ed52011-11-17 22:14:31 +00004161Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004162{
4163 // First set up the Read Thread for reading/handling process I/O
4164
4165 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4166
4167 if (conn_ap.get())
4168 {
4169 m_stdio_communication.SetConnection (conn_ap.release());
4170 if (m_stdio_communication.IsConnected())
4171 {
4172 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4173 m_stdio_communication.StartReadThread();
4174
4175 // Now read thread is set up, set up input reader.
4176
4177 if (!m_process_input_reader.get())
4178 {
4179 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4180 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4181 this,
4182 eInputReaderGranularityByte,
4183 NULL,
4184 NULL,
4185 false));
4186
4187 if (err.Fail())
4188 m_process_input_reader.reset();
4189 }
4190 }
4191 }
4192}
4193
4194void
4195Process::PushProcessInputReader ()
4196{
4197 if (m_process_input_reader && !m_process_input_reader->IsActive())
4198 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4199}
4200
4201void
4202Process::PopProcessInputReader ()
4203{
4204 if (m_process_input_reader && m_process_input_reader->IsActive())
4205 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4206}
4207
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004208// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004209void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004210Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004211{
Greg Clayton67cc0632012-08-22 17:17:09 +00004212// static std::vector<OptionEnumValueElement> g_plugins;
4213//
4214// int i=0;
4215// const char *name;
4216// OptionEnumValueElement option_enum;
4217// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4218// {
4219// if (name)
4220// {
4221// option_enum.value = i;
4222// option_enum.string_value = name;
4223// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4224// g_plugins.push_back (option_enum);
4225// }
4226// ++i;
4227// }
4228// option_enum.value = 0;
4229// option_enum.string_value = NULL;
4230// option_enum.usage = NULL;
4231// g_plugins.push_back (option_enum);
4232//
4233// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4234// {
4235// if (::strcmp (name, "plugin") == 0)
4236// {
4237// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4238// break;
4239// }
4240// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004241//
Greg Clayton6920b522012-08-22 18:39:03 +00004242 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004243}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004244
Greg Clayton99d0faf2010-11-18 23:32:35 +00004245void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004246Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004247{
Greg Clayton6920b522012-08-22 18:39:03 +00004248 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004249}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004250
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004251ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004252Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004253 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00004254 bool stop_others,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004255 bool run_others,
Jim Inghamf48169b2010-11-30 02:22:11 +00004256 bool discard_on_error,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004257 uint32_t timeout_usec,
Jim Inghamf48169b2010-11-30 02:22:11 +00004258 Stream &errors)
4259{
4260 ExecutionResults return_value = eExecutionSetupError;
4261
Jim Ingham77787032011-01-20 02:03:18 +00004262 if (thread_plan_sp.get() == NULL)
4263 {
4264 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004265 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004266 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004267
4268 if (exe_ctx.GetProcessPtr() != this)
4269 {
4270 errors.Printf("RunThreadPlan called on wrong process.");
4271 return eExecutionSetupError;
4272 }
4273
4274 Thread *thread = exe_ctx.GetThreadPtr();
4275 if (thread == NULL)
4276 {
4277 errors.Printf("RunThreadPlan called with invalid thread.");
4278 return eExecutionSetupError;
4279 }
Jim Ingham77787032011-01-20 02:03:18 +00004280
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004281 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4282 // For that to be true the plan can't be private - since private plans suppress themselves in the
4283 // GetCompletedPlan call.
4284
4285 bool orig_plan_private = thread_plan_sp->GetPrivate();
4286 thread_plan_sp->SetPrivate(false);
4287
Jim Ingham444586b2011-01-24 06:34:17 +00004288 if (m_private_state.GetValue() != eStateStopped)
4289 {
4290 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004291 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004292 }
4293
Jim Ingham66243842011-08-13 00:56:10 +00004294 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004295 const uint32_t thread_idx_id = thread->GetIndexID();
4296 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004297
4298 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4299 // so we should arrange to reset them as well.
4300
Greg Claytonc14ee322011-09-22 04:58:26 +00004301 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004302
Jim Ingham66243842011-08-13 00:56:10 +00004303 uint32_t selected_tid;
4304 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004305 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004306 {
4307 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004308 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004309 }
4310 else
4311 {
4312 selected_tid = LLDB_INVALID_THREAD_ID;
4313 }
4314
Jim Ingham372787f2012-04-07 00:00:41 +00004315 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004316 lldb::StateType old_state;
4317 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004318
Jim Ingham076b3042012-04-10 01:21:57 +00004319 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004320 if (Host::GetCurrentThread() == m_private_state_thread)
4321 {
Jim Ingham076b3042012-04-10 01:21:57 +00004322 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4323 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004324 // 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 +00004325 // we are fielding public events here.
4326 if (log)
4327 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4328
4329
Jim Ingham372787f2012-04-07 00:00:41 +00004330 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004331
4332 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4333 // returning control here.
4334 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4335 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4336 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4337 // do just what we want.
4338 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4339 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4340 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4341 old_state = m_public_state.GetValue();
4342 m_public_state.SetValueNoLock(eStateStopped);
4343
4344 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004345 StartPrivateStateThread(true);
4346 }
4347
4348 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004349
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004350 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004351
Sean Callanana46ec452012-07-11 21:31:24 +00004352 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004353
Jim Ingham77787032011-01-20 02:03:18 +00004354 {
Sean Callanana46ec452012-07-11 21:31:24 +00004355 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4356 // restored on exit to the function.
4357 //
4358 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4359 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004360
Sean Callanana46ec452012-07-11 21:31:24 +00004361 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004362
Jim Inghamf48169b2010-11-30 02:22:11 +00004363 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004364 {
4365 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004366 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4367 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4368 thread->GetIndexID(),
4369 thread->GetID(),
4370 s.GetData());
4371 }
4372
4373 bool got_event;
4374 lldb::EventSP event_sp;
4375 lldb::StateType stop_state = lldb::eStateInvalid;
4376
4377 TimeValue* timeout_ptr = NULL;
4378 TimeValue real_timeout;
4379
4380 bool first_timeout = true;
4381 bool do_resume = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004382 const uint64_t default_one_thread_timeout_usec = 250000;
4383 uint64_t computed_timeout = 0;
Sean Callanana46ec452012-07-11 21:31:24 +00004384
4385 while (1)
4386 {
4387 // We usually want to resume the process if we get to the top of the loop.
4388 // The only exception is if we get two running events with no intervening
4389 // stop, which can happen, we will just wait for then next stop event.
4390
4391 if (do_resume)
4392 {
4393 // Do the initial resume and wait for the running event before going further.
4394
4395 Error resume_error = PrivateResume ();
4396 if (!resume_error.Success())
4397 {
4398 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4399 return_value = eExecutionSetupError;
4400 break;
4401 }
4402
4403 real_timeout = TimeValue::Now();
4404 real_timeout.OffsetWithMicroSeconds(500000);
4405 timeout_ptr = &real_timeout;
4406
4407 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4408 if (!got_event)
4409 {
4410 if (log)
4411 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4412
4413 errors.Printf("Didn't get any event after initial resume, exiting.");
4414 return_value = eExecutionSetupError;
4415 break;
4416 }
4417
4418 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4419 if (stop_state != eStateRunning)
4420 {
4421 if (log)
Jim Ingham35e1bda2012-10-16 21:41:58 +00004422 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4423 "initial resume, got %s instead.",
4424 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004425
Jim Ingham35e1bda2012-10-16 21:41:58 +00004426 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4427 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004428 return_value = eExecutionSetupError;
4429 break;
4430 }
4431
4432 if (log)
4433 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4434 // We need to call the function synchronously, so spin waiting for it to return.
4435 // If we get interrupted while executing, we're going to lose our context, and
4436 // won't be able to gather the result at this point.
4437 // We set the timeout AFTER the resume, since the resume takes some time and we
4438 // don't want to charge that to the timeout.
4439
Jim Ingham35e1bda2012-10-16 21:41:58 +00004440 if (first_timeout)
4441 {
4442 if (run_others)
4443 {
4444 // If we are running all threads then we take half the time to run all threads, bounded by
4445 // .25 sec.
4446 if (timeout_usec == 0)
4447 computed_timeout = default_one_thread_timeout_usec;
4448 else
4449 {
4450 computed_timeout = timeout_usec / 2;
4451 if (computed_timeout > default_one_thread_timeout_usec)
4452 {
4453 computed_timeout = default_one_thread_timeout_usec;
4454 }
4455 timeout_usec -= computed_timeout;
4456 }
4457 }
4458 else
4459 {
4460 computed_timeout = timeout_usec;
4461 }
4462 }
4463 else
4464 {
4465 computed_timeout = timeout_usec;
4466 }
4467
4468 if (computed_timeout != 0)
Sean Callanana46ec452012-07-11 21:31:24 +00004469 {
Enrico Granata3372f582012-07-16 23:10:35 +00004470 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanana46ec452012-07-11 21:31:24 +00004471 real_timeout = TimeValue::Now();
Jim Ingham35e1bda2012-10-16 21:41:58 +00004472 real_timeout.OffsetWithMicroSeconds(computed_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00004473
4474 timeout_ptr = &real_timeout;
4475 }
Enrico Granata3372f582012-07-16 23:10:35 +00004476 else
4477 {
Jim Ingham35e1bda2012-10-16 21:41:58 +00004478 timeout_ptr = NULL;
Enrico Granata3372f582012-07-16 23:10:35 +00004479 }
Sean Callanana46ec452012-07-11 21:31:24 +00004480 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004481 else
4482 {
Sean Callanana46ec452012-07-11 21:31:24 +00004483 if (log)
4484 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4485 do_resume = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00004486 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004487
Sean Callanana46ec452012-07-11 21:31:24 +00004488 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00004489 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00004490
Jim Ingham0f16e732011-02-08 05:20:59 +00004491 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004492 {
Sean Callanana46ec452012-07-11 21:31:24 +00004493 if (timeout_ptr)
4494 {
4495 StreamString s;
4496 s.Printf ("about to wait - timeout is:\n ");
4497 timeout_ptr->Dump (&s, 120);
4498 s.Printf ("\nNow is:\n ");
4499 TimeValue::Now().Dump (&s, 120);
4500 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4501 }
Jim Ingham20829ac2011-08-09 22:24:33 +00004502 else
Sean Callanana46ec452012-07-11 21:31:24 +00004503 {
4504 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4505 }
4506 }
4507
4508 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4509
4510 if (got_event)
4511 {
4512 if (event_sp.get())
4513 {
4514 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00004515 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004516 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004517 Halt();
4518 keep_going = false;
4519 return_value = eExecutionInterrupted;
4520 errors.Printf ("Execution halted by user interrupt.");
4521 if (log)
4522 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4523 }
4524 else
4525 {
4526 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4527 if (log)
4528 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4529
4530 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00004531 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004532 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00004533 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004534 // Yay, we're done. Now make sure that our thread plan actually completed.
4535 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4536 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004537 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004538 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00004539 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00004540 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4541 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00004542 }
4543 else
4544 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004545 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4546 StopReason stop_reason = eStopReasonInvalid;
4547 if (stop_info_sp)
4548 stop_reason = stop_info_sp->GetStopReason();
4549 if (stop_reason == eStopReasonPlanComplete)
4550 {
4551 if (log)
4552 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4553 // Now mark this plan as private so it doesn't get reported as the stop reason
4554 // after this point.
4555 if (thread_plan_sp)
4556 thread_plan_sp->SetPrivate (orig_plan_private);
4557 return_value = eExecutionCompleted;
4558 }
4559 else
4560 {
4561 if (log)
4562 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanana46ec452012-07-11 21:31:24 +00004563
Jim Inghamcfc09352012-07-27 23:57:19 +00004564 return_value = eExecutionInterrupted;
4565 }
Sean Callanana46ec452012-07-11 21:31:24 +00004566 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004567 }
4568 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004569
Jim Inghamcfc09352012-07-27 23:57:19 +00004570 case lldb::eStateCrashed:
4571 if (log)
4572 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4573 return_value = eExecutionInterrupted;
4574 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004575
Jim Inghamcfc09352012-07-27 23:57:19 +00004576 case lldb::eStateRunning:
4577 do_resume = false;
4578 keep_going = true;
4579 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004580
Jim Inghamcfc09352012-07-27 23:57:19 +00004581 default:
4582 if (log)
4583 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4584
4585 if (stop_state == eStateExited)
4586 event_to_broadcast_sp = event_sp;
4587
Sean Callananbf154da2012-08-08 17:35:10 +00004588 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00004589 return_value = eExecutionInterrupted;
4590 break;
4591 }
Sean Callanana46ec452012-07-11 21:31:24 +00004592 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004593
Sean Callanana46ec452012-07-11 21:31:24 +00004594 if (keep_going)
4595 continue;
4596 else
4597 break;
4598 }
4599 else
4600 {
4601 if (log)
4602 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4603 return_value = eExecutionInterrupted;
4604 break;
4605 }
4606 }
4607 else
4608 {
4609 // If we didn't get an event that means we've timed out...
4610 // We will interrupt the process here. Depending on what we were asked to do we will
4611 // either exit, or try with all threads running for the same timeout.
4612 // Not really sure what to do if Halt fails here...
4613
4614 if (log) {
Jim Ingham35e1bda2012-10-16 21:41:58 +00004615 if (run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00004616 {
4617 if (first_timeout)
Jim Ingham35e1bda2012-10-16 21:41:58 +00004618 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %lld timed out, "
4619 "trying for %d usec with all threads enabled.",
4620 computed_timeout, timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004621 else
4622 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham35e1bda2012-10-16 21:41:58 +00004623 "and timeout: %d timed out, abandoning execution.",
4624 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004625 }
4626 else
4627 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00004628 "abandoning execution.",
4629 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004630 }
4631
4632 Error halt_error = Halt();
4633 if (halt_error.Success())
4634 {
4635 if (log)
4636 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4637
4638 // If halt succeeds, it always produces a stopped event. Wait for that:
4639
4640 real_timeout = TimeValue::Now();
4641 real_timeout.OffsetWithMicroSeconds(500000);
4642
4643 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4644
4645 if (got_event)
4646 {
4647 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4648 if (log)
4649 {
4650 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4651 if (stop_state == lldb::eStateStopped
4652 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4653 log->PutCString (" Event was the Halt interruption event.");
4654 }
4655
4656 if (stop_state == lldb::eStateStopped)
4657 {
4658 // Between the time we initiated the Halt and the time we delivered it, the process could have
4659 // already finished its job. Check that here:
4660
4661 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4662 {
4663 if (log)
4664 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4665 "Exiting wait loop.");
4666 return_value = eExecutionCompleted;
4667 break;
4668 }
4669
Jim Ingham35e1bda2012-10-16 21:41:58 +00004670 if (!run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00004671 {
4672 if (log)
4673 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4674 return_value = eExecutionInterrupted;
4675 break;
4676 }
4677
4678 if (first_timeout)
4679 {
4680 // Set all the other threads to run, and return to the top of the loop, which will continue;
4681 first_timeout = false;
4682 thread_plan_sp->SetStopOthers (false);
4683 if (log)
4684 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4685
4686 continue;
4687 }
4688 else
4689 {
4690 // Running all threads failed, so return Interrupted.
4691 if (log)
4692 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4693 return_value = eExecutionInterrupted;
4694 break;
4695 }
4696 }
4697 }
4698 else
4699 { if (log)
4700 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4701 "I'm getting out of here passing Interrupted.");
4702 return_value = eExecutionInterrupted;
4703 break;
4704 }
4705 }
4706 else
4707 {
4708 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4709 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4710 if (log)
4711 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.",
4712 halt_error.AsCString());
4713 real_timeout = TimeValue::Now();
4714 real_timeout.OffsetWithMicroSeconds(500000);
4715 timeout_ptr = &real_timeout;
4716 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4717 if (!got_event || event_sp.get() == NULL)
4718 {
4719 // This is not going anywhere, bag out.
4720 if (log)
4721 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4722 return_value = eExecutionInterrupted;
4723 break;
4724 }
4725 else
4726 {
4727 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4728 if (log)
4729 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4730 if (stop_state == lldb::eStateStopped)
4731 {
4732 // Between the time we initiated the Halt and the time we delivered it, the process could have
4733 // already finished its job. Check that here:
4734
4735 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4736 {
4737 if (log)
4738 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4739 "Exiting wait loop.");
4740 return_value = eExecutionCompleted;
4741 break;
4742 }
4743
4744 if (first_timeout)
4745 {
4746 // Set all the other threads to run, and return to the top of the loop, which will continue;
4747 first_timeout = false;
4748 thread_plan_sp->SetStopOthers (false);
4749 if (log)
4750 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4751
4752 continue;
4753 }
4754 else
4755 {
4756 // Running all threads failed, so return Interrupted.
4757 if (log)
4758 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4759 return_value = eExecutionInterrupted;
4760 break;
4761 }
4762 }
4763 else
4764 {
4765 if (log)
4766 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4767 " a stopped event, instead got %s.", StateAsCString(stop_state));
4768 return_value = eExecutionInterrupted;
4769 break;
4770 }
4771 }
4772 }
4773
4774 }
4775
4776 } // END WAIT LOOP
4777
4778 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4779 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4780 {
4781 StopPrivateStateThread();
4782 Error error;
4783 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00004784 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004785 {
4786 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4787 }
4788 m_public_state.SetValueNoLock(old_state);
4789
4790 }
4791
4792
4793 // Now do some processing on the results of the run:
4794 if (return_value == eExecutionInterrupted)
4795 {
4796 if (log)
4797 {
4798 StreamString s;
4799 if (event_sp)
4800 event_sp->Dump (&s);
4801 else
4802 {
4803 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4804 }
4805
4806 StreamString ts;
4807
4808 const char *event_explanation = NULL;
4809
4810 do
4811 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004812 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004813 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004814 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00004815 break;
4816 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004817 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004818 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004819 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00004820 break;
4821 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004822 else
Sean Callanana46ec452012-07-11 21:31:24 +00004823 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004824 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4825
4826 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00004827 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004828 event_explanation = "<no event data>";
4829 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004830 }
4831
Jim Inghamcfc09352012-07-27 23:57:19 +00004832 Process *process = event_data->GetProcessSP().get();
4833
4834 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00004835 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004836 event_explanation = "<no process>";
4837 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004838 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004839
4840 ThreadList &thread_list = process->GetThreadList();
4841
4842 uint32_t num_threads = thread_list.GetSize();
4843 uint32_t thread_index;
4844
4845 ts.Printf("<%u threads> ", num_threads);
4846
4847 for (thread_index = 0;
4848 thread_index < num_threads;
4849 ++thread_index)
4850 {
4851 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4852
4853 if (!thread)
4854 {
4855 ts.Printf("<?> ");
4856 continue;
4857 }
4858
4859 ts.Printf("<0x%4.4llx ", thread->GetID());
4860 RegisterContext *register_context = thread->GetRegisterContext().get();
4861
4862 if (register_context)
4863 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4864 else
4865 ts.Printf("[ip unknown] ");
4866
4867 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4868 if (stop_info_sp)
4869 {
4870 const char *stop_desc = stop_info_sp->GetDescription();
4871 if (stop_desc)
4872 ts.PutCString (stop_desc);
4873 }
4874 ts.Printf(">");
4875 }
4876
4877 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00004878 }
Sean Callanana46ec452012-07-11 21:31:24 +00004879 } while (0);
4880
Jim Inghamcfc09352012-07-27 23:57:19 +00004881 if (event_explanation)
4882 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00004883 else
Jim Inghamcfc09352012-07-27 23:57:19 +00004884 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4885 }
4886
4887 if (discard_on_error && thread_plan_sp)
4888 {
4889 if (log)
4890 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4891 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4892 thread_plan_sp->SetPrivate (orig_plan_private);
4893 }
4894 else
4895 {
4896 if (log)
4897 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00004898 }
4899 }
4900 else if (return_value == eExecutionSetupError)
4901 {
4902 if (log)
4903 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004904
4905 if (discard_on_error && thread_plan_sp)
4906 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004907 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004908 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004909 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004910 }
4911 else
4912 {
Sean Callanana46ec452012-07-11 21:31:24 +00004913 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004914 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004915 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00004916 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4917 return_value = eExecutionCompleted;
4918 }
4919 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4920 {
4921 if (log)
4922 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4923 return_value = eExecutionDiscarded;
4924 }
4925 else
4926 {
4927 if (log)
4928 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4929 if (discard_on_error && thread_plan_sp)
4930 {
4931 if (log)
4932 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4933 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4934 thread_plan_sp->SetPrivate (orig_plan_private);
4935 }
4936 }
4937 }
4938
4939 // Thread we ran the function in may have gone away because we ran the target
4940 // Check that it's still there, and if it is put it back in the context. Also restore the
4941 // frame in the context if it is still present.
4942 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4943 if (thread)
4944 {
4945 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4946 }
4947
4948 // Also restore the current process'es selected frame & thread, since this function calling may
4949 // be done behind the user's back.
4950
4951 if (selected_tid != LLDB_INVALID_THREAD_ID)
4952 {
4953 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4954 {
4955 // We were able to restore the selected thread, now restore the frame:
4956 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4957 if (old_frame_sp)
4958 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004959 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004960 }
4961 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004962
Sean Callanana46ec452012-07-11 21:31:24 +00004963 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00004964
Sean Callanana46ec452012-07-11 21:31:24 +00004965 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004966 {
Sean Callanana46ec452012-07-11 21:31:24 +00004967 if (log)
4968 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4969 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004970 }
4971
4972 return return_value;
4973}
4974
4975const char *
4976Process::ExecutionResultAsCString (ExecutionResults result)
4977{
4978 const char *result_name;
4979
4980 switch (result)
4981 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004982 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004983 result_name = "eExecutionCompleted";
4984 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004985 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004986 result_name = "eExecutionDiscarded";
4987 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004988 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004989 result_name = "eExecutionInterrupted";
4990 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004991 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004992 result_name = "eExecutionSetupError";
4993 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004994 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004995 result_name = "eExecutionTimedOut";
4996 break;
4997 }
4998 return result_name;
4999}
5000
Greg Clayton7260f622011-04-18 08:33:37 +00005001void
5002Process::GetStatus (Stream &strm)
5003{
5004 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005005 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005006 {
5007 if (state == eStateExited)
5008 {
5009 int exit_status = GetExitStatus();
5010 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00005011 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005012 GetID(),
5013 exit_status,
5014 exit_status,
5015 exit_description ? exit_description : "");
5016 }
5017 else
5018 {
5019 if (state == eStateConnected)
5020 strm.Printf ("Connected to remote target.\n");
5021 else
Greg Clayton81c22f62011-10-19 18:09:39 +00005022 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005023 }
5024 }
5025 else
5026 {
Greg Clayton81c22f62011-10-19 18:09:39 +00005027 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005028 }
5029}
5030
5031size_t
5032Process::GetThreadStatus (Stream &strm,
5033 bool only_threads_with_stop_reason,
5034 uint32_t start_frame,
5035 uint32_t num_frames,
5036 uint32_t num_frames_with_source)
5037{
5038 size_t num_thread_infos_dumped = 0;
5039
Jim Ingham41f2b942012-09-10 20:50:15 +00005040 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005041 const size_t num_threads = GetThreadList().GetSize();
5042 for (uint32_t i = 0; i < num_threads; i++)
5043 {
5044 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5045 if (thread)
5046 {
5047 if (only_threads_with_stop_reason)
5048 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005049 StopInfoSP stop_info_sp = thread->GetStopInfo();
5050 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005051 continue;
5052 }
5053 thread->GetStatus (strm,
5054 start_frame,
5055 num_frames,
5056 num_frames_with_source);
5057 ++num_thread_infos_dumped;
5058 }
5059 }
5060 return num_thread_infos_dumped;
5061}
5062
Greg Claytona9f40ad2012-02-22 04:37:26 +00005063void
5064Process::AddInvalidMemoryRegion (const LoadRange &region)
5065{
5066 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5067}
5068
5069bool
5070Process::RemoveInvalidMemoryRange (const LoadRange &region)
5071{
5072 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5073}
5074
Jim Ingham372787f2012-04-07 00:00:41 +00005075void
5076Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5077{
5078 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5079}
5080
5081bool
5082Process::RunPreResumeActions ()
5083{
5084 bool result = true;
5085 while (!m_pre_resume_actions.empty())
5086 {
5087 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5088 m_pre_resume_actions.pop_back();
5089 bool this_result = action.callback (action.baton);
5090 if (result == true) result = this_result;
5091 }
5092 return result;
5093}
5094
5095void
5096Process::ClearPreResumeActions ()
5097{
5098 m_pre_resume_actions.clear();
5099}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005100
Greg Claytonfa559e52012-05-18 02:38:05 +00005101void
5102Process::Flush ()
5103{
5104 m_thread_list.Flush();
5105}