blob: b6aa066e492a0f091c63c2ad77a858479f0fc734 [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." },
Jim Ingham8c3f2762012-11-29 00:41:12 +000096 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
97 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Greg Claytone1e835c2012-11-29 18:48:47 +000098 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
Greg Clayton67cc0632012-08-22 17:17:09 +000099 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
100};
101
102enum {
103 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000104 ePropertyExtraStartCommand,
105 ePropertyPythonOSPluginPath
Greg Clayton67cc0632012-08-22 17:17:09 +0000106};
107
108ProcessProperties::ProcessProperties (bool is_global) :
109 Properties ()
110{
111 if (is_global)
112 {
113 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
114 m_collection_sp->Initialize(g_properties);
115 m_collection_sp->AppendProperty(ConstString("thread"),
116 ConstString("Settings specify to threads."),
117 true,
118 Thread::GetGlobalProperties()->GetValueProperties());
119 }
120 else
121 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
122}
123
124ProcessProperties::~ProcessProperties()
125{
126}
127
128bool
129ProcessProperties::GetDisableMemoryCache() const
130{
131 const uint32_t idx = ePropertyDisableMemCache;
132 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
133}
134
135Args
136ProcessProperties::GetExtraStartupCommands () const
137{
138 Args args;
139 const uint32_t idx = ePropertyExtraStartCommand;
140 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
141 return args;
142}
143
144void
145ProcessProperties::SetExtraStartupCommands (const Args &args)
146{
147 const uint32_t idx = ePropertyExtraStartCommand;
148 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
149}
150
Greg Claytonc9d645d2012-10-18 22:40:37 +0000151FileSpec
152ProcessProperties::GetPythonOSPluginPath () const
153{
154 const uint32_t idx = ePropertyPythonOSPluginPath;
155 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
156}
157
158void
159ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
160{
161 const uint32_t idx = ePropertyPythonOSPluginPath;
162 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
163}
164
Greg Clayton32e0a752011-03-30 18:16:51 +0000165void
Greg Clayton8b82f082011-04-12 05:54:46 +0000166ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000167{
168 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000169 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +0000170 s.Printf (" pid = %llu\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000171
172 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +0000173 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000174
175 if (m_executable)
176 {
177 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
178 s.PutCString (" file = ");
179 m_executable.Dump(&s);
180 s.EOL();
181 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000182 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000183 if (argc > 0)
184 {
185 for (uint32_t i=0; i<argc; i++)
186 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000187 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000188 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000189 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000190 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000191 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000192 }
193 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000194
195 const uint32_t envc = m_environment.GetArgumentCount();
196 if (envc > 0)
197 {
198 for (uint32_t i=0; i<envc; i++)
199 {
200 const char *env = m_environment.GetArgumentAtIndex(i);
201 if (i < 10)
202 s.Printf (" env[%u] = %s\n", i, env);
203 else
204 s.Printf ("env[%u] = %s\n", i, env);
205 }
206 }
207
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000208 if (m_arch.IsValid())
209 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
210
Greg Clayton8b82f082011-04-12 05:54:46 +0000211 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000212 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000213 cstr = platform->GetUserName (m_uid);
214 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000215 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000216 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000217 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000218 cstr = platform->GetGroupName (m_gid);
219 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000220 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000221 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000222 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000223 cstr = platform->GetUserName (m_euid);
224 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000225 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000226 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000227 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000228 cstr = platform->GetGroupName (m_egid);
229 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000230 }
231}
232
233void
Greg Clayton8b82f082011-04-12 05:54:46 +0000234ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000235{
Greg Clayton8b82f082011-04-12 05:54:46 +0000236 const char *label;
237 if (show_args || verbose)
238 label = "ARGUMENTS";
239 else
240 label = "NAME";
241
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000242 if (verbose)
243 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000244 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000245 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
246 }
247 else
248 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000249 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000250 s.PutCString ("====== ====== ========== ======= ============================\n");
251 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000252}
253
254void
Greg Clayton8b82f082011-04-12 05:54:46 +0000255ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000256{
257 if (m_pid != LLDB_INVALID_PROCESS_ID)
258 {
259 const char *cstr;
Greg Clayton61e7a582011-12-01 23:28:38 +0000260 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000261
Greg Clayton32e0a752011-03-30 18:16:51 +0000262
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000263 if (verbose)
264 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000265 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000266 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
267 s.Printf ("%-10s ", cstr);
268 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000269 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000270
Greg Clayton8b82f082011-04-12 05:54:46 +0000271 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000272 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
273 s.Printf ("%-10s ", cstr);
274 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000275 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000276
Greg Clayton8b82f082011-04-12 05:54:46 +0000277 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000278 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
279 s.Printf ("%-10s ", cstr);
280 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000281 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000282
Greg Clayton8b82f082011-04-12 05:54:46 +0000283 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000284 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
285 s.Printf ("%-10s ", cstr);
286 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000287 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000288 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
289 }
290 else
291 {
Jason Molendafd54b362011-09-20 21:44:10 +0000292 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000293 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000294 (int)m_arch.GetTriple().getArchName().size(),
295 m_arch.GetTriple().getArchName().data());
296 }
297
Greg Clayton8b82f082011-04-12 05:54:46 +0000298 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000299 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000300 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000301 if (argc > 0)
302 {
303 for (uint32_t i=0; i<argc; i++)
304 {
305 if (i > 0)
306 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000307 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000308 }
309 }
310 }
311 else
312 {
313 s.PutCString (GetName());
314 }
315
316 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000317 }
318}
319
Greg Clayton8b82f082011-04-12 05:54:46 +0000320
321void
Greg Clayton45392552012-10-17 22:57:12 +0000322ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton982c9762011-11-03 21:22:33 +0000323{
324 m_arguments.SetArguments (argv);
325
326 // Is the first argument the executable?
327 if (first_arg_is_executable)
328 {
329 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
330 if (first_arg)
331 {
332 // Yes the first argument is an executable, set it as the executable
333 // in the launch options. Don't resolve the file path as the path
334 // could be a remote platform path
335 const bool resolve = false;
336 m_executable.SetFile(first_arg, resolve);
Greg Clayton982c9762011-11-03 21:22:33 +0000337 }
338 }
339}
340void
Greg Clayton45392552012-10-17 22:57:12 +0000341ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Clayton8b82f082011-04-12 05:54:46 +0000342{
343 // Copy all arguments
344 m_arguments = args;
345
346 // Is the first argument the executable?
347 if (first_arg_is_executable)
348 {
Greg Clayton982c9762011-11-03 21:22:33 +0000349 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000350 if (first_arg)
351 {
352 // Yes the first argument is an executable, set it as the executable
353 // in the launch options. Don't resolve the file path as the path
354 // could be a remote platform path
355 const bool resolve = false;
356 m_executable.SetFile(first_arg, resolve);
Greg Clayton8b82f082011-04-12 05:54:46 +0000357 }
358 }
359}
360
Greg Clayton1d885962011-11-08 02:43:13 +0000361void
Greg Claytonee95ed52011-11-17 22:14:31 +0000362ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-11-08 02:43:13 +0000363{
364 // If notthing was specified, then check the process for any default
365 // settings that were set with "settings set"
366 if (m_file_actions.empty())
367 {
Greg Clayton1d885962011-11-08 02:43:13 +0000368 if (m_flags.Test(eLaunchFlagDisableSTDIO))
369 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000370 AppendSuppressFileAction (STDIN_FILENO , true, false);
371 AppendSuppressFileAction (STDOUT_FILENO, false, true);
372 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000373 }
374 else
375 {
376 // Check for any values that might have gotten set with any of:
377 // (lldb) settings set target.input-path
378 // (lldb) settings set target.output-path
379 // (lldb) settings set target.error-path
Greg Clayton67cc0632012-08-22 17:17:09 +0000380 FileSpec in_path;
381 FileSpec out_path;
382 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000383 if (target)
384 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000385 in_path = target->GetStandardInputPath();
386 out_path = target->GetStandardOutputPath();
387 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000388 }
389
Greg Clayton67cc0632012-08-22 17:17:09 +0000390 if (in_path || out_path || err_path)
391 {
392 char path[PATH_MAX];
393 if (in_path && in_path.GetPath(path, sizeof(path)))
394 AppendOpenFileAction(STDIN_FILENO, path, true, false);
395
396 if (out_path && out_path.GetPath(path, sizeof(path)))
397 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
398
399 if (err_path && err_path.GetPath(path, sizeof(path)))
400 AppendOpenFileAction(STDERR_FILENO, path, false, true);
401 }
402 else if (default_to_use_pty)
Greg Claytonee95ed52011-11-17 22:14:31 +0000403 {
404 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000405 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000406 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
407 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
408 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
409 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000410 }
411 }
Greg Clayton1d885962011-11-08 02:43:13 +0000412 }
413 }
414}
415
Greg Clayton144f3a92011-11-15 03:53:30 +0000416
417bool
Greg Claytond1cf11a2012-04-14 01:42:46 +0000418ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
419 bool localhost,
420 bool will_debug,
421 bool first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000422{
423 error.Clear();
424
425 if (GetFlags().Test (eLaunchFlagLaunchInShell))
426 {
427 const char *shell_executable = GetShell();
428 if (shell_executable)
429 {
430 char shell_resolved_path[PATH_MAX];
431
432 if (localhost)
433 {
434 FileSpec shell_filespec (shell_executable, true);
435
436 if (!shell_filespec.Exists())
437 {
438 // Resolve the path in case we just got "bash", "sh" or "tcsh"
439 if (!shell_filespec.ResolveExecutableLocation ())
440 {
441 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
442 return false;
443 }
444 }
445 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
446 shell_executable = shell_resolved_path;
447 }
448
Greg Clayton45392552012-10-17 22:57:12 +0000449 const char **argv = GetArguments().GetConstArgumentVector ();
450 if (argv == NULL || argv[0] == NULL)
451 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000452 Args shell_arguments;
453 std::string safe_arg;
454 shell_arguments.AppendArgument (shell_executable);
Greg Clayton144f3a92011-11-15 03:53:30 +0000455 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000456 StreamString shell_command;
457 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000458 {
Greg Clayton45392552012-10-17 22:57:12 +0000459 // Add a modified PATH environment variable in case argv[0]
460 // is a relative path
461 const char *argv0 = argv[0];
462 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
463 {
464 // We have a relative path to our executable which may not work if
465 // we just try to run "a.out" (without it being converted to "./a.out")
466 const char *working_dir = GetWorkingDirectory();
467 std::string new_path("PATH=");
468 const size_t empty_path_len = new_path.size();
469
470 if (working_dir && working_dir[0])
471 {
472 new_path += working_dir;
473 }
474 else
475 {
476 char current_working_dir[PATH_MAX];
477 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
478 if (cwd && cwd[0])
479 new_path += cwd;
480 }
481 const char *curr_path = getenv("PATH");
482 if (curr_path)
483 {
484 if (new_path.size() > empty_path_len)
485 new_path += ':';
486 new_path += curr_path;
487 }
488 new_path += ' ';
489 shell_command.PutCString(new_path.c_str());
490 }
491
Greg Claytond1cf11a2012-04-14 01:42:46 +0000492 shell_command.PutCString ("exec");
Greg Clayton45392552012-10-17 22:57:12 +0000493
494#if defined(__APPLE__)
495 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Claytond1cf11a2012-04-14 01:42:46 +0000496 if (GetArchitecture().IsValid())
497 {
498 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton45392552012-10-17 22:57:12 +0000499 // Set the resume count to 2:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000500 // 1 - stop in shell
501 // 2 - stop in /usr/bin/arch
502 // 3 - then we will stop in our program
503 SetResumeCount(2);
504 }
505 else
506 {
Greg Clayton45392552012-10-17 22:57:12 +0000507 // Set the resume count to 1:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000508 // 1 - stop in shell
509 // 2 - then we will stop in our program
510 SetResumeCount(1);
511 }
Greg Clayton45392552012-10-17 22:57:12 +0000512#else
513 // Set the resume count to 1:
514 // 1 - stop in shell
515 // 2 - then we will stop in our program
516 SetResumeCount(1);
517#endif
Greg Clayton144f3a92011-11-15 03:53:30 +0000518 }
Greg Clayton45392552012-10-17 22:57:12 +0000519
520 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000521 {
Greg Clayton45392552012-10-17 22:57:12 +0000522 // There should only be one argument that is the shell command itself to be used as is
523 if (argv[0] && !argv[1])
524 shell_command.Printf("%s", argv[0]);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000525 else
Greg Clayton45392552012-10-17 22:57:12 +0000526 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000527 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000528 else
529 {
Greg Clayton45392552012-10-17 22:57:12 +0000530 for (size_t i=0; argv[i] != NULL; ++i)
531 {
532 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
533 shell_command.Printf(" %s", arg);
534 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000535 }
Greg Clayton45392552012-10-17 22:57:12 +0000536 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton144f3a92011-11-15 03:53:30 +0000537 m_executable.SetFile(shell_executable, false);
538 m_arguments = shell_arguments;
539 return true;
540 }
541 else
542 {
543 error.SetErrorString ("invalid shell path");
544 }
545 }
546 else
547 {
548 error.SetErrorString ("not launching in shell");
549 }
550 return false;
551}
552
553
Greg Clayton32e0a752011-03-30 18:16:51 +0000554bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000555ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
556{
557 if ((read || write) && fd >= 0 && path && path[0])
558 {
559 m_action = eFileActionOpen;
560 m_fd = fd;
561 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000562 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000563 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000564 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000565 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000566 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000567 m_path.assign (path);
568 return true;
569 }
570 else
571 {
572 Clear();
573 }
574 return false;
575}
576
577bool
578ProcessLaunchInfo::FileAction::Close (int fd)
579{
580 Clear();
581 if (fd >= 0)
582 {
583 m_action = eFileActionClose;
584 m_fd = fd;
585 }
586 return m_fd >= 0;
587}
588
589
590bool
591ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
592{
593 Clear();
594 if (fd >= 0 && dup_fd >= 0)
595 {
596 m_action = eFileActionDuplicate;
597 m_fd = fd;
598 m_arg = dup_fd;
599 }
600 return m_fd >= 0;
601}
602
603
604
605bool
606ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
607 const FileAction *info,
608 Log *log,
609 Error& error)
610{
611 if (info == NULL)
612 return false;
613
614 switch (info->m_action)
615 {
616 case eFileActionNone:
617 error.Clear();
618 break;
619
620 case eFileActionClose:
621 if (info->m_fd == -1)
622 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
623 else
624 {
625 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
626 eErrorTypePOSIX);
627 if (log && (error.Fail() || log))
628 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
629 file_actions, info->m_fd);
630 }
631 break;
632
633 case eFileActionDuplicate:
634 if (info->m_fd == -1)
635 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
636 else if (info->m_arg == -1)
637 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
638 else
639 {
640 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
641 eErrorTypePOSIX);
642 if (log && (error.Fail() || log))
643 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
644 file_actions, info->m_fd, info->m_arg);
645 }
646 break;
647
648 case eFileActionOpen:
649 if (info->m_fd == -1)
650 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
651 else
652 {
653 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000654
Greg Clayton8b82f082011-04-12 05:54:46 +0000655 mode_t mode = 0;
656
Greg Clayton144f3a92011-11-15 03:53:30 +0000657 if (oflag & O_CREAT)
658 mode = 0640;
659
Greg Clayton8b82f082011-04-12 05:54:46 +0000660 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
661 info->m_fd,
662 info->m_path.c_str(),
663 oflag,
664 mode),
665 eErrorTypePOSIX);
666 if (error.Fail() || log)
667 error.PutToLog(log,
668 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
669 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
670 }
671 break;
672
673 default:
674 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
675 break;
676 }
677 return error.Success();
678}
679
680Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000681ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000682{
683 Error error;
684 char short_option = (char) m_getopt_table[option_idx].val;
685
686 switch (short_option)
687 {
688 case 's': // Stop at program entry point
689 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
690 break;
691
Greg Clayton8b82f082011-04-12 05:54:46 +0000692 case 'i': // STDIN for read only
693 {
694 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000695 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000696 launch_info.AppendFileAction (action);
697 }
698 break;
699
700 case 'o': // Open STDOUT for write only
701 {
702 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000703 if (action.Open (STDOUT_FILENO, option_arg, false, true))
704 launch_info.AppendFileAction (action);
705 }
706 break;
707
708 case 'e': // STDERR for write only
709 {
710 ProcessLaunchInfo::FileAction action;
711 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000712 launch_info.AppendFileAction (action);
713 }
714 break;
715
Greg Clayton9845a8d2012-03-06 04:01:04 +0000716
Greg Clayton8b82f082011-04-12 05:54:46 +0000717 case 'p': // Process plug-in name
718 launch_info.SetProcessPluginName (option_arg);
719 break;
720
721 case 'n': // Disable STDIO
722 {
723 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000724 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000725 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000726 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000727 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000728 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000729 launch_info.AppendFileAction (action);
730 }
731 break;
732
733 case 'w':
734 launch_info.SetWorkingDirectory (option_arg);
735 break;
736
737 case 't': // Open process in new terminal window
738 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
739 break;
740
741 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000742 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
743 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000744 break;
745
746 case 'A':
747 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
748 break;
749
Greg Clayton982c9762011-11-03 21:22:33 +0000750 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000751 if (option_arg && option_arg[0])
752 launch_info.SetShell (option_arg);
753 else
754 launch_info.SetShell ("/bin/bash");
Greg Clayton982c9762011-11-03 21:22:33 +0000755 break;
756
Greg Clayton8b82f082011-04-12 05:54:46 +0000757 case 'v':
758 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
759 break;
760
761 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000762 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000763 break;
764
765 }
766 return error;
767}
768
769OptionDefinition
770ProcessLaunchCommandOptions::g_option_table[] =
771{
772{ 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."},
773{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
774{ 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 +0000775{ 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 +0000776{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
777{ 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 +0000778{ 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 +0000779
Sean Callanan31542552012-10-24 01:12:14 +0000780{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
781{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
782{ 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 +0000783
784{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
785
786{ 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."},
787
788{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
789};
790
791
792
793bool
794ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000795{
796 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
797 return true;
798 const char *match_name = m_match_info.GetName();
799 if (!match_name)
800 return true;
801
802 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
803}
804
805bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000806ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000807{
808 if (!NameMatches (proc_info.GetName()))
809 return false;
810
811 if (m_match_info.ProcessIDIsValid() &&
812 m_match_info.GetProcessID() != proc_info.GetProcessID())
813 return false;
814
815 if (m_match_info.ParentProcessIDIsValid() &&
816 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
817 return false;
818
Greg Clayton8b82f082011-04-12 05:54:46 +0000819 if (m_match_info.UserIDIsValid () &&
820 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000821 return false;
822
Greg Clayton8b82f082011-04-12 05:54:46 +0000823 if (m_match_info.GroupIDIsValid () &&
824 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000825 return false;
826
827 if (m_match_info.EffectiveUserIDIsValid () &&
828 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
829 return false;
830
831 if (m_match_info.EffectiveGroupIDIsValid () &&
832 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
833 return false;
834
835 if (m_match_info.GetArchitecture().IsValid() &&
836 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
837 return false;
838 return true;
839}
840
841bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000842ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000843{
844 if (m_name_match_type != eNameMatchIgnore)
845 return false;
846
847 if (m_match_info.ProcessIDIsValid())
848 return false;
849
850 if (m_match_info.ParentProcessIDIsValid())
851 return false;
852
Greg Clayton8b82f082011-04-12 05:54:46 +0000853 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000854 return false;
855
Greg Clayton8b82f082011-04-12 05:54:46 +0000856 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000857 return false;
858
859 if (m_match_info.EffectiveUserIDIsValid ())
860 return false;
861
862 if (m_match_info.EffectiveGroupIDIsValid ())
863 return false;
864
865 if (m_match_info.GetArchitecture().IsValid())
866 return false;
867
868 if (m_match_all_users)
869 return false;
870
871 return true;
872
873}
874
875void
Greg Clayton8b82f082011-04-12 05:54:46 +0000876ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000877{
878 m_match_info.Clear();
879 m_name_match_type = eNameMatchIgnore;
880 m_match_all_users = false;
881}
Greg Clayton58be07b2011-01-07 06:08:19 +0000882
Greg Claytonc3776bf2012-02-09 06:16:32 +0000883ProcessSP
884Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000886 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887 ProcessCreateInstance create_callback = NULL;
888 if (plugin_name)
889 {
890 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
891 if (create_callback)
892 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000893 process_sp = create_callback(target, listener, crash_file_path);
894 if (process_sp)
895 {
896 if (!process_sp->CanDebug(target, true))
897 process_sp.reset();
898 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000899 }
900 }
901 else
902 {
Greg Claytonc982c762010-07-09 20:39:50 +0000903 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000904 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000905 process_sp = create_callback(target, listener, crash_file_path);
906 if (process_sp)
907 {
908 if (!process_sp->CanDebug(target, false))
909 process_sp.reset();
910 else
911 break;
912 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000913 }
914 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000915 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000916}
917
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000918ConstString &
919Process::GetStaticBroadcasterClass ()
920{
921 static ConstString class_name ("lldb.process");
922 return class_name;
923}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000924
925//----------------------------------------------------------------------
926// Process constructor
927//----------------------------------------------------------------------
928Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000929 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000930 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000931 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000932 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000933 m_public_state (eStateUnloaded),
934 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000935 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
936 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000937 m_private_state_listener ("lldb.process.internal_state_listener"),
938 m_private_state_control_wait(),
939 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000940 m_mod_id (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000941 m_thread_index_id (0),
942 m_exit_status (-1),
943 m_exit_string (),
944 m_thread_list (this),
945 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000946 m_image_tokens (),
947 m_listener (listener),
948 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000949 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000950 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000951 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000952 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000953 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000954 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000955 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000956 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000957 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
958 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000959 m_memory_cache (*this),
960 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000961 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000962 m_next_event_action_ap(),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000963 m_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000964 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000965 m_finalize_called(false),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000966 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000967{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000968 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000969
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000970 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000971 if (log)
972 log->Printf ("%p Process::Process()", this);
973
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000974 SetEventName (eBroadcastBitStateChanged, "state-changed");
975 SetEventName (eBroadcastBitInterrupt, "interrupt");
976 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
977 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000978 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000979
Greg Clayton35a4cc52012-10-29 20:52:08 +0000980 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
981 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
982 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
983
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000984 listener.StartListeningForEvents (this,
985 eBroadcastBitStateChanged |
986 eBroadcastBitInterrupt |
987 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000988 eBroadcastBitSTDERR |
989 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000990
991 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000992 eBroadcastBitStateChanged |
993 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000994
995 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
996 eBroadcastInternalStateControlStop |
997 eBroadcastInternalStateControlPause |
998 eBroadcastInternalStateControlResume);
999}
1000
1001//----------------------------------------------------------------------
1002// Destructor
1003//----------------------------------------------------------------------
1004Process::~Process()
1005{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001006 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001007 if (log)
1008 log->Printf ("%p Process::~Process()", this);
1009 StopPrivateStateThread();
1010}
1011
Greg Clayton67cc0632012-08-22 17:17:09 +00001012const ProcessPropertiesSP &
1013Process::GetGlobalProperties()
1014{
1015 static ProcessPropertiesSP g_settings_sp;
1016 if (!g_settings_sp)
1017 g_settings_sp.reset (new ProcessProperties (true));
1018 return g_settings_sp;
1019}
1020
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021void
1022Process::Finalize()
1023{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001024 switch (GetPrivateState())
1025 {
1026 case eStateConnected:
1027 case eStateAttaching:
1028 case eStateLaunching:
1029 case eStateStopped:
1030 case eStateRunning:
1031 case eStateStepping:
1032 case eStateCrashed:
1033 case eStateSuspended:
1034 if (GetShouldDetach())
1035 Detach();
1036 else
1037 Destroy();
1038 break;
1039
1040 case eStateInvalid:
1041 case eStateUnloaded:
1042 case eStateDetached:
1043 case eStateExited:
1044 break;
1045 }
1046
Greg Clayton1ed54f52011-10-01 00:45:15 +00001047 // Clear our broadcaster before we proceed with destroying
1048 Broadcaster::Clear();
1049
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050 // Do any cleanup needed prior to being destructed... Subclasses
1051 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001052
1053 // We need to destroy the loader before the derived Process class gets destroyed
1054 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001055 m_dynamic_checkers_ap.reset();
1056 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001057 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001058 m_dyld_ap.reset();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001059 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +00001060 std::vector<Notifications> empty_notifications;
1061 m_notifications.swap(empty_notifications);
1062 m_image_tokens.clear();
1063 m_memory_cache.Clear();
1064 m_allocated_memory_cache.Clear();
1065 m_language_runtimes.clear();
1066 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001067//#ifdef LLDB_CONFIGURATION_DEBUG
1068// StreamFile s(stdout, false);
1069// EventSP event_sp;
1070// while (m_private_state_listener.GetNextEvent(event_sp))
1071// {
1072// event_sp->Dump (&s);
1073// s.EOL();
1074// }
1075//#endif
1076 // We have to be very careful here as the m_private_state_listener might
1077 // contain events that have ProcessSP values in them which can keep this
1078 // process around forever. These events need to be cleared out.
1079 m_private_state_listener.Clear();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001080 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081}
1082
1083void
1084Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1085{
1086 m_notifications.push_back(callbacks);
1087 if (callbacks.initialize != NULL)
1088 callbacks.initialize (callbacks.baton, this);
1089}
1090
1091bool
1092Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1093{
1094 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1095 for (pos = m_notifications.begin(); pos != end; ++pos)
1096 {
1097 if (pos->baton == callbacks.baton &&
1098 pos->initialize == callbacks.initialize &&
1099 pos->process_state_changed == callbacks.process_state_changed)
1100 {
1101 m_notifications.erase(pos);
1102 return true;
1103 }
1104 }
1105 return false;
1106}
1107
1108void
1109Process::SynchronouslyNotifyStateChanged (StateType state)
1110{
1111 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1112 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1113 {
1114 if (notification_pos->process_state_changed)
1115 notification_pos->process_state_changed (notification_pos->baton, this, state);
1116 }
1117}
1118
1119// FIXME: We need to do some work on events before the general Listener sees them.
1120// For instance if we are continuing from a breakpoint, we need to ensure that we do
1121// the little "insert real insn, step & stop" trick. But we can't do that when the
1122// event is delivered by the broadcaster - since that is done on the thread that is
1123// waiting for new events, so if we needed more than one event for our handling, we would
1124// stall. So instead we do it when we fetch the event off of the queue.
1125//
1126
1127StateType
1128Process::GetNextEvent (EventSP &event_sp)
1129{
1130 StateType state = eStateInvalid;
1131
1132 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1133 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1134
1135 return state;
1136}
1137
1138
1139StateType
Greg Clayton85fb1b92012-09-11 02:33:37 +00001140Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141{
Jim Ingham4b536182011-08-09 02:12:22 +00001142 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1143 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1144 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001145 if (event_sp_ptr)
1146 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001147 StateType state = GetState();
1148 // If we are exited or detached, we won't ever get back to any
1149 // other valid state...
1150 if (state == eStateDetached || state == eStateExited)
1151 return state;
1152
1153 while (state != eStateInvalid)
1154 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001155 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001156 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001157 if (event_sp_ptr && event_sp)
1158 *event_sp_ptr = event_sp;
1159
Jim Ingham4b536182011-08-09 02:12:22 +00001160 switch (state)
1161 {
1162 case eStateCrashed:
1163 case eStateDetached:
1164 case eStateExited:
1165 case eStateUnloaded:
1166 return state;
1167 case eStateStopped:
1168 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1169 continue;
1170 else
1171 return state;
1172 default:
1173 continue;
1174 }
1175 }
1176 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001177}
1178
1179
1180StateType
1181Process::WaitForState
1182(
1183 const TimeValue *timeout,
1184 const StateType *match_states, const uint32_t num_match_states
1185)
1186{
1187 EventSP event_sp;
1188 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001189 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001190 while (state != eStateInvalid)
1191 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001192 // If we are exited or detached, we won't ever get back to any
1193 // other valid state...
1194 if (state == eStateDetached || state == eStateExited)
1195 return state;
1196
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197 state = WaitForStateChangedEvents (timeout, event_sp);
1198
1199 for (i=0; i<num_match_states; ++i)
1200 {
1201 if (match_states[i] == state)
1202 return state;
1203 }
1204 }
1205 return state;
1206}
1207
Jim Ingham30f9b212010-10-11 23:53:14 +00001208bool
1209Process::HijackProcessEvents (Listener *listener)
1210{
1211 if (listener != NULL)
1212 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001213 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001214 }
1215 else
1216 return false;
1217}
1218
1219void
1220Process::RestoreProcessEvents ()
1221{
1222 RestoreBroadcaster();
1223}
1224
Jim Ingham0f16e732011-02-08 05:20:59 +00001225bool
1226Process::HijackPrivateProcessEvents (Listener *listener)
1227{
1228 if (listener != NULL)
1229 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001230 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001231 }
1232 else
1233 return false;
1234}
1235
1236void
1237Process::RestorePrivateProcessEvents ()
1238{
1239 m_private_state_broadcaster.RestoreBroadcaster();
1240}
1241
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001242StateType
1243Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1244{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001245 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001246
1247 if (log)
1248 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1249
1250 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001251 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1252 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001253 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001254 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001255 {
1256 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1257 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1258 else if (log)
1259 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1260 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001261
1262 if (log)
1263 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1264 __FUNCTION__,
1265 timeout,
1266 StateAsCString(state));
1267 return state;
1268}
1269
1270Event *
1271Process::PeekAtStateChangedEvents ()
1272{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001273 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001274
1275 if (log)
1276 log->Printf ("Process::%s...", __FUNCTION__);
1277
1278 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001279 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1280 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001281 if (log)
1282 {
1283 if (event_ptr)
1284 {
1285 log->Printf ("Process::%s (event_ptr) => %s",
1286 __FUNCTION__,
1287 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1288 }
1289 else
1290 {
1291 log->Printf ("Process::%s no events found",
1292 __FUNCTION__);
1293 }
1294 }
1295 return event_ptr;
1296}
1297
1298StateType
1299Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1300{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001301 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001302
1303 if (log)
1304 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1305
1306 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001307 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1308 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001309 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001310 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001311 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1312 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001313
1314 // This is a bit of a hack, but when we wait here we could very well return
1315 // to the command-line, and that could disable the log, which would render the
1316 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001317 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001318 {
1319 if (state == eStateInvalid)
1320 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1321 else
1322 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1323 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001324 return state;
1325}
1326
1327bool
1328Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1329{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001330 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001331
1332 if (log)
1333 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1334
1335 if (control_only)
1336 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1337 else
1338 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1339}
1340
1341bool
1342Process::IsRunning () const
1343{
1344 return StateIsRunningState (m_public_state.GetValue());
1345}
1346
1347int
1348Process::GetExitStatus ()
1349{
1350 if (m_public_state.GetValue() == eStateExited)
1351 return m_exit_status;
1352 return -1;
1353}
1354
Greg Clayton85851dd2010-12-04 00:10:17 +00001355
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001356const char *
1357Process::GetExitDescription ()
1358{
1359 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1360 return m_exit_string.c_str();
1361 return NULL;
1362}
1363
Greg Clayton6779606a2011-01-22 23:43:18 +00001364bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001365Process::SetExitStatus (int status, const char *cstr)
1366{
Greg Clayton414f5d32011-01-25 02:58:48 +00001367 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1368 if (log)
1369 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1370 status, status,
1371 cstr ? "\"" : "",
1372 cstr ? cstr : "NULL",
1373 cstr ? "\"" : "");
1374
Greg Clayton6779606a2011-01-22 23:43:18 +00001375 // We were already in the exited state
1376 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001377 {
Greg Clayton385d6032011-01-26 23:47:29 +00001378 if (log)
1379 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001380 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001381 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001382
1383 m_exit_status = status;
1384 if (cstr)
1385 m_exit_string = cstr;
1386 else
1387 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001388
Greg Clayton6779606a2011-01-22 23:43:18 +00001389 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001390
Greg Clayton6779606a2011-01-22 23:43:18 +00001391 SetPrivateState (eStateExited);
1392 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001393}
1394
1395// This static callback can be used to watch for local child processes on
1396// the current host. The the child process exits, the process will be
1397// found in the global target list (we want to be completely sure that the
1398// lldb_private::Process doesn't go away before we can deliver the signal.
1399bool
Greg Claytone4e45922011-11-16 05:37:56 +00001400Process::SetProcessExitStatus (void *callback_baton,
1401 lldb::pid_t pid,
1402 bool exited,
1403 int signo, // Zero for no signal
1404 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405)
1406{
Greg Claytone4e45922011-11-16 05:37:56 +00001407 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1408 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00001409 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001410 callback_baton,
1411 pid,
1412 exited,
1413 signo,
1414 exit_status);
1415
1416 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001417 {
Greg Clayton66111032010-06-23 01:19:29 +00001418 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001419 if (target_sp)
1420 {
1421 ProcessSP process_sp (target_sp->GetProcessSP());
1422 if (process_sp)
1423 {
1424 const char *signal_cstr = NULL;
1425 if (signo)
1426 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1427
1428 process_sp->SetExitStatus (exit_status, signal_cstr);
1429 }
1430 }
1431 return true;
1432 }
1433 return false;
1434}
1435
1436
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001437void
1438Process::UpdateThreadListIfNeeded ()
1439{
1440 const uint32_t stop_id = GetStopID();
1441 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1442 {
Greg Clayton2637f822011-11-17 01:23:07 +00001443 const StateType state = GetPrivateState();
1444 if (StateIsStoppedState (state, true))
1445 {
1446 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001447 // m_thread_list does have its own mutex, but we need to
1448 // hold onto the mutex between the call to UpdateThreadList(...)
1449 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton2637f822011-11-17 01:23:07 +00001450 ThreadList new_thread_list(this);
1451 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001452 // thread list, but only update if "true" is returned
1453 if (UpdateThreadList (m_thread_list, new_thread_list))
1454 {
1455 OperatingSystem *os = GetOperatingSystem ();
1456 if (os)
1457 os->UpdateThreadList (m_thread_list, new_thread_list);
1458 m_thread_list.Update (new_thread_list);
1459 m_thread_list.SetStopID (stop_id);
1460 }
Greg Clayton2637f822011-11-17 01:23:07 +00001461 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001462 }
1463}
1464
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001465uint32_t
1466Process::GetNextThreadIndexID ()
1467{
1468 return ++m_thread_index_id;
1469}
1470
1471StateType
1472Process::GetState()
1473{
1474 // If any other threads access this we will need a mutex for it
1475 return m_public_state.GetValue ();
1476}
1477
1478void
1479Process::SetPublicState (StateType new_state)
1480{
Greg Clayton414f5d32011-01-25 02:58:48 +00001481 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001482 if (log)
1483 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001484 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001485 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001486
1487 // On the transition from Run to Stopped, we unlock the writer end of the
1488 // run lock. The lock gets locked in Resume, which is the public API
1489 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001490 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1491 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001492 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001493 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001494 if (log)
1495 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1496 m_run_lock.WriteUnlock();
1497 }
1498 else
1499 {
1500 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1501 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1502 if (old_state_is_stopped != new_state_is_stopped)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001503 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001504 if (new_state_is_stopped)
1505 {
1506 if (log)
1507 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1508 m_run_lock.WriteUnlock();
1509 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001510 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001511 }
1512 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001513}
1514
Jim Ingham3b8285d2012-04-19 01:40:33 +00001515Error
1516Process::Resume ()
1517{
1518 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1519 if (log)
1520 log->Printf("Process::Resume -- locking run lock");
1521 if (!m_run_lock.WriteTryLock())
1522 {
1523 Error error("Resume request failed - process still running.");
1524 if (log)
1525 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1526 return error;
1527 }
1528 return PrivateResume();
1529}
1530
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001531StateType
1532Process::GetPrivateState ()
1533{
1534 return m_private_state.GetValue();
1535}
1536
1537void
1538Process::SetPrivateState (StateType new_state)
1539{
Greg Clayton414f5d32011-01-25 02:58:48 +00001540 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001541 bool state_changed = false;
1542
1543 if (log)
1544 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1545
1546 Mutex::Locker locker(m_private_state.GetMutex());
1547
1548 const StateType old_state = m_private_state.GetValueNoLock ();
1549 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001550 // This code is left commented out in case we ever need to control
1551 // the private process state with another run lock. Right now it doesn't
1552 // seem like we need to do this, but if we ever do, we can uncomment and
1553 // use this code.
1554// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1555// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1556// if (old_state_is_stopped != new_state_is_stopped)
1557// {
1558// if (new_state_is_stopped)
1559// m_private_run_lock.WriteUnlock();
1560// else
1561// m_private_run_lock.WriteLock();
1562// }
1563
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001564 if (state_changed)
1565 {
1566 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001567 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001568 {
Jim Ingham4b536182011-08-09 02:12:22 +00001569 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001570 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001571 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001572 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001573 }
1574 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001575 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1576 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1577 else
1578 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001579 }
1580 else
1581 {
1582 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001583 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001584 }
1585}
1586
Jim Ingham0faa43f2011-11-08 03:00:11 +00001587void
1588Process::SetRunningUserExpression (bool on)
1589{
1590 m_mod_id.SetRunningUserExpression (on);
1591}
1592
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001593addr_t
1594Process::GetImageInfoAddress()
1595{
1596 return LLDB_INVALID_ADDRESS;
1597}
1598
Greg Clayton8f343b02010-11-04 01:54:29 +00001599//----------------------------------------------------------------------
1600// LoadImage
1601//
1602// This function provides a default implementation that works for most
1603// unix variants. Any Process subclasses that need to do shared library
1604// loading differently should override LoadImage and UnloadImage and
1605// do what is needed.
1606//----------------------------------------------------------------------
1607uint32_t
1608Process::LoadImage (const FileSpec &image_spec, Error &error)
1609{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001610 char path[PATH_MAX];
1611 image_spec.GetPath(path, sizeof(path));
1612
Greg Clayton8f343b02010-11-04 01:54:29 +00001613 DynamicLoader *loader = GetDynamicLoader();
1614 if (loader)
1615 {
1616 error = loader->CanLoadImage();
1617 if (error.Fail())
1618 return LLDB_INVALID_IMAGE_TOKEN;
1619 }
1620
1621 if (error.Success())
1622 {
1623 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001624
1625 if (thread_sp)
1626 {
1627 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1628
1629 if (frame_sp)
1630 {
1631 ExecutionContext exe_ctx;
1632 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001633 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001634 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001635 expr.Printf("dlopen (\"%s\", 2)", path);
1636 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001637 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001638 ClangUserExpression::Evaluate (exe_ctx,
1639 eExecutionPolicyAlways,
1640 lldb::eLanguageTypeUnknown,
1641 ClangUserExpression::eResultTypeAny,
1642 unwind_on_error,
1643 expr.GetData(),
1644 prefix,
1645 result_valobj_sp,
1646 true,
1647 ClangUserExpression::kDefaultTimeout);
Johnny Chene92aa432011-09-09 00:01:43 +00001648 error = result_valobj_sp->GetError();
1649 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001650 {
1651 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001652 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001653 {
1654 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1655 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1656 {
1657 uint32_t image_token = m_image_tokens.size();
1658 m_image_tokens.push_back (image_ptr);
1659 return image_token;
1660 }
1661 }
1662 }
1663 }
1664 }
1665 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001666 if (!error.AsCString())
1667 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001668 return LLDB_INVALID_IMAGE_TOKEN;
1669}
1670
1671//----------------------------------------------------------------------
1672// UnloadImage
1673//
1674// This function provides a default implementation that works for most
1675// unix variants. Any Process subclasses that need to do shared library
1676// loading differently should override LoadImage and UnloadImage and
1677// do what is needed.
1678//----------------------------------------------------------------------
1679Error
1680Process::UnloadImage (uint32_t image_token)
1681{
1682 Error error;
1683 if (image_token < m_image_tokens.size())
1684 {
1685 const addr_t image_addr = m_image_tokens[image_token];
1686 if (image_addr == LLDB_INVALID_ADDRESS)
1687 {
1688 error.SetErrorString("image already unloaded");
1689 }
1690 else
1691 {
1692 DynamicLoader *loader = GetDynamicLoader();
1693 if (loader)
1694 error = loader->CanLoadImage();
1695
1696 if (error.Success())
1697 {
1698 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001699
1700 if (thread_sp)
1701 {
1702 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1703
1704 if (frame_sp)
1705 {
1706 ExecutionContext exe_ctx;
1707 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001708 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001709 StreamString expr;
1710 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1711 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001712 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001713 ClangUserExpression::Evaluate (exe_ctx,
1714 eExecutionPolicyAlways,
1715 lldb::eLanguageTypeUnknown,
1716 ClangUserExpression::eResultTypeAny,
1717 unwind_on_error,
1718 expr.GetData(),
1719 prefix,
1720 result_valobj_sp,
1721 true,
1722 ClangUserExpression::kDefaultTimeout);
Greg Clayton8f343b02010-11-04 01:54:29 +00001723 if (result_valobj_sp->GetError().Success())
1724 {
1725 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001726 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001727 {
1728 if (scalar.UInt(1))
1729 {
1730 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1731 }
1732 else
1733 {
1734 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1735 }
1736 }
1737 }
1738 else
1739 {
1740 error = result_valobj_sp->GetError();
1741 }
1742 }
1743 }
1744 }
1745 }
1746 }
1747 else
1748 {
1749 error.SetErrorString("invalid image token");
1750 }
1751 return error;
1752}
1753
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001754const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001755Process::GetABI()
1756{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001757 if (!m_abi_sp)
1758 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1759 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001760}
1761
Jim Ingham22777012010-09-23 02:01:19 +00001762LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001763Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001764{
1765 LanguageRuntimeCollection::iterator pos;
1766 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001767 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001768 {
Jim Inghamab175242012-03-10 00:22:19 +00001769 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001770
Jim Inghamab175242012-03-10 00:22:19 +00001771 m_language_runtimes[language] = runtime_sp;
1772 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001773 }
1774 else
1775 return (*pos).second.get();
1776}
1777
1778CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001779Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001780{
Jim Inghamab175242012-03-10 00:22:19 +00001781 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001782 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1783 return static_cast<CPPLanguageRuntime *> (runtime);
1784 return NULL;
1785}
1786
1787ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001788Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001789{
Jim Inghamab175242012-03-10 00:22:19 +00001790 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001791 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1792 return static_cast<ObjCLanguageRuntime *> (runtime);
1793 return NULL;
1794}
1795
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001796bool
1797Process::IsPossibleDynamicValue (ValueObject& in_value)
1798{
1799 if (in_value.IsDynamic())
1800 return false;
1801 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1802
1803 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1804 {
1805 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1806 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1807 }
1808
1809 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1810 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1811 return true;
1812
1813 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1814 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1815}
1816
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001817BreakpointSiteList &
1818Process::GetBreakpointSiteList()
1819{
1820 return m_breakpoint_site_list;
1821}
1822
1823const BreakpointSiteList &
1824Process::GetBreakpointSiteList() const
1825{
1826 return m_breakpoint_site_list;
1827}
1828
1829
1830void
1831Process::DisableAllBreakpointSites ()
1832{
1833 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham43c555d2012-07-04 00:35:43 +00001834 size_t num_sites = m_breakpoint_site_list.GetSize();
1835 for (size_t i = 0; i < num_sites; i++)
1836 {
1837 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1838 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001839}
1840
1841Error
1842Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1843{
1844 Error error (DisableBreakpointSiteByID (break_id));
1845
1846 if (error.Success())
1847 m_breakpoint_site_list.Remove(break_id);
1848
1849 return error;
1850}
1851
1852Error
1853Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1854{
1855 Error error;
1856 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1857 if (bp_site_sp)
1858 {
1859 if (bp_site_sp->IsEnabled())
1860 error = DisableBreakpoint (bp_site_sp.get());
1861 }
1862 else
1863 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001864 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865 }
1866
1867 return error;
1868}
1869
1870Error
1871Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1872{
1873 Error error;
1874 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1875 if (bp_site_sp)
1876 {
1877 if (!bp_site_sp->IsEnabled())
1878 error = EnableBreakpoint (bp_site_sp.get());
1879 }
1880 else
1881 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001882 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001883 }
1884 return error;
1885}
1886
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001887lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001888Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001889{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001890 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001891 if (load_addr != LLDB_INVALID_ADDRESS)
1892 {
1893 BreakpointSiteSP bp_site_sp;
1894
1895 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1896 // create a new breakpoint site and add it.
1897
1898 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1899
1900 if (bp_site_sp)
1901 {
1902 bp_site_sp->AddOwner (owner);
1903 owner->SetBreakpointSite (bp_site_sp);
1904 return bp_site_sp->GetID();
1905 }
1906 else
1907 {
1908 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1909 if (bp_site_sp)
1910 {
1911 if (EnableBreakpoint (bp_site_sp.get()).Success())
1912 {
1913 owner->SetBreakpointSite (bp_site_sp);
1914 return m_breakpoint_site_list.Add (bp_site_sp);
1915 }
1916 }
1917 }
1918 }
1919 // We failed to enable the breakpoint
1920 return LLDB_INVALID_BREAK_ID;
1921
1922}
1923
1924void
1925Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1926{
1927 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1928 if (num_owners == 0)
1929 {
1930 DisableBreakpoint(bp_site_sp.get());
1931 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1932 }
1933}
1934
1935
1936size_t
1937Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1938{
1939 size_t bytes_removed = 0;
1940 addr_t intersect_addr;
1941 size_t intersect_size;
1942 size_t opcode_offset;
1943 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001944 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001945 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001946
Jim Ingham20c77192011-06-29 19:42:28 +00001947 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001948 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001949 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001950 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001951 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001952 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001953 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001954 {
1955 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1956 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001957 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001958 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001959 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001960 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001961 }
1962 }
1963 }
1964 return bytes_removed;
1965}
1966
1967
Greg Claytonded470d2011-03-19 01:12:21 +00001968
1969size_t
1970Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1971{
1972 PlatformSP platform_sp (m_target.GetPlatform());
1973 if (platform_sp)
1974 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1975 return 0;
1976}
1977
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001978Error
1979Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1980{
1981 Error error;
1982 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001983 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001984 const addr_t bp_addr = bp_site->GetLoadAddress();
1985 if (log)
1986 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1987 if (bp_site->IsEnabled())
1988 {
1989 if (log)
1990 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1991 return error;
1992 }
1993
1994 if (bp_addr == LLDB_INVALID_ADDRESS)
1995 {
1996 error.SetErrorString("BreakpointSite contains an invalid load address.");
1997 return error;
1998 }
1999 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2000 // trap for the breakpoint site
2001 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2002
2003 if (bp_opcode_size == 0)
2004 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002005 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002006 }
2007 else
2008 {
2009 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2010
2011 if (bp_opcode_bytes == NULL)
2012 {
2013 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2014 return error;
2015 }
2016
2017 // Save the original opcode by reading it
2018 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2019 {
2020 // Write a software breakpoint in place of the original opcode
2021 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2022 {
2023 uint8_t verify_bp_opcode_bytes[64];
2024 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2025 {
2026 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2027 {
2028 bp_site->SetEnabled(true);
2029 bp_site->SetType (BreakpointSite::eSoftware);
2030 if (log)
2031 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
2032 bp_site->GetID(),
2033 (uint64_t)bp_addr);
2034 }
2035 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002036 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002037 }
2038 else
2039 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2040 }
2041 else
2042 error.SetErrorString("Unable to write breakpoint trap to memory.");
2043 }
2044 else
2045 error.SetErrorString("Unable to read memory at breakpoint address.");
2046 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002047 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002048 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2049 bp_site->GetID(),
2050 (uint64_t)bp_addr,
2051 error.AsCString());
2052 return error;
2053}
2054
2055Error
2056Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2057{
2058 Error error;
2059 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002060 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002061 addr_t bp_addr = bp_site->GetLoadAddress();
2062 lldb::user_id_t breakID = bp_site->GetID();
2063 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002064 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002065
2066 if (bp_site->IsHardware())
2067 {
2068 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2069 }
2070 else if (bp_site->IsEnabled())
2071 {
2072 const size_t break_op_size = bp_site->GetByteSize();
2073 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2074 if (break_op_size > 0)
2075 {
2076 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002077 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002078 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002079 bool break_op_found = false;
2080
2081 // Read the breakpoint opcode
2082 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2083 {
2084 bool verify = false;
2085 // Make sure we have the a breakpoint opcode exists at this address
2086 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2087 {
2088 break_op_found = true;
2089 // We found a valid breakpoint opcode at this address, now restore
2090 // the saved opcode.
2091 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2092 {
2093 verify = true;
2094 }
2095 else
2096 error.SetErrorString("Memory write failed when restoring original opcode.");
2097 }
2098 else
2099 {
2100 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2101 // Set verify to true and so we can check if the original opcode has already been restored
2102 verify = true;
2103 }
2104
2105 if (verify)
2106 {
Greg Claytonc982c762010-07-09 20:39:50 +00002107 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002108 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002109 // Verify that our original opcode made it back to the inferior
2110 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2111 {
2112 // compare the memory we just read with the original opcode
2113 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2114 {
2115 // SUCCESS
2116 bp_site->SetEnabled(false);
2117 if (log)
2118 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2119 return error;
2120 }
2121 else
2122 {
2123 if (break_op_found)
2124 error.SetErrorString("Failed to restore original opcode.");
2125 }
2126 }
2127 else
2128 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2129 }
2130 }
2131 else
2132 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2133 }
2134 }
2135 else
2136 {
2137 if (log)
2138 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2139 return error;
2140 }
2141
2142 if (log)
2143 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2144 bp_site->GetID(),
2145 (uint64_t)bp_addr,
2146 error.AsCString());
2147 return error;
2148
2149}
2150
Greg Clayton58be07b2011-01-07 06:08:19 +00002151// Uncomment to verify memory caching works after making changes to caching code
2152//#define VERIFY_MEMORY_READS
2153
Sean Callanan64c0cf22012-06-07 22:26:42 +00002154size_t
2155Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2156{
2157 if (!GetDisableMemoryCache())
2158 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002159#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002160 // Memory caching is enabled, with debug verification
2161
2162 if (buf && size)
2163 {
2164 // Uncomment the line below to make sure memory caching is working.
2165 // I ran this through the test suite and got no assertions, so I am
2166 // pretty confident this is working well. If any changes are made to
2167 // memory caching, uncomment the line below and test your changes!
2168
2169 // Verify all memory reads by using the cache first, then redundantly
2170 // reading the same memory from the inferior and comparing to make sure
2171 // everything is exactly the same.
2172 std::string verify_buf (size, '\0');
2173 assert (verify_buf.size() == size);
2174 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2175 Error verify_error;
2176 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2177 assert (cache_bytes_read == verify_bytes_read);
2178 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2179 assert (verify_error.Success() == error.Success());
2180 return cache_bytes_read;
2181 }
2182 return 0;
2183#else // !defined(VERIFY_MEMORY_READS)
2184 // Memory caching is enabled, without debug verification
2185
2186 return m_memory_cache.Read (addr, buf, size, error);
2187#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002188 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002189 else
2190 {
2191 // Memory caching is disabled
2192
2193 return ReadMemoryFromInferior (addr, buf, size, error);
2194 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002195}
Greg Clayton58be07b2011-01-07 06:08:19 +00002196
Greg Clayton4c82d422012-05-18 23:20:01 +00002197size_t
2198Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2199{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002200 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002201 out_str.clear();
2202 addr_t curr_addr = addr;
2203 while (1)
2204 {
2205 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2206 if (length == 0)
2207 break;
2208 out_str.append(buf, length);
2209 // If we got "length - 1" bytes, we didn't get the whole C string, we
2210 // need to read some more characters
2211 if (length == sizeof(buf) - 1)
2212 curr_addr += length;
2213 else
2214 break;
2215 }
2216 return out_str.size();
2217}
2218
Greg Clayton58be07b2011-01-07 06:08:19 +00002219
2220size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002221Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002222{
2223 size_t total_cstr_len = 0;
2224 if (dst && dst_max_len)
2225 {
Greg Claytone91b7952011-12-15 03:14:23 +00002226 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002227 // NULL out everything just to be safe
2228 memset (dst, 0, dst_max_len);
2229 Error error;
2230 addr_t curr_addr = addr;
2231 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2232 size_t bytes_left = dst_max_len - 1;
2233 char *curr_dst = dst;
2234
2235 while (bytes_left > 0)
2236 {
2237 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2238 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2239 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2240
2241 if (bytes_read == 0)
2242 {
Greg Claytone91b7952011-12-15 03:14:23 +00002243 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002244 dst[total_cstr_len] = '\0';
2245 break;
2246 }
2247 const size_t len = strlen(curr_dst);
2248
2249 total_cstr_len += len;
2250
2251 if (len < bytes_to_read)
2252 break;
2253
2254 curr_dst += bytes_read;
2255 curr_addr += bytes_read;
2256 bytes_left -= bytes_read;
2257 }
2258 }
Greg Claytone91b7952011-12-15 03:14:23 +00002259 else
2260 {
2261 if (dst == NULL)
2262 result_error.SetErrorString("invalid arguments");
2263 else
2264 result_error.Clear();
2265 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002266 return total_cstr_len;
2267}
2268
2269size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002270Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2271{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002272 if (buf == NULL || size == 0)
2273 return 0;
2274
2275 size_t bytes_read = 0;
2276 uint8_t *bytes = (uint8_t *)buf;
2277
2278 while (bytes_read < size)
2279 {
2280 const size_t curr_size = size - bytes_read;
2281 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2282 bytes + bytes_read,
2283 curr_size,
2284 error);
2285 bytes_read += curr_bytes_read;
2286 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2287 break;
2288 }
2289
2290 // Replace any software breakpoint opcodes that fall into this range back
2291 // into "buf" before we return
2292 if (bytes_read > 0)
2293 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2294 return bytes_read;
2295}
2296
Greg Clayton58a4c462010-12-16 20:01:20 +00002297uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002298Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002299{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002300 Scalar scalar;
2301 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2302 return scalar.ULongLong(fail_value);
2303 return fail_value;
2304}
2305
2306addr_t
2307Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2308{
2309 Scalar scalar;
2310 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2311 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2312 return LLDB_INVALID_ADDRESS;
2313}
2314
2315
2316bool
2317Process::WritePointerToMemory (lldb::addr_t vm_addr,
2318 lldb::addr_t ptr_value,
2319 Error &error)
2320{
2321 Scalar scalar;
2322 const uint32_t addr_byte_size = GetAddressByteSize();
2323 if (addr_byte_size <= 4)
2324 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002325 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002326 scalar = ptr_value;
2327 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002328}
2329
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330size_t
2331Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2332{
2333 size_t bytes_written = 0;
2334 const uint8_t *bytes = (const uint8_t *)buf;
2335
2336 while (bytes_written < size)
2337 {
2338 const size_t curr_size = size - bytes_written;
2339 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2340 bytes + bytes_written,
2341 curr_size,
2342 error);
2343 bytes_written += curr_bytes_written;
2344 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2345 break;
2346 }
2347 return bytes_written;
2348}
2349
2350size_t
2351Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2352{
Greg Clayton58be07b2011-01-07 06:08:19 +00002353#if defined (ENABLE_MEMORY_CACHING)
2354 m_memory_cache.Flush (addr, size);
2355#endif
2356
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002357 if (buf == NULL || size == 0)
2358 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002359
Jim Ingham4b536182011-08-09 02:12:22 +00002360 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002361
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002362 // We need to write any data that would go where any current software traps
2363 // (enabled software breakpoints) any software traps (breakpoints) that we
2364 // may have placed in our tasks memory.
2365
2366 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2367 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2368
2369 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002370 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002371
2372 BreakpointSiteList::collection::const_iterator pos;
2373 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002374 addr_t intersect_addr = 0;
2375 size_t intersect_size = 0;
2376 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002377 const uint8_t *ubuf = (const uint8_t *)buf;
2378
2379 for (pos = iter; pos != end; ++pos)
2380 {
2381 BreakpointSiteSP bp;
2382 bp = pos->second;
2383
2384 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2385 assert(addr <= intersect_addr && intersect_addr < addr + size);
2386 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2387 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2388
2389 // Check for bytes before this breakpoint
2390 const addr_t curr_addr = addr + bytes_written;
2391 if (intersect_addr > curr_addr)
2392 {
2393 // There are some bytes before this breakpoint that we need to
2394 // just write to memory
2395 size_t curr_size = intersect_addr - curr_addr;
2396 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2397 ubuf + bytes_written,
2398 curr_size,
2399 error);
2400 bytes_written += curr_bytes_written;
2401 if (curr_bytes_written != curr_size)
2402 {
2403 // We weren't able to write all of the requested bytes, we
2404 // are done looping and will return the number of bytes that
2405 // we have written so far.
2406 break;
2407 }
2408 }
2409
2410 // Now write any bytes that would cover up any software breakpoints
2411 // directly into the breakpoint opcode buffer
2412 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2413 bytes_written += intersect_size;
2414 }
2415
2416 // Write any remaining bytes after the last breakpoint if we have any left
2417 if (bytes_written < size)
2418 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2419 ubuf + bytes_written,
2420 size - bytes_written,
2421 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002422
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002423 return bytes_written;
2424}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002425
2426size_t
2427Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2428{
2429 if (byte_size == UINT32_MAX)
2430 byte_size = scalar.GetByteSize();
2431 if (byte_size > 0)
2432 {
2433 uint8_t buf[32];
2434 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2435 if (mem_size > 0)
2436 return WriteMemory(addr, buf, mem_size, error);
2437 else
2438 error.SetErrorString ("failed to get scalar as memory data");
2439 }
2440 else
2441 {
2442 error.SetErrorString ("invalid scalar value");
2443 }
2444 return 0;
2445}
2446
2447size_t
2448Process::ReadScalarIntegerFromMemory (addr_t addr,
2449 uint32_t byte_size,
2450 bool is_signed,
2451 Scalar &scalar,
2452 Error &error)
2453{
2454 uint64_t uval;
2455
2456 if (byte_size <= sizeof(uval))
2457 {
2458 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2459 if (bytes_read == byte_size)
2460 {
2461 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2462 uint32_t offset = 0;
2463 if (byte_size <= 4)
2464 scalar = data.GetMaxU32 (&offset, byte_size);
2465 else
2466 scalar = data.GetMaxU64 (&offset, byte_size);
2467
2468 if (is_signed)
2469 scalar.SignExtend(byte_size * 8);
2470 return bytes_read;
2471 }
2472 }
2473 else
2474 {
2475 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2476 }
2477 return 0;
2478}
2479
Greg Claytond495c532011-05-17 03:37:42 +00002480#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002481addr_t
2482Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2483{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002484 if (GetPrivateState() != eStateStopped)
2485 return LLDB_INVALID_ADDRESS;
2486
Greg Claytond495c532011-05-17 03:37:42 +00002487#if defined (USE_ALLOCATE_MEMORY_CACHE)
2488 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2489#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002490 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2491 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2492 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002493 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 +00002494 size,
Greg Claytond495c532011-05-17 03:37:42 +00002495 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002496 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002497 m_mod_id.GetStopID(),
2498 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002499 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002500#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002501}
2502
Sean Callanan90539452011-09-20 23:01:51 +00002503bool
2504Process::CanJIT ()
2505{
Sean Callanana7b443a2012-02-14 22:50:38 +00002506 if (m_can_jit == eCanJITDontKnow)
2507 {
2508 Error err;
2509
2510 uint64_t allocated_memory = AllocateMemory(8,
2511 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2512 err);
2513
2514 if (err.Success())
2515 m_can_jit = eCanJITYes;
2516 else
2517 m_can_jit = eCanJITNo;
2518
2519 DeallocateMemory (allocated_memory);
2520 }
2521
Sean Callanan90539452011-09-20 23:01:51 +00002522 return m_can_jit == eCanJITYes;
2523}
2524
2525void
2526Process::SetCanJIT (bool can_jit)
2527{
2528 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2529}
2530
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002531Error
2532Process::DeallocateMemory (addr_t ptr)
2533{
Greg Claytond495c532011-05-17 03:37:42 +00002534 Error error;
2535#if defined (USE_ALLOCATE_MEMORY_CACHE)
2536 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2537 {
2538 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2539 }
2540#else
2541 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002542
2543 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2544 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002545 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 +00002546 ptr,
2547 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002548 m_mod_id.GetStopID(),
2549 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002550#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002551 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002552}
2553
Han Ming Ongc811d382012-11-17 00:33:14 +00002554
Greg Claytonc9660542012-02-05 02:38:54 +00002555ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002556Process::ReadModuleFromMemory (const FileSpec& file_spec,
2557 lldb::addr_t header_addr,
2558 bool add_image_to_target,
2559 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002560{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002561 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002562 if (module_sp)
2563 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002564 Error error;
2565 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2566 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002567 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002568 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002569 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002570 m_target.GetImages().Append(module_sp);
2571 if (load_sections_in_target)
2572 {
2573 bool changed = false;
2574 module_sp->SetLoadAddress (m_target, 0, changed);
2575 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002576 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002577 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002578 }
Greg Claytonc9660542012-02-05 02:38:54 +00002579 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002580 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002581}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002582
2583Error
Johnny Chen01a67862011-10-14 00:42:25 +00002584Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002585{
2586 Error error;
2587 error.SetErrorString("watchpoints are not supported");
2588 return error;
2589}
2590
2591Error
Johnny Chen01a67862011-10-14 00:42:25 +00002592Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002593{
2594 Error error;
2595 error.SetErrorString("watchpoints are not supported");
2596 return error;
2597}
2598
2599StateType
2600Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2601{
2602 StateType state;
2603 // Now wait for the process to launch and return control to us, and then
2604 // call DidLaunch:
2605 while (1)
2606 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002607 event_sp.reset();
2608 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2609
Greg Clayton2637f822011-11-17 01:23:07 +00002610 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002611 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002612
2613 // If state is invalid, then we timed out
2614 if (state == eStateInvalid)
2615 break;
2616
2617 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002618 HandlePrivateEvent (event_sp);
2619 }
2620 return state;
2621}
2622
2623Error
Greg Clayton982c9762011-11-03 21:22:33 +00002624Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002625{
2626 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002627 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002628 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002629 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002630 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002631
Greg Claytonaa149cb2011-08-11 02:48:45 +00002632 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002633 if (exe_module)
2634 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002635 char local_exec_file_path[PATH_MAX];
2636 char platform_exec_file_path[PATH_MAX];
2637 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2638 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002639 if (exe_module->GetFileSpec().Exists())
2640 {
Greg Clayton71337622011-02-24 22:24:29 +00002641 if (PrivateStateThreadIsValid ())
2642 PausePrivateStateThread ();
2643
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002644 error = WillLaunch (exe_module);
2645 if (error.Success())
2646 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002647 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002648 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002649
Greg Clayton69fd4be2012-09-04 20:29:05 +00002650 if (m_run_lock.WriteTryLock())
2651 {
2652 // Now launch using these arguments.
2653 error = DoLaunch (exe_module, launch_info);
2654 }
2655 else
2656 {
2657 // This shouldn't happen
2658 error.SetErrorString("failed to acquire process run lock");
2659 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002660
2661 if (error.Fail())
2662 {
2663 if (GetID() != LLDB_INVALID_PROCESS_ID)
2664 {
2665 SetID (LLDB_INVALID_PROCESS_ID);
2666 const char *error_string = error.AsCString();
2667 if (error_string == NULL)
2668 error_string = "launch failed";
2669 SetExitStatus (-1, error_string);
2670 }
2671 }
2672 else
2673 {
2674 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002675 TimeValue timeout_time;
2676 timeout_time = TimeValue::Now();
2677 timeout_time.OffsetWithSeconds(10);
2678 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002679
Greg Clayton1a38ea72011-06-22 01:42:17 +00002680 if (state == eStateInvalid || event_sp.get() == NULL)
2681 {
2682 // We were able to launch the process, but we failed to
2683 // catch the initial stop.
2684 SetExitStatus (0, "failed to catch stop after launch");
2685 Destroy();
2686 }
2687 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002688 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002689
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002690 DidLaunch ();
2691
Greg Claytonc859e2d2012-02-13 23:10:39 +00002692 DynamicLoader *dyld = GetDynamicLoader ();
2693 if (dyld)
2694 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002695
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002696 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002697 // This delays passing the stopped event to listeners till DidLaunch gets
2698 // a chance to complete...
2699 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002700
2701 if (PrivateStateThreadIsValid ())
2702 ResumePrivateStateThread ();
2703 else
2704 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002705 }
2706 else if (state == eStateExited)
2707 {
2708 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2709 // not likely to work, and return an invalid pid.
2710 HandlePrivateEvent (event_sp);
2711 }
2712 }
2713 }
2714 }
2715 else
2716 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002717 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002718 }
2719 }
2720 return error;
2721}
2722
Greg Claytonc3776bf2012-02-09 06:16:32 +00002723
2724Error
2725Process::LoadCore ()
2726{
2727 Error error = DoLoadCore();
2728 if (error.Success())
2729 {
2730 if (PrivateStateThreadIsValid ())
2731 ResumePrivateStateThread ();
2732 else
2733 StartPrivateStateThread ();
2734
Greg Claytonc859e2d2012-02-13 23:10:39 +00002735 DynamicLoader *dyld = GetDynamicLoader ();
2736 if (dyld)
2737 dyld->DidAttach();
2738
2739 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002740 // We successfully loaded a core file, now pretend we stopped so we can
2741 // show all of the threads in the core file and explore the crashed
2742 // state.
2743 SetPrivateState (eStateStopped);
2744
2745 }
2746 return error;
2747}
2748
Greg Claytonc859e2d2012-02-13 23:10:39 +00002749DynamicLoader *
2750Process::GetDynamicLoader ()
2751{
2752 if (m_dyld_ap.get() == NULL)
2753 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2754 return m_dyld_ap.get();
2755}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002756
2757
Jim Inghambb3a2832011-01-29 01:49:25 +00002758Process::NextEventAction::EventActionResult
2759Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002760{
Jim Inghambb3a2832011-01-29 01:49:25 +00002761 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2762 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002763 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002764 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002765 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002766 return eEventActionRetry;
2767
2768 case eStateStopped:
2769 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002770 {
2771 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002772 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002773 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2774 if (m_exec_count > 0)
2775 {
2776 --m_exec_count;
Jim Ingham3b8285d2012-04-19 01:40:33 +00002777 m_process->PrivateResume ();
Jim Ingham04e0a222012-05-23 15:46:31 +00002778 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Claytonc9ed4782011-11-12 02:10:56 +00002779 return eEventActionRetry;
2780 }
2781 else
2782 {
2783 m_process->CompleteAttach ();
2784 return eEventActionSuccess;
2785 }
2786 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002787 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002788
Greg Clayton513c26c2011-01-29 07:10:55 +00002789 default:
2790 case eStateExited:
2791 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002792 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002793 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002794
2795 m_exit_string.assign ("No valid Process");
2796 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002797}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002798
Jim Inghambb3a2832011-01-29 01:49:25 +00002799Process::NextEventAction::EventActionResult
2800Process::AttachCompletionHandler::HandleBeingInterrupted()
2801{
2802 return eEventActionSuccess;
2803}
2804
2805const char *
2806Process::AttachCompletionHandler::GetExitString ()
2807{
2808 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002809}
2810
2811Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002812Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002814 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002815 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002816 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002817 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002818
Greg Clayton144f3a92011-11-15 03:53:30 +00002819 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002820 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002821 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002822 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002823 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002824
Greg Clayton144f3a92011-11-15 03:53:30 +00002825 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002826 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002827 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2828
2829 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002830 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002831 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2832 if (error.Success())
2833 {
Greg Clayton926cce72012-10-12 16:10:12 +00002834 if (m_run_lock.WriteTryLock())
2835 {
2836 m_should_detach = true;
2837 SetPublicState (eStateAttaching);
2838 // Now attach using these arguments.
2839 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2840 }
2841 else
2842 {
2843 // This shouldn't happen
2844 error.SetErrorString("failed to acquire process run lock");
2845 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00002846
Greg Clayton144f3a92011-11-15 03:53:30 +00002847 if (error.Fail())
2848 {
2849 if (GetID() != LLDB_INVALID_PROCESS_ID)
2850 {
2851 SetID (LLDB_INVALID_PROCESS_ID);
2852 if (error.AsCString() == NULL)
2853 error.SetErrorString("attach failed");
2854
2855 SetExitStatus(-1, error.AsCString());
2856 }
2857 }
2858 else
2859 {
2860 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2861 StartPrivateStateThread();
2862 }
2863 return error;
2864 }
Greg Claytone996fd32011-03-08 22:40:15 +00002865 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002866 else
Greg Claytone996fd32011-03-08 22:40:15 +00002867 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002868 ProcessInstanceInfoList process_infos;
2869 PlatformSP platform_sp (m_target.GetPlatform ());
2870
2871 if (platform_sp)
2872 {
2873 ProcessInstanceInfoMatch match_info;
2874 match_info.GetProcessInfo() = attach_info;
2875 match_info.SetNameMatchType (eNameMatchEquals);
2876 platform_sp->FindProcesses (match_info, process_infos);
2877 const uint32_t num_matches = process_infos.GetSize();
2878 if (num_matches == 1)
2879 {
2880 attach_pid = process_infos.GetProcessIDAtIndex(0);
2881 // Fall through and attach using the above process ID
2882 }
2883 else
2884 {
2885 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2886 if (num_matches > 1)
2887 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2888 else
2889 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2890 }
2891 }
2892 else
2893 {
2894 error.SetErrorString ("invalid platform, can't find processes by name");
2895 return error;
2896 }
Greg Claytone996fd32011-03-08 22:40:15 +00002897 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002898 }
2899 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002900 {
2901 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002902 }
2903 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002904
2905 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002906 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002907 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002908 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002909 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002910
Greg Clayton926cce72012-10-12 16:10:12 +00002911 if (m_run_lock.WriteTryLock())
2912 {
2913 // Now attach using these arguments.
2914 m_should_detach = true;
2915 SetPublicState (eStateAttaching);
2916 error = DoAttachToProcessWithID (attach_pid, attach_info);
2917 }
2918 else
2919 {
2920 // This shouldn't happen
2921 error.SetErrorString("failed to acquire process run lock");
2922 }
2923
Greg Clayton144f3a92011-11-15 03:53:30 +00002924 if (error.Success())
2925 {
2926
2927 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2928 StartPrivateStateThread();
2929 }
2930 else
Greg Claytone996fd32011-03-08 22:40:15 +00002931 {
2932 if (GetID() != LLDB_INVALID_PROCESS_ID)
2933 {
2934 SetID (LLDB_INVALID_PROCESS_ID);
2935 const char *error_string = error.AsCString();
2936 if (error_string == NULL)
2937 error_string = "attach failed";
2938
2939 SetExitStatus(-1, error_string);
2940 }
2941 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002942 }
2943 }
2944 return error;
2945}
2946
Greg Clayton93d3c8332011-02-16 04:46:07 +00002947void
2948Process::CompleteAttach ()
2949{
2950 // Let the process subclass figure out at much as it can about the process
2951 // before we go looking for a dynamic loader plug-in.
2952 DidAttach();
2953
Jim Ingham4299fdb2011-09-15 01:10:17 +00002954 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2955 // the same as the one we've already set, switch architectures.
2956 PlatformSP platform_sp (m_target.GetPlatform ());
2957 assert (platform_sp.get());
2958 if (platform_sp)
2959 {
Greg Clayton70512312012-05-08 01:45:38 +00002960 const ArchSpec &target_arch = m_target.GetArchitecture();
2961 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2962 {
2963 ArchSpec platform_arch;
2964 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2965 if (platform_sp)
2966 {
2967 m_target.SetPlatform (platform_sp);
2968 m_target.SetArchitecture(platform_arch);
2969 }
2970 }
2971 else
2972 {
2973 ProcessInstanceInfo process_info;
2974 platform_sp->GetProcessInfo (GetID(), process_info);
2975 const ArchSpec &process_arch = process_info.GetArchitecture();
2976 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2977 m_target.SetArchitecture (process_arch);
2978 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00002979 }
2980
2981 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002982 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002983 DynamicLoader *dyld = GetDynamicLoader ();
2984 if (dyld)
2985 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002986
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002987 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002988 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00002989 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002990 Mutex::Locker modules_locker(target_modules.GetMutex());
2991 size_t num_modules = target_modules.GetSize();
2992 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002993
Greg Clayton93d3c8332011-02-16 04:46:07 +00002994 for (int i = 0; i < num_modules; i++)
2995 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002996 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002997 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002998 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002999 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003000 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003001 break;
3002 }
3003 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003004 if (new_executable_module_sp)
3005 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003006}
3007
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003008Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003009Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003010{
Greg Claytonb766a732011-02-04 01:58:07 +00003011 m_abi_sp.reset();
3012 m_process_input_reader.reset();
3013
3014 // Find the process and its architecture. Make sure it matches the architecture
3015 // of the current Target, and if not adjust it.
3016
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003017 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003018 if (error.Success())
3019 {
Greg Clayton71337622011-02-24 22:24:29 +00003020 if (GetID() != LLDB_INVALID_PROCESS_ID)
3021 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003022 EventSP event_sp;
3023 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3024
3025 if (state == eStateStopped || state == eStateCrashed)
3026 {
3027 // If we attached and actually have a process on the other end, then
3028 // this ended up being the equivalent of an attach.
3029 CompleteAttach ();
3030
3031 // This delays passing the stopped event to listeners till
3032 // CompleteAttach gets a chance to complete...
3033 HandlePrivateEvent (event_sp);
3034
3035 }
Greg Clayton71337622011-02-24 22:24:29 +00003036 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003037
3038 if (PrivateStateThreadIsValid ())
3039 ResumePrivateStateThread ();
3040 else
3041 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003042 }
3043 return error;
3044}
3045
3046
3047Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003048Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003049{
Jim Ingham46ef1802012-09-06 19:24:17 +00003050 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003051 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00003052 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003053 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003054 StateAsCString(m_public_state.GetValue()),
3055 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003056
3057 Error error (WillResume());
3058 // Tell the process it is about to resume before the thread list
3059 if (error.Success())
3060 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003061 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003062 // can let all of our threads know that they are about to be
3063 // resumed. Threads will each be called with
3064 // Thread::WillResume(StateType) where StateType contains the state
3065 // that they are supposed to have when the process is resumed
3066 // (suspended/running/stepping). Threads should also check
3067 // their resume signal in lldb::Thread::GetResumeSignal()
3068 // to see if they are suppoed to start back up with a signal.
3069 if (m_thread_list.WillResume())
3070 {
Jim Ingham372787f2012-04-07 00:00:41 +00003071 // Last thing, do the PreResumeActions.
3072 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003073 {
Jim Ingham372787f2012-04-07 00:00:41 +00003074 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3075 }
3076 else
3077 {
3078 m_mod_id.BumpResumeID();
3079 error = DoResume();
3080 if (error.Success())
3081 {
3082 DidResume();
3083 m_thread_list.DidResume();
3084 if (log)
3085 log->Printf ("Process thinks the process has resumed.");
3086 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003087 }
3088 }
3089 else
3090 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003091 // Somebody wanted to run without running. So generate a continue & a stopped event,
3092 // and let the world handle them.
3093 if (log)
3094 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3095
3096 SetPrivateState(eStateRunning);
3097 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003098 }
3099 }
Jim Ingham444586b2011-01-24 06:34:17 +00003100 else if (log)
3101 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003102 return error;
3103}
3104
3105Error
3106Process::Halt ()
3107{
Jim Inghamaacc3182012-06-06 00:29:30 +00003108 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3109 // we could just straightaway get another event. It just narrows the window...
3110 m_currently_handling_event.WaitForValueEqualTo(false);
3111
3112
Jim Inghambb3a2832011-01-29 01:49:25 +00003113 // Pause our private state thread so we can ensure no one else eats
3114 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003115 Listener halt_listener ("lldb.process.halt_listener");
3116 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003117
Jim Inghambb3a2832011-01-29 01:49:25 +00003118 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003119 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003120
Greg Clayton513c26c2011-01-29 07:10:55 +00003121 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003122 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003123
Greg Clayton513c26c2011-01-29 07:10:55 +00003124 bool caused_stop = false;
3125
3126 // Ask the process subclass to actually halt our process
3127 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003128 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003129 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003130 if (m_public_state.GetValue() == eStateAttaching)
3131 {
3132 SetExitStatus(SIGKILL, "Cancelled async attach.");
3133 Destroy ();
3134 }
3135 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003136 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003137 // If "caused_stop" is true, then DoHalt stopped the process. If
3138 // "caused_stop" is false, the process was already stopped.
3139 // If the DoHalt caused the process to stop, then we want to catch
3140 // this event and set the interrupted bool to true before we pass
3141 // this along so clients know that the process was interrupted by
3142 // a halt command.
3143 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003144 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003145 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003146 TimeValue timeout_time;
3147 timeout_time = TimeValue::Now();
3148 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003149 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3150 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003151
Jim Ingham0f16e732011-02-08 05:20:59 +00003152 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003153 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003154 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003155 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003156 }
3157 else
3158 {
Greg Clayton2637f822011-11-17 01:23:07 +00003159 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003160 {
3161 // We caused the process to interrupt itself, so mark this
3162 // as such in the stop event so clients can tell an interrupted
3163 // process from a natural stop
3164 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3165 }
3166 else
3167 {
3168 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3169 if (log)
3170 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3171 error.SetErrorString ("Did not get stopped event after halt.");
3172 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003173 }
3174 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003175 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003176 }
3177 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003178 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003179 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003180 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003181
3182 // Post any event we might have consumed. If all goes well, we will have
3183 // stopped the process, intercepted the event and set the interrupted
3184 // bool in the event. Post it to the private event queue and that will end up
3185 // correctly setting the state.
3186 if (event_sp)
3187 m_private_state_broadcaster.BroadcastEvent(event_sp);
3188
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003189 return error;
3190}
3191
3192Error
3193Process::Detach ()
3194{
3195 Error error (WillDetach());
3196
3197 if (error.Success())
3198 {
3199 DisableAllBreakpointSites();
3200 error = DoDetach();
3201 if (error.Success())
3202 {
3203 DidDetach();
3204 StopPrivateStateThread();
3205 }
3206 }
3207 return error;
3208}
3209
3210Error
3211Process::Destroy ()
3212{
3213 Error error (WillDestroy());
3214 if (error.Success())
3215 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003216 EventSP exit_event_sp;
Jim Ingham04e0a222012-05-23 15:46:31 +00003217 if (m_public_state.GetValue() == eStateRunning)
3218 {
Greg Claytona28d2032012-09-05 00:37:58 +00003219 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003220 if (log)
3221 log->Printf("Process::Destroy() About to halt.");
Jim Ingham04e0a222012-05-23 15:46:31 +00003222 error = Halt();
3223 if (error.Success())
3224 {
3225 // Consume the halt event.
Jim Ingham04e0a222012-05-23 15:46:31 +00003226 TimeValue timeout (TimeValue::Now());
Jim Inghamaacc3182012-06-06 00:29:30 +00003227 timeout.OffsetWithSeconds(1);
Greg Clayton85fb1b92012-09-11 02:33:37 +00003228 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3229 if (state != eStateExited)
3230 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3231
Jim Ingham04e0a222012-05-23 15:46:31 +00003232 if (state != eStateStopped)
3233 {
Jim Ingham04e0a222012-05-23 15:46:31 +00003234 if (log)
3235 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Inghamaacc3182012-06-06 00:29:30 +00003236 // If we really couldn't stop the process then we should just error out here, but if the
3237 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3238 StateType private_state = m_private_state.GetValue();
3239 if (private_state != eStateStopped && private_state != eStateExited)
3240 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003241 // If we exited when we were waiting for a process to stop, then
3242 // forward the event here so we don't lose the event
Jim Inghamaacc3182012-06-06 00:29:30 +00003243 return error;
3244 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003245 }
3246 }
3247 else
3248 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003249 if (log)
3250 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3251 return error;
Jim Ingham04e0a222012-05-23 15:46:31 +00003252 }
3253 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003254
3255 if (m_public_state.GetValue() != eStateRunning)
3256 {
3257 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3258 // kill it, we don't want it hitting a breakpoint...
3259 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3260 // we're not going to have much luck doing this now.
3261 m_thread_list.DiscardThreadPlans();
3262 DisableAllBreakpointSites();
3263 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003264
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265 error = DoDestroy();
3266 if (error.Success())
3267 {
3268 DidDestroy();
3269 StopPrivateStateThread();
3270 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003271 m_stdio_communication.StopReadThread();
3272 m_stdio_communication.Disconnect();
3273 if (m_process_input_reader && m_process_input_reader->IsActive())
3274 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3275 if (m_process_input_reader)
3276 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003277
3278 // If we exited when we were waiting for a process to stop, then
3279 // forward the event here so we don't lose the event
3280 if (exit_event_sp)
3281 {
3282 // Directly broadcast our exited event because we shut down our
3283 // private state thread above
3284 BroadcastEvent(exit_event_sp);
3285 }
3286
Jim Inghamb1e2e842012-04-12 18:49:31 +00003287 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3288 // the last events through the event system, in which case we might strand the write lock. Unlock
3289 // it here so when we do to tear down the process we don't get an error destroying the lock.
3290 m_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003291 }
3292 return error;
3293}
3294
3295Error
3296Process::Signal (int signal)
3297{
3298 Error error (WillSignal());
3299 if (error.Success())
3300 {
3301 error = DoSignal(signal);
3302 if (error.Success())
3303 DidSignal();
3304 }
3305 return error;
3306}
3307
Greg Clayton514487e2011-02-15 21:59:32 +00003308lldb::ByteOrder
3309Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003310{
Greg Clayton514487e2011-02-15 21:59:32 +00003311 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003312}
3313
3314uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003315Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003316{
Greg Clayton514487e2011-02-15 21:59:32 +00003317 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003318}
3319
Greg Clayton514487e2011-02-15 21:59:32 +00003320
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003321bool
3322Process::ShouldBroadcastEvent (Event *event_ptr)
3323{
3324 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3325 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003326 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003327
3328 switch (state)
3329 {
Greg Claytonb766a732011-02-04 01:58:07 +00003330 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003331 case eStateAttaching:
3332 case eStateLaunching:
3333 case eStateDetached:
3334 case eStateExited:
3335 case eStateUnloaded:
3336 // These events indicate changes in the state of the debugging session, always report them.
3337 return_value = true;
3338 break;
3339 case eStateInvalid:
3340 // We stopped for no apparent reason, don't report it.
3341 return_value = false;
3342 break;
3343 case eStateRunning:
3344 case eStateStepping:
3345 // If we've started the target running, we handle the cases where we
3346 // are already running and where there is a transition from stopped to
3347 // running differently.
3348 // running -> running: Automatically suppress extra running events
3349 // stopped -> running: Report except when there is one or more no votes
3350 // and no yes votes.
3351 SynchronouslyNotifyStateChanged (state);
3352 switch (m_public_state.GetValue())
3353 {
3354 case eStateRunning:
3355 case eStateStepping:
3356 // We always suppress multiple runnings with no PUBLIC stop in between.
3357 return_value = false;
3358 break;
3359 default:
3360 // TODO: make this work correctly. For now always report
3361 // run if we aren't running so we don't miss any runnning
3362 // events. If I run the lldb/test/thread/a.out file and
3363 // break at main.cpp:58, run and hit the breakpoints on
3364 // multiple threads, then somehow during the stepping over
3365 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003366
3367 // This is a transition from stop to run.
3368 switch (m_thread_list.ShouldReportRun (event_ptr))
3369 {
Greg Clayton23f59502012-07-17 03:23:13 +00003370 default:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003371 case eVoteYes:
3372 case eVoteNoOpinion:
3373 return_value = true;
3374 break;
3375 case eVoteNo:
3376 return_value = false;
3377 break;
3378 }
3379 break;
3380 }
3381 break;
3382 case eStateStopped:
3383 case eStateCrashed:
3384 case eStateSuspended:
3385 {
3386 // We've stopped. First see if we're going to restart the target.
3387 // If we are going to stop, then we always broadcast the event.
3388 // 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 +00003389 // If no thread has an opinion, we don't report it.
Jim Inghamcb4ca112012-05-16 01:32:14 +00003390
3391 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003392 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003393 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003394 if (log)
3395 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003396 return true;
3397 }
3398 else
3399 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003400
3401 if (m_thread_list.ShouldStop (event_ptr) == false)
3402 {
Jim Inghamcb95f342012-09-05 21:13:56 +00003403 // ShouldStop may have restarted the target already. If so, don't
3404 // resume it twice.
3405 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003406 switch (m_thread_list.ShouldReportStop (event_ptr))
3407 {
3408 case eVoteYes:
3409 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003410 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003411 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003412 case eVoteNo:
3413 return_value = false;
3414 break;
3415 }
3416
3417 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003418 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Inghamcb95f342012-09-05 21:13:56 +00003419 if (!was_restarted)
3420 PrivateResume ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003421 }
3422 else
3423 {
3424 return_value = true;
3425 SynchronouslyNotifyStateChanged (state);
3426 }
3427 }
3428 }
3429 }
3430
3431 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003432 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003433 return return_value;
3434}
3435
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003436
3437bool
Jim Ingham372787f2012-04-07 00:00:41 +00003438Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003439{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003440 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003441
Greg Clayton8b82f082011-04-12 05:54:46 +00003442 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003443 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003444 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3445
Jim Ingham372787f2012-04-07 00:00:41 +00003446 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003447 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003448
3449 // Create a thread that watches our internal state and controls which
3450 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003451 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003452 if (already_running)
3453 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3454 else
3455 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003456
3457 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003458 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003459 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3460 if (success)
3461 {
3462 ResumePrivateStateThread();
3463 return true;
3464 }
3465 else
3466 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003467}
3468
3469void
3470Process::PausePrivateStateThread ()
3471{
3472 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3473}
3474
3475void
3476Process::ResumePrivateStateThread ()
3477{
3478 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3479}
3480
3481void
3482Process::StopPrivateStateThread ()
3483{
Greg Clayton8b82f082011-04-12 05:54:46 +00003484 if (PrivateStateThreadIsValid ())
3485 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003486 else
3487 {
3488 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3489 if (log)
3490 printf ("Went to stop the private state thread, but it was already invalid.");
3491 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003492}
3493
3494void
3495Process::ControlPrivateStateThread (uint32_t signal)
3496{
Jim Inghamb1e2e842012-04-12 18:49:31 +00003497 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003498
3499 assert (signal == eBroadcastInternalStateControlStop ||
3500 signal == eBroadcastInternalStateControlPause ||
3501 signal == eBroadcastInternalStateControlResume);
3502
3503 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003504 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003505
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003506 // Signal the private state thread. First we should copy this is case the
3507 // thread starts exiting since the private state thread will NULL this out
3508 // when it exits
3509 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003510 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003511 {
3512 TimeValue timeout_time;
3513 bool timed_out;
3514
3515 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3516
3517 timeout_time = TimeValue::Now();
3518 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003519 if (log)
3520 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003521 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3522 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3523
3524 if (signal == eBroadcastInternalStateControlStop)
3525 {
3526 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003527 {
3528 Error error;
3529 Host::ThreadCancel (private_state_thread, &error);
3530 if (log)
3531 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3532 }
3533 else
3534 {
3535 if (log)
3536 log->Printf ("The control event killed the private state thread without having to cancel.");
3537 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003538
3539 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003540 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003541 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003542 }
3543 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003544 else
3545 {
3546 if (log)
3547 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3548 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003549}
3550
3551void
Jim Inghamcfc09352012-07-27 23:57:19 +00003552Process::SendAsyncInterrupt ()
3553{
3554 if (PrivateStateThreadIsValid())
3555 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3556 else
3557 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3558}
3559
3560void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561Process::HandlePrivateEvent (EventSP &event_sp)
3562{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003563 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003564 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003565
Greg Clayton414f5d32011-01-25 02:58:48 +00003566 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003567
3568 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003569 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003570 {
Jim Ingham754ab982011-01-29 04:05:41 +00003571 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003572 switch (action_result)
3573 {
3574 case NextEventAction::eEventActionSuccess:
3575 SetNextEventAction(NULL);
3576 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003577
Jim Inghambb3a2832011-01-29 01:49:25 +00003578 case NextEventAction::eEventActionRetry:
3579 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003580
Jim Inghambb3a2832011-01-29 01:49:25 +00003581 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003582 // Handle Exiting Here. If we already got an exited event,
3583 // we should just propagate it. Otherwise, swallow this event,
3584 // and set our state to exit so the next event will kill us.
3585 if (new_state != eStateExited)
3586 {
3587 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003588 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003589 SetNextEventAction(NULL);
3590 return;
3591 }
3592 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003593 break;
3594 }
3595 }
3596
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003597 // See if we should broadcast this state to external clients?
3598 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003599
3600 if (should_broadcast)
3601 {
3602 if (log)
3603 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003604 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003605 __FUNCTION__,
3606 GetID(),
3607 StateAsCString(new_state),
3608 StateAsCString (GetState ()),
3609 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003610 }
Jim Ingham9575d842011-03-11 03:53:59 +00003611 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003612 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003613 PushProcessInputReader ();
3614 else
3615 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003616
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003617 BroadcastEvent (event_sp);
3618 }
3619 else
3620 {
3621 if (log)
3622 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003623 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003624 __FUNCTION__,
3625 GetID(),
3626 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003627 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003628 }
3629 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003630 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003631}
3632
3633void *
3634Process::PrivateStateThread (void *arg)
3635{
3636 Process *proc = static_cast<Process*> (arg);
3637 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003638 return result;
3639}
3640
3641void *
3642Process::RunPrivateStateThread ()
3643{
Jim Ingham076b3042012-04-10 01:21:57 +00003644 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003645 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003646
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003647 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003648 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003649 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003650
3651 bool exit_now = false;
3652 while (!exit_now)
3653 {
3654 EventSP event_sp;
3655 WaitForEventsPrivate (NULL, event_sp, control_only);
3656 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3657 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003658 if (log)
3659 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3660
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003661 switch (event_sp->GetType())
3662 {
3663 case eBroadcastInternalStateControlStop:
3664 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003665 break; // doing any internal state managment below
3666
3667 case eBroadcastInternalStateControlPause:
3668 control_only = true;
3669 break;
3670
3671 case eBroadcastInternalStateControlResume:
3672 control_only = false;
3673 break;
3674 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003675
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003676 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003677 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003678 }
Jim Inghamcfc09352012-07-27 23:57:19 +00003679 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3680 {
3681 if (m_public_state.GetValue() == eStateAttaching)
3682 {
3683 if (log)
3684 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3685 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3686 }
3687 else
3688 {
3689 if (log)
3690 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3691 Halt();
3692 }
3693 continue;
3694 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003695
3696 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3697
3698 if (internal_state != eStateInvalid)
3699 {
3700 HandlePrivateEvent (event_sp);
3701 }
3702
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003703 if (internal_state == eStateInvalid ||
3704 internal_state == eStateExited ||
3705 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003706 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003707 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003708 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 +00003709
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003710 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003711 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003712 }
3713
Caroline Tice20ad3c42010-10-29 21:48:37 +00003714 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003715 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003716 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003717
Greg Clayton6ed95942011-01-22 07:12:45 +00003718 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3719 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003720 return NULL;
3721}
3722
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003723//------------------------------------------------------------------
3724// Process Event Data
3725//------------------------------------------------------------------
3726
3727Process::ProcessEventData::ProcessEventData () :
3728 EventData (),
3729 m_process_sp (),
3730 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003731 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003732 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003733 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003734{
3735}
3736
3737Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3738 EventData (),
3739 m_process_sp (process_sp),
3740 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003741 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003742 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003743 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003744{
3745}
3746
3747Process::ProcessEventData::~ProcessEventData()
3748{
3749}
3750
3751const ConstString &
3752Process::ProcessEventData::GetFlavorString ()
3753{
3754 static ConstString g_flavor ("Process::ProcessEventData");
3755 return g_flavor;
3756}
3757
3758const ConstString &
3759Process::ProcessEventData::GetFlavor () const
3760{
3761 return ProcessEventData::GetFlavorString ();
3762}
3763
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003764void
3765Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3766{
3767 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003768 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3769 // the public event queue, then other times when we're pretending that this is where we stopped at the
3770 // end of expression evaluation. m_update_state is used to distinguish these
3771 // three cases; it is 0 when we're just pulling it off for private handling,
3772 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003773
Jim Inghama8604692011-05-22 21:45:01 +00003774 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003775 return;
3776
3777 m_process_sp->SetPublicState (m_state);
3778
3779 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3780 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003781 {
3782 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003783 uint32_t num_threads = curr_thread_list.GetSize();
3784 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003785
Jim Ingham4b536182011-08-09 02:12:22 +00003786 // The actions might change one of the thread's stop_info's opinions about whether we should
3787 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003788
3789 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3790 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3791 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3792 // 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
3793 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003794 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003795 for (idx = 0; idx < num_threads; ++idx)
3796 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3797
Jim Ingham4b536182011-08-09 02:12:22 +00003798 bool still_should_stop = true;
3799
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003800 for (idx = 0; idx < num_threads; ++idx)
3801 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003802 curr_thread_list = m_process_sp->GetThreadList();
3803 if (curr_thread_list.GetSize() != num_threads)
3804 {
3805 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003806 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003807 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 +00003808 break;
3809 }
3810
3811 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3812
3813 if (thread_sp->GetIndexID() != thread_index_array[idx])
3814 {
3815 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003816 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003817 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003818 idx,
3819 thread_index_array[idx],
3820 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003821 break;
3822 }
3823
Jim Inghamb15bfc72010-10-20 00:39:53 +00003824 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00003825 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003826 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003827 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003828 // The stop action might restart the target. If it does, then we want to mark that in the
3829 // event so that whoever is receiving it will know to wait for the running event and reflect
3830 // that state appropriately.
3831 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003832
3833 // FIXME: we might have run.
3834 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003835 {
3836 SetRestarted (true);
3837 break;
3838 }
3839 else if (!stop_info_sp->ShouldStop(event_ptr))
3840 {
3841 still_should_stop = false;
3842 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003843 }
3844 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003845
Jim Ingham4b536182011-08-09 02:12:22 +00003846
3847 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003848 {
Jim Ingham4b536182011-08-09 02:12:22 +00003849 if (!still_should_stop)
3850 {
3851 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003852 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00003853 // Use the public resume method here, since this is just
3854 // extending a public resume.
Jim Ingham4b536182011-08-09 02:12:22 +00003855 m_process_sp->Resume();
3856 }
3857 else
3858 {
3859 // If we didn't restart, run the Stop Hooks here:
3860 // They might also restart the target, so watch for that.
3861 m_process_sp->GetTarget().RunStopHooks();
3862 if (m_process_sp->GetPrivateState() == eStateRunning)
3863 SetRestarted(true);
3864 }
Jim Ingham9575d842011-03-11 03:53:59 +00003865 }
3866
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003867 }
3868}
3869
3870void
3871Process::ProcessEventData::Dump (Stream *s) const
3872{
3873 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003874 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003875
Greg Clayton8b82f082011-04-12 05:54:46 +00003876 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003877}
3878
3879const Process::ProcessEventData *
3880Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3881{
3882 if (event_ptr)
3883 {
3884 const EventData *event_data = event_ptr->GetData();
3885 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3886 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3887 }
3888 return NULL;
3889}
3890
3891ProcessSP
3892Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3893{
3894 ProcessSP process_sp;
3895 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3896 if (data)
3897 process_sp = data->GetProcessSP();
3898 return process_sp;
3899}
3900
3901StateType
3902Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3903{
3904 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3905 if (data == NULL)
3906 return eStateInvalid;
3907 else
3908 return data->GetState();
3909}
3910
3911bool
3912Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3913{
3914 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3915 if (data == NULL)
3916 return false;
3917 else
3918 return data->GetRestarted();
3919}
3920
3921void
3922Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3923{
3924 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3925 if (data != NULL)
3926 data->SetRestarted(new_value);
3927}
3928
3929bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003930Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3931{
3932 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3933 if (data == NULL)
3934 return false;
3935 else
3936 return data->GetInterrupted ();
3937}
3938
3939void
3940Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3941{
3942 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3943 if (data != NULL)
3944 data->SetInterrupted(new_value);
3945}
3946
3947bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003948Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3949{
3950 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3951 if (data)
3952 {
3953 data->SetUpdateStateOnRemoval();
3954 return true;
3955 }
3956 return false;
3957}
3958
Greg Claytond9e416c2012-02-18 05:35:26 +00003959lldb::TargetSP
3960Process::CalculateTarget ()
3961{
3962 return m_target.shared_from_this();
3963}
3964
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003965void
Greg Clayton0603aa92010-10-04 01:05:56 +00003966Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003967{
Greg Claytonc14ee322011-09-22 04:58:26 +00003968 exe_ctx.SetTargetPtr (&m_target);
3969 exe_ctx.SetProcessPtr (this);
3970 exe_ctx.SetThreadPtr(NULL);
3971 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003972}
3973
Greg Claytone996fd32011-03-08 22:40:15 +00003974//uint32_t
3975//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3976//{
3977// return 0;
3978//}
3979//
3980//ArchSpec
3981//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3982//{
3983// return Host::GetArchSpecForExistingProcess (pid);
3984//}
3985//
3986//ArchSpec
3987//Process::GetArchSpecForExistingProcess (const char *process_name)
3988//{
3989// return Host::GetArchSpecForExistingProcess (process_name);
3990//}
3991//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003992void
3993Process::AppendSTDOUT (const char * s, size_t len)
3994{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003995 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003996 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00003997 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003998}
3999
4000void
Greg Clayton93e86192011-11-13 04:45:22 +00004001Process::AppendSTDERR (const char * s, size_t len)
4002{
4003 Mutex::Locker locker (m_stdio_communication_mutex);
4004 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004005 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004006}
4007
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004008void
4009Process::BroadcastAsyncProfileData(const char *s, size_t len)
4010{
4011 Mutex::Locker locker (m_profile_data_comm_mutex);
4012 m_profile_data.append (s, len);
4013 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4014}
4015
4016size_t
4017Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4018{
4019 Mutex::Locker locker(m_profile_data_comm_mutex);
4020 size_t bytes_available = m_profile_data.size();
4021 if (bytes_available > 0)
4022 {
4023 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4024 if (log)
4025 log->Printf ("Process::GetProfileData (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
4026 if (bytes_available > buf_size)
4027 {
4028 memcpy(buf, m_profile_data.c_str(), buf_size);
4029 m_profile_data.erase(0, buf_size);
4030 bytes_available = buf_size;
4031 }
4032 else
4033 {
4034 memcpy(buf, m_profile_data.c_str(), bytes_available);
4035 m_profile_data.clear();
4036 }
4037 }
4038 return bytes_available;
4039}
4040
4041
Greg Clayton93e86192011-11-13 04:45:22 +00004042//------------------------------------------------------------------
4043// Process STDIO
4044//------------------------------------------------------------------
4045
4046size_t
4047Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4048{
4049 Mutex::Locker locker(m_stdio_communication_mutex);
4050 size_t bytes_available = m_stdout_data.size();
4051 if (bytes_available > 0)
4052 {
4053 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4054 if (log)
Greg Clayton43e0af02012-09-18 18:04:04 +00004055 log->Printf ("Process::GetSTDOUT (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004056 if (bytes_available > buf_size)
4057 {
4058 memcpy(buf, m_stdout_data.c_str(), buf_size);
4059 m_stdout_data.erase(0, buf_size);
4060 bytes_available = buf_size;
4061 }
4062 else
4063 {
4064 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4065 m_stdout_data.clear();
4066 }
4067 }
4068 return bytes_available;
4069}
4070
4071
4072size_t
4073Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4074{
4075 Mutex::Locker locker(m_stdio_communication_mutex);
4076 size_t bytes_available = m_stderr_data.size();
4077 if (bytes_available > 0)
4078 {
4079 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4080 if (log)
Greg Clayton43e0af02012-09-18 18:04:04 +00004081 log->Printf ("Process::GetSTDERR (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004082 if (bytes_available > buf_size)
4083 {
4084 memcpy(buf, m_stderr_data.c_str(), buf_size);
4085 m_stderr_data.erase(0, buf_size);
4086 bytes_available = buf_size;
4087 }
4088 else
4089 {
4090 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4091 m_stderr_data.clear();
4092 }
4093 }
4094 return bytes_available;
4095}
4096
4097void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004098Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4099{
4100 Process *process = (Process *) baton;
4101 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4102}
4103
4104size_t
4105Process::ProcessInputReaderCallback (void *baton,
4106 InputReader &reader,
4107 lldb::InputReaderAction notification,
4108 const char *bytes,
4109 size_t bytes_len)
4110{
4111 Process *process = (Process *) baton;
4112
4113 switch (notification)
4114 {
4115 case eInputReaderActivate:
4116 break;
4117
4118 case eInputReaderDeactivate:
4119 break;
4120
4121 case eInputReaderReactivate:
4122 break;
4123
Caroline Tice969ed3d2011-05-02 20:41:46 +00004124 case eInputReaderAsynchronousOutputWritten:
4125 break;
4126
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004127 case eInputReaderGotToken:
4128 {
4129 Error error;
4130 process->PutSTDIN (bytes, bytes_len, error);
4131 }
4132 break;
4133
Caroline Ticeefed6132010-11-19 20:47:54 +00004134 case eInputReaderInterrupt:
4135 process->Halt ();
4136 break;
4137
4138 case eInputReaderEndOfFile:
4139 process->AppendSTDOUT ("^D", 2);
4140 break;
4141
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004142 case eInputReaderDone:
4143 break;
4144
4145 }
4146
4147 return bytes_len;
4148}
4149
4150void
4151Process::ResetProcessInputReader ()
4152{
4153 m_process_input_reader.reset();
4154}
4155
4156void
Greg Claytonee95ed52011-11-17 22:14:31 +00004157Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004158{
4159 // First set up the Read Thread for reading/handling process I/O
4160
4161 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4162
4163 if (conn_ap.get())
4164 {
4165 m_stdio_communication.SetConnection (conn_ap.release());
4166 if (m_stdio_communication.IsConnected())
4167 {
4168 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4169 m_stdio_communication.StartReadThread();
4170
4171 // Now read thread is set up, set up input reader.
4172
4173 if (!m_process_input_reader.get())
4174 {
4175 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4176 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4177 this,
4178 eInputReaderGranularityByte,
4179 NULL,
4180 NULL,
4181 false));
4182
4183 if (err.Fail())
4184 m_process_input_reader.reset();
4185 }
4186 }
4187 }
4188}
4189
4190void
4191Process::PushProcessInputReader ()
4192{
4193 if (m_process_input_reader && !m_process_input_reader->IsActive())
4194 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4195}
4196
4197void
4198Process::PopProcessInputReader ()
4199{
4200 if (m_process_input_reader && m_process_input_reader->IsActive())
4201 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4202}
4203
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004204// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004205void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004206Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004207{
Greg Clayton67cc0632012-08-22 17:17:09 +00004208// static std::vector<OptionEnumValueElement> g_plugins;
4209//
4210// int i=0;
4211// const char *name;
4212// OptionEnumValueElement option_enum;
4213// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4214// {
4215// if (name)
4216// {
4217// option_enum.value = i;
4218// option_enum.string_value = name;
4219// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4220// g_plugins.push_back (option_enum);
4221// }
4222// ++i;
4223// }
4224// option_enum.value = 0;
4225// option_enum.string_value = NULL;
4226// option_enum.usage = NULL;
4227// g_plugins.push_back (option_enum);
4228//
4229// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4230// {
4231// if (::strcmp (name, "plugin") == 0)
4232// {
4233// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4234// break;
4235// }
4236// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004237//
Greg Clayton6920b522012-08-22 18:39:03 +00004238 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004239}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004240
Greg Clayton99d0faf2010-11-18 23:32:35 +00004241void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004242Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004243{
Greg Clayton6920b522012-08-22 18:39:03 +00004244 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004245}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004246
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004247ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004248Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004249 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00004250 bool stop_others,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004251 bool run_others,
Jim Inghamf48169b2010-11-30 02:22:11 +00004252 bool discard_on_error,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004253 uint32_t timeout_usec,
Jim Inghamf48169b2010-11-30 02:22:11 +00004254 Stream &errors)
4255{
4256 ExecutionResults return_value = eExecutionSetupError;
4257
Jim Ingham77787032011-01-20 02:03:18 +00004258 if (thread_plan_sp.get() == NULL)
4259 {
4260 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004261 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004262 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004263
4264 if (exe_ctx.GetProcessPtr() != this)
4265 {
4266 errors.Printf("RunThreadPlan called on wrong process.");
4267 return eExecutionSetupError;
4268 }
4269
4270 Thread *thread = exe_ctx.GetThreadPtr();
4271 if (thread == NULL)
4272 {
4273 errors.Printf("RunThreadPlan called with invalid thread.");
4274 return eExecutionSetupError;
4275 }
Jim Ingham77787032011-01-20 02:03:18 +00004276
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004277 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4278 // For that to be true the plan can't be private - since private plans suppress themselves in the
4279 // GetCompletedPlan call.
4280
4281 bool orig_plan_private = thread_plan_sp->GetPrivate();
4282 thread_plan_sp->SetPrivate(false);
4283
Jim Ingham444586b2011-01-24 06:34:17 +00004284 if (m_private_state.GetValue() != eStateStopped)
4285 {
4286 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004287 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004288 }
4289
Jim Ingham66243842011-08-13 00:56:10 +00004290 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004291 const uint32_t thread_idx_id = thread->GetIndexID();
4292 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004293
4294 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4295 // so we should arrange to reset them as well.
4296
Greg Claytonc14ee322011-09-22 04:58:26 +00004297 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004298
Jim Ingham66243842011-08-13 00:56:10 +00004299 uint32_t selected_tid;
4300 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004301 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004302 {
4303 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004304 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004305 }
4306 else
4307 {
4308 selected_tid = LLDB_INVALID_THREAD_ID;
4309 }
4310
Jim Ingham372787f2012-04-07 00:00:41 +00004311 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004312 lldb::StateType old_state;
4313 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004314
Jim Ingham076b3042012-04-10 01:21:57 +00004315 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004316 if (Host::GetCurrentThread() == m_private_state_thread)
4317 {
Jim Ingham076b3042012-04-10 01:21:57 +00004318 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4319 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004320 // 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 +00004321 // we are fielding public events here.
4322 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004323 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
Jim Ingham076b3042012-04-10 01:21:57 +00004324
4325
Jim Ingham372787f2012-04-07 00:00:41 +00004326 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004327
4328 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4329 // returning control here.
4330 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4331 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4332 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4333 // do just what we want.
4334 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4335 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4336 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4337 old_state = m_public_state.GetValue();
4338 m_public_state.SetValueNoLock(eStateStopped);
4339
4340 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004341 StartPrivateStateThread(true);
4342 }
4343
4344 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004345
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004346 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004347
Sean Callanana46ec452012-07-11 21:31:24 +00004348 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004349
Jim Ingham77787032011-01-20 02:03:18 +00004350 {
Sean Callanana46ec452012-07-11 21:31:24 +00004351 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4352 // restored on exit to the function.
4353 //
4354 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4355 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004356
Sean Callanana46ec452012-07-11 21:31:24 +00004357 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004358
Jim Inghamf48169b2010-11-30 02:22:11 +00004359 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004360 {
4361 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004362 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4363 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4364 thread->GetIndexID(),
4365 thread->GetID(),
4366 s.GetData());
4367 }
4368
4369 bool got_event;
4370 lldb::EventSP event_sp;
4371 lldb::StateType stop_state = lldb::eStateInvalid;
4372
4373 TimeValue* timeout_ptr = NULL;
4374 TimeValue real_timeout;
4375
4376 bool first_timeout = true;
4377 bool do_resume = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004378 const uint64_t default_one_thread_timeout_usec = 250000;
4379 uint64_t computed_timeout = 0;
Sean Callanana46ec452012-07-11 21:31:24 +00004380
Jim Ingham8559a352012-11-26 23:52:18 +00004381 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4382 // So don't call return anywhere within it.
4383
Sean Callanana46ec452012-07-11 21:31:24 +00004384 while (1)
4385 {
4386 // We usually want to resume the process if we get to the top of the loop.
4387 // The only exception is if we get two running events with no intervening
4388 // stop, which can happen, we will just wait for then next stop event.
4389
4390 if (do_resume)
4391 {
4392 // Do the initial resume and wait for the running event before going further.
4393
4394 Error resume_error = PrivateResume ();
4395 if (!resume_error.Success())
4396 {
4397 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4398 return_value = eExecutionSetupError;
4399 break;
4400 }
4401
4402 real_timeout = TimeValue::Now();
4403 real_timeout.OffsetWithMicroSeconds(500000);
4404 timeout_ptr = &real_timeout;
4405
4406 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4407 if (!got_event)
4408 {
4409 if (log)
4410 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4411
4412 errors.Printf("Didn't get any event after initial resume, exiting.");
4413 return_value = eExecutionSetupError;
4414 break;
4415 }
4416
4417 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4418 if (stop_state != eStateRunning)
4419 {
4420 if (log)
Jim Ingham35e1bda2012-10-16 21:41:58 +00004421 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4422 "initial resume, got %s instead.",
4423 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004424
Jim Ingham35e1bda2012-10-16 21:41:58 +00004425 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4426 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004427 return_value = eExecutionSetupError;
4428 break;
4429 }
4430
4431 if (log)
4432 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4433 // We need to call the function synchronously, so spin waiting for it to return.
4434 // If we get interrupted while executing, we're going to lose our context, and
4435 // won't be able to gather the result at this point.
4436 // We set the timeout AFTER the resume, since the resume takes some time and we
4437 // don't want to charge that to the timeout.
4438
Jim Ingham35e1bda2012-10-16 21:41:58 +00004439 if (first_timeout)
4440 {
4441 if (run_others)
4442 {
4443 // If we are running all threads then we take half the time to run all threads, bounded by
4444 // .25 sec.
4445 if (timeout_usec == 0)
4446 computed_timeout = default_one_thread_timeout_usec;
4447 else
4448 {
4449 computed_timeout = timeout_usec / 2;
4450 if (computed_timeout > default_one_thread_timeout_usec)
4451 {
4452 computed_timeout = default_one_thread_timeout_usec;
4453 }
4454 timeout_usec -= computed_timeout;
4455 }
4456 }
4457 else
4458 {
4459 computed_timeout = timeout_usec;
4460 }
4461 }
4462 else
4463 {
4464 computed_timeout = timeout_usec;
4465 }
4466
4467 if (computed_timeout != 0)
Sean Callanana46ec452012-07-11 21:31:24 +00004468 {
Enrico Granata3372f582012-07-16 23:10:35 +00004469 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanana46ec452012-07-11 21:31:24 +00004470 real_timeout = TimeValue::Now();
Jim Ingham35e1bda2012-10-16 21:41:58 +00004471 real_timeout.OffsetWithMicroSeconds(computed_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00004472
4473 timeout_ptr = &real_timeout;
4474 }
Enrico Granata3372f582012-07-16 23:10:35 +00004475 else
4476 {
Jim Ingham35e1bda2012-10-16 21:41:58 +00004477 timeout_ptr = NULL;
Enrico Granata3372f582012-07-16 23:10:35 +00004478 }
Sean Callanana46ec452012-07-11 21:31:24 +00004479 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004480 else
4481 {
Sean Callanana46ec452012-07-11 21:31:24 +00004482 if (log)
4483 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4484 do_resume = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00004485 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004486
Sean Callanana46ec452012-07-11 21:31:24 +00004487 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00004488 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00004489
Jim Ingham0f16e732011-02-08 05:20:59 +00004490 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004491 {
Sean Callanana46ec452012-07-11 21:31:24 +00004492 if (timeout_ptr)
4493 {
4494 StreamString s;
4495 s.Printf ("about to wait - timeout is:\n ");
4496 timeout_ptr->Dump (&s, 120);
4497 s.Printf ("\nNow is:\n ");
4498 TimeValue::Now().Dump (&s, 120);
4499 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4500 }
Jim Ingham20829ac2011-08-09 22:24:33 +00004501 else
Sean Callanana46ec452012-07-11 21:31:24 +00004502 {
4503 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4504 }
4505 }
4506
4507 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4508
4509 if (got_event)
4510 {
4511 if (event_sp.get())
4512 {
4513 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00004514 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004515 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004516 Halt();
4517 keep_going = false;
4518 return_value = eExecutionInterrupted;
4519 errors.Printf ("Execution halted by user interrupt.");
4520 if (log)
4521 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4522 }
4523 else
4524 {
4525 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4526 if (log)
4527 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4528
4529 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00004530 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004531 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00004532 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004533 // Yay, we're done. Now make sure that our thread plan actually completed.
4534 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4535 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004536 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004537 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00004538 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00004539 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4540 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00004541 }
4542 else
4543 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004544 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4545 StopReason stop_reason = eStopReasonInvalid;
4546 if (stop_info_sp)
4547 stop_reason = stop_info_sp->GetStopReason();
4548 if (stop_reason == eStopReasonPlanComplete)
4549 {
4550 if (log)
4551 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4552 // Now mark this plan as private so it doesn't get reported as the stop reason
4553 // after this point.
4554 if (thread_plan_sp)
4555 thread_plan_sp->SetPrivate (orig_plan_private);
4556 return_value = eExecutionCompleted;
4557 }
4558 else
4559 {
4560 if (log)
4561 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanana46ec452012-07-11 21:31:24 +00004562
Jim Inghamcfc09352012-07-27 23:57:19 +00004563 return_value = eExecutionInterrupted;
4564 }
Sean Callanana46ec452012-07-11 21:31:24 +00004565 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004566 }
4567 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004568
Jim Inghamcfc09352012-07-27 23:57:19 +00004569 case lldb::eStateCrashed:
4570 if (log)
4571 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4572 return_value = eExecutionInterrupted;
4573 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004574
Jim Inghamcfc09352012-07-27 23:57:19 +00004575 case lldb::eStateRunning:
4576 do_resume = false;
4577 keep_going = true;
4578 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004579
Jim Inghamcfc09352012-07-27 23:57:19 +00004580 default:
4581 if (log)
4582 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4583
4584 if (stop_state == eStateExited)
4585 event_to_broadcast_sp = event_sp;
4586
Sean Callananbf154da2012-08-08 17:35:10 +00004587 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00004588 return_value = eExecutionInterrupted;
4589 break;
4590 }
Sean Callanana46ec452012-07-11 21:31:24 +00004591 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004592
Sean Callanana46ec452012-07-11 21:31:24 +00004593 if (keep_going)
4594 continue;
4595 else
4596 break;
4597 }
4598 else
4599 {
4600 if (log)
4601 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4602 return_value = eExecutionInterrupted;
4603 break;
4604 }
4605 }
4606 else
4607 {
4608 // If we didn't get an event that means we've timed out...
4609 // We will interrupt the process here. Depending on what we were asked to do we will
4610 // either exit, or try with all threads running for the same timeout.
4611 // Not really sure what to do if Halt fails here...
4612
4613 if (log) {
Jim Ingham35e1bda2012-10-16 21:41:58 +00004614 if (run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00004615 {
4616 if (first_timeout)
Jim Ingham35e1bda2012-10-16 21:41:58 +00004617 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %lld timed out, "
4618 "trying for %d usec with all threads enabled.",
4619 computed_timeout, timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004620 else
4621 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham35e1bda2012-10-16 21:41:58 +00004622 "and timeout: %d timed out, abandoning execution.",
4623 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004624 }
4625 else
4626 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00004627 "abandoning execution.",
4628 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00004629 }
4630
4631 Error halt_error = Halt();
4632 if (halt_error.Success())
4633 {
4634 if (log)
4635 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4636
4637 // If halt succeeds, it always produces a stopped event. Wait for that:
4638
4639 real_timeout = TimeValue::Now();
4640 real_timeout.OffsetWithMicroSeconds(500000);
4641
4642 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4643
4644 if (got_event)
4645 {
4646 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4647 if (log)
4648 {
4649 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4650 if (stop_state == lldb::eStateStopped
4651 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4652 log->PutCString (" Event was the Halt interruption event.");
4653 }
4654
4655 if (stop_state == lldb::eStateStopped)
4656 {
4657 // Between the time we initiated the Halt and the time we delivered it, the process could have
4658 // already finished its job. Check that here:
4659
4660 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4661 {
4662 if (log)
4663 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4664 "Exiting wait loop.");
4665 return_value = eExecutionCompleted;
4666 break;
4667 }
4668
Jim Ingham35e1bda2012-10-16 21:41:58 +00004669 if (!run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00004670 {
4671 if (log)
4672 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4673 return_value = eExecutionInterrupted;
4674 break;
4675 }
4676
4677 if (first_timeout)
4678 {
4679 // Set all the other threads to run, and return to the top of the loop, which will continue;
4680 first_timeout = false;
4681 thread_plan_sp->SetStopOthers (false);
4682 if (log)
4683 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4684
4685 continue;
4686 }
4687 else
4688 {
4689 // Running all threads failed, so return Interrupted.
4690 if (log)
4691 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4692 return_value = eExecutionInterrupted;
4693 break;
4694 }
4695 }
4696 }
4697 else
4698 { if (log)
4699 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4700 "I'm getting out of here passing Interrupted.");
4701 return_value = eExecutionInterrupted;
4702 break;
4703 }
4704 }
4705 else
4706 {
4707 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4708 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4709 if (log)
4710 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.",
4711 halt_error.AsCString());
4712 real_timeout = TimeValue::Now();
4713 real_timeout.OffsetWithMicroSeconds(500000);
4714 timeout_ptr = &real_timeout;
4715 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4716 if (!got_event || event_sp.get() == NULL)
4717 {
4718 // This is not going anywhere, bag out.
4719 if (log)
4720 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4721 return_value = eExecutionInterrupted;
4722 break;
4723 }
4724 else
4725 {
4726 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4727 if (log)
4728 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4729 if (stop_state == lldb::eStateStopped)
4730 {
4731 // Between the time we initiated the Halt and the time we delivered it, the process could have
4732 // already finished its job. Check that here:
4733
4734 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4735 {
4736 if (log)
4737 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4738 "Exiting wait loop.");
4739 return_value = eExecutionCompleted;
4740 break;
4741 }
4742
4743 if (first_timeout)
4744 {
4745 // Set all the other threads to run, and return to the top of the loop, which will continue;
4746 first_timeout = false;
4747 thread_plan_sp->SetStopOthers (false);
4748 if (log)
4749 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4750
4751 continue;
4752 }
4753 else
4754 {
4755 // Running all threads failed, so return Interrupted.
4756 if (log)
4757 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4758 return_value = eExecutionInterrupted;
4759 break;
4760 }
4761 }
4762 else
4763 {
4764 if (log)
4765 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4766 " a stopped event, instead got %s.", StateAsCString(stop_state));
4767 return_value = eExecutionInterrupted;
4768 break;
4769 }
4770 }
4771 }
4772
4773 }
4774
4775 } // END WAIT LOOP
4776
4777 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4778 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4779 {
4780 StopPrivateStateThread();
4781 Error error;
4782 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00004783 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004784 {
4785 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4786 }
4787 m_public_state.SetValueNoLock(old_state);
4788
4789 }
4790
Jim Ingham8559a352012-11-26 23:52:18 +00004791 // Restore the thread state if we are going to discard the plan execution.
4792
4793 if (return_value == eExecutionCompleted || discard_on_error)
4794 {
4795 thread_plan_sp->RestoreThreadState();
4796 }
Sean Callanana46ec452012-07-11 21:31:24 +00004797
4798 // Now do some processing on the results of the run:
4799 if (return_value == eExecutionInterrupted)
4800 {
4801 if (log)
4802 {
4803 StreamString s;
4804 if (event_sp)
4805 event_sp->Dump (&s);
4806 else
4807 {
4808 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4809 }
4810
4811 StreamString ts;
4812
4813 const char *event_explanation = NULL;
4814
4815 do
4816 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004817 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004818 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004819 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00004820 break;
4821 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004822 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004823 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004824 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00004825 break;
4826 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004827 else
Sean Callanana46ec452012-07-11 21:31:24 +00004828 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004829 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4830
4831 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00004832 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004833 event_explanation = "<no event data>";
4834 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004835 }
4836
Jim Inghamcfc09352012-07-27 23:57:19 +00004837 Process *process = event_data->GetProcessSP().get();
4838
4839 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00004840 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004841 event_explanation = "<no process>";
4842 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004843 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004844
4845 ThreadList &thread_list = process->GetThreadList();
4846
4847 uint32_t num_threads = thread_list.GetSize();
4848 uint32_t thread_index;
4849
4850 ts.Printf("<%u threads> ", num_threads);
4851
4852 for (thread_index = 0;
4853 thread_index < num_threads;
4854 ++thread_index)
4855 {
4856 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4857
4858 if (!thread)
4859 {
4860 ts.Printf("<?> ");
4861 continue;
4862 }
4863
4864 ts.Printf("<0x%4.4llx ", thread->GetID());
4865 RegisterContext *register_context = thread->GetRegisterContext().get();
4866
4867 if (register_context)
4868 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4869 else
4870 ts.Printf("[ip unknown] ");
4871
4872 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4873 if (stop_info_sp)
4874 {
4875 const char *stop_desc = stop_info_sp->GetDescription();
4876 if (stop_desc)
4877 ts.PutCString (stop_desc);
4878 }
4879 ts.Printf(">");
4880 }
4881
4882 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00004883 }
Sean Callanana46ec452012-07-11 21:31:24 +00004884 } while (0);
4885
Jim Inghamcfc09352012-07-27 23:57:19 +00004886 if (event_explanation)
4887 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00004888 else
Jim Inghamcfc09352012-07-27 23:57:19 +00004889 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4890 }
4891
4892 if (discard_on_error && thread_plan_sp)
4893 {
4894 if (log)
4895 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4896 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4897 thread_plan_sp->SetPrivate (orig_plan_private);
4898 }
4899 else
4900 {
4901 if (log)
4902 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00004903 }
4904 }
4905 else if (return_value == eExecutionSetupError)
4906 {
4907 if (log)
4908 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004909
4910 if (discard_on_error && thread_plan_sp)
4911 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004912 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004913 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004914 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004915 }
4916 else
4917 {
Sean Callanana46ec452012-07-11 21:31:24 +00004918 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004919 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004920 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00004921 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4922 return_value = eExecutionCompleted;
4923 }
4924 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4925 {
4926 if (log)
4927 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4928 return_value = eExecutionDiscarded;
4929 }
4930 else
4931 {
4932 if (log)
4933 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4934 if (discard_on_error && thread_plan_sp)
4935 {
4936 if (log)
4937 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4938 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4939 thread_plan_sp->SetPrivate (orig_plan_private);
4940 }
4941 }
4942 }
4943
4944 // Thread we ran the function in may have gone away because we ran the target
4945 // Check that it's still there, and if it is put it back in the context. Also restore the
4946 // frame in the context if it is still present.
4947 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4948 if (thread)
4949 {
4950 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4951 }
4952
4953 // Also restore the current process'es selected frame & thread, since this function calling may
4954 // be done behind the user's back.
4955
4956 if (selected_tid != LLDB_INVALID_THREAD_ID)
4957 {
4958 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4959 {
4960 // We were able to restore the selected thread, now restore the frame:
4961 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4962 if (old_frame_sp)
4963 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004964 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004965 }
4966 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004967
Sean Callanana46ec452012-07-11 21:31:24 +00004968 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00004969
Sean Callanana46ec452012-07-11 21:31:24 +00004970 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004971 {
Sean Callanana46ec452012-07-11 21:31:24 +00004972 if (log)
4973 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4974 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004975 }
4976
4977 return return_value;
4978}
4979
4980const char *
4981Process::ExecutionResultAsCString (ExecutionResults result)
4982{
4983 const char *result_name;
4984
4985 switch (result)
4986 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004987 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004988 result_name = "eExecutionCompleted";
4989 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004990 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004991 result_name = "eExecutionDiscarded";
4992 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004993 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004994 result_name = "eExecutionInterrupted";
4995 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004996 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004997 result_name = "eExecutionSetupError";
4998 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004999 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005000 result_name = "eExecutionTimedOut";
5001 break;
5002 }
5003 return result_name;
5004}
5005
Greg Clayton7260f622011-04-18 08:33:37 +00005006void
5007Process::GetStatus (Stream &strm)
5008{
5009 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005010 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005011 {
5012 if (state == eStateExited)
5013 {
5014 int exit_status = GetExitStatus();
5015 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00005016 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005017 GetID(),
5018 exit_status,
5019 exit_status,
5020 exit_description ? exit_description : "");
5021 }
5022 else
5023 {
5024 if (state == eStateConnected)
5025 strm.Printf ("Connected to remote target.\n");
5026 else
Greg Clayton81c22f62011-10-19 18:09:39 +00005027 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005028 }
5029 }
5030 else
5031 {
Greg Clayton81c22f62011-10-19 18:09:39 +00005032 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005033 }
5034}
5035
5036size_t
5037Process::GetThreadStatus (Stream &strm,
5038 bool only_threads_with_stop_reason,
5039 uint32_t start_frame,
5040 uint32_t num_frames,
5041 uint32_t num_frames_with_source)
5042{
5043 size_t num_thread_infos_dumped = 0;
5044
Jim Ingham41f2b942012-09-10 20:50:15 +00005045 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005046 const size_t num_threads = GetThreadList().GetSize();
5047 for (uint32_t i = 0; i < num_threads; i++)
5048 {
5049 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5050 if (thread)
5051 {
5052 if (only_threads_with_stop_reason)
5053 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005054 StopInfoSP stop_info_sp = thread->GetStopInfo();
5055 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005056 continue;
5057 }
5058 thread->GetStatus (strm,
5059 start_frame,
5060 num_frames,
5061 num_frames_with_source);
5062 ++num_thread_infos_dumped;
5063 }
5064 }
5065 return num_thread_infos_dumped;
5066}
5067
Greg Claytona9f40ad2012-02-22 04:37:26 +00005068void
5069Process::AddInvalidMemoryRegion (const LoadRange &region)
5070{
5071 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5072}
5073
5074bool
5075Process::RemoveInvalidMemoryRange (const LoadRange &region)
5076{
5077 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5078}
5079
Jim Ingham372787f2012-04-07 00:00:41 +00005080void
5081Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5082{
5083 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5084}
5085
5086bool
5087Process::RunPreResumeActions ()
5088{
5089 bool result = true;
5090 while (!m_pre_resume_actions.empty())
5091 {
5092 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5093 m_pre_resume_actions.pop_back();
5094 bool this_result = action.callback (action.baton);
5095 if (result == true) result = this_result;
5096 }
5097 return result;
5098}
5099
5100void
5101Process::ClearPreResumeActions ()
5102{
5103 m_pre_resume_actions.clear();
5104}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005105
Greg Claytonfa559e52012-05-18 02:38:05 +00005106void
5107Process::Flush ()
5108{
5109 m_thread_list.Flush();
5110}