blob: 425274eef1b4b7da6ae863b55e1c73c9a9d36495 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malead891f9b2012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner24943d22010-06-08 16:52:24 +000012#include "lldb/Target/Process.h"
13
14#include "lldb/lldb-private-log.h"
15
16#include "lldb/Breakpoint/StoppointCallbackContext.h"
17#include "lldb/Breakpoint/BreakpointLocation.h"
18#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000021#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000022#include "lldb/Core/Log.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
25#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000026#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000027#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#include "lldb/Host/Host.h"
29#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000030#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000031#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000032#include "lldb/Target/LanguageRuntime.h"
33#include "lldb/Target/CPPLanguageRuntime.h"
34#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000035#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000037#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Target/Target.h"
39#include "lldb/Target/TargetList.h"
40#include "lldb/Target/Thread.h"
41#include "lldb/Target/ThreadPlan.h"
Jim Inghamd21d98b2012-04-10 01:21:57 +000042#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner24943d22010-06-08 16:52:24 +000043
44using namespace lldb;
45using namespace lldb_private;
46
Greg Clayton73844aa2012-08-22 17:17:09 +000047
48// Comment out line below to disable memory caching, overriding the process setting
49// target.process.disable-memory-cache
50#define ENABLE_MEMORY_CACHING
51
52#ifdef ENABLE_MEMORY_CACHING
53#define DISABLE_MEM_CACHE_DEFAULT false
54#else
55#define DISABLE_MEM_CACHE_DEFAULT true
56#endif
57
58class ProcessOptionValueProperties : public OptionValueProperties
59{
60public:
61 ProcessOptionValueProperties (const ConstString &name) :
62 OptionValueProperties (name)
63 {
64 }
65
66 // This constructor is used when creating ProcessOptionValueProperties when it
67 // is part of a new lldb_private::Process instance. It will copy all current
68 // global property values as needed
69 ProcessOptionValueProperties (ProcessProperties *global_properties) :
70 OptionValueProperties(*global_properties->GetValueProperties())
71 {
72 }
73
74 virtual const Property *
75 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
76 {
77 // When gettings the value for a key from the process options, we will always
78 // try and grab the setting from the current process if there is one. Else we just
79 // use the one from this instance.
80 if (exe_ctx)
81 {
82 Process *process = exe_ctx->GetProcessPtr();
83 if (process)
84 {
85 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
86 if (this != instance_properties)
87 return instance_properties->ProtectedGetPropertyAtIndex (idx);
88 }
89 }
90 return ProtectedGetPropertyAtIndex (idx);
91 }
92};
93
94static PropertyDefinition
95g_properties[] =
96{
97 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
Jim Inghamdacdc012012-11-29 00:41:12 +000098 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
99 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamb7940202013-01-15 02:47:48 +0000100 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
101 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
Greg Clayton507a6382012-11-29 18:48:47 +0000102 { "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 Clayton73844aa2012-08-22 17:17:09 +0000103 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
104};
105
106enum {
107 ePropertyDisableMemCache,
Greg Clayton2e7f3132012-10-18 22:40:37 +0000108 ePropertyExtraStartCommand,
Jim Inghamb7940202013-01-15 02:47:48 +0000109 ePropertyIgnoreBreakpointsInExpressions,
110 ePropertyUnwindOnErrorInExpressions,
Greg Clayton2e7f3132012-10-18 22:40:37 +0000111 ePropertyPythonOSPluginPath
Greg Clayton73844aa2012-08-22 17:17:09 +0000112};
113
114ProcessProperties::ProcessProperties (bool is_global) :
115 Properties ()
116{
117 if (is_global)
118 {
119 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
120 m_collection_sp->Initialize(g_properties);
121 m_collection_sp->AppendProperty(ConstString("thread"),
122 ConstString("Settings specify to threads."),
123 true,
124 Thread::GetGlobalProperties()->GetValueProperties());
125 }
126 else
127 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
128}
129
130ProcessProperties::~ProcessProperties()
131{
132}
133
134bool
135ProcessProperties::GetDisableMemoryCache() const
136{
137 const uint32_t idx = ePropertyDisableMemCache;
138 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
139}
140
141Args
142ProcessProperties::GetExtraStartupCommands () const
143{
144 Args args;
145 const uint32_t idx = ePropertyExtraStartCommand;
146 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
147 return args;
148}
149
150void
151ProcessProperties::SetExtraStartupCommands (const Args &args)
152{
153 const uint32_t idx = ePropertyExtraStartCommand;
154 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
155}
156
Greg Clayton2e7f3132012-10-18 22:40:37 +0000157FileSpec
158ProcessProperties::GetPythonOSPluginPath () const
159{
160 const uint32_t idx = ePropertyPythonOSPluginPath;
161 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
162}
163
164void
165ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
166{
167 const uint32_t idx = ePropertyPythonOSPluginPath;
168 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
169}
170
Jim Inghamb7940202013-01-15 02:47:48 +0000171
172bool
173ProcessProperties::GetIgnoreBreakpointsInExpressions () const
174{
175 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
176 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
177}
178
179void
180ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
181{
182 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
183 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
184}
185
186bool
187ProcessProperties::GetUnwindOnErrorInExpressions () const
188{
189 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
190 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
191}
192
193void
194ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
195{
196 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
197 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
198}
199
Greg Clayton24bc5d92011-03-30 18:16:51 +0000200void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000201ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000202{
203 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +0000204 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000205 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000206
207 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000208 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000209
210 if (m_executable)
211 {
212 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
213 s.PutCString (" file = ");
214 m_executable.Dump(&s);
215 s.EOL();
216 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000217 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000218 if (argc > 0)
219 {
220 for (uint32_t i=0; i<argc; i++)
221 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000222 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +0000223 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000224 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000225 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000226 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000227 }
228 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000229
230 const uint32_t envc = m_environment.GetArgumentCount();
231 if (envc > 0)
232 {
233 for (uint32_t i=0; i<envc; i++)
234 {
235 const char *env = m_environment.GetArgumentAtIndex(i);
236 if (i < 10)
237 s.Printf (" env[%u] = %s\n", i, env);
238 else
239 s.Printf ("env[%u] = %s\n", i, env);
240 }
241 }
242
Greg Claytonff39f742011-04-01 00:29:43 +0000243 if (m_arch.IsValid())
244 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
245
Greg Claytonb72d0f02011-04-12 05:54:46 +0000246 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000247 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000248 cstr = platform->GetUserName (m_uid);
249 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000250 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000251 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000252 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000253 cstr = platform->GetGroupName (m_gid);
254 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000255 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000256 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000257 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000258 cstr = platform->GetUserName (m_euid);
259 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000260 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000261 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000262 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000263 cstr = platform->GetGroupName (m_egid);
264 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000265 }
266}
267
268void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000269ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000270{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000271 const char *label;
272 if (show_args || verbose)
273 label = "ARGUMENTS";
274 else
275 label = "NAME";
276
Greg Claytonff39f742011-04-01 00:29:43 +0000277 if (verbose)
278 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000279 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000280 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
281 }
282 else
283 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000284 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000285 s.PutCString ("====== ====== ========== ======= ============================\n");
286 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000287}
288
289void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000290ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000291{
292 if (m_pid != LLDB_INVALID_PROCESS_ID)
293 {
294 const char *cstr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000295 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000296
Greg Clayton24bc5d92011-03-30 18:16:51 +0000297
Greg Claytonff39f742011-04-01 00:29:43 +0000298 if (verbose)
299 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000300 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000301 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
302 s.Printf ("%-10s ", cstr);
303 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000304 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000305
Greg Claytonb72d0f02011-04-12 05:54:46 +0000306 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000307 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
308 s.Printf ("%-10s ", cstr);
309 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000310 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000311
Greg Claytonb72d0f02011-04-12 05:54:46 +0000312 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000313 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
314 s.Printf ("%-10s ", cstr);
315 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000316 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000317
Greg Claytonb72d0f02011-04-12 05:54:46 +0000318 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000319 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
320 s.Printf ("%-10s ", cstr);
321 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000322 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000323 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
324 }
325 else
326 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000327 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000328 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000329 (int)m_arch.GetTriple().getArchName().size(),
330 m_arch.GetTriple().getArchName().data());
331 }
332
Greg Claytonb72d0f02011-04-12 05:54:46 +0000333 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000334 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000335 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000336 if (argc > 0)
337 {
338 for (uint32_t i=0; i<argc; i++)
339 {
340 if (i > 0)
341 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000342 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000343 }
344 }
345 }
346 else
347 {
348 s.PutCString (GetName());
349 }
350
351 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000352 }
353}
354
Greg Claytonb72d0f02011-04-12 05:54:46 +0000355
356void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000357ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000358{
359 m_arguments.SetArguments (argv);
360
361 // Is the first argument the executable?
362 if (first_arg_is_executable)
363 {
364 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
365 if (first_arg)
366 {
367 // Yes the first argument is an executable, set it as the executable
368 // in the launch options. Don't resolve the file path as the path
369 // could be a remote platform path
370 const bool resolve = false;
371 m_executable.SetFile(first_arg, resolve);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000372 }
373 }
374}
375void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000376ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000377{
378 // Copy all arguments
379 m_arguments = args;
380
381 // Is the first argument the executable?
382 if (first_arg_is_executable)
383 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000384 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000385 if (first_arg)
386 {
387 // Yes the first argument is an executable, set it as the executable
388 // in the launch options. Don't resolve the file path as the path
389 // could be a remote platform path
390 const bool resolve = false;
391 m_executable.SetFile(first_arg, resolve);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000392 }
393 }
394}
395
Greg Claytonabb33022011-11-08 02:43:13 +0000396void
Greg Clayton464c6162011-11-17 22:14:31 +0000397ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000398{
399 // If notthing was specified, then check the process for any default
400 // settings that were set with "settings set"
401 if (m_file_actions.empty())
402 {
Greg Claytonabb33022011-11-08 02:43:13 +0000403 if (m_flags.Test(eLaunchFlagDisableSTDIO))
404 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000405 AppendSuppressFileAction (STDIN_FILENO , true, false);
406 AppendSuppressFileAction (STDOUT_FILENO, false, true);
407 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000408 }
409 else
410 {
411 // Check for any values that might have gotten set with any of:
412 // (lldb) settings set target.input-path
413 // (lldb) settings set target.output-path
414 // (lldb) settings set target.error-path
Greg Clayton73844aa2012-08-22 17:17:09 +0000415 FileSpec in_path;
416 FileSpec out_path;
417 FileSpec err_path;
Greg Claytonabb33022011-11-08 02:43:13 +0000418 if (target)
419 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000420 in_path = target->GetStandardInputPath();
421 out_path = target->GetStandardOutputPath();
422 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000423 }
424
Greg Clayton73844aa2012-08-22 17:17:09 +0000425 if (in_path || out_path || err_path)
426 {
427 char path[PATH_MAX];
428 if (in_path && in_path.GetPath(path, sizeof(path)))
429 AppendOpenFileAction(STDIN_FILENO, path, true, false);
430
431 if (out_path && out_path.GetPath(path, sizeof(path)))
432 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
433
434 if (err_path && err_path.GetPath(path, sizeof(path)))
435 AppendOpenFileAction(STDERR_FILENO, path, false, true);
436 }
437 else if (default_to_use_pty)
Greg Clayton464c6162011-11-17 22:14:31 +0000438 {
439 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000440 {
Greg Clayton73844aa2012-08-22 17:17:09 +0000441 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
442 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
443 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
444 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000445 }
446 }
Greg Claytonabb33022011-11-08 02:43:13 +0000447 }
448 }
449}
450
Greg Clayton527154d2011-11-15 03:53:30 +0000451
452bool
Greg Clayton97471182012-04-14 01:42:46 +0000453ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
454 bool localhost,
455 bool will_debug,
456 bool first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000457{
458 error.Clear();
459
460 if (GetFlags().Test (eLaunchFlagLaunchInShell))
461 {
462 const char *shell_executable = GetShell();
463 if (shell_executable)
464 {
465 char shell_resolved_path[PATH_MAX];
466
467 if (localhost)
468 {
469 FileSpec shell_filespec (shell_executable, true);
470
471 if (!shell_filespec.Exists())
472 {
473 // Resolve the path in case we just got "bash", "sh" or "tcsh"
474 if (!shell_filespec.ResolveExecutableLocation ())
475 {
476 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
477 return false;
478 }
479 }
480 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
481 shell_executable = shell_resolved_path;
482 }
483
Greg Clayton0c8446c2012-10-17 22:57:12 +0000484 const char **argv = GetArguments().GetConstArgumentVector ();
485 if (argv == NULL || argv[0] == NULL)
486 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000487 Args shell_arguments;
488 std::string safe_arg;
489 shell_arguments.AppendArgument (shell_executable);
Greg Clayton527154d2011-11-15 03:53:30 +0000490 shell_arguments.AppendArgument ("-c");
Greg Clayton97471182012-04-14 01:42:46 +0000491 StreamString shell_command;
492 if (will_debug)
Greg Clayton527154d2011-11-15 03:53:30 +0000493 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000494 // Add a modified PATH environment variable in case argv[0]
495 // is a relative path
496 const char *argv0 = argv[0];
497 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
498 {
499 // We have a relative path to our executable which may not work if
500 // we just try to run "a.out" (without it being converted to "./a.out")
501 const char *working_dir = GetWorkingDirectory();
502 std::string new_path("PATH=");
503 const size_t empty_path_len = new_path.size();
504
505 if (working_dir && working_dir[0])
506 {
507 new_path += working_dir;
508 }
509 else
510 {
511 char current_working_dir[PATH_MAX];
512 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
513 if (cwd && cwd[0])
514 new_path += cwd;
515 }
516 const char *curr_path = getenv("PATH");
517 if (curr_path)
518 {
519 if (new_path.size() > empty_path_len)
520 new_path += ':';
521 new_path += curr_path;
522 }
523 new_path += ' ';
524 shell_command.PutCString(new_path.c_str());
525 }
526
Greg Clayton97471182012-04-14 01:42:46 +0000527 shell_command.PutCString ("exec");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000528
529#if defined(__APPLE__)
530 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Clayton97471182012-04-14 01:42:46 +0000531 if (GetArchitecture().IsValid())
532 {
533 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton0c8446c2012-10-17 22:57:12 +0000534 // Set the resume count to 2:
Greg Clayton97471182012-04-14 01:42:46 +0000535 // 1 - stop in shell
536 // 2 - stop in /usr/bin/arch
537 // 3 - then we will stop in our program
538 SetResumeCount(2);
539 }
540 else
541 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000542 // Set the resume count to 1:
Greg Clayton97471182012-04-14 01:42:46 +0000543 // 1 - stop in shell
544 // 2 - then we will stop in our program
545 SetResumeCount(1);
546 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000547#else
548 // Set the resume count to 1:
549 // 1 - stop in shell
550 // 2 - then we will stop in our program
551 SetResumeCount(1);
552#endif
Greg Clayton527154d2011-11-15 03:53:30 +0000553 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000554
555 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000556 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000557 // There should only be one argument that is the shell command itself to be used as is
558 if (argv[0] && !argv[1])
559 shell_command.Printf("%s", argv[0]);
Greg Clayton97471182012-04-14 01:42:46 +0000560 else
Greg Clayton0c8446c2012-10-17 22:57:12 +0000561 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000562 }
Greg Clayton97471182012-04-14 01:42:46 +0000563 else
564 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000565 for (size_t i=0; argv[i] != NULL; ++i)
566 {
567 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
568 shell_command.Printf(" %s", arg);
569 }
Greg Clayton97471182012-04-14 01:42:46 +0000570 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000571 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000572 m_executable.SetFile(shell_executable, false);
573 m_arguments = shell_arguments;
574 return true;
575 }
576 else
577 {
578 error.SetErrorString ("invalid shell path");
579 }
580 }
581 else
582 {
583 error.SetErrorString ("not launching in shell");
584 }
585 return false;
586}
587
588
Greg Clayton24bc5d92011-03-30 18:16:51 +0000589bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000590ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
591{
592 if ((read || write) && fd >= 0 && path && path[0])
593 {
594 m_action = eFileActionOpen;
595 m_fd = fd;
596 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000597 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000598 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000599 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000600 else
Greg Clayton527154d2011-11-15 03:53:30 +0000601 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000602 m_path.assign (path);
603 return true;
604 }
605 else
606 {
607 Clear();
608 }
609 return false;
610}
611
612bool
613ProcessLaunchInfo::FileAction::Close (int fd)
614{
615 Clear();
616 if (fd >= 0)
617 {
618 m_action = eFileActionClose;
619 m_fd = fd;
620 }
621 return m_fd >= 0;
622}
623
624
625bool
626ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
627{
628 Clear();
629 if (fd >= 0 && dup_fd >= 0)
630 {
631 m_action = eFileActionDuplicate;
632 m_fd = fd;
633 m_arg = dup_fd;
634 }
635 return m_fd >= 0;
636}
637
638
639
640bool
641ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
642 const FileAction *info,
643 Log *log,
644 Error& error)
645{
646 if (info == NULL)
647 return false;
648
649 switch (info->m_action)
650 {
651 case eFileActionNone:
652 error.Clear();
653 break;
654
655 case eFileActionClose:
656 if (info->m_fd == -1)
657 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
658 else
659 {
660 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
661 eErrorTypePOSIX);
662 if (log && (error.Fail() || log))
663 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
664 file_actions, info->m_fd);
665 }
666 break;
667
668 case eFileActionDuplicate:
669 if (info->m_fd == -1)
670 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
671 else if (info->m_arg == -1)
672 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
673 else
674 {
675 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
676 eErrorTypePOSIX);
677 if (log && (error.Fail() || log))
678 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
679 file_actions, info->m_fd, info->m_arg);
680 }
681 break;
682
683 case eFileActionOpen:
684 if (info->m_fd == -1)
685 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
686 else
687 {
688 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000689
Greg Claytonb72d0f02011-04-12 05:54:46 +0000690 mode_t mode = 0;
691
Greg Clayton527154d2011-11-15 03:53:30 +0000692 if (oflag & O_CREAT)
693 mode = 0640;
694
Greg Claytonb72d0f02011-04-12 05:54:46 +0000695 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
696 info->m_fd,
697 info->m_path.c_str(),
698 oflag,
699 mode),
700 eErrorTypePOSIX);
701 if (error.Fail() || log)
702 error.PutToLog(log,
703 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
704 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
705 }
706 break;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000707 }
708 return error.Success();
709}
710
711Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000712ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000713{
714 Error error;
Greg Clayton6475c422012-12-04 00:32:51 +0000715 const int short_option = m_getopt_table[option_idx].val;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000716
717 switch (short_option)
718 {
719 case 's': // Stop at program entry point
720 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
721 break;
722
Greg Claytonb72d0f02011-04-12 05:54:46 +0000723 case 'i': // STDIN for read only
724 {
725 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000726 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000727 launch_info.AppendFileAction (action);
728 }
729 break;
730
731 case 'o': // Open STDOUT for write only
732 {
733 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000734 if (action.Open (STDOUT_FILENO, option_arg, false, true))
735 launch_info.AppendFileAction (action);
736 }
737 break;
738
739 case 'e': // STDERR for write only
740 {
741 ProcessLaunchInfo::FileAction action;
742 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000743 launch_info.AppendFileAction (action);
744 }
745 break;
746
Greg Clayton95ec1682012-03-06 04:01:04 +0000747
Greg Claytonb72d0f02011-04-12 05:54:46 +0000748 case 'p': // Process plug-in name
749 launch_info.SetProcessPluginName (option_arg);
750 break;
751
752 case 'n': // Disable STDIO
753 {
754 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000755 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000756 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000757 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000758 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000759 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000760 launch_info.AppendFileAction (action);
761 }
762 break;
763
764 case 'w':
765 launch_info.SetWorkingDirectory (option_arg);
766 break;
767
768 case 't': // Open process in new terminal window
769 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
770 break;
771
772 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000773 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
774 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000775 break;
776
777 case 'A':
778 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
779 break;
780
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000781 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000782 if (option_arg && option_arg[0])
783 launch_info.SetShell (option_arg);
784 else
785 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000786 break;
787
Greg Claytonb72d0f02011-04-12 05:54:46 +0000788 case 'v':
789 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
790 break;
791
792 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000793 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000794 break;
795
796 }
797 return error;
798}
799
800OptionDefinition
801ProcessLaunchCommandOptions::g_option_table[] =
802{
803{ 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."},
804{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
805{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
Sean Callanan9a91ef62012-10-24 01:12:14 +0000806{ 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 Claytonb72d0f02011-04-12 05:54:46 +0000807{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
808{ 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 Callanan9a91ef62012-10-24 01:12:14 +0000809{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000810
Sean Callanan9a91ef62012-10-24 01:12:14 +0000811{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
812{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
813{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000814
815{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
816
817{ 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."},
818
819{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
820};
821
822
823
824bool
825ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000826{
827 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
828 return true;
829 const char *match_name = m_match_info.GetName();
830 if (!match_name)
831 return true;
832
833 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
834}
835
836bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000837ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000838{
839 if (!NameMatches (proc_info.GetName()))
840 return false;
841
842 if (m_match_info.ProcessIDIsValid() &&
843 m_match_info.GetProcessID() != proc_info.GetProcessID())
844 return false;
845
846 if (m_match_info.ParentProcessIDIsValid() &&
847 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
848 return false;
849
Greg Claytonb72d0f02011-04-12 05:54:46 +0000850 if (m_match_info.UserIDIsValid () &&
851 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000852 return false;
853
Greg Claytonb72d0f02011-04-12 05:54:46 +0000854 if (m_match_info.GroupIDIsValid () &&
855 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000856 return false;
857
858 if (m_match_info.EffectiveUserIDIsValid () &&
859 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
860 return false;
861
862 if (m_match_info.EffectiveGroupIDIsValid () &&
863 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
864 return false;
865
866 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callanan40e278c2012-12-13 22:07:14 +0000867 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton24bc5d92011-03-30 18:16:51 +0000868 return false;
869 return true;
870}
871
872bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000873ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000874{
875 if (m_name_match_type != eNameMatchIgnore)
876 return false;
877
878 if (m_match_info.ProcessIDIsValid())
879 return false;
880
881 if (m_match_info.ParentProcessIDIsValid())
882 return false;
883
Greg Claytonb72d0f02011-04-12 05:54:46 +0000884 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000885 return false;
886
Greg Claytonb72d0f02011-04-12 05:54:46 +0000887 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000888 return false;
889
890 if (m_match_info.EffectiveUserIDIsValid ())
891 return false;
892
893 if (m_match_info.EffectiveGroupIDIsValid ())
894 return false;
895
896 if (m_match_info.GetArchitecture().IsValid())
897 return false;
898
899 if (m_match_all_users)
900 return false;
901
902 return true;
903
904}
905
906void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000907ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000908{
909 m_match_info.Clear();
910 m_name_match_type = eNameMatchIgnore;
911 m_match_all_users = false;
912}
Greg Claytonfd119992011-01-07 06:08:19 +0000913
Greg Clayton46c9a352012-02-09 06:16:32 +0000914ProcessSP
915Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000916{
Greg Clayton64742742013-01-16 17:29:04 +0000917 static uint32_t g_process_unique_id = 0;
918
Greg Clayton46c9a352012-02-09 06:16:32 +0000919 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000920 ProcessCreateInstance create_callback = NULL;
921 if (plugin_name)
922 {
923 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
924 if (create_callback)
925 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000926 process_sp = create_callback(target, listener, crash_file_path);
927 if (process_sp)
928 {
Greg Clayton64742742013-01-16 17:29:04 +0000929 if (process_sp->CanDebug(target, true))
930 {
931 process_sp->m_process_unique_id = ++g_process_unique_id;
932 }
933 else
Greg Clayton46c9a352012-02-09 06:16:32 +0000934 process_sp.reset();
935 }
Chris Lattner24943d22010-06-08 16:52:24 +0000936 }
937 }
938 else
939 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000940 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000941 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000942 process_sp = create_callback(target, listener, crash_file_path);
943 if (process_sp)
944 {
Greg Clayton64742742013-01-16 17:29:04 +0000945 if (process_sp->CanDebug(target, false))
946 {
947 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Clayton46c9a352012-02-09 06:16:32 +0000948 break;
Greg Clayton64742742013-01-16 17:29:04 +0000949 }
950 else
951 process_sp.reset();
Greg Clayton46c9a352012-02-09 06:16:32 +0000952 }
Chris Lattner24943d22010-06-08 16:52:24 +0000953 }
954 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000955 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000956}
957
Jim Ingham5a15e692012-02-16 06:50:00 +0000958ConstString &
959Process::GetStaticBroadcasterClass ()
960{
961 static ConstString class_name ("lldb.process");
962 return class_name;
963}
Chris Lattner24943d22010-06-08 16:52:24 +0000964
965//----------------------------------------------------------------------
966// Process constructor
967//----------------------------------------------------------------------
968Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +0000969 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +0000970 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000971 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +0000972 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000973 m_public_state (eStateUnloaded),
974 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000975 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
976 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000977 m_private_state_listener ("lldb.process.internal_state_listener"),
978 m_private_state_control_wait(),
979 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000980 m_mod_id (),
Greg Clayton64742742013-01-16 17:29:04 +0000981 m_process_unique_id(0),
Chris Lattner24943d22010-06-08 16:52:24 +0000982 m_thread_index_id (0),
Han Ming Ongccd5c4e2013-01-08 22:10:01 +0000983 m_thread_id_to_index_id_map (),
Chris Lattner24943d22010-06-08 16:52:24 +0000984 m_exit_status (-1),
985 m_exit_string (),
986 m_thread_list (this),
987 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000988 m_image_tokens (),
989 m_listener (listener),
990 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000991 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000992 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000993 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000994 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000995 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000996 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000997 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000998 m_stderr_data (),
Han Ming Ongfb9cee62012-11-17 00:21:04 +0000999 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1000 m_profile_data (),
Greg Clayton613b8732011-05-17 03:37:42 +00001001 m_memory_cache (*this),
1002 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +00001003 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +00001004 m_next_event_action_ap(),
Bill Wendlingce96dad2012-04-06 00:10:21 +00001005 m_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +00001006 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001007 m_finalize_called(false),
Bill Wendlingce96dad2012-04-06 00:10:21 +00001008 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +00001009{
Jim Ingham5a15e692012-02-16 06:50:00 +00001010 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +00001011
Greg Claytone005f2c2010-11-06 01:53:30 +00001012 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001013 if (log)
1014 log->Printf ("%p Process::Process()", this);
1015
Greg Clayton49ce6822010-10-31 03:01:06 +00001016 SetEventName (eBroadcastBitStateChanged, "state-changed");
1017 SetEventName (eBroadcastBitInterrupt, "interrupt");
1018 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1019 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001020 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Clayton49ce6822010-10-31 03:01:06 +00001021
Greg Clayton84332782012-10-29 20:52:08 +00001022 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1023 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1024 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1025
Chris Lattner24943d22010-06-08 16:52:24 +00001026 listener.StartListeningForEvents (this,
1027 eBroadcastBitStateChanged |
1028 eBroadcastBitInterrupt |
1029 eBroadcastBitSTDOUT |
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001030 eBroadcastBitSTDERR |
1031 eBroadcastBitProfileData);
Chris Lattner24943d22010-06-08 16:52:24 +00001032
1033 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001034 eBroadcastBitStateChanged |
1035 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +00001036
1037 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1038 eBroadcastInternalStateControlStop |
1039 eBroadcastInternalStateControlPause |
1040 eBroadcastInternalStateControlResume);
1041}
1042
1043//----------------------------------------------------------------------
1044// Destructor
1045//----------------------------------------------------------------------
1046Process::~Process()
1047{
Greg Claytone005f2c2010-11-06 01:53:30 +00001048 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001049 if (log)
1050 log->Printf ("%p Process::~Process()", this);
1051 StopPrivateStateThread();
1052}
1053
Greg Clayton73844aa2012-08-22 17:17:09 +00001054const ProcessPropertiesSP &
1055Process::GetGlobalProperties()
1056{
1057 static ProcessPropertiesSP g_settings_sp;
1058 if (!g_settings_sp)
1059 g_settings_sp.reset (new ProcessProperties (true));
1060 return g_settings_sp;
1061}
1062
Chris Lattner24943d22010-06-08 16:52:24 +00001063void
1064Process::Finalize()
1065{
Greg Claytonffa43a62011-11-17 04:46:02 +00001066 switch (GetPrivateState())
1067 {
1068 case eStateConnected:
1069 case eStateAttaching:
1070 case eStateLaunching:
1071 case eStateStopped:
1072 case eStateRunning:
1073 case eStateStepping:
1074 case eStateCrashed:
1075 case eStateSuspended:
1076 if (GetShouldDetach())
1077 Detach();
1078 else
1079 Destroy();
1080 break;
1081
1082 case eStateInvalid:
1083 case eStateUnloaded:
1084 case eStateDetached:
1085 case eStateExited:
1086 break;
1087 }
1088
Greg Clayton2f57db02011-10-01 00:45:15 +00001089 // Clear our broadcaster before we proceed with destroying
1090 Broadcaster::Clear();
1091
Chris Lattner24943d22010-06-08 16:52:24 +00001092 // Do any cleanup needed prior to being destructed... Subclasses
1093 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001094
1095 // We need to destroy the loader before the derived Process class gets destroyed
1096 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001097 m_dynamic_checkers_ap.reset();
1098 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001099 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001100 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001101 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001102 std::vector<Notifications> empty_notifications;
1103 m_notifications.swap(empty_notifications);
1104 m_image_tokens.clear();
1105 m_memory_cache.Clear();
1106 m_allocated_memory_cache.Clear();
1107 m_language_runtimes.clear();
1108 m_next_event_action_ap.reset();
Greg Clayton84332782012-10-29 20:52:08 +00001109//#ifdef LLDB_CONFIGURATION_DEBUG
1110// StreamFile s(stdout, false);
1111// EventSP event_sp;
1112// while (m_private_state_listener.GetNextEvent(event_sp))
1113// {
1114// event_sp->Dump (&s);
1115// s.EOL();
1116// }
1117//#endif
1118 // We have to be very careful here as the m_private_state_listener might
1119 // contain events that have ProcessSP values in them which can keep this
1120 // process around forever. These events need to be cleared out.
1121 m_private_state_listener.Clear();
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001122 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001123}
1124
1125void
1126Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1127{
1128 m_notifications.push_back(callbacks);
1129 if (callbacks.initialize != NULL)
1130 callbacks.initialize (callbacks.baton, this);
1131}
1132
1133bool
1134Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1135{
1136 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1137 for (pos = m_notifications.begin(); pos != end; ++pos)
1138 {
1139 if (pos->baton == callbacks.baton &&
1140 pos->initialize == callbacks.initialize &&
1141 pos->process_state_changed == callbacks.process_state_changed)
1142 {
1143 m_notifications.erase(pos);
1144 return true;
1145 }
1146 }
1147 return false;
1148}
1149
1150void
1151Process::SynchronouslyNotifyStateChanged (StateType state)
1152{
1153 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1154 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1155 {
1156 if (notification_pos->process_state_changed)
1157 notification_pos->process_state_changed (notification_pos->baton, this, state);
1158 }
1159}
1160
1161// FIXME: We need to do some work on events before the general Listener sees them.
1162// For instance if we are continuing from a breakpoint, we need to ensure that we do
1163// the little "insert real insn, step & stop" trick. But we can't do that when the
1164// event is delivered by the broadcaster - since that is done on the thread that is
1165// waiting for new events, so if we needed more than one event for our handling, we would
1166// stall. So instead we do it when we fetch the event off of the queue.
1167//
1168
1169StateType
1170Process::GetNextEvent (EventSP &event_sp)
1171{
1172 StateType state = eStateInvalid;
1173
1174 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1175 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1176
1177 return state;
1178}
1179
1180
1181StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001182Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001183{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001184 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1185 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1186 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001187 if (event_sp_ptr)
1188 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001189 StateType state = GetState();
1190 // If we are exited or detached, we won't ever get back to any
1191 // other valid state...
1192 if (state == eStateDetached || state == eStateExited)
1193 return state;
1194
1195 while (state != eStateInvalid)
1196 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001197 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001198 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001199 if (event_sp_ptr && event_sp)
1200 *event_sp_ptr = event_sp;
1201
Jim Ingham21f37ad2011-08-09 02:12:22 +00001202 switch (state)
1203 {
1204 case eStateCrashed:
1205 case eStateDetached:
1206 case eStateExited:
1207 case eStateUnloaded:
1208 return state;
1209 case eStateStopped:
1210 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1211 continue;
1212 else
1213 return state;
1214 default:
1215 continue;
1216 }
1217 }
1218 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001219}
1220
1221
1222StateType
1223Process::WaitForState
1224(
1225 const TimeValue *timeout,
1226 const StateType *match_states, const uint32_t num_match_states
1227)
1228{
1229 EventSP event_sp;
1230 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001231 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001232 while (state != eStateInvalid)
1233 {
Greg Claytond8c62532010-10-07 04:19:01 +00001234 // If we are exited or detached, we won't ever get back to any
1235 // other valid state...
1236 if (state == eStateDetached || state == eStateExited)
1237 return state;
1238
Chris Lattner24943d22010-06-08 16:52:24 +00001239 state = WaitForStateChangedEvents (timeout, event_sp);
1240
1241 for (i=0; i<num_match_states; ++i)
1242 {
1243 if (match_states[i] == state)
1244 return state;
1245 }
1246 }
1247 return state;
1248}
1249
Jim Ingham63e24d72010-10-11 23:53:14 +00001250bool
1251Process::HijackProcessEvents (Listener *listener)
1252{
1253 if (listener != NULL)
1254 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001255 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001256 }
1257 else
1258 return false;
1259}
1260
1261void
1262Process::RestoreProcessEvents ()
1263{
1264 RestoreBroadcaster();
1265}
1266
Jim Inghamf9f40c22011-02-08 05:20:59 +00001267bool
1268Process::HijackPrivateProcessEvents (Listener *listener)
1269{
1270 if (listener != NULL)
1271 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001272 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001273 }
1274 else
1275 return false;
1276}
1277
1278void
1279Process::RestorePrivateProcessEvents ()
1280{
1281 m_private_state_broadcaster.RestoreBroadcaster();
1282}
1283
Chris Lattner24943d22010-06-08 16:52:24 +00001284StateType
1285Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1286{
Greg Claytone005f2c2010-11-06 01:53:30 +00001287 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001288
1289 if (log)
1290 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1291
1292 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001293 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1294 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001295 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001296 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001297 {
1298 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1299 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1300 else if (log)
1301 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1302 }
Chris Lattner24943d22010-06-08 16:52:24 +00001303
1304 if (log)
1305 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1306 __FUNCTION__,
1307 timeout,
1308 StateAsCString(state));
1309 return state;
1310}
1311
1312Event *
1313Process::PeekAtStateChangedEvents ()
1314{
Greg Claytone005f2c2010-11-06 01:53:30 +00001315 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001316
1317 if (log)
1318 log->Printf ("Process::%s...", __FUNCTION__);
1319
1320 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001321 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1322 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001323 if (log)
1324 {
1325 if (event_ptr)
1326 {
1327 log->Printf ("Process::%s (event_ptr) => %s",
1328 __FUNCTION__,
1329 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1330 }
1331 else
1332 {
1333 log->Printf ("Process::%s no events found",
1334 __FUNCTION__);
1335 }
1336 }
1337 return event_ptr;
1338}
1339
1340StateType
1341Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1342{
Greg Claytone005f2c2010-11-06 01:53:30 +00001343 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001344
1345 if (log)
1346 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1347
1348 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001349 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1350 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001351 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001352 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001353 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1354 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001355
1356 // This is a bit of a hack, but when we wait here we could very well return
1357 // to the command-line, and that could disable the log, which would render the
1358 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001359 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001360 {
1361 if (state == eStateInvalid)
1362 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1363 else
1364 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1365 }
Chris Lattner24943d22010-06-08 16:52:24 +00001366 return state;
1367}
1368
1369bool
1370Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1371{
Greg Claytone005f2c2010-11-06 01:53:30 +00001372 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001373
1374 if (log)
1375 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1376
1377 if (control_only)
1378 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1379 else
1380 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1381}
1382
1383bool
1384Process::IsRunning () const
1385{
1386 return StateIsRunningState (m_public_state.GetValue());
1387}
1388
1389int
1390Process::GetExitStatus ()
1391{
1392 if (m_public_state.GetValue() == eStateExited)
1393 return m_exit_status;
1394 return -1;
1395}
1396
Greg Clayton638351a2010-12-04 00:10:17 +00001397
Chris Lattner24943d22010-06-08 16:52:24 +00001398const char *
1399Process::GetExitDescription ()
1400{
1401 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1402 return m_exit_string.c_str();
1403 return NULL;
1404}
1405
Greg Clayton72e1c782011-01-22 23:43:18 +00001406bool
Chris Lattner24943d22010-06-08 16:52:24 +00001407Process::SetExitStatus (int status, const char *cstr)
1408{
Greg Clayton68ca8232011-01-25 02:58:48 +00001409 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1410 if (log)
1411 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1412 status, status,
1413 cstr ? "\"" : "",
1414 cstr ? cstr : "NULL",
1415 cstr ? "\"" : "");
1416
Greg Clayton72e1c782011-01-22 23:43:18 +00001417 // We were already in the exited state
1418 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001419 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001420 if (log)
1421 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001422 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001423 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001424
1425 m_exit_status = status;
1426 if (cstr)
1427 m_exit_string = cstr;
1428 else
1429 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001430
Greg Clayton72e1c782011-01-22 23:43:18 +00001431 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001432
Greg Clayton72e1c782011-01-22 23:43:18 +00001433 SetPrivateState (eStateExited);
1434 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001435}
1436
1437// This static callback can be used to watch for local child processes on
1438// the current host. The the child process exits, the process will be
1439// found in the global target list (we want to be completely sure that the
1440// lldb_private::Process doesn't go away before we can deliver the signal.
1441bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001442Process::SetProcessExitStatus (void *callback_baton,
1443 lldb::pid_t pid,
1444 bool exited,
1445 int signo, // Zero for no signal
1446 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001447)
1448{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001449 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1450 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001451 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001452 callback_baton,
1453 pid,
1454 exited,
1455 signo,
1456 exit_status);
1457
1458 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001459 {
Greg Clayton63094e02010-06-23 01:19:29 +00001460 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001461 if (target_sp)
1462 {
1463 ProcessSP process_sp (target_sp->GetProcessSP());
1464 if (process_sp)
1465 {
1466 const char *signal_cstr = NULL;
1467 if (signo)
1468 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1469
1470 process_sp->SetExitStatus (exit_status, signal_cstr);
1471 }
1472 }
1473 return true;
1474 }
1475 return false;
1476}
1477
1478
Greg Clayton37f962e2011-08-22 02:49:39 +00001479void
1480Process::UpdateThreadListIfNeeded ()
1481{
1482 const uint32_t stop_id = GetStopID();
1483 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1484 {
Greg Clayton20206082011-11-17 01:23:07 +00001485 const StateType state = GetPrivateState();
1486 if (StateIsStoppedState (state, true))
1487 {
1488 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001489 // m_thread_list does have its own mutex, but we need to
1490 // hold onto the mutex between the call to UpdateThreadList(...)
1491 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001492 ThreadList new_thread_list(this);
1493 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001494 // thread list, but only update if "true" is returned
1495 if (UpdateThreadList (m_thread_list, new_thread_list))
1496 {
1497 OperatingSystem *os = GetOperatingSystem ();
1498 if (os)
1499 os->UpdateThreadList (m_thread_list, new_thread_list);
1500 m_thread_list.Update (new_thread_list);
1501 m_thread_list.SetStopID (stop_id);
1502 }
Greg Clayton20206082011-11-17 01:23:07 +00001503 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001504 }
1505}
1506
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001507// This is obsoleted. Staged removal for Xcode.
Chris Lattner24943d22010-06-08 16:52:24 +00001508uint32_t
1509Process::GetNextThreadIndexID ()
1510{
1511 return ++m_thread_index_id;
1512}
1513
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001514uint32_t
1515Process::GetNextThreadIndexID (uint64_t thread_id)
1516{
1517 return AssignIndexIDToThread(thread_id);
1518}
1519
1520bool
1521Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1522{
1523 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1524 if (iterator == m_thread_id_to_index_id_map.end())
1525 {
1526 return false;
1527 }
1528 else
1529 {
1530 return true;
1531 }
1532}
1533
1534uint32_t
1535Process::AssignIndexIDToThread(uint64_t thread_id)
1536{
1537 uint32_t result = 0;
1538 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1539 if (iterator == m_thread_id_to_index_id_map.end())
1540 {
1541 result = ++m_thread_index_id;
1542 m_thread_id_to_index_id_map[thread_id] = result;
1543 }
1544 else
1545 {
1546 result = iterator->second;
1547 }
1548
1549 return result;
1550}
1551
Chris Lattner24943d22010-06-08 16:52:24 +00001552StateType
1553Process::GetState()
1554{
1555 // If any other threads access this we will need a mutex for it
1556 return m_public_state.GetValue ();
1557}
1558
1559void
1560Process::SetPublicState (StateType new_state)
1561{
Greg Clayton68ca8232011-01-25 02:58:48 +00001562 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001563 if (log)
1564 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001565 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001566 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001567
1568 // On the transition from Run to Stopped, we unlock the writer end of the
1569 // run lock. The lock gets locked in Resume, which is the public API
1570 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001571 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1572 {
Sean Callanana3772862012-06-02 01:16:20 +00001573 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001574 {
Sean Callanana3772862012-06-02 01:16:20 +00001575 if (log)
1576 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1577 m_run_lock.WriteUnlock();
1578 }
1579 else
1580 {
1581 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1582 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1583 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001584 {
Sean Callanana3772862012-06-02 01:16:20 +00001585 if (new_state_is_stopped)
1586 {
1587 if (log)
1588 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1589 m_run_lock.WriteUnlock();
1590 }
Greg Claytona894fe72012-04-05 16:12:35 +00001591 }
Greg Claytona894fe72012-04-05 16:12:35 +00001592 }
1593 }
Chris Lattner24943d22010-06-08 16:52:24 +00001594}
1595
Jim Ingham027aaa72012-04-19 01:40:33 +00001596Error
1597Process::Resume ()
1598{
1599 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1600 if (log)
1601 log->Printf("Process::Resume -- locking run lock");
1602 if (!m_run_lock.WriteTryLock())
1603 {
1604 Error error("Resume request failed - process still running.");
1605 if (log)
1606 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1607 return error;
1608 }
1609 return PrivateResume();
1610}
1611
Chris Lattner24943d22010-06-08 16:52:24 +00001612StateType
1613Process::GetPrivateState ()
1614{
1615 return m_private_state.GetValue();
1616}
1617
1618void
1619Process::SetPrivateState (StateType new_state)
1620{
Greg Clayton68ca8232011-01-25 02:58:48 +00001621 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001622 bool state_changed = false;
1623
1624 if (log)
1625 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1626
1627 Mutex::Locker locker(m_private_state.GetMutex());
1628
1629 const StateType old_state = m_private_state.GetValueNoLock ();
1630 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001631 // This code is left commented out in case we ever need to control
1632 // the private process state with another run lock. Right now it doesn't
1633 // seem like we need to do this, but if we ever do, we can uncomment and
1634 // use this code.
1635// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1636// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1637// if (old_state_is_stopped != new_state_is_stopped)
1638// {
1639// if (new_state_is_stopped)
1640// m_private_run_lock.WriteUnlock();
1641// else
1642// m_private_run_lock.WriteLock();
1643// }
1644
Chris Lattner24943d22010-06-08 16:52:24 +00001645 if (state_changed)
1646 {
1647 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001648 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001649 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001650 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001651 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001652 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001653 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001654 }
1655 // Use our target to get a shared pointer to ourselves...
Greg Clayton84332782012-10-29 20:52:08 +00001656 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1657 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1658 else
1659 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001660 }
1661 else
1662 {
1663 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001664 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001665 }
1666}
1667
Jim Ingham0296fe72011-11-08 03:00:11 +00001668void
1669Process::SetRunningUserExpression (bool on)
1670{
1671 m_mod_id.SetRunningUserExpression (on);
1672}
1673
Chris Lattner24943d22010-06-08 16:52:24 +00001674addr_t
1675Process::GetImageInfoAddress()
1676{
1677 return LLDB_INVALID_ADDRESS;
1678}
1679
Greg Clayton0baa3942010-11-04 01:54:29 +00001680//----------------------------------------------------------------------
1681// LoadImage
1682//
1683// This function provides a default implementation that works for most
1684// unix variants. Any Process subclasses that need to do shared library
1685// loading differently should override LoadImage and UnloadImage and
1686// do what is needed.
1687//----------------------------------------------------------------------
1688uint32_t
1689Process::LoadImage (const FileSpec &image_spec, Error &error)
1690{
Greg Clayton77d40712012-04-18 00:05:19 +00001691 char path[PATH_MAX];
1692 image_spec.GetPath(path, sizeof(path));
1693
Greg Clayton0baa3942010-11-04 01:54:29 +00001694 DynamicLoader *loader = GetDynamicLoader();
1695 if (loader)
1696 {
1697 error = loader->CanLoadImage();
1698 if (error.Fail())
1699 return LLDB_INVALID_IMAGE_TOKEN;
1700 }
1701
1702 if (error.Success())
1703 {
1704 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001705
1706 if (thread_sp)
1707 {
1708 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1709
1710 if (frame_sp)
1711 {
1712 ExecutionContext exe_ctx;
1713 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001714 const bool unwind_on_error = true;
1715 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001716 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001717 expr.Printf("dlopen (\"%s\", 2)", path);
1718 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001719 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001720 ClangUserExpression::Evaluate (exe_ctx,
1721 eExecutionPolicyAlways,
1722 lldb::eLanguageTypeUnknown,
1723 ClangUserExpression::eResultTypeAny,
1724 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001725 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001726 expr.GetData(),
1727 prefix,
1728 result_valobj_sp,
1729 true,
1730 ClangUserExpression::kDefaultTimeout);
Johnny Chenb14ec342011-09-09 00:01:43 +00001731 error = result_valobj_sp->GetError();
1732 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001733 {
1734 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001735 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001736 {
1737 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1738 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1739 {
1740 uint32_t image_token = m_image_tokens.size();
1741 m_image_tokens.push_back (image_ptr);
1742 return image_token;
1743 }
1744 }
1745 }
1746 }
1747 }
1748 }
Greg Clayton77d40712012-04-18 00:05:19 +00001749 if (!error.AsCString())
1750 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001751 return LLDB_INVALID_IMAGE_TOKEN;
1752}
1753
1754//----------------------------------------------------------------------
1755// UnloadImage
1756//
1757// This function provides a default implementation that works for most
1758// unix variants. Any Process subclasses that need to do shared library
1759// loading differently should override LoadImage and UnloadImage and
1760// do what is needed.
1761//----------------------------------------------------------------------
1762Error
1763Process::UnloadImage (uint32_t image_token)
1764{
1765 Error error;
1766 if (image_token < m_image_tokens.size())
1767 {
1768 const addr_t image_addr = m_image_tokens[image_token];
1769 if (image_addr == LLDB_INVALID_ADDRESS)
1770 {
1771 error.SetErrorString("image already unloaded");
1772 }
1773 else
1774 {
1775 DynamicLoader *loader = GetDynamicLoader();
1776 if (loader)
1777 error = loader->CanLoadImage();
1778
1779 if (error.Success())
1780 {
1781 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001782
1783 if (thread_sp)
1784 {
1785 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1786
1787 if (frame_sp)
1788 {
1789 ExecutionContext exe_ctx;
1790 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001791 const bool unwind_on_error = true;
1792 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001793 StreamString expr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001794 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton0baa3942010-11-04 01:54:29 +00001795 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001796 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001797 ClangUserExpression::Evaluate (exe_ctx,
1798 eExecutionPolicyAlways,
1799 lldb::eLanguageTypeUnknown,
1800 ClangUserExpression::eResultTypeAny,
1801 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001802 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001803 expr.GetData(),
1804 prefix,
1805 result_valobj_sp,
1806 true,
1807 ClangUserExpression::kDefaultTimeout);
Greg Clayton0baa3942010-11-04 01:54:29 +00001808 if (result_valobj_sp->GetError().Success())
1809 {
1810 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001811 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001812 {
1813 if (scalar.UInt(1))
1814 {
1815 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1816 }
1817 else
1818 {
1819 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1820 }
1821 }
1822 }
1823 else
1824 {
1825 error = result_valobj_sp->GetError();
1826 }
1827 }
1828 }
1829 }
1830 }
1831 }
1832 else
1833 {
1834 error.SetErrorString("invalid image token");
1835 }
1836 return error;
1837}
1838
Greg Clayton75906e42011-05-11 18:39:18 +00001839const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001840Process::GetABI()
1841{
Greg Clayton75906e42011-05-11 18:39:18 +00001842 if (!m_abi_sp)
1843 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1844 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001845}
1846
Jim Ingham642036f2010-09-23 02:01:19 +00001847LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001848Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001849{
1850 LanguageRuntimeCollection::iterator pos;
1851 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001852 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001853 {
Jim Inghame3117662012-03-10 00:22:19 +00001854 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001855
Jim Inghame3117662012-03-10 00:22:19 +00001856 m_language_runtimes[language] = runtime_sp;
1857 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001858 }
1859 else
1860 return (*pos).second.get();
1861}
1862
1863CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001864Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001865{
Jim Inghame3117662012-03-10 00:22:19 +00001866 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001867 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1868 return static_cast<CPPLanguageRuntime *> (runtime);
1869 return NULL;
1870}
1871
1872ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001873Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001874{
Jim Inghame3117662012-03-10 00:22:19 +00001875 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001876 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1877 return static_cast<ObjCLanguageRuntime *> (runtime);
1878 return NULL;
1879}
1880
Enrico Granata6b1763b2012-05-21 16:51:35 +00001881bool
1882Process::IsPossibleDynamicValue (ValueObject& in_value)
1883{
1884 if (in_value.IsDynamic())
1885 return false;
1886 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1887
1888 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1889 {
1890 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1891 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1892 }
1893
1894 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1895 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1896 return true;
1897
1898 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1899 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1900}
1901
Chris Lattner24943d22010-06-08 16:52:24 +00001902BreakpointSiteList &
1903Process::GetBreakpointSiteList()
1904{
1905 return m_breakpoint_site_list;
1906}
1907
1908const BreakpointSiteList &
1909Process::GetBreakpointSiteList() const
1910{
1911 return m_breakpoint_site_list;
1912}
1913
1914
1915void
1916Process::DisableAllBreakpointSites ()
1917{
1918 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001919 size_t num_sites = m_breakpoint_site_list.GetSize();
1920 for (size_t i = 0; i < num_sites; i++)
1921 {
1922 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1923 }
Chris Lattner24943d22010-06-08 16:52:24 +00001924}
1925
1926Error
1927Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1928{
1929 Error error (DisableBreakpointSiteByID (break_id));
1930
1931 if (error.Success())
1932 m_breakpoint_site_list.Remove(break_id);
1933
1934 return error;
1935}
1936
1937Error
1938Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1939{
1940 Error error;
1941 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1942 if (bp_site_sp)
1943 {
1944 if (bp_site_sp->IsEnabled())
1945 error = DisableBreakpoint (bp_site_sp.get());
1946 }
1947 else
1948 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001949 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001950 }
1951
1952 return error;
1953}
1954
1955Error
1956Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1957{
1958 Error error;
1959 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1960 if (bp_site_sp)
1961 {
1962 if (!bp_site_sp->IsEnabled())
1963 error = EnableBreakpoint (bp_site_sp.get());
1964 }
1965 else
1966 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001967 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001968 }
1969 return error;
1970}
1971
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001972lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001973Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001974{
Greg Clayton265ab332011-05-19 18:17:41 +00001975 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001976 if (load_addr != LLDB_INVALID_ADDRESS)
1977 {
1978 BreakpointSiteSP bp_site_sp;
1979
1980 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1981 // create a new breakpoint site and add it.
1982
1983 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1984
1985 if (bp_site_sp)
1986 {
1987 bp_site_sp->AddOwner (owner);
1988 owner->SetBreakpointSite (bp_site_sp);
1989 return bp_site_sp->GetID();
1990 }
1991 else
1992 {
1993 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1994 if (bp_site_sp)
1995 {
1996 if (EnableBreakpoint (bp_site_sp.get()).Success())
1997 {
1998 owner->SetBreakpointSite (bp_site_sp);
1999 return m_breakpoint_site_list.Add (bp_site_sp);
2000 }
2001 }
2002 }
2003 }
2004 // We failed to enable the breakpoint
2005 return LLDB_INVALID_BREAK_ID;
2006
2007}
2008
2009void
2010Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2011{
2012 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2013 if (num_owners == 0)
2014 {
2015 DisableBreakpoint(bp_site_sp.get());
2016 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2017 }
2018}
2019
2020
2021size_t
2022Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2023{
2024 size_t bytes_removed = 0;
2025 addr_t intersect_addr;
2026 size_t intersect_size;
2027 size_t opcode_offset;
2028 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002029 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00002030 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00002031
Jim Ingham82820f92011-06-29 19:42:28 +00002032 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00002033 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002034 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00002035 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002036 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00002037 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002038 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00002039 {
2040 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2041 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00002042 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00002043 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002044 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00002045 }
Chris Lattner24943d22010-06-08 16:52:24 +00002046 }
2047 }
2048 }
2049 return bytes_removed;
2050}
2051
2052
Greg Claytonb1888f22011-03-19 01:12:21 +00002053
2054size_t
2055Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2056{
2057 PlatformSP platform_sp (m_target.GetPlatform());
2058 if (platform_sp)
2059 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2060 return 0;
2061}
2062
Chris Lattner24943d22010-06-08 16:52:24 +00002063Error
2064Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2065{
2066 Error error;
2067 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002068 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002069 const addr_t bp_addr = bp_site->GetLoadAddress();
2070 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002071 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002072 if (bp_site->IsEnabled())
2073 {
2074 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002075 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002076 return error;
2077 }
2078
2079 if (bp_addr == LLDB_INVALID_ADDRESS)
2080 {
2081 error.SetErrorString("BreakpointSite contains an invalid load address.");
2082 return error;
2083 }
2084 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2085 // trap for the breakpoint site
2086 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2087
2088 if (bp_opcode_size == 0)
2089 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002090 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002091 }
2092 else
2093 {
2094 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2095
2096 if (bp_opcode_bytes == NULL)
2097 {
2098 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2099 return error;
2100 }
2101
2102 // Save the original opcode by reading it
2103 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2104 {
2105 // Write a software breakpoint in place of the original opcode
2106 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2107 {
2108 uint8_t verify_bp_opcode_bytes[64];
2109 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2110 {
2111 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2112 {
2113 bp_site->SetEnabled(true);
2114 bp_site->SetType (BreakpointSite::eSoftware);
2115 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002116 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner24943d22010-06-08 16:52:24 +00002117 bp_site->GetID(),
2118 (uint64_t)bp_addr);
2119 }
2120 else
Greg Clayton9c236732011-10-26 00:56:27 +00002121 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00002122 }
2123 else
2124 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2125 }
2126 else
2127 error.SetErrorString("Unable to write breakpoint trap to memory.");
2128 }
2129 else
2130 error.SetErrorString("Unable to read memory at breakpoint address.");
2131 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002132 if (log && error.Fail())
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002133 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002134 bp_site->GetID(),
2135 (uint64_t)bp_addr,
2136 error.AsCString());
2137 return error;
2138}
2139
2140Error
2141Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2142{
2143 Error error;
2144 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002145 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002146 addr_t bp_addr = bp_site->GetLoadAddress();
2147 lldb::user_id_t breakID = bp_site->GetID();
2148 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002149 log->Printf ("Process::DisableBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002150
2151 if (bp_site->IsHardware())
2152 {
2153 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2154 }
2155 else if (bp_site->IsEnabled())
2156 {
2157 const size_t break_op_size = bp_site->GetByteSize();
2158 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2159 if (break_op_size > 0)
2160 {
2161 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002162 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002163 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002164 bool break_op_found = false;
2165
2166 // Read the breakpoint opcode
2167 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2168 {
2169 bool verify = false;
2170 // Make sure we have the a breakpoint opcode exists at this address
2171 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2172 {
2173 break_op_found = true;
2174 // We found a valid breakpoint opcode at this address, now restore
2175 // the saved opcode.
2176 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2177 {
2178 verify = true;
2179 }
2180 else
2181 error.SetErrorString("Memory write failed when restoring original opcode.");
2182 }
2183 else
2184 {
2185 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2186 // Set verify to true and so we can check if the original opcode has already been restored
2187 verify = true;
2188 }
2189
2190 if (verify)
2191 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002192 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002193 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002194 // Verify that our original opcode made it back to the inferior
2195 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2196 {
2197 // compare the memory we just read with the original opcode
2198 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2199 {
2200 // SUCCESS
2201 bp_site->SetEnabled(false);
2202 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002203 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002204 return error;
2205 }
2206 else
2207 {
2208 if (break_op_found)
2209 error.SetErrorString("Failed to restore original opcode.");
2210 }
2211 }
2212 else
2213 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2214 }
2215 }
2216 else
2217 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2218 }
2219 }
2220 else
2221 {
2222 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002223 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002224 return error;
2225 }
2226
2227 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002228 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002229 bp_site->GetID(),
2230 (uint64_t)bp_addr,
2231 error.AsCString());
2232 return error;
2233
2234}
2235
Greg Claytonfd119992011-01-07 06:08:19 +00002236// Uncomment to verify memory caching works after making changes to caching code
2237//#define VERIFY_MEMORY_READS
2238
Sean Callananf90b5f32012-06-07 22:26:42 +00002239size_t
2240Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2241{
2242 if (!GetDisableMemoryCache())
2243 {
Greg Claytonfd119992011-01-07 06:08:19 +00002244#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002245 // Memory caching is enabled, with debug verification
2246
2247 if (buf && size)
2248 {
2249 // Uncomment the line below to make sure memory caching is working.
2250 // I ran this through the test suite and got no assertions, so I am
2251 // pretty confident this is working well. If any changes are made to
2252 // memory caching, uncomment the line below and test your changes!
2253
2254 // Verify all memory reads by using the cache first, then redundantly
2255 // reading the same memory from the inferior and comparing to make sure
2256 // everything is exactly the same.
2257 std::string verify_buf (size, '\0');
2258 assert (verify_buf.size() == size);
2259 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2260 Error verify_error;
2261 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2262 assert (cache_bytes_read == verify_bytes_read);
2263 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2264 assert (verify_error.Success() == error.Success());
2265 return cache_bytes_read;
2266 }
2267 return 0;
2268#else // !defined(VERIFY_MEMORY_READS)
2269 // Memory caching is enabled, without debug verification
2270
2271 return m_memory_cache.Read (addr, buf, size, error);
2272#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002273 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002274 else
2275 {
2276 // Memory caching is disabled
2277
2278 return ReadMemoryFromInferior (addr, buf, size, error);
2279 }
Greg Claytonfd119992011-01-07 06:08:19 +00002280}
Greg Claytonfd119992011-01-07 06:08:19 +00002281
Greg Claytondd29b972012-05-18 23:20:01 +00002282size_t
2283Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2284{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002285 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002286 out_str.clear();
2287 addr_t curr_addr = addr;
2288 while (1)
2289 {
2290 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2291 if (length == 0)
2292 break;
2293 out_str.append(buf, length);
2294 // If we got "length - 1" bytes, we didn't get the whole C string, we
2295 // need to read some more characters
2296 if (length == sizeof(buf) - 1)
2297 curr_addr += length;
2298 else
2299 break;
2300 }
2301 return out_str.size();
2302}
2303
Greg Claytonfd119992011-01-07 06:08:19 +00002304
2305size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002306Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002307{
2308 size_t total_cstr_len = 0;
2309 if (dst && dst_max_len)
2310 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002311 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002312 // NULL out everything just to be safe
2313 memset (dst, 0, dst_max_len);
2314 Error error;
2315 addr_t curr_addr = addr;
2316 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2317 size_t bytes_left = dst_max_len - 1;
2318 char *curr_dst = dst;
2319
2320 while (bytes_left > 0)
2321 {
2322 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2323 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2324 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2325
2326 if (bytes_read == 0)
2327 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002328 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002329 dst[total_cstr_len] = '\0';
2330 break;
2331 }
2332 const size_t len = strlen(curr_dst);
2333
2334 total_cstr_len += len;
2335
2336 if (len < bytes_to_read)
2337 break;
2338
2339 curr_dst += bytes_read;
2340 curr_addr += bytes_read;
2341 bytes_left -= bytes_read;
2342 }
2343 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002344 else
2345 {
2346 if (dst == NULL)
2347 result_error.SetErrorString("invalid arguments");
2348 else
2349 result_error.Clear();
2350 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002351 return total_cstr_len;
2352}
2353
2354size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002355Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2356{
Chris Lattner24943d22010-06-08 16:52:24 +00002357 if (buf == NULL || size == 0)
2358 return 0;
2359
2360 size_t bytes_read = 0;
2361 uint8_t *bytes = (uint8_t *)buf;
2362
2363 while (bytes_read < size)
2364 {
2365 const size_t curr_size = size - bytes_read;
2366 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2367 bytes + bytes_read,
2368 curr_size,
2369 error);
2370 bytes_read += curr_bytes_read;
2371 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2372 break;
2373 }
2374
2375 // Replace any software breakpoint opcodes that fall into this range back
2376 // into "buf" before we return
2377 if (bytes_read > 0)
2378 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2379 return bytes_read;
2380}
2381
Greg Claytonf72fdee2010-12-16 20:01:20 +00002382uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002383Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002384{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002385 Scalar scalar;
2386 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2387 return scalar.ULongLong(fail_value);
2388 return fail_value;
2389}
2390
2391addr_t
2392Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2393{
2394 Scalar scalar;
2395 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2396 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2397 return LLDB_INVALID_ADDRESS;
2398}
2399
2400
2401bool
2402Process::WritePointerToMemory (lldb::addr_t vm_addr,
2403 lldb::addr_t ptr_value,
2404 Error &error)
2405{
2406 Scalar scalar;
2407 const uint32_t addr_byte_size = GetAddressByteSize();
2408 if (addr_byte_size <= 4)
2409 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002410 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002411 scalar = ptr_value;
2412 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002413}
2414
Chris Lattner24943d22010-06-08 16:52:24 +00002415size_t
2416Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2417{
2418 size_t bytes_written = 0;
2419 const uint8_t *bytes = (const uint8_t *)buf;
2420
2421 while (bytes_written < size)
2422 {
2423 const size_t curr_size = size - bytes_written;
2424 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2425 bytes + bytes_written,
2426 curr_size,
2427 error);
2428 bytes_written += curr_bytes_written;
2429 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2430 break;
2431 }
2432 return bytes_written;
2433}
2434
2435size_t
2436Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2437{
Greg Claytonfd119992011-01-07 06:08:19 +00002438#if defined (ENABLE_MEMORY_CACHING)
2439 m_memory_cache.Flush (addr, size);
2440#endif
2441
Chris Lattner24943d22010-06-08 16:52:24 +00002442 if (buf == NULL || size == 0)
2443 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002444
Jim Ingham21f37ad2011-08-09 02:12:22 +00002445 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002446
Chris Lattner24943d22010-06-08 16:52:24 +00002447 // We need to write any data that would go where any current software traps
2448 // (enabled software breakpoints) any software traps (breakpoints) that we
2449 // may have placed in our tasks memory.
2450
2451 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2452 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2453
2454 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002455 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002456
2457 BreakpointSiteList::collection::const_iterator pos;
2458 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002459 addr_t intersect_addr = 0;
2460 size_t intersect_size = 0;
2461 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002462 const uint8_t *ubuf = (const uint8_t *)buf;
2463
2464 for (pos = iter; pos != end; ++pos)
2465 {
2466 BreakpointSiteSP bp;
2467 bp = pos->second;
2468
2469 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2470 assert(addr <= intersect_addr && intersect_addr < addr + size);
2471 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2472 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2473
2474 // Check for bytes before this breakpoint
2475 const addr_t curr_addr = addr + bytes_written;
2476 if (intersect_addr > curr_addr)
2477 {
2478 // There are some bytes before this breakpoint that we need to
2479 // just write to memory
2480 size_t curr_size = intersect_addr - curr_addr;
2481 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2482 ubuf + bytes_written,
2483 curr_size,
2484 error);
2485 bytes_written += curr_bytes_written;
2486 if (curr_bytes_written != curr_size)
2487 {
2488 // We weren't able to write all of the requested bytes, we
2489 // are done looping and will return the number of bytes that
2490 // we have written so far.
2491 break;
2492 }
2493 }
2494
2495 // Now write any bytes that would cover up any software breakpoints
2496 // directly into the breakpoint opcode buffer
2497 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2498 bytes_written += intersect_size;
2499 }
2500
2501 // Write any remaining bytes after the last breakpoint if we have any left
2502 if (bytes_written < size)
2503 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2504 ubuf + bytes_written,
2505 size - bytes_written,
2506 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002507
Chris Lattner24943d22010-06-08 16:52:24 +00002508 return bytes_written;
2509}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002510
2511size_t
2512Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2513{
2514 if (byte_size == UINT32_MAX)
2515 byte_size = scalar.GetByteSize();
2516 if (byte_size > 0)
2517 {
2518 uint8_t buf[32];
2519 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2520 if (mem_size > 0)
2521 return WriteMemory(addr, buf, mem_size, error);
2522 else
2523 error.SetErrorString ("failed to get scalar as memory data");
2524 }
2525 else
2526 {
2527 error.SetErrorString ("invalid scalar value");
2528 }
2529 return 0;
2530}
2531
2532size_t
2533Process::ReadScalarIntegerFromMemory (addr_t addr,
2534 uint32_t byte_size,
2535 bool is_signed,
2536 Scalar &scalar,
2537 Error &error)
2538{
2539 uint64_t uval;
2540
2541 if (byte_size <= sizeof(uval))
2542 {
2543 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2544 if (bytes_read == byte_size)
2545 {
2546 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2547 uint32_t offset = 0;
2548 if (byte_size <= 4)
2549 scalar = data.GetMaxU32 (&offset, byte_size);
2550 else
2551 scalar = data.GetMaxU64 (&offset, byte_size);
2552
2553 if (is_signed)
2554 scalar.SignExtend(byte_size * 8);
2555 return bytes_read;
2556 }
2557 }
2558 else
2559 {
2560 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2561 }
2562 return 0;
2563}
2564
Greg Clayton613b8732011-05-17 03:37:42 +00002565#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002566addr_t
2567Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2568{
Jim Inghame6bd1422011-06-20 17:32:44 +00002569 if (GetPrivateState() != eStateStopped)
2570 return LLDB_INVALID_ADDRESS;
2571
Greg Clayton613b8732011-05-17 03:37:42 +00002572#if defined (USE_ALLOCATE_MEMORY_CACHE)
2573 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2574#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002575 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2576 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2577 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002578 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002579 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002580 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002581 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002582 m_mod_id.GetStopID(),
2583 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002584 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002585#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002586}
2587
Sean Callanan6cf6c472011-09-20 23:01:51 +00002588bool
2589Process::CanJIT ()
2590{
Sean Callanan04200f62012-02-14 22:50:38 +00002591 if (m_can_jit == eCanJITDontKnow)
2592 {
2593 Error err;
2594
2595 uint64_t allocated_memory = AllocateMemory(8,
2596 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2597 err);
2598
2599 if (err.Success())
2600 m_can_jit = eCanJITYes;
2601 else
2602 m_can_jit = eCanJITNo;
2603
2604 DeallocateMemory (allocated_memory);
2605 }
2606
Sean Callanan6cf6c472011-09-20 23:01:51 +00002607 return m_can_jit == eCanJITYes;
2608}
2609
2610void
2611Process::SetCanJIT (bool can_jit)
2612{
2613 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2614}
2615
Chris Lattner24943d22010-06-08 16:52:24 +00002616Error
2617Process::DeallocateMemory (addr_t ptr)
2618{
Greg Clayton613b8732011-05-17 03:37:42 +00002619 Error error;
2620#if defined (USE_ALLOCATE_MEMORY_CACHE)
2621 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2622 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002623 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Clayton613b8732011-05-17 03:37:42 +00002624 }
2625#else
2626 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002627
2628 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2629 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002630 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002631 ptr,
2632 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002633 m_mod_id.GetStopID(),
2634 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002635#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002636 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002637}
2638
Han Ming Ong2529aa32012-11-17 00:33:14 +00002639
Greg Claytonb5a8f142012-02-05 02:38:54 +00002640ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002641Process::ReadModuleFromMemory (const FileSpec& file_spec,
2642 lldb::addr_t header_addr,
2643 bool add_image_to_target,
2644 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002645{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002646 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002647 if (module_sp)
2648 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002649 Error error;
2650 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2651 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002652 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002653 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002654 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002655 m_target.GetImages().Append(module_sp);
2656 if (load_sections_in_target)
2657 {
2658 bool changed = false;
2659 module_sp->SetLoadAddress (m_target, 0, changed);
2660 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002661 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002662 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002663 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002664 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002665 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002666}
Chris Lattner24943d22010-06-08 16:52:24 +00002667
2668Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002669Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002670{
2671 Error error;
2672 error.SetErrorString("watchpoints are not supported");
2673 return error;
2674}
2675
2676Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002677Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002678{
2679 Error error;
2680 error.SetErrorString("watchpoints are not supported");
2681 return error;
2682}
2683
2684StateType
2685Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2686{
2687 StateType state;
2688 // Now wait for the process to launch and return control to us, and then
2689 // call DidLaunch:
2690 while (1)
2691 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002692 event_sp.reset();
2693 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2694
Greg Clayton20206082011-11-17 01:23:07 +00002695 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002696 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002697
2698 // If state is invalid, then we timed out
2699 if (state == eStateInvalid)
2700 break;
2701
2702 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002703 HandlePrivateEvent (event_sp);
2704 }
2705 return state;
2706}
2707
2708Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002709Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002710{
2711 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002712 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002713 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002714 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002715 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002716
Greg Clayton5beb99d2011-08-11 02:48:45 +00002717 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002718 if (exe_module)
2719 {
Greg Clayton180546b2011-04-30 01:09:13 +00002720 char local_exec_file_path[PATH_MAX];
2721 char platform_exec_file_path[PATH_MAX];
2722 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2723 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002724 if (exe_module->GetFileSpec().Exists())
2725 {
Greg Claytona2f74232011-02-24 22:24:29 +00002726 if (PrivateStateThreadIsValid ())
2727 PausePrivateStateThread ();
2728
Chris Lattner24943d22010-06-08 16:52:24 +00002729 error = WillLaunch (exe_module);
2730 if (error.Success())
2731 {
Greg Claytond8c62532010-10-07 04:19:01 +00002732 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002733 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002734
Greg Clayton777c6b72012-09-04 20:29:05 +00002735 if (m_run_lock.WriteTryLock())
2736 {
2737 // Now launch using these arguments.
2738 error = DoLaunch (exe_module, launch_info);
2739 }
2740 else
2741 {
2742 // This shouldn't happen
2743 error.SetErrorString("failed to acquire process run lock");
2744 }
Chris Lattner24943d22010-06-08 16:52:24 +00002745
2746 if (error.Fail())
2747 {
2748 if (GetID() != LLDB_INVALID_PROCESS_ID)
2749 {
2750 SetID (LLDB_INVALID_PROCESS_ID);
2751 const char *error_string = error.AsCString();
2752 if (error_string == NULL)
2753 error_string = "launch failed";
2754 SetExitStatus (-1, error_string);
2755 }
2756 }
2757 else
2758 {
2759 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002760 TimeValue timeout_time;
2761 timeout_time = TimeValue::Now();
2762 timeout_time.OffsetWithSeconds(10);
2763 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002764
Greg Clayton49859592011-06-22 01:42:17 +00002765 if (state == eStateInvalid || event_sp.get() == NULL)
2766 {
2767 // We were able to launch the process, but we failed to
2768 // catch the initial stop.
2769 SetExitStatus (0, "failed to catch stop after launch");
2770 Destroy();
2771 }
2772 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002773 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002774
Chris Lattner24943d22010-06-08 16:52:24 +00002775 DidLaunch ();
2776
Greg Clayton9ce95382012-02-13 23:10:39 +00002777 DynamicLoader *dyld = GetDynamicLoader ();
2778 if (dyld)
2779 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002780
Greg Clayton37f962e2011-08-22 02:49:39 +00002781 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002782 // This delays passing the stopped event to listeners till DidLaunch gets
2783 // a chance to complete...
2784 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002785
2786 if (PrivateStateThreadIsValid ())
2787 ResumePrivateStateThread ();
2788 else
2789 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002790 }
2791 else if (state == eStateExited)
2792 {
2793 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2794 // not likely to work, and return an invalid pid.
2795 HandlePrivateEvent (event_sp);
2796 }
2797 }
2798 }
2799 }
2800 else
2801 {
Greg Clayton9c236732011-10-26 00:56:27 +00002802 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002803 }
2804 }
2805 return error;
2806}
2807
Greg Clayton46c9a352012-02-09 06:16:32 +00002808
2809Error
2810Process::LoadCore ()
2811{
2812 Error error = DoLoadCore();
2813 if (error.Success())
2814 {
2815 if (PrivateStateThreadIsValid ())
2816 ResumePrivateStateThread ();
2817 else
2818 StartPrivateStateThread ();
2819
Greg Clayton9ce95382012-02-13 23:10:39 +00002820 DynamicLoader *dyld = GetDynamicLoader ();
2821 if (dyld)
2822 dyld->DidAttach();
2823
2824 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002825 // We successfully loaded a core file, now pretend we stopped so we can
2826 // show all of the threads in the core file and explore the crashed
2827 // state.
2828 SetPrivateState (eStateStopped);
2829
2830 }
2831 return error;
2832}
2833
Greg Clayton9ce95382012-02-13 23:10:39 +00002834DynamicLoader *
2835Process::GetDynamicLoader ()
2836{
2837 if (m_dyld_ap.get() == NULL)
2838 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2839 return m_dyld_ap.get();
2840}
Greg Clayton46c9a352012-02-09 06:16:32 +00002841
2842
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002843Process::NextEventAction::EventActionResult
2844Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002845{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002846 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2847 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002848 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002849 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002850 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002851 return eEventActionRetry;
2852
2853 case eStateStopped:
2854 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002855 {
2856 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002857 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002858 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2859 if (m_exec_count > 0)
2860 {
2861 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002862 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002863 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002864 return eEventActionRetry;
2865 }
2866 else
2867 {
2868 m_process->CompleteAttach ();
2869 return eEventActionSuccess;
2870 }
2871 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002872 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002873
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002874 default:
2875 case eStateExited:
2876 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002877 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002878 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002879
2880 m_exit_string.assign ("No valid Process");
2881 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002882}
Chris Lattner24943d22010-06-08 16:52:24 +00002883
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002884Process::NextEventAction::EventActionResult
2885Process::AttachCompletionHandler::HandleBeingInterrupted()
2886{
2887 return eEventActionSuccess;
2888}
2889
2890const char *
2891Process::AttachCompletionHandler::GetExitString ()
2892{
2893 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002894}
2895
2896Error
Greg Clayton527154d2011-11-15 03:53:30 +00002897Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002898{
Chris Lattner24943d22010-06-08 16:52:24 +00002899 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002900 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002901 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002902 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002903
Greg Clayton527154d2011-11-15 03:53:30 +00002904 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002905 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002906 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002907 {
Greg Clayton527154d2011-11-15 03:53:30 +00002908 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002909
Greg Clayton527154d2011-11-15 03:53:30 +00002910 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002911 {
Greg Clayton527154d2011-11-15 03:53:30 +00002912 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2913
2914 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002915 {
Greg Clayton527154d2011-11-15 03:53:30 +00002916 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2917 if (error.Success())
2918 {
Greg Claytond34a3b22012-10-12 16:10:12 +00002919 if (m_run_lock.WriteTryLock())
2920 {
2921 m_should_detach = true;
2922 SetPublicState (eStateAttaching);
2923 // Now attach using these arguments.
2924 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2925 }
2926 else
2927 {
2928 // This shouldn't happen
2929 error.SetErrorString("failed to acquire process run lock");
2930 }
Greg Claytonffa43a62011-11-17 04:46:02 +00002931
Greg Clayton527154d2011-11-15 03:53:30 +00002932 if (error.Fail())
2933 {
2934 if (GetID() != LLDB_INVALID_PROCESS_ID)
2935 {
2936 SetID (LLDB_INVALID_PROCESS_ID);
2937 if (error.AsCString() == NULL)
2938 error.SetErrorString("attach failed");
2939
2940 SetExitStatus(-1, error.AsCString());
2941 }
2942 }
2943 else
2944 {
2945 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2946 StartPrivateStateThread();
2947 }
2948 return error;
2949 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002950 }
Greg Clayton527154d2011-11-15 03:53:30 +00002951 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002952 {
Greg Clayton527154d2011-11-15 03:53:30 +00002953 ProcessInstanceInfoList process_infos;
2954 PlatformSP platform_sp (m_target.GetPlatform ());
2955
2956 if (platform_sp)
2957 {
2958 ProcessInstanceInfoMatch match_info;
2959 match_info.GetProcessInfo() = attach_info;
2960 match_info.SetNameMatchType (eNameMatchEquals);
2961 platform_sp->FindProcesses (match_info, process_infos);
2962 const uint32_t num_matches = process_infos.GetSize();
2963 if (num_matches == 1)
2964 {
2965 attach_pid = process_infos.GetProcessIDAtIndex(0);
2966 // Fall through and attach using the above process ID
2967 }
2968 else
2969 {
2970 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2971 if (num_matches > 1)
2972 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2973 else
2974 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2975 }
2976 }
2977 else
2978 {
2979 error.SetErrorString ("invalid platform, can't find processes by name");
2980 return error;
2981 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002982 }
Chris Lattner24943d22010-06-08 16:52:24 +00002983 }
2984 else
Greg Clayton527154d2011-11-15 03:53:30 +00002985 {
2986 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002987 }
2988 }
Greg Clayton527154d2011-11-15 03:53:30 +00002989
2990 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002991 {
Greg Clayton527154d2011-11-15 03:53:30 +00002992 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002993 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002994 {
Greg Clayton527154d2011-11-15 03:53:30 +00002995
Greg Claytond34a3b22012-10-12 16:10:12 +00002996 if (m_run_lock.WriteTryLock())
2997 {
2998 // Now attach using these arguments.
2999 m_should_detach = true;
3000 SetPublicState (eStateAttaching);
3001 error = DoAttachToProcessWithID (attach_pid, attach_info);
3002 }
3003 else
3004 {
3005 // This shouldn't happen
3006 error.SetErrorString("failed to acquire process run lock");
3007 }
3008
Greg Clayton527154d2011-11-15 03:53:30 +00003009 if (error.Success())
3010 {
3011
3012 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3013 StartPrivateStateThread();
3014 }
3015 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003016 {
3017 if (GetID() != LLDB_INVALID_PROCESS_ID)
3018 {
3019 SetID (LLDB_INVALID_PROCESS_ID);
3020 const char *error_string = error.AsCString();
3021 if (error_string == NULL)
3022 error_string = "attach failed";
3023
3024 SetExitStatus(-1, error_string);
3025 }
3026 }
Chris Lattner24943d22010-06-08 16:52:24 +00003027 }
3028 }
3029 return error;
3030}
3031
Greg Clayton75c703d2011-02-16 04:46:07 +00003032void
3033Process::CompleteAttach ()
3034{
3035 // Let the process subclass figure out at much as it can about the process
3036 // before we go looking for a dynamic loader plug-in.
3037 DidAttach();
3038
Jim Ingham0d7f7772011-09-15 01:10:17 +00003039 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3040 // the same as the one we've already set, switch architectures.
3041 PlatformSP platform_sp (m_target.GetPlatform ());
3042 assert (platform_sp.get());
3043 if (platform_sp)
3044 {
Greg Claytonb170aee2012-05-08 01:45:38 +00003045 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Claytonaad2b0f2013-01-11 20:49:54 +00003046 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Claytonb170aee2012-05-08 01:45:38 +00003047 {
3048 ArchSpec platform_arch;
3049 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3050 if (platform_sp)
3051 {
3052 m_target.SetPlatform (platform_sp);
3053 m_target.SetArchitecture(platform_arch);
3054 }
3055 }
3056 else
3057 {
3058 ProcessInstanceInfo process_info;
3059 platform_sp->GetProcessInfo (GetID(), process_info);
3060 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callanan40e278c2012-12-13 22:07:14 +00003061 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Claytonb170aee2012-05-08 01:45:38 +00003062 m_target.SetArchitecture (process_arch);
3063 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00003064 }
3065
3066 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00003067 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00003068 DynamicLoader *dyld = GetDynamicLoader ();
3069 if (dyld)
3070 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00003071
Greg Clayton37f962e2011-08-22 02:49:39 +00003072 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00003073 // Figure out which one is the executable, and set that in our target:
Enrico Granata146d9522012-11-08 02:22:02 +00003074 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham93367902012-05-30 02:19:25 +00003075 Mutex::Locker modules_locker(target_modules.GetMutex());
3076 size_t num_modules = target_modules.GetSize();
3077 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003078
Greg Clayton75c703d2011-02-16 04:46:07 +00003079 for (int i = 0; i < num_modules; i++)
3080 {
Jim Ingham93367902012-05-30 02:19:25 +00003081 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00003082 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00003083 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00003084 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00003085 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003086 break;
3087 }
3088 }
Jim Ingham93367902012-05-30 02:19:25 +00003089 if (new_executable_module_sp)
3090 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00003091}
3092
Chris Lattner24943d22010-06-08 16:52:24 +00003093Error
Jason Molendafac2e622012-09-29 04:02:01 +00003094Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00003095{
Greg Claytone71e2582011-02-04 01:58:07 +00003096 m_abi_sp.reset();
3097 m_process_input_reader.reset();
3098
3099 // Find the process and its architecture. Make sure it matches the architecture
3100 // of the current Target, and if not adjust it.
3101
Jason Molendafac2e622012-09-29 04:02:01 +00003102 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00003103 if (error.Success())
3104 {
Greg Claytona2f74232011-02-24 22:24:29 +00003105 if (GetID() != LLDB_INVALID_PROCESS_ID)
3106 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00003107 EventSP event_sp;
3108 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3109
3110 if (state == eStateStopped || state == eStateCrashed)
3111 {
3112 // If we attached and actually have a process on the other end, then
3113 // this ended up being the equivalent of an attach.
3114 CompleteAttach ();
3115
3116 // This delays passing the stopped event to listeners till
3117 // CompleteAttach gets a chance to complete...
3118 HandlePrivateEvent (event_sp);
3119
3120 }
Greg Claytona2f74232011-02-24 22:24:29 +00003121 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00003122
3123 if (PrivateStateThreadIsValid ())
3124 ResumePrivateStateThread ();
3125 else
3126 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00003127 }
3128 return error;
3129}
3130
3131
3132Error
Jim Ingham027aaa72012-04-19 01:40:33 +00003133Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00003134{
Jim Inghame1a654b2012-09-06 19:24:17 +00003135 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00003136 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00003137 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00003138 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00003139 StateAsCString(m_public_state.GetValue()),
3140 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00003141
3142 Error error (WillResume());
3143 // Tell the process it is about to resume before the thread list
3144 if (error.Success())
3145 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003146 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003147 // can let all of our threads know that they are about to be
3148 // resumed. Threads will each be called with
3149 // Thread::WillResume(StateType) where StateType contains the state
3150 // that they are supposed to have when the process is resumed
3151 // (suspended/running/stepping). Threads should also check
3152 // their resume signal in lldb::Thread::GetResumeSignal()
3153 // to see if they are suppoed to start back up with a signal.
3154 if (m_thread_list.WillResume())
3155 {
Jim Ingham1831e782012-04-07 00:00:41 +00003156 // Last thing, do the PreResumeActions.
3157 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003158 {
Jim Ingham1831e782012-04-07 00:00:41 +00003159 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3160 }
3161 else
3162 {
3163 m_mod_id.BumpResumeID();
3164 error = DoResume();
3165 if (error.Success())
3166 {
3167 DidResume();
3168 m_thread_list.DidResume();
3169 if (log)
3170 log->Printf ("Process thinks the process has resumed.");
3171 }
Chris Lattner24943d22010-06-08 16:52:24 +00003172 }
3173 }
3174 else
3175 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003176 // Somebody wanted to run without running. So generate a continue & a stopped event,
3177 // and let the world handle them.
3178 if (log)
3179 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3180
3181 SetPrivateState(eStateRunning);
3182 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003183 }
3184 }
Jim Inghamac959662011-01-24 06:34:17 +00003185 else if (log)
3186 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003187 return error;
3188}
3189
3190Error
3191Process::Halt ()
3192{
Jim Ingham43892562012-06-06 00:29:30 +00003193 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3194 // we could just straightaway get another event. It just narrows the window...
3195 m_currently_handling_event.WaitForValueEqualTo(false);
3196
3197
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003198 // Pause our private state thread so we can ensure no one else eats
3199 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003200 Listener halt_listener ("lldb.process.halt_listener");
3201 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003202
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003203 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003204 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003205
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003206 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003207 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003208
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003209 bool caused_stop = false;
3210
3211 // Ask the process subclass to actually halt our process
3212 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003213 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003214 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003215 if (m_public_state.GetValue() == eStateAttaching)
3216 {
3217 SetExitStatus(SIGKILL, "Cancelled async attach.");
3218 Destroy ();
3219 }
3220 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003221 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003222 // If "caused_stop" is true, then DoHalt stopped the process. If
3223 // "caused_stop" is false, the process was already stopped.
3224 // If the DoHalt caused the process to stop, then we want to catch
3225 // this event and set the interrupted bool to true before we pass
3226 // this along so clients know that the process was interrupted by
3227 // a halt command.
3228 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003229 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003230 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003231 TimeValue timeout_time;
3232 timeout_time = TimeValue::Now();
3233 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003234 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3235 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003236
Jim Inghamf9f40c22011-02-08 05:20:59 +00003237 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003238 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003239 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003240 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003241 }
3242 else
3243 {
Greg Clayton20206082011-11-17 01:23:07 +00003244 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003245 {
3246 // We caused the process to interrupt itself, so mark this
3247 // as such in the stop event so clients can tell an interrupted
3248 // process from a natural stop
3249 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3250 }
3251 else
3252 {
3253 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3254 if (log)
3255 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3256 error.SetErrorString ("Did not get stopped event after halt.");
3257 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003258 }
3259 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003260 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003261 }
3262 }
Chris Lattner24943d22010-06-08 16:52:24 +00003263 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003264 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003265 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003266
3267 // Post any event we might have consumed. If all goes well, we will have
3268 // stopped the process, intercepted the event and set the interrupted
3269 // bool in the event. Post it to the private event queue and that will end up
3270 // correctly setting the state.
3271 if (event_sp)
3272 m_private_state_broadcaster.BroadcastEvent(event_sp);
3273
Chris Lattner24943d22010-06-08 16:52:24 +00003274 return error;
3275}
3276
3277Error
3278Process::Detach ()
3279{
3280 Error error (WillDetach());
3281
3282 if (error.Success())
3283 {
3284 DisableAllBreakpointSites();
3285 error = DoDetach();
3286 if (error.Success())
3287 {
3288 DidDetach();
3289 StopPrivateStateThread();
3290 }
3291 }
3292 return error;
3293}
3294
3295Error
3296Process::Destroy ()
3297{
3298 Error error (WillDestroy());
3299 if (error.Success())
3300 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003301 EventSP exit_event_sp;
Jim Inghamf4928de2012-05-23 15:46:31 +00003302 if (m_public_state.GetValue() == eStateRunning)
3303 {
Greg Clayton38ae5b92012-09-05 00:37:58 +00003304 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003305 if (log)
3306 log->Printf("Process::Destroy() About to halt.");
Jim Inghamf4928de2012-05-23 15:46:31 +00003307 error = Halt();
3308 if (error.Success())
3309 {
3310 // Consume the halt event.
Jim Inghamf4928de2012-05-23 15:46:31 +00003311 TimeValue timeout (TimeValue::Now());
Jim Ingham43892562012-06-06 00:29:30 +00003312 timeout.OffsetWithSeconds(1);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003313 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3314 if (state != eStateExited)
3315 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3316
Jim Inghamf4928de2012-05-23 15:46:31 +00003317 if (state != eStateStopped)
3318 {
Jim Inghamf4928de2012-05-23 15:46:31 +00003319 if (log)
3320 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Ingham43892562012-06-06 00:29:30 +00003321 // If we really couldn't stop the process then we should just error out here, but if the
3322 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3323 StateType private_state = m_private_state.GetValue();
3324 if (private_state != eStateStopped && private_state != eStateExited)
3325 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003326 // If we exited when we were waiting for a process to stop, then
3327 // forward the event here so we don't lose the event
Jim Ingham43892562012-06-06 00:29:30 +00003328 return error;
3329 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003330 }
3331 }
3332 else
3333 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003334 if (log)
3335 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3336 return error;
Jim Inghamf4928de2012-05-23 15:46:31 +00003337 }
3338 }
Jim Ingham43892562012-06-06 00:29:30 +00003339
3340 if (m_public_state.GetValue() != eStateRunning)
3341 {
3342 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3343 // kill it, we don't want it hitting a breakpoint...
3344 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3345 // we're not going to have much luck doing this now.
3346 m_thread_list.DiscardThreadPlans();
3347 DisableAllBreakpointSites();
3348 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003349
Chris Lattner24943d22010-06-08 16:52:24 +00003350 error = DoDestroy();
3351 if (error.Success())
3352 {
3353 DidDestroy();
3354 StopPrivateStateThread();
3355 }
Caroline Tice861efb32010-11-16 05:07:41 +00003356 m_stdio_communication.StopReadThread();
3357 m_stdio_communication.Disconnect();
3358 if (m_process_input_reader && m_process_input_reader->IsActive())
3359 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3360 if (m_process_input_reader)
3361 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003362
3363 // If we exited when we were waiting for a process to stop, then
3364 // forward the event here so we don't lose the event
3365 if (exit_event_sp)
3366 {
3367 // Directly broadcast our exited event because we shut down our
3368 // private state thread above
3369 BroadcastEvent(exit_event_sp);
3370 }
3371
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003372 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3373 // the last events through the event system, in which case we might strand the write lock. Unlock
3374 // it here so when we do to tear down the process we don't get an error destroying the lock.
3375 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003376 }
3377 return error;
3378}
3379
3380Error
3381Process::Signal (int signal)
3382{
3383 Error error (WillSignal());
3384 if (error.Success())
3385 {
3386 error = DoSignal(signal);
3387 if (error.Success())
3388 DidSignal();
3389 }
3390 return error;
3391}
3392
Greg Clayton395fc332011-02-15 21:59:32 +00003393lldb::ByteOrder
3394Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003395{
Greg Clayton395fc332011-02-15 21:59:32 +00003396 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003397}
3398
3399uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003400Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003401{
Greg Clayton395fc332011-02-15 21:59:32 +00003402 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003403}
3404
Greg Clayton395fc332011-02-15 21:59:32 +00003405
Chris Lattner24943d22010-06-08 16:52:24 +00003406bool
3407Process::ShouldBroadcastEvent (Event *event_ptr)
3408{
3409 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3410 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00003411 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003412
3413 switch (state)
3414 {
Greg Claytone71e2582011-02-04 01:58:07 +00003415 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003416 case eStateAttaching:
3417 case eStateLaunching:
3418 case eStateDetached:
3419 case eStateExited:
3420 case eStateUnloaded:
3421 // These events indicate changes in the state of the debugging session, always report them.
3422 return_value = true;
3423 break;
3424 case eStateInvalid:
3425 // We stopped for no apparent reason, don't report it.
3426 return_value = false;
3427 break;
3428 case eStateRunning:
3429 case eStateStepping:
3430 // If we've started the target running, we handle the cases where we
3431 // are already running and where there is a transition from stopped to
3432 // running differently.
3433 // running -> running: Automatically suppress extra running events
3434 // stopped -> running: Report except when there is one or more no votes
3435 // and no yes votes.
3436 SynchronouslyNotifyStateChanged (state);
3437 switch (m_public_state.GetValue())
3438 {
3439 case eStateRunning:
3440 case eStateStepping:
3441 // We always suppress multiple runnings with no PUBLIC stop in between.
3442 return_value = false;
3443 break;
3444 default:
3445 // TODO: make this work correctly. For now always report
3446 // run if we aren't running so we don't miss any runnning
3447 // events. If I run the lldb/test/thread/a.out file and
3448 // break at main.cpp:58, run and hit the breakpoints on
3449 // multiple threads, then somehow during the stepping over
3450 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003451
3452 // This is a transition from stop to run.
3453 switch (m_thread_list.ShouldReportRun (event_ptr))
3454 {
3455 case eVoteYes:
3456 case eVoteNoOpinion:
3457 return_value = true;
3458 break;
3459 case eVoteNo:
3460 return_value = false;
3461 break;
3462 }
3463 break;
3464 }
3465 break;
3466 case eStateStopped:
3467 case eStateCrashed:
3468 case eStateSuspended:
3469 {
3470 // We've stopped. First see if we're going to restart the target.
3471 // If we are going to stop, then we always broadcast the event.
3472 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00003473 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003474
3475 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003476 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003477 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003478 if (log)
3479 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003480 return true;
3481 }
3482 else
3483 {
Chris Lattner24943d22010-06-08 16:52:24 +00003484
3485 if (m_thread_list.ShouldStop (event_ptr) == false)
3486 {
Jim Ingham8290bba2012-09-05 21:13:56 +00003487 // ShouldStop may have restarted the target already. If so, don't
3488 // resume it twice.
3489 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00003490 switch (m_thread_list.ShouldReportStop (event_ptr))
3491 {
3492 case eVoteYes:
3493 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003494 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003495 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003496 case eVoteNo:
3497 return_value = false;
3498 break;
3499 }
3500
3501 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003502 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham8290bba2012-09-05 21:13:56 +00003503 if (!was_restarted)
3504 PrivateResume ();
Chris Lattner24943d22010-06-08 16:52:24 +00003505 }
3506 else
3507 {
3508 return_value = true;
3509 SynchronouslyNotifyStateChanged (state);
3510 }
3511 }
3512 }
3513 }
3514
3515 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003516 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003517 return return_value;
3518}
3519
Chris Lattner24943d22010-06-08 16:52:24 +00003520
3521bool
Jim Ingham1831e782012-04-07 00:00:41 +00003522Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003523{
Greg Claytone005f2c2010-11-06 01:53:30 +00003524 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003525
Greg Claytonb72d0f02011-04-12 05:54:46 +00003526 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003527 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003528 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3529
Jim Ingham1831e782012-04-07 00:00:41 +00003530 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003531 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003532
3533 // Create a thread that watches our internal state and controls which
3534 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003535 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003536 if (already_running)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003537 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham1831e782012-04-07 00:00:41 +00003538 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003539 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003540
3541 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003542 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003543 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3544 if (success)
3545 {
3546 ResumePrivateStateThread();
3547 return true;
3548 }
3549 else
3550 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003551}
3552
3553void
3554Process::PausePrivateStateThread ()
3555{
3556 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3557}
3558
3559void
3560Process::ResumePrivateStateThread ()
3561{
3562 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3563}
3564
3565void
3566Process::StopPrivateStateThread ()
3567{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003568 if (PrivateStateThreadIsValid ())
3569 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003570 else
3571 {
3572 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3573 if (log)
3574 printf ("Went to stop the private state thread, but it was already invalid.");
3575 }
Chris Lattner24943d22010-06-08 16:52:24 +00003576}
3577
3578void
3579Process::ControlPrivateStateThread (uint32_t signal)
3580{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003581 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003582
3583 assert (signal == eBroadcastInternalStateControlStop ||
3584 signal == eBroadcastInternalStateControlPause ||
3585 signal == eBroadcastInternalStateControlResume);
3586
3587 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003588 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003589
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003590 // Signal the private state thread. First we should copy this is case the
3591 // thread starts exiting since the private state thread will NULL this out
3592 // when it exits
3593 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003594 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003595 {
3596 TimeValue timeout_time;
3597 bool timed_out;
3598
3599 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3600
3601 timeout_time = TimeValue::Now();
3602 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003603 if (log)
3604 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003605 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3606 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3607
3608 if (signal == eBroadcastInternalStateControlStop)
3609 {
3610 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003611 {
3612 Error error;
3613 Host::ThreadCancel (private_state_thread, &error);
3614 if (log)
3615 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3616 }
3617 else
3618 {
3619 if (log)
3620 log->Printf ("The control event killed the private state thread without having to cancel.");
3621 }
Chris Lattner24943d22010-06-08 16:52:24 +00003622
3623 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003624 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003625 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003626 }
3627 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003628 else
3629 {
3630 if (log)
3631 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3632 }
Chris Lattner24943d22010-06-08 16:52:24 +00003633}
3634
3635void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003636Process::SendAsyncInterrupt ()
3637{
3638 if (PrivateStateThreadIsValid())
3639 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3640 else
3641 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3642}
3643
3644void
Chris Lattner24943d22010-06-08 16:52:24 +00003645Process::HandlePrivateEvent (EventSP &event_sp)
3646{
Greg Claytone005f2c2010-11-06 01:53:30 +00003647 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003648 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003649
Greg Clayton68ca8232011-01-25 02:58:48 +00003650 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003651
3652 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003653 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003654 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003655 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003656 switch (action_result)
3657 {
3658 case NextEventAction::eEventActionSuccess:
3659 SetNextEventAction(NULL);
3660 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003661
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003662 case NextEventAction::eEventActionRetry:
3663 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003664
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003665 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003666 // Handle Exiting Here. If we already got an exited event,
3667 // we should just propagate it. Otherwise, swallow this event,
3668 // and set our state to exit so the next event will kill us.
3669 if (new_state != eStateExited)
3670 {
3671 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003672 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003673 SetNextEventAction(NULL);
3674 return;
3675 }
3676 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003677 break;
3678 }
3679 }
3680
Chris Lattner24943d22010-06-08 16:52:24 +00003681 // See if we should broadcast this state to external clients?
3682 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003683
3684 if (should_broadcast)
3685 {
3686 if (log)
3687 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003688 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003689 __FUNCTION__,
3690 GetID(),
3691 StateAsCString(new_state),
3692 StateAsCString (GetState ()),
3693 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003694 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003695 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003696 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003697 PushProcessInputReader ();
3698 else
3699 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003700
Chris Lattner24943d22010-06-08 16:52:24 +00003701 BroadcastEvent (event_sp);
3702 }
3703 else
3704 {
3705 if (log)
3706 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003707 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003708 __FUNCTION__,
3709 GetID(),
3710 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003711 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003712 }
3713 }
Jim Ingham43892562012-06-06 00:29:30 +00003714 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003715}
3716
3717void *
3718Process::PrivateStateThread (void *arg)
3719{
3720 Process *proc = static_cast<Process*> (arg);
3721 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003722 return result;
3723}
3724
3725void *
3726Process::RunPrivateStateThread ()
3727{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003728 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003729 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003730
Greg Claytone005f2c2010-11-06 01:53:30 +00003731 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003732 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003733 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003734
3735 bool exit_now = false;
3736 while (!exit_now)
3737 {
3738 EventSP event_sp;
3739 WaitForEventsPrivate (NULL, event_sp, control_only);
3740 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3741 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003742 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003743 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003744
Chris Lattner24943d22010-06-08 16:52:24 +00003745 switch (event_sp->GetType())
3746 {
3747 case eBroadcastInternalStateControlStop:
3748 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003749 break; // doing any internal state managment below
3750
3751 case eBroadcastInternalStateControlPause:
3752 control_only = true;
3753 break;
3754
3755 case eBroadcastInternalStateControlResume:
3756 control_only = false;
3757 break;
3758 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003759
Chris Lattner24943d22010-06-08 16:52:24 +00003760 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003761 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003762 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003763 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3764 {
3765 if (m_public_state.GetValue() == eStateAttaching)
3766 {
3767 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003768 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00003769 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3770 }
3771 else
3772 {
3773 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003774 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00003775 Halt();
3776 }
3777 continue;
3778 }
Chris Lattner24943d22010-06-08 16:52:24 +00003779
3780 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3781
3782 if (internal_state != eStateInvalid)
3783 {
3784 HandlePrivateEvent (event_sp);
3785 }
3786
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003787 if (internal_state == eStateInvalid ||
3788 internal_state == eStateExited ||
3789 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003790 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003791 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003792 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003793
Chris Lattner24943d22010-06-08 16:52:24 +00003794 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003795 }
Chris Lattner24943d22010-06-08 16:52:24 +00003796 }
3797
Caroline Tice926060e2010-10-29 21:48:37 +00003798 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003799 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003800 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003801
Greg Claytona4881d02011-01-22 07:12:45 +00003802 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3803 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003804 return NULL;
3805}
3806
Chris Lattner24943d22010-06-08 16:52:24 +00003807//------------------------------------------------------------------
3808// Process Event Data
3809//------------------------------------------------------------------
3810
3811Process::ProcessEventData::ProcessEventData () :
3812 EventData (),
3813 m_process_sp (),
3814 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003815 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003816 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003817 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003818{
3819}
3820
3821Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3822 EventData (),
3823 m_process_sp (process_sp),
3824 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003825 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003826 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003827 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003828{
3829}
3830
3831Process::ProcessEventData::~ProcessEventData()
3832{
3833}
3834
3835const ConstString &
3836Process::ProcessEventData::GetFlavorString ()
3837{
3838 static ConstString g_flavor ("Process::ProcessEventData");
3839 return g_flavor;
3840}
3841
3842const ConstString &
3843Process::ProcessEventData::GetFlavor () const
3844{
3845 return ProcessEventData::GetFlavorString ();
3846}
3847
Chris Lattner24943d22010-06-08 16:52:24 +00003848void
3849Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3850{
3851 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003852 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3853 // the public event queue, then other times when we're pretending that this is where we stopped at the
3854 // end of expression evaluation. m_update_state is used to distinguish these
3855 // three cases; it is 0 when we're just pulling it off for private handling,
3856 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003857
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003858 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003859 return;
3860
3861 m_process_sp->SetPublicState (m_state);
3862
3863 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3864 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003865 {
3866 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003867 uint32_t num_threads = curr_thread_list.GetSize();
3868 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003869
Jim Ingham21f37ad2011-08-09 02:12:22 +00003870 // The actions might change one of the thread's stop_info's opinions about whether we should
3871 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003872
3873 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3874 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3875 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3876 // 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
3877 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003878 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003879 for (idx = 0; idx < num_threads; ++idx)
3880 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3881
Jim Inghamb6059b22012-12-13 22:24:15 +00003882 // Use this to track whether we should continue from here. We will only continue the target running if
3883 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
3884 // then it doesn't matter what the other threads say...
3885
3886 bool still_should_stop = false;
Jim Ingham21f37ad2011-08-09 02:12:22 +00003887
Chris Lattner24943d22010-06-08 16:52:24 +00003888 for (idx = 0; idx < num_threads; ++idx)
3889 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003890 curr_thread_list = m_process_sp->GetThreadList();
3891 if (curr_thread_list.GetSize() != num_threads)
3892 {
3893 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003894 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003895 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0296fe72011-11-08 03:00:11 +00003896 break;
3897 }
3898
3899 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3900
3901 if (thread_sp->GetIndexID() != thread_index_array[idx])
3902 {
3903 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003904 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003905 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003906 idx,
3907 thread_index_array[idx],
3908 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003909 break;
3910 }
3911
Jim Ingham6297a3a2010-10-20 00:39:53 +00003912 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00003913 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00003914 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003915 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003916 // The stop action might restart the target. If it does, then we want to mark that in the
3917 // event so that whoever is receiving it will know to wait for the running event and reflect
3918 // that state appropriately.
3919 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003920
3921 // FIXME: we might have run.
3922 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003923 {
3924 SetRestarted (true);
3925 break;
3926 }
Jim Inghamb6059b22012-12-13 22:24:15 +00003927
3928 bool this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
3929 if (still_should_stop == false)
3930 still_should_stop = this_thread_wants_to_stop;
Chris Lattner24943d22010-06-08 16:52:24 +00003931 }
3932 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003933
Jim Ingham21f37ad2011-08-09 02:12:22 +00003934
3935 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003936 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003937 if (!still_should_stop)
3938 {
3939 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003940 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00003941 // Use the public resume method here, since this is just
3942 // extending a public resume.
Jim Ingham21f37ad2011-08-09 02:12:22 +00003943 m_process_sp->Resume();
3944 }
3945 else
3946 {
3947 // If we didn't restart, run the Stop Hooks here:
3948 // They might also restart the target, so watch for that.
3949 m_process_sp->GetTarget().RunStopHooks();
3950 if (m_process_sp->GetPrivateState() == eStateRunning)
3951 SetRestarted(true);
3952 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003953 }
3954
Chris Lattner24943d22010-06-08 16:52:24 +00003955 }
3956}
3957
3958void
3959Process::ProcessEventData::Dump (Stream *s) const
3960{
3961 if (m_process_sp)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003962 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003963
Greg Claytonb72d0f02011-04-12 05:54:46 +00003964 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003965}
3966
3967const Process::ProcessEventData *
3968Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3969{
3970 if (event_ptr)
3971 {
3972 const EventData *event_data = event_ptr->GetData();
3973 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3974 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3975 }
3976 return NULL;
3977}
3978
3979ProcessSP
3980Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3981{
3982 ProcessSP process_sp;
3983 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3984 if (data)
3985 process_sp = data->GetProcessSP();
3986 return process_sp;
3987}
3988
3989StateType
3990Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3991{
3992 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3993 if (data == NULL)
3994 return eStateInvalid;
3995 else
3996 return data->GetState();
3997}
3998
3999bool
4000Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4001{
4002 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4003 if (data == NULL)
4004 return false;
4005 else
4006 return data->GetRestarted();
4007}
4008
4009void
4010Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4011{
4012 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4013 if (data != NULL)
4014 data->SetRestarted(new_value);
4015}
4016
4017bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00004018Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4019{
4020 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4021 if (data == NULL)
4022 return false;
4023 else
4024 return data->GetInterrupted ();
4025}
4026
4027void
4028Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4029{
4030 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4031 if (data != NULL)
4032 data->SetInterrupted(new_value);
4033}
4034
4035bool
Chris Lattner24943d22010-06-08 16:52:24 +00004036Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4037{
4038 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4039 if (data)
4040 {
4041 data->SetUpdateStateOnRemoval();
4042 return true;
4043 }
4044 return false;
4045}
4046
Greg Clayton289afcb2012-02-18 05:35:26 +00004047lldb::TargetSP
4048Process::CalculateTarget ()
4049{
4050 return m_target.shared_from_this();
4051}
4052
Chris Lattner24943d22010-06-08 16:52:24 +00004053void
Greg Claytona830adb2010-10-04 01:05:56 +00004054Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00004055{
Greg Clayton567e7f32011-09-22 04:58:26 +00004056 exe_ctx.SetTargetPtr (&m_target);
4057 exe_ctx.SetProcessPtr (this);
4058 exe_ctx.SetThreadPtr(NULL);
4059 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00004060}
4061
Greg Claytone4b9c1f2011-03-08 22:40:15 +00004062//uint32_t
4063//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4064//{
4065// return 0;
4066//}
4067//
4068//ArchSpec
4069//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4070//{
4071// return Host::GetArchSpecForExistingProcess (pid);
4072//}
4073//
4074//ArchSpec
4075//Process::GetArchSpecForExistingProcess (const char *process_name)
4076//{
4077// return Host::GetArchSpecForExistingProcess (process_name);
4078//}
4079//
Caroline Tice861efb32010-11-16 05:07:41 +00004080void
4081Process::AppendSTDOUT (const char * s, size_t len)
4082{
Greg Clayton20d338f2010-11-18 05:57:03 +00004083 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00004084 m_stdout_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004085 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00004086}
4087
4088void
Greg Claytonbd06ff42011-11-13 04:45:22 +00004089Process::AppendSTDERR (const char * s, size_t len)
4090{
4091 Mutex::Locker locker (m_stdio_communication_mutex);
4092 m_stderr_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004093 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004094}
4095
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004096void
4097Process::BroadcastAsyncProfileData(const char *s, size_t len)
4098{
4099 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004100 m_profile_data.push_back(s);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004101 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4102}
4103
4104size_t
4105Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4106{
4107 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004108 if (m_profile_data.empty())
4109 return 0;
4110
4111 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004112 if (bytes_available > 0)
4113 {
4114 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4115 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004116 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004117 if (bytes_available > buf_size)
4118 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004119 memcpy(buf, m_profile_data.front().data(), buf_size);
4120 m_profile_data.front().erase(0, buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004121 bytes_available = buf_size;
4122 }
4123 else
4124 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004125 memcpy(buf, m_profile_data.front().data(), bytes_available);
4126 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004127 }
4128 }
4129 return bytes_available;
4130}
4131
4132
Greg Claytonbd06ff42011-11-13 04:45:22 +00004133//------------------------------------------------------------------
4134// Process STDIO
4135//------------------------------------------------------------------
4136
4137size_t
4138Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4139{
4140 Mutex::Locker locker(m_stdio_communication_mutex);
4141 size_t bytes_available = m_stdout_data.size();
4142 if (bytes_available > 0)
4143 {
4144 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4145 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004146 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004147 if (bytes_available > buf_size)
4148 {
4149 memcpy(buf, m_stdout_data.c_str(), buf_size);
4150 m_stdout_data.erase(0, buf_size);
4151 bytes_available = buf_size;
4152 }
4153 else
4154 {
4155 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4156 m_stdout_data.clear();
4157 }
4158 }
4159 return bytes_available;
4160}
4161
4162
4163size_t
4164Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4165{
4166 Mutex::Locker locker(m_stdio_communication_mutex);
4167 size_t bytes_available = m_stderr_data.size();
4168 if (bytes_available > 0)
4169 {
4170 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4171 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004172 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004173 if (bytes_available > buf_size)
4174 {
4175 memcpy(buf, m_stderr_data.c_str(), buf_size);
4176 m_stderr_data.erase(0, buf_size);
4177 bytes_available = buf_size;
4178 }
4179 else
4180 {
4181 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4182 m_stderr_data.clear();
4183 }
4184 }
4185 return bytes_available;
4186}
4187
4188void
Caroline Tice861efb32010-11-16 05:07:41 +00004189Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4190{
4191 Process *process = (Process *) baton;
4192 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4193}
4194
4195size_t
4196Process::ProcessInputReaderCallback (void *baton,
4197 InputReader &reader,
4198 lldb::InputReaderAction notification,
4199 const char *bytes,
4200 size_t bytes_len)
4201{
4202 Process *process = (Process *) baton;
4203
4204 switch (notification)
4205 {
4206 case eInputReaderActivate:
4207 break;
4208
4209 case eInputReaderDeactivate:
4210 break;
4211
4212 case eInputReaderReactivate:
4213 break;
4214
Caroline Tice4a348082011-05-02 20:41:46 +00004215 case eInputReaderAsynchronousOutputWritten:
4216 break;
4217
Caroline Tice861efb32010-11-16 05:07:41 +00004218 case eInputReaderGotToken:
4219 {
4220 Error error;
4221 process->PutSTDIN (bytes, bytes_len, error);
4222 }
4223 break;
4224
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004225 case eInputReaderInterrupt:
4226 process->Halt ();
4227 break;
4228
4229 case eInputReaderEndOfFile:
4230 process->AppendSTDOUT ("^D", 2);
4231 break;
4232
Caroline Tice861efb32010-11-16 05:07:41 +00004233 case eInputReaderDone:
4234 break;
4235
4236 }
4237
4238 return bytes_len;
4239}
4240
4241void
4242Process::ResetProcessInputReader ()
4243{
4244 m_process_input_reader.reset();
4245}
4246
4247void
Greg Clayton464c6162011-11-17 22:14:31 +00004248Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004249{
4250 // First set up the Read Thread for reading/handling process I/O
4251
4252 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4253
4254 if (conn_ap.get())
4255 {
4256 m_stdio_communication.SetConnection (conn_ap.release());
4257 if (m_stdio_communication.IsConnected())
4258 {
4259 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4260 m_stdio_communication.StartReadThread();
4261
4262 // Now read thread is set up, set up input reader.
4263
4264 if (!m_process_input_reader.get())
4265 {
4266 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4267 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4268 this,
4269 eInputReaderGranularityByte,
4270 NULL,
4271 NULL,
4272 false));
4273
4274 if (err.Fail())
4275 m_process_input_reader.reset();
4276 }
4277 }
4278 }
4279}
4280
4281void
4282Process::PushProcessInputReader ()
4283{
4284 if (m_process_input_reader && !m_process_input_reader->IsActive())
4285 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4286}
4287
4288void
4289Process::PopProcessInputReader ()
4290{
4291 if (m_process_input_reader && m_process_input_reader->IsActive())
4292 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4293}
4294
Greg Claytond284b662011-02-18 01:44:25 +00004295// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004296void
Caroline Tice2a456812011-03-10 22:14:10 +00004297Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004298{
Greg Clayton73844aa2012-08-22 17:17:09 +00004299// static std::vector<OptionEnumValueElement> g_plugins;
4300//
4301// int i=0;
4302// const char *name;
4303// OptionEnumValueElement option_enum;
4304// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4305// {
4306// if (name)
4307// {
4308// option_enum.value = i;
4309// option_enum.string_value = name;
4310// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4311// g_plugins.push_back (option_enum);
4312// }
4313// ++i;
4314// }
4315// option_enum.value = 0;
4316// option_enum.string_value = NULL;
4317// option_enum.usage = NULL;
4318// g_plugins.push_back (option_enum);
4319//
4320// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4321// {
4322// if (::strcmp (name, "plugin") == 0)
4323// {
4324// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4325// break;
4326// }
4327// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004328//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004329 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004330}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004331
Greg Clayton990de7b2010-11-18 23:32:35 +00004332void
Caroline Tice2a456812011-03-10 22:14:10 +00004333Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004334{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004335 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004336}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004337
Greg Clayton427f2902010-12-14 02:59:59 +00004338ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004339Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004340 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004341 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004342 bool run_others,
Jim Inghamb7940202013-01-15 02:47:48 +00004343 bool unwind_on_error,
4344 bool ignore_breakpoints,
Jim Ingham47beabb2012-10-16 21:41:58 +00004345 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004346 Stream &errors)
4347{
4348 ExecutionResults return_value = eExecutionSetupError;
4349
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004350 if (thread_plan_sp.get() == NULL)
4351 {
4352 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004353 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004354 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004355
4356 if (exe_ctx.GetProcessPtr() != this)
4357 {
4358 errors.Printf("RunThreadPlan called on wrong process.");
4359 return eExecutionSetupError;
4360 }
4361
4362 Thread *thread = exe_ctx.GetThreadPtr();
4363 if (thread == NULL)
4364 {
4365 errors.Printf("RunThreadPlan called with invalid thread.");
4366 return eExecutionSetupError;
4367 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004368
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004369 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4370 // For that to be true the plan can't be private - since private plans suppress themselves in the
4371 // GetCompletedPlan call.
4372
4373 bool orig_plan_private = thread_plan_sp->GetPrivate();
4374 thread_plan_sp->SetPrivate(false);
4375
Jim Inghamac959662011-01-24 06:34:17 +00004376 if (m_private_state.GetValue() != eStateStopped)
4377 {
4378 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004379 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004380 }
4381
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004382 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004383 const uint32_t thread_idx_id = thread->GetIndexID();
4384 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004385
4386 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4387 // so we should arrange to reset them as well.
4388
Greg Clayton567e7f32011-09-22 04:58:26 +00004389 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004390
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004391 uint32_t selected_tid;
4392 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004393 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004394 {
4395 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004396 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004397 }
4398 else
4399 {
4400 selected_tid = LLDB_INVALID_THREAD_ID;
4401 }
4402
Jim Ingham1831e782012-04-07 00:00:41 +00004403 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004404 lldb::StateType old_state;
4405 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004406
Jim Inghamd21d98b2012-04-10 01:21:57 +00004407 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004408 if (Host::GetCurrentThread() == m_private_state_thread)
4409 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004410 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4411 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004412 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Inghamd21d98b2012-04-10 01:21:57 +00004413 // we are fielding public events here.
4414 if (log)
Jason Molenda559cf6e2012-11-17 01:41:04 +00004415 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
Jim Inghamd21d98b2012-04-10 01:21:57 +00004416
4417
Jim Ingham1831e782012-04-07 00:00:41 +00004418 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004419
4420 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4421 // returning control here.
4422 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4423 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4424 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4425 // do just what we want.
4426 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4427 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4428 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4429 old_state = m_public_state.GetValue();
4430 m_public_state.SetValueNoLock(eStateStopped);
4431
4432 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004433 StartPrivateStateThread(true);
4434 }
4435
4436 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004437
Jim Ingham6ae318c2011-01-23 21:14:08 +00004438 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004439
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004440 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004441
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004442 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004443 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4444 // restored on exit to the function.
4445 //
4446 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4447 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004448
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004449 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004450
Jim Ingham360f53f2010-11-30 02:22:11 +00004451 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004452 {
4453 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004454 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004455 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004456 thread->GetIndexID(),
4457 thread->GetID(),
4458 s.GetData());
4459 }
4460
4461 bool got_event;
4462 lldb::EventSP event_sp;
4463 lldb::StateType stop_state = lldb::eStateInvalid;
4464
4465 TimeValue* timeout_ptr = NULL;
4466 TimeValue real_timeout;
4467
4468 bool first_timeout = true;
4469 bool do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004470 bool handle_running_event = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004471 const uint64_t default_one_thread_timeout_usec = 250000;
4472 uint64_t computed_timeout = 0;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004473
Jim Ingham76b258d2012-11-26 23:52:18 +00004474 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4475 // So don't call return anywhere within it.
4476
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004477 while (1)
4478 {
4479 // We usually want to resume the process if we get to the top of the loop.
4480 // The only exception is if we get two running events with no intervening
4481 // stop, which can happen, we will just wait for then next stop event.
4482
Jim Inghamb7940202013-01-15 02:47:48 +00004483 if (do_resume || handle_running_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004484 {
4485 // Do the initial resume and wait for the running event before going further.
4486
Jim Inghamb7940202013-01-15 02:47:48 +00004487 if (do_resume)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004488 {
Jim Inghamb7940202013-01-15 02:47:48 +00004489 Error resume_error = PrivateResume ();
4490 if (!resume_error.Success())
4491 {
4492 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4493 return_value = eExecutionSetupError;
4494 break;
4495 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004496 }
4497
4498 real_timeout = TimeValue::Now();
4499 real_timeout.OffsetWithMicroSeconds(500000);
4500 timeout_ptr = &real_timeout;
4501
4502 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4503 if (!got_event)
4504 {
4505 if (log)
4506 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4507
4508 errors.Printf("Didn't get any event after initial resume, exiting.");
4509 return_value = eExecutionSetupError;
4510 break;
4511 }
4512
4513 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4514 if (stop_state != eStateRunning)
4515 {
4516 if (log)
Jim Ingham47beabb2012-10-16 21:41:58 +00004517 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4518 "initial resume, got %s instead.",
4519 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004520
Jim Ingham47beabb2012-10-16 21:41:58 +00004521 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4522 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004523 return_value = eExecutionSetupError;
4524 break;
4525 }
4526
4527 if (log)
4528 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4529 // We need to call the function synchronously, so spin waiting for it to return.
4530 // If we get interrupted while executing, we're going to lose our context, and
4531 // won't be able to gather the result at this point.
4532 // We set the timeout AFTER the resume, since the resume takes some time and we
4533 // don't want to charge that to the timeout.
4534
Jim Ingham47beabb2012-10-16 21:41:58 +00004535 if (first_timeout)
4536 {
4537 if (run_others)
4538 {
4539 // If we are running all threads then we take half the time to run all threads, bounded by
4540 // .25 sec.
4541 if (timeout_usec == 0)
4542 computed_timeout = default_one_thread_timeout_usec;
4543 else
4544 {
4545 computed_timeout = timeout_usec / 2;
4546 if (computed_timeout > default_one_thread_timeout_usec)
4547 {
4548 computed_timeout = default_one_thread_timeout_usec;
4549 }
4550 timeout_usec -= computed_timeout;
4551 }
4552 }
4553 else
4554 {
4555 computed_timeout = timeout_usec;
4556 }
4557 }
4558 else
4559 {
4560 computed_timeout = timeout_usec;
4561 }
4562
4563 if (computed_timeout != 0)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004564 {
Enrico Granata6cca9692012-07-16 23:10:35 +00004565 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004566 real_timeout = TimeValue::Now();
Jim Ingham47beabb2012-10-16 21:41:58 +00004567 real_timeout.OffsetWithMicroSeconds(computed_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004568
4569 timeout_ptr = &real_timeout;
4570 }
Enrico Granata6cca9692012-07-16 23:10:35 +00004571 else
4572 {
Jim Ingham47beabb2012-10-16 21:41:58 +00004573 timeout_ptr = NULL;
Enrico Granata6cca9692012-07-16 23:10:35 +00004574 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004575 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004576 else
4577 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004578 if (log)
4579 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4580 do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004581 handle_running_event = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004582 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004583
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004584 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004585 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004586
Jim Inghamf9f40c22011-02-08 05:20:59 +00004587 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004588 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004589 if (timeout_ptr)
4590 {
4591 StreamString s;
4592 s.Printf ("about to wait - timeout is:\n ");
4593 timeout_ptr->Dump (&s, 120);
4594 s.Printf ("\nNow is:\n ");
4595 TimeValue::Now().Dump (&s, 120);
4596 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4597 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004598 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004599 {
4600 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4601 }
4602 }
4603
4604 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4605
4606 if (got_event)
4607 {
4608 if (event_sp.get())
4609 {
4610 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004611 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004612 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004613 Halt();
4614 keep_going = false;
4615 return_value = eExecutionInterrupted;
4616 errors.Printf ("Execution halted by user interrupt.");
4617 if (log)
4618 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4619 }
4620 else
4621 {
4622 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4623 if (log)
4624 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4625
4626 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004627 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004628 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004629 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004630 // Yay, we're done. Now make sure that our thread plan actually completed.
4631 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4632 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004633 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004634 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004635 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004636 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4637 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004638 }
4639 else
4640 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004641 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4642 StopReason stop_reason = eStopReasonInvalid;
4643 if (stop_info_sp)
4644 stop_reason = stop_info_sp->GetStopReason();
4645 if (stop_reason == eStopReasonPlanComplete)
4646 {
4647 if (log)
4648 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4649 // Now mark this plan as private so it doesn't get reported as the stop reason
4650 // after this point.
4651 if (thread_plan_sp)
4652 thread_plan_sp->SetPrivate (orig_plan_private);
4653 return_value = eExecutionCompleted;
4654 }
4655 else
4656 {
Jim Inghamb7940202013-01-15 02:47:48 +00004657 // Something restarted the target, so just wait for it to stop for real.
4658 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4659 {
4660 if (log)
4661 log->PutCString ("Process::RunThreadPlan(): Somebody stopped and then restarted, we'll continue waiting.");
4662 keep_going = true;
4663 do_resume = false;
4664 handle_running_event = true;
4665 }
4666 else
4667 {
4668 if (log)
4669 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
4670 if (stop_reason == eStopReasonBreakpoint)
4671 return_value = eExecutionHitBreakpoint;
4672 else
4673 return_value = eExecutionInterrupted;
4674 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004675 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004676 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004677 }
4678 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004679
Jim Ingham5d90ade2012-07-27 23:57:19 +00004680 case lldb::eStateCrashed:
4681 if (log)
4682 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4683 return_value = eExecutionInterrupted;
4684 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004685
Jim Ingham5d90ade2012-07-27 23:57:19 +00004686 case lldb::eStateRunning:
4687 do_resume = false;
4688 keep_going = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004689 handle_running_event = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004690 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004691
Jim Ingham5d90ade2012-07-27 23:57:19 +00004692 default:
4693 if (log)
4694 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4695
4696 if (stop_state == eStateExited)
4697 event_to_broadcast_sp = event_sp;
4698
Sean Callanan96abc622012-08-08 17:35:10 +00004699 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00004700 return_value = eExecutionInterrupted;
4701 break;
4702 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004703 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004704
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004705 if (keep_going)
4706 continue;
4707 else
4708 break;
4709 }
4710 else
4711 {
4712 if (log)
4713 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4714 return_value = eExecutionInterrupted;
4715 break;
4716 }
4717 }
4718 else
4719 {
4720 // If we didn't get an event that means we've timed out...
4721 // We will interrupt the process here. Depending on what we were asked to do we will
4722 // either exit, or try with all threads running for the same timeout.
4723 // Not really sure what to do if Halt fails here...
4724
4725 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00004726 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004727 {
4728 if (first_timeout)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004729 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %" PRId64 " timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004730 "trying for %d usec with all threads enabled.",
4731 computed_timeout, timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004732 else
4733 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00004734 "and timeout: %d timed out, abandoning execution.",
4735 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004736 }
4737 else
4738 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004739 "abandoning execution.",
4740 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004741 }
4742
4743 Error halt_error = Halt();
4744 if (halt_error.Success())
4745 {
4746 if (log)
4747 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4748
4749 // If halt succeeds, it always produces a stopped event. Wait for that:
4750
4751 real_timeout = TimeValue::Now();
4752 real_timeout.OffsetWithMicroSeconds(500000);
4753
4754 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4755
4756 if (got_event)
4757 {
4758 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4759 if (log)
4760 {
4761 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4762 if (stop_state == lldb::eStateStopped
4763 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4764 log->PutCString (" Event was the Halt interruption event.");
4765 }
4766
4767 if (stop_state == lldb::eStateStopped)
4768 {
4769 // Between the time we initiated the Halt and the time we delivered it, the process could have
4770 // already finished its job. Check that here:
4771
4772 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4773 {
4774 if (log)
4775 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4776 "Exiting wait loop.");
4777 return_value = eExecutionCompleted;
4778 break;
4779 }
4780
Jim Ingham47beabb2012-10-16 21:41:58 +00004781 if (!run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004782 {
4783 if (log)
4784 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4785 return_value = eExecutionInterrupted;
4786 break;
4787 }
4788
4789 if (first_timeout)
4790 {
4791 // Set all the other threads to run, and return to the top of the loop, which will continue;
4792 first_timeout = false;
4793 thread_plan_sp->SetStopOthers (false);
4794 if (log)
4795 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4796
4797 continue;
4798 }
4799 else
4800 {
4801 // Running all threads failed, so return Interrupted.
4802 if (log)
4803 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4804 return_value = eExecutionInterrupted;
4805 break;
4806 }
4807 }
4808 }
4809 else
4810 { if (log)
4811 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4812 "I'm getting out of here passing Interrupted.");
4813 return_value = eExecutionInterrupted;
4814 break;
4815 }
4816 }
4817 else
4818 {
4819 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4820 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4821 if (log)
4822 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.",
4823 halt_error.AsCString());
4824 real_timeout = TimeValue::Now();
4825 real_timeout.OffsetWithMicroSeconds(500000);
4826 timeout_ptr = &real_timeout;
4827 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4828 if (!got_event || event_sp.get() == NULL)
4829 {
4830 // This is not going anywhere, bag out.
4831 if (log)
4832 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4833 return_value = eExecutionInterrupted;
4834 break;
4835 }
4836 else
4837 {
4838 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4839 if (log)
4840 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4841 if (stop_state == lldb::eStateStopped)
4842 {
4843 // Between the time we initiated the Halt and the time we delivered it, the process could have
4844 // already finished its job. Check that here:
4845
4846 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4847 {
4848 if (log)
4849 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4850 "Exiting wait loop.");
4851 return_value = eExecutionCompleted;
4852 break;
4853 }
4854
4855 if (first_timeout)
4856 {
4857 // Set all the other threads to run, and return to the top of the loop, which will continue;
4858 first_timeout = false;
4859 thread_plan_sp->SetStopOthers (false);
4860 if (log)
4861 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4862
4863 continue;
4864 }
4865 else
4866 {
4867 // Running all threads failed, so return Interrupted.
4868 if (log)
4869 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4870 return_value = eExecutionInterrupted;
4871 break;
4872 }
4873 }
4874 else
4875 {
4876 if (log)
4877 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4878 " a stopped event, instead got %s.", StateAsCString(stop_state));
4879 return_value = eExecutionInterrupted;
4880 break;
4881 }
4882 }
4883 }
4884
4885 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004886 } // END WAIT LOOP
4887
4888 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4889 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4890 {
4891 StopPrivateStateThread();
4892 Error error;
4893 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00004894 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004895 {
4896 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4897 }
4898 m_public_state.SetValueNoLock(old_state);
4899
4900 }
4901
Jim Inghamb7940202013-01-15 02:47:48 +00004902 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
4903 // could happen:
4904 // 1) The execution successfully completed
4905 // 2) We hit a breakpoint, and ignore_breakpoints was true
4906 // 3) We got some other error, and discard_on_error was true
4907 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
4908 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham76b258d2012-11-26 23:52:18 +00004909
Jim Inghamb7940202013-01-15 02:47:48 +00004910 if (return_value == eExecutionCompleted
4911 || should_unwind)
Jim Ingham76b258d2012-11-26 23:52:18 +00004912 {
4913 thread_plan_sp->RestoreThreadState();
4914 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004915
4916 // Now do some processing on the results of the run:
Jim Inghamb7940202013-01-15 02:47:48 +00004917 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004918 {
4919 if (log)
4920 {
4921 StreamString s;
4922 if (event_sp)
4923 event_sp->Dump (&s);
4924 else
4925 {
4926 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4927 }
4928
4929 StreamString ts;
4930
4931 const char *event_explanation = NULL;
4932
4933 do
4934 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004935 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004936 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004937 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004938 break;
4939 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004940 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004941 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004942 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004943 break;
4944 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004945 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004946 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004947 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4948
4949 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004950 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004951 event_explanation = "<no event data>";
4952 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004953 }
4954
Jim Ingham5d90ade2012-07-27 23:57:19 +00004955 Process *process = event_data->GetProcessSP().get();
4956
4957 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004958 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004959 event_explanation = "<no process>";
4960 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004961 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004962
4963 ThreadList &thread_list = process->GetThreadList();
4964
4965 uint32_t num_threads = thread_list.GetSize();
4966 uint32_t thread_index;
4967
4968 ts.Printf("<%u threads> ", num_threads);
4969
4970 for (thread_index = 0;
4971 thread_index < num_threads;
4972 ++thread_index)
4973 {
4974 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4975
4976 if (!thread)
4977 {
4978 ts.Printf("<?> ");
4979 continue;
4980 }
4981
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004982 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00004983 RegisterContext *register_context = thread->GetRegisterContext().get();
4984
4985 if (register_context)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004986 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Ingham5d90ade2012-07-27 23:57:19 +00004987 else
4988 ts.Printf("[ip unknown] ");
4989
4990 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4991 if (stop_info_sp)
4992 {
4993 const char *stop_desc = stop_info_sp->GetDescription();
4994 if (stop_desc)
4995 ts.PutCString (stop_desc);
4996 }
4997 ts.Printf(">");
4998 }
4999
5000 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005001 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005002 } while (0);
5003
Jim Ingham5d90ade2012-07-27 23:57:19 +00005004 if (event_explanation)
5005 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005006 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00005007 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5008 }
5009
Jim Inghamb7940202013-01-15 02:47:48 +00005010 if (should_unwind && thread_plan_sp)
Jim Ingham5d90ade2012-07-27 23:57:19 +00005011 {
5012 if (log)
5013 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5014 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5015 thread_plan_sp->SetPrivate (orig_plan_private);
5016 }
5017 else
5018 {
5019 if (log)
5020 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005021 }
5022 }
5023 else if (return_value == eExecutionSetupError)
5024 {
5025 if (log)
5026 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00005027
Jim Inghamb7940202013-01-15 02:47:48 +00005028 if (unwind_on_error && thread_plan_sp)
Jim Inghamf9f40c22011-02-08 05:20:59 +00005029 {
Greg Clayton567e7f32011-09-22 04:58:26 +00005030 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00005031 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00005032 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005033 }
5034 else
5035 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005036 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00005037 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00005038 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005039 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5040 return_value = eExecutionCompleted;
5041 }
5042 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5043 {
5044 if (log)
5045 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5046 return_value = eExecutionDiscarded;
5047 }
5048 else
5049 {
5050 if (log)
5051 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamb7940202013-01-15 02:47:48 +00005052 if (unwind_on_error && thread_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005053 {
5054 if (log)
Jim Inghamb7940202013-01-15 02:47:48 +00005055 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005056 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5057 thread_plan_sp->SetPrivate (orig_plan_private);
5058 }
5059 }
5060 }
5061
5062 // Thread we ran the function in may have gone away because we ran the target
5063 // Check that it's still there, and if it is put it back in the context. Also restore the
5064 // frame in the context if it is still present.
5065 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5066 if (thread)
5067 {
5068 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5069 }
5070
5071 // Also restore the current process'es selected frame & thread, since this function calling may
5072 // be done behind the user's back.
5073
5074 if (selected_tid != LLDB_INVALID_THREAD_ID)
5075 {
5076 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5077 {
5078 // We were able to restore the selected thread, now restore the frame:
5079 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5080 if (old_frame_sp)
5081 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00005082 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005083 }
5084 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005085
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005086 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00005087
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005088 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00005089 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005090 if (log)
5091 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5092 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00005093 }
5094
5095 return return_value;
5096}
5097
5098const char *
5099Process::ExecutionResultAsCString (ExecutionResults result)
5100{
5101 const char *result_name;
5102
5103 switch (result)
5104 {
Greg Claytonb3448432011-03-24 21:19:54 +00005105 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005106 result_name = "eExecutionCompleted";
5107 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005108 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00005109 result_name = "eExecutionDiscarded";
5110 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005111 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005112 result_name = "eExecutionInterrupted";
5113 break;
Jim Inghamb7940202013-01-15 02:47:48 +00005114 case eExecutionHitBreakpoint:
5115 result_name = "eExecutionHitBreakpoint";
5116 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005117 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00005118 result_name = "eExecutionSetupError";
5119 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005120 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00005121 result_name = "eExecutionTimedOut";
5122 break;
5123 }
5124 return result_name;
5125}
5126
Greg Claytonabe0fed2011-04-18 08:33:37 +00005127void
5128Process::GetStatus (Stream &strm)
5129{
5130 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00005131 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00005132 {
5133 if (state == eStateExited)
5134 {
5135 int exit_status = GetExitStatus();
5136 const char *exit_description = GetExitDescription();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005137 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00005138 GetID(),
5139 exit_status,
5140 exit_status,
5141 exit_description ? exit_description : "");
5142 }
5143 else
5144 {
5145 if (state == eStateConnected)
5146 strm.Printf ("Connected to remote target.\n");
5147 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005148 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00005149 }
5150 }
5151 else
5152 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005153 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005154 }
5155}
5156
5157size_t
5158Process::GetThreadStatus (Stream &strm,
5159 bool only_threads_with_stop_reason,
5160 uint32_t start_frame,
5161 uint32_t num_frames,
5162 uint32_t num_frames_with_source)
5163{
5164 size_t num_thread_infos_dumped = 0;
5165
Jim Inghamb9950592012-09-10 20:50:15 +00005166 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005167 const size_t num_threads = GetThreadList().GetSize();
5168 for (uint32_t i = 0; i < num_threads; i++)
5169 {
5170 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5171 if (thread)
5172 {
5173 if (only_threads_with_stop_reason)
5174 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00005175 StopInfoSP stop_info_sp = thread->GetStopInfo();
5176 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00005177 continue;
5178 }
5179 thread->GetStatus (strm,
5180 start_frame,
5181 num_frames,
5182 num_frames_with_source);
5183 ++num_thread_infos_dumped;
5184 }
5185 }
5186 return num_thread_infos_dumped;
5187}
5188
Greg Clayton76113302012-02-22 04:37:26 +00005189void
5190Process::AddInvalidMemoryRegion (const LoadRange &region)
5191{
5192 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5193}
5194
5195bool
5196Process::RemoveInvalidMemoryRange (const LoadRange &region)
5197{
5198 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5199}
5200
Jim Ingham1831e782012-04-07 00:00:41 +00005201void
5202Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5203{
5204 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5205}
5206
5207bool
5208Process::RunPreResumeActions ()
5209{
5210 bool result = true;
5211 while (!m_pre_resume_actions.empty())
5212 {
5213 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5214 m_pre_resume_actions.pop_back();
5215 bool this_result = action.callback (action.baton);
5216 if (result == true) result = this_result;
5217 }
5218 return result;
5219}
5220
5221void
5222Process::ClearPreResumeActions ()
5223{
5224 m_pre_resume_actions.clear();
5225}
Greg Clayton76113302012-02-22 04:37:26 +00005226
Greg Claytoncf5927e2012-05-18 02:38:05 +00005227void
5228Process::Flush ()
5229{
5230 m_thread_list.Flush();
5231}
Greg Clayton0bce9a22012-12-05 00:16:59 +00005232
5233void
5234Process::DidExec ()
5235{
5236 Target &target = GetTarget();
5237 target.CleanupProcess ();
5238 ModuleList unloaded_modules (target.GetImages());
5239 target.ModulesDidUnload (unloaded_modules);
5240 target.GetSectionLoadList().Clear();
5241 m_dynamic_checkers_ap.reset();
5242 m_abi_sp.reset();
5243 m_os_ap.reset();
5244 m_dyld_ap.reset();
5245 m_image_tokens.clear();
5246 m_allocated_memory_cache.Clear();
5247 m_language_runtimes.clear();
5248 DoDidExec();
5249 CompleteAttach ();
5250}