blob: 5bda3c61717c2b500c54027371468cb1d2d5ae8b [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-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 Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000021#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
25#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000026#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000027#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000028#include "lldb/Host/Host.h"
29#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000030#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000031#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000032#include "lldb/Target/LanguageRuntime.h"
33#include "lldb/Target/CPPLanguageRuntime.h"
34#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000035#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000037#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-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 Ingham076b3042012-04-10 01:21:57 +000042#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043
44using namespace lldb;
45using namespace lldb_private;
46
Greg Clayton67cc0632012-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 Ingham8c3f2762012-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 Inghamafc1b122013-01-31 19:48:57 +0000100 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
101 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
Greg Claytone1e835c2012-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." },
Jim Ingham29950772013-01-26 02:19:28 +0000103 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
Jim Inghamacff8952013-05-02 00:27:30 +0000104 { "detach-keeps-stopped" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, detach will attempt to keep the process stopped." },
Greg Clayton67cc0632012-08-22 17:17:09 +0000105 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
106};
107
108enum {
109 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000110 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000111 ePropertyIgnoreBreakpointsInExpressions,
112 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000113 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000114 ePropertyStopOnSharedLibraryEvents,
115 ePropertyDetachKeepsStopped
Greg Clayton67cc0632012-08-22 17:17:09 +0000116};
117
118ProcessProperties::ProcessProperties (bool is_global) :
119 Properties ()
120{
121 if (is_global)
122 {
123 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
124 m_collection_sp->Initialize(g_properties);
125 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000126 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000127 true,
128 Thread::GetGlobalProperties()->GetValueProperties());
129 }
130 else
131 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
132}
133
134ProcessProperties::~ProcessProperties()
135{
136}
137
138bool
139ProcessProperties::GetDisableMemoryCache() const
140{
141 const uint32_t idx = ePropertyDisableMemCache;
142 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
143}
144
145Args
146ProcessProperties::GetExtraStartupCommands () const
147{
148 Args args;
149 const uint32_t idx = ePropertyExtraStartCommand;
150 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
151 return args;
152}
153
154void
155ProcessProperties::SetExtraStartupCommands (const Args &args)
156{
157 const uint32_t idx = ePropertyExtraStartCommand;
158 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
159}
160
Greg Claytonc9d645d2012-10-18 22:40:37 +0000161FileSpec
162ProcessProperties::GetPythonOSPluginPath () const
163{
164 const uint32_t idx = ePropertyPythonOSPluginPath;
165 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
166}
167
168void
169ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
170{
171 const uint32_t idx = ePropertyPythonOSPluginPath;
172 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
173}
174
Jim Ingham184e9812013-01-15 02:47:48 +0000175
176bool
177ProcessProperties::GetIgnoreBreakpointsInExpressions () const
178{
179 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
180 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
181}
182
183void
184ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
185{
186 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
187 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
188}
189
190bool
191ProcessProperties::GetUnwindOnErrorInExpressions () const
192{
193 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
194 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
195}
196
197void
198ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
199{
200 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
201 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
202}
203
Jim Ingham29950772013-01-26 02:19:28 +0000204bool
205ProcessProperties::GetStopOnSharedLibraryEvents () const
206{
207 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
208 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
209}
210
211void
212ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
213{
214 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
215 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
216}
217
Jim Inghamacff8952013-05-02 00:27:30 +0000218bool
219ProcessProperties::GetDetachKeepsStopped () const
220{
221 const uint32_t idx = ePropertyDetachKeepsStopped;
222 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
223}
224
225void
226ProcessProperties::SetDetachKeepsStopped (bool stop)
227{
228 const uint32_t idx = ePropertyDetachKeepsStopped;
229 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
230}
231
Greg Clayton32e0a752011-03-30 18:16:51 +0000232void
Greg Clayton8b82f082011-04-12 05:54:46 +0000233ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000234{
235 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000236 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000237 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000238
239 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000240 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000241
242 if (m_executable)
243 {
244 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
245 s.PutCString (" file = ");
246 m_executable.Dump(&s);
247 s.EOL();
248 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000249 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000250 if (argc > 0)
251 {
252 for (uint32_t i=0; i<argc; i++)
253 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000254 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000255 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000256 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000257 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000258 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000259 }
260 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000261
262 const uint32_t envc = m_environment.GetArgumentCount();
263 if (envc > 0)
264 {
265 for (uint32_t i=0; i<envc; i++)
266 {
267 const char *env = m_environment.GetArgumentAtIndex(i);
268 if (i < 10)
269 s.Printf (" env[%u] = %s\n", i, env);
270 else
271 s.Printf ("env[%u] = %s\n", i, env);
272 }
273 }
274
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000275 if (m_arch.IsValid())
276 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
277
Greg Clayton8b82f082011-04-12 05:54:46 +0000278 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000279 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000280 cstr = platform->GetUserName (m_uid);
281 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000282 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000283 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000284 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000285 cstr = platform->GetGroupName (m_gid);
286 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000287 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000288 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000289 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000290 cstr = platform->GetUserName (m_euid);
291 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000292 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000293 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000294 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000295 cstr = platform->GetGroupName (m_egid);
296 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000297 }
298}
299
300void
Greg Clayton8b82f082011-04-12 05:54:46 +0000301ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000302{
Greg Clayton8b82f082011-04-12 05:54:46 +0000303 const char *label;
304 if (show_args || verbose)
305 label = "ARGUMENTS";
306 else
307 label = "NAME";
308
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000309 if (verbose)
310 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000311 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000312 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
313 }
314 else
315 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000316 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000317 s.PutCString ("====== ====== ========== ======= ============================\n");
318 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000319}
320
321void
Greg Clayton8b82f082011-04-12 05:54:46 +0000322ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000323{
324 if (m_pid != LLDB_INVALID_PROCESS_ID)
325 {
326 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000327 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000328
Greg Clayton32e0a752011-03-30 18:16:51 +0000329
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000330 if (verbose)
331 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000332 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000333 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
334 s.Printf ("%-10s ", cstr);
335 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000336 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000337
Greg Clayton8b82f082011-04-12 05:54:46 +0000338 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000339 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
340 s.Printf ("%-10s ", cstr);
341 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000342 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000343
Greg Clayton8b82f082011-04-12 05:54:46 +0000344 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000345 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
346 s.Printf ("%-10s ", cstr);
347 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000348 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000349
Greg Clayton8b82f082011-04-12 05:54:46 +0000350 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000351 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
352 s.Printf ("%-10s ", cstr);
353 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000354 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000355 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
356 }
357 else
358 {
Jason Molendafd54b362011-09-20 21:44:10 +0000359 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000360 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000361 (int)m_arch.GetTriple().getArchName().size(),
362 m_arch.GetTriple().getArchName().data());
363 }
364
Greg Clayton8b82f082011-04-12 05:54:46 +0000365 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000366 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000367 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000368 if (argc > 0)
369 {
370 for (uint32_t i=0; i<argc; i++)
371 {
372 if (i > 0)
373 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000374 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000375 }
376 }
377 }
378 else
379 {
380 s.PutCString (GetName());
381 }
382
383 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000384 }
385}
386
Greg Clayton8b82f082011-04-12 05:54:46 +0000387
388void
Greg Clayton45392552012-10-17 22:57:12 +0000389ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton982c9762011-11-03 21:22:33 +0000390{
391 m_arguments.SetArguments (argv);
392
393 // Is the first argument the executable?
394 if (first_arg_is_executable)
395 {
396 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
397 if (first_arg)
398 {
399 // Yes the first argument is an executable, set it as the executable
400 // in the launch options. Don't resolve the file path as the path
401 // could be a remote platform path
402 const bool resolve = false;
403 m_executable.SetFile(first_arg, resolve);
Greg Clayton982c9762011-11-03 21:22:33 +0000404 }
405 }
406}
407void
Greg Clayton45392552012-10-17 22:57:12 +0000408ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Clayton8b82f082011-04-12 05:54:46 +0000409{
410 // Copy all arguments
411 m_arguments = args;
412
413 // Is the first argument the executable?
414 if (first_arg_is_executable)
415 {
Greg Clayton982c9762011-11-03 21:22:33 +0000416 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000417 if (first_arg)
418 {
419 // Yes the first argument is an executable, set it as the executable
420 // in the launch options. Don't resolve the file path as the path
421 // could be a remote platform path
422 const bool resolve = false;
423 m_executable.SetFile(first_arg, resolve);
Greg Clayton8b82f082011-04-12 05:54:46 +0000424 }
425 }
426}
427
Greg Clayton1d885962011-11-08 02:43:13 +0000428void
Greg Claytonee95ed52011-11-17 22:14:31 +0000429ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-11-08 02:43:13 +0000430{
431 // If notthing was specified, then check the process for any default
432 // settings that were set with "settings set"
433 if (m_file_actions.empty())
434 {
Greg Clayton1d885962011-11-08 02:43:13 +0000435 if (m_flags.Test(eLaunchFlagDisableSTDIO))
436 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000437 AppendSuppressFileAction (STDIN_FILENO , true, false);
438 AppendSuppressFileAction (STDOUT_FILENO, false, true);
439 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000440 }
441 else
442 {
443 // Check for any values that might have gotten set with any of:
444 // (lldb) settings set target.input-path
445 // (lldb) settings set target.output-path
446 // (lldb) settings set target.error-path
Greg Clayton67cc0632012-08-22 17:17:09 +0000447 FileSpec in_path;
448 FileSpec out_path;
449 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000450 if (target)
451 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000452 in_path = target->GetStandardInputPath();
453 out_path = target->GetStandardOutputPath();
454 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000455 }
456
Greg Clayton67cc0632012-08-22 17:17:09 +0000457 if (in_path || out_path || err_path)
458 {
459 char path[PATH_MAX];
460 if (in_path && in_path.GetPath(path, sizeof(path)))
461 AppendOpenFileAction(STDIN_FILENO, path, true, false);
462
463 if (out_path && out_path.GetPath(path, sizeof(path)))
464 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
465
466 if (err_path && err_path.GetPath(path, sizeof(path)))
467 AppendOpenFileAction(STDERR_FILENO, path, false, true);
468 }
469 else if (default_to_use_pty)
Greg Claytonee95ed52011-11-17 22:14:31 +0000470 {
471 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000472 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000473 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
474 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
475 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
476 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000477 }
478 }
Greg Clayton1d885962011-11-08 02:43:13 +0000479 }
480 }
481}
482
Greg Clayton144f3a92011-11-15 03:53:30 +0000483
484bool
Greg Claytond1cf11a2012-04-14 01:42:46 +0000485ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
486 bool localhost,
487 bool will_debug,
488 bool first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000489{
490 error.Clear();
491
492 if (GetFlags().Test (eLaunchFlagLaunchInShell))
493 {
494 const char *shell_executable = GetShell();
495 if (shell_executable)
496 {
497 char shell_resolved_path[PATH_MAX];
498
499 if (localhost)
500 {
501 FileSpec shell_filespec (shell_executable, true);
502
503 if (!shell_filespec.Exists())
504 {
505 // Resolve the path in case we just got "bash", "sh" or "tcsh"
506 if (!shell_filespec.ResolveExecutableLocation ())
507 {
508 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
509 return false;
510 }
511 }
512 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
513 shell_executable = shell_resolved_path;
514 }
515
Greg Clayton45392552012-10-17 22:57:12 +0000516 const char **argv = GetArguments().GetConstArgumentVector ();
517 if (argv == NULL || argv[0] == NULL)
518 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000519 Args shell_arguments;
520 std::string safe_arg;
521 shell_arguments.AppendArgument (shell_executable);
Greg Clayton144f3a92011-11-15 03:53:30 +0000522 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000523 StreamString shell_command;
524 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000525 {
Greg Clayton45392552012-10-17 22:57:12 +0000526 // Add a modified PATH environment variable in case argv[0]
527 // is a relative path
528 const char *argv0 = argv[0];
529 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
530 {
531 // We have a relative path to our executable which may not work if
532 // we just try to run "a.out" (without it being converted to "./a.out")
533 const char *working_dir = GetWorkingDirectory();
Greg Clayton8938f8d2013-02-14 03:54:39 +0000534 // Be sure to put quotes around PATH's value in case any paths have spaces...
535 std::string new_path("PATH=\"");
Greg Clayton45392552012-10-17 22:57:12 +0000536 const size_t empty_path_len = new_path.size();
537
538 if (working_dir && working_dir[0])
539 {
540 new_path += working_dir;
541 }
542 else
543 {
544 char current_working_dir[PATH_MAX];
545 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
546 if (cwd && cwd[0])
547 new_path += cwd;
548 }
549 const char *curr_path = getenv("PATH");
550 if (curr_path)
551 {
552 if (new_path.size() > empty_path_len)
553 new_path += ':';
554 new_path += curr_path;
555 }
Greg Clayton8938f8d2013-02-14 03:54:39 +0000556 new_path += "\" ";
Greg Clayton45392552012-10-17 22:57:12 +0000557 shell_command.PutCString(new_path.c_str());
558 }
559
Greg Claytond1cf11a2012-04-14 01:42:46 +0000560 shell_command.PutCString ("exec");
Greg Clayton45392552012-10-17 22:57:12 +0000561
Greg Clayton45392552012-10-17 22:57:12 +0000562 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Claytond1cf11a2012-04-14 01:42:46 +0000563 if (GetArchitecture().IsValid())
564 {
565 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton45392552012-10-17 22:57:12 +0000566 // Set the resume count to 2:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000567 // 1 - stop in shell
568 // 2 - stop in /usr/bin/arch
569 // 3 - then we will stop in our program
570 SetResumeCount(2);
571 }
572 else
573 {
Greg Clayton45392552012-10-17 22:57:12 +0000574 // Set the resume count to 1:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000575 // 1 - stop in shell
576 // 2 - then we will stop in our program
577 SetResumeCount(1);
578 }
Greg Clayton144f3a92011-11-15 03:53:30 +0000579 }
Greg Clayton45392552012-10-17 22:57:12 +0000580
581 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000582 {
Greg Clayton45392552012-10-17 22:57:12 +0000583 // There should only be one argument that is the shell command itself to be used as is
584 if (argv[0] && !argv[1])
585 shell_command.Printf("%s", argv[0]);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000586 else
Greg Clayton45392552012-10-17 22:57:12 +0000587 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000588 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000589 else
590 {
Greg Clayton45392552012-10-17 22:57:12 +0000591 for (size_t i=0; argv[i] != NULL; ++i)
592 {
593 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
594 shell_command.Printf(" %s", arg);
595 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000596 }
Greg Clayton45392552012-10-17 22:57:12 +0000597 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton144f3a92011-11-15 03:53:30 +0000598 m_executable.SetFile(shell_executable, false);
599 m_arguments = shell_arguments;
600 return true;
601 }
602 else
603 {
604 error.SetErrorString ("invalid shell path");
605 }
606 }
607 else
608 {
609 error.SetErrorString ("not launching in shell");
610 }
611 return false;
612}
613
614
Greg Clayton32e0a752011-03-30 18:16:51 +0000615bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000616ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
617{
618 if ((read || write) && fd >= 0 && path && path[0])
619 {
620 m_action = eFileActionOpen;
621 m_fd = fd;
622 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000623 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000624 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000625 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000626 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000627 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000628 m_path.assign (path);
629 return true;
630 }
631 else
632 {
633 Clear();
634 }
635 return false;
636}
637
638bool
639ProcessLaunchInfo::FileAction::Close (int fd)
640{
641 Clear();
642 if (fd >= 0)
643 {
644 m_action = eFileActionClose;
645 m_fd = fd;
646 }
647 return m_fd >= 0;
648}
649
650
651bool
652ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
653{
654 Clear();
655 if (fd >= 0 && dup_fd >= 0)
656 {
657 m_action = eFileActionDuplicate;
658 m_fd = fd;
659 m_arg = dup_fd;
660 }
661 return m_fd >= 0;
662}
663
664
665
666bool
667ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
668 const FileAction *info,
669 Log *log,
670 Error& error)
671{
672 if (info == NULL)
673 return false;
674
675 switch (info->m_action)
676 {
677 case eFileActionNone:
678 error.Clear();
679 break;
680
681 case eFileActionClose:
682 if (info->m_fd == -1)
683 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
684 else
685 {
686 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
687 eErrorTypePOSIX);
688 if (log && (error.Fail() || log))
689 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
690 file_actions, info->m_fd);
691 }
692 break;
693
694 case eFileActionDuplicate:
695 if (info->m_fd == -1)
696 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
697 else if (info->m_arg == -1)
698 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
699 else
700 {
701 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
702 eErrorTypePOSIX);
703 if (log && (error.Fail() || log))
704 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
705 file_actions, info->m_fd, info->m_arg);
706 }
707 break;
708
709 case eFileActionOpen:
710 if (info->m_fd == -1)
711 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
712 else
713 {
714 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000715
Greg Clayton8b82f082011-04-12 05:54:46 +0000716 mode_t mode = 0;
717
Greg Clayton144f3a92011-11-15 03:53:30 +0000718 if (oflag & O_CREAT)
719 mode = 0640;
720
Greg Clayton8b82f082011-04-12 05:54:46 +0000721 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
722 info->m_fd,
723 info->m_path.c_str(),
724 oflag,
725 mode),
726 eErrorTypePOSIX);
727 if (error.Fail() || log)
728 error.PutToLog(log,
729 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
730 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
731 }
732 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000733 }
734 return error.Success();
735}
736
737Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000738ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000739{
740 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000741 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000742
743 switch (short_option)
744 {
745 case 's': // Stop at program entry point
746 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
747 break;
748
Greg Clayton8b82f082011-04-12 05:54:46 +0000749 case 'i': // STDIN for read only
750 {
751 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000752 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000753 launch_info.AppendFileAction (action);
754 }
755 break;
756
757 case 'o': // Open STDOUT for write only
758 {
759 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000760 if (action.Open (STDOUT_FILENO, option_arg, false, true))
761 launch_info.AppendFileAction (action);
762 }
763 break;
764
765 case 'e': // STDERR for write only
766 {
767 ProcessLaunchInfo::FileAction action;
768 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000769 launch_info.AppendFileAction (action);
770 }
771 break;
772
Greg Clayton9845a8d2012-03-06 04:01:04 +0000773
Greg Clayton8b82f082011-04-12 05:54:46 +0000774 case 'p': // Process plug-in name
775 launch_info.SetProcessPluginName (option_arg);
776 break;
777
778 case 'n': // Disable STDIO
779 {
780 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000781 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000782 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000783 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000784 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000785 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000786 launch_info.AppendFileAction (action);
787 }
788 break;
789
790 case 'w':
791 launch_info.SetWorkingDirectory (option_arg);
792 break;
793
794 case 't': // Open process in new terminal window
795 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
796 break;
797
798 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000799 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
800 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000801 break;
802
803 case 'A':
804 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
805 break;
806
Greg Clayton982c9762011-11-03 21:22:33 +0000807 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000808 if (option_arg && option_arg[0])
809 launch_info.SetShell (option_arg);
810 else
811 launch_info.SetShell ("/bin/bash");
Greg Clayton982c9762011-11-03 21:22:33 +0000812 break;
813
Greg Clayton8b82f082011-04-12 05:54:46 +0000814 case 'v':
815 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
816 break;
817
818 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000819 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000820 break;
821
822 }
823 return error;
824}
825
826OptionDefinition
827ProcessLaunchCommandOptions::g_option_table[] =
828{
829{ 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."},
830{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
831{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
Sean Callanan31542552012-10-24 01:12:14 +0000832{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000833{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
834{ LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Sean Callanan31542552012-10-24 01:12:14 +0000835{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000836
Sean Callanan31542552012-10-24 01:12:14 +0000837{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
838{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
839{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000840
841{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
842
843{ 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."},
844
845{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
846};
847
848
849
850bool
851ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000852{
853 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
854 return true;
855 const char *match_name = m_match_info.GetName();
856 if (!match_name)
857 return true;
858
859 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
860}
861
862bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000863ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000864{
865 if (!NameMatches (proc_info.GetName()))
866 return false;
867
868 if (m_match_info.ProcessIDIsValid() &&
869 m_match_info.GetProcessID() != proc_info.GetProcessID())
870 return false;
871
872 if (m_match_info.ParentProcessIDIsValid() &&
873 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
874 return false;
875
Greg Clayton8b82f082011-04-12 05:54:46 +0000876 if (m_match_info.UserIDIsValid () &&
877 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000878 return false;
879
Greg Clayton8b82f082011-04-12 05:54:46 +0000880 if (m_match_info.GroupIDIsValid () &&
881 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000882 return false;
883
884 if (m_match_info.EffectiveUserIDIsValid () &&
885 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
886 return false;
887
888 if (m_match_info.EffectiveGroupIDIsValid () &&
889 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
890 return false;
891
892 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000893 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000894 return false;
895 return true;
896}
897
898bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000899ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000900{
901 if (m_name_match_type != eNameMatchIgnore)
902 return false;
903
904 if (m_match_info.ProcessIDIsValid())
905 return false;
906
907 if (m_match_info.ParentProcessIDIsValid())
908 return false;
909
Greg Clayton8b82f082011-04-12 05:54:46 +0000910 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000911 return false;
912
Greg Clayton8b82f082011-04-12 05:54:46 +0000913 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000914 return false;
915
916 if (m_match_info.EffectiveUserIDIsValid ())
917 return false;
918
919 if (m_match_info.EffectiveGroupIDIsValid ())
920 return false;
921
922 if (m_match_info.GetArchitecture().IsValid())
923 return false;
924
925 if (m_match_all_users)
926 return false;
927
928 return true;
929
930}
931
932void
Greg Clayton8b82f082011-04-12 05:54:46 +0000933ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000934{
935 m_match_info.Clear();
936 m_name_match_type = eNameMatchIgnore;
937 m_match_all_users = false;
938}
Greg Clayton58be07b2011-01-07 06:08:19 +0000939
Greg Claytonc3776bf2012-02-09 06:16:32 +0000940ProcessSP
941Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000942{
Greg Clayton949e8222013-01-16 17:29:04 +0000943 static uint32_t g_process_unique_id = 0;
944
Greg Claytonc3776bf2012-02-09 06:16:32 +0000945 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000946 ProcessCreateInstance create_callback = NULL;
947 if (plugin_name)
948 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000949 ConstString const_plugin_name(plugin_name);
950 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000951 if (create_callback)
952 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000953 process_sp = create_callback(target, listener, crash_file_path);
954 if (process_sp)
955 {
Greg Clayton949e8222013-01-16 17:29:04 +0000956 if (process_sp->CanDebug(target, true))
957 {
958 process_sp->m_process_unique_id = ++g_process_unique_id;
959 }
960 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000961 process_sp.reset();
962 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000963 }
964 }
965 else
966 {
Greg Claytonc982c762010-07-09 20:39:50 +0000967 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000969 process_sp = create_callback(target, listener, crash_file_path);
970 if (process_sp)
971 {
Greg Clayton949e8222013-01-16 17:29:04 +0000972 if (process_sp->CanDebug(target, false))
973 {
974 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000975 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000976 }
977 else
978 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000979 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980 }
981 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000982 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000983}
984
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000985ConstString &
986Process::GetStaticBroadcasterClass ()
987{
988 static ConstString class_name ("lldb.process");
989 return class_name;
990}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991
992//----------------------------------------------------------------------
993// Process constructor
994//----------------------------------------------------------------------
995Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000996 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000998 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Sean Callananbb777042013-05-16 17:30:37 +0000999 m_reservation_cache (*this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001 m_public_state (eStateUnloaded),
1002 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001003 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1004 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001005 m_private_state_listener ("lldb.process.internal_state_listener"),
1006 m_private_state_control_wait(),
1007 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +00001008 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +00001009 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001011 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001012 m_exit_status (-1),
1013 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001014 m_thread_mutex (Mutex::eMutexTypeRecursive),
1015 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016 m_thread_list (this),
1017 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001018 m_image_tokens (),
1019 m_listener (listener),
1020 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001021 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001022 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001023 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001024 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +00001025 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001026 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +00001027 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +00001028 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001029 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1030 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +00001031 m_memory_cache (*this),
1032 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +00001033 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +00001034 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +00001035 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +00001036 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +00001037 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001038 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +00001039 m_clear_thread_plans_on_stop (false),
Jim Ingham0161b492013-02-09 01:29:05 +00001040 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +00001041 m_destroy_in_process (false),
1042 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001043{
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001044 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +00001045
Greg Clayton5160ce52013-03-27 23:08:40 +00001046 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047 if (log)
1048 log->Printf ("%p Process::Process()", this);
1049
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001050 SetEventName (eBroadcastBitStateChanged, "state-changed");
1051 SetEventName (eBroadcastBitInterrupt, "interrupt");
1052 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1053 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001054 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001055
Greg Clayton35a4cc52012-10-29 20:52:08 +00001056 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1057 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1058 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1059
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001060 listener.StartListeningForEvents (this,
1061 eBroadcastBitStateChanged |
1062 eBroadcastBitInterrupt |
1063 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001064 eBroadcastBitSTDERR |
1065 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001066
1067 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001068 eBroadcastBitStateChanged |
1069 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070
1071 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1072 eBroadcastInternalStateControlStop |
1073 eBroadcastInternalStateControlPause |
1074 eBroadcastInternalStateControlResume);
1075}
1076
1077//----------------------------------------------------------------------
1078// Destructor
1079//----------------------------------------------------------------------
1080Process::~Process()
1081{
Greg Clayton5160ce52013-03-27 23:08:40 +00001082 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083 if (log)
1084 log->Printf ("%p Process::~Process()", this);
1085 StopPrivateStateThread();
1086}
1087
Greg Clayton67cc0632012-08-22 17:17:09 +00001088const ProcessPropertiesSP &
1089Process::GetGlobalProperties()
1090{
1091 static ProcessPropertiesSP g_settings_sp;
1092 if (!g_settings_sp)
1093 g_settings_sp.reset (new ProcessProperties (true));
1094 return g_settings_sp;
1095}
1096
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001097void
1098Process::Finalize()
1099{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001100 switch (GetPrivateState())
1101 {
1102 case eStateConnected:
1103 case eStateAttaching:
1104 case eStateLaunching:
1105 case eStateStopped:
1106 case eStateRunning:
1107 case eStateStepping:
1108 case eStateCrashed:
1109 case eStateSuspended:
1110 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +00001111 {
1112 // FIXME: This will have to be a process setting:
1113 bool keep_stopped = false;
1114 Detach(keep_stopped);
1115 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00001116 else
1117 Destroy();
1118 break;
1119
1120 case eStateInvalid:
1121 case eStateUnloaded:
1122 case eStateDetached:
1123 case eStateExited:
1124 break;
1125 }
1126
Greg Clayton1ed54f52011-10-01 00:45:15 +00001127 // Clear our broadcaster before we proceed with destroying
1128 Broadcaster::Clear();
1129
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001130 // Do any cleanup needed prior to being destructed... Subclasses
1131 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001132
1133 // We need to destroy the loader before the derived Process class gets destroyed
1134 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001135 m_dynamic_checkers_ap.reset();
1136 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001137 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001138 m_dyld_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001139 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001140 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +00001141 std::vector<Notifications> empty_notifications;
1142 m_notifications.swap(empty_notifications);
1143 m_image_tokens.clear();
1144 m_memory_cache.Clear();
1145 m_allocated_memory_cache.Clear();
1146 m_language_runtimes.clear();
1147 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001148//#ifdef LLDB_CONFIGURATION_DEBUG
1149// StreamFile s(stdout, false);
1150// EventSP event_sp;
1151// while (m_private_state_listener.GetNextEvent(event_sp))
1152// {
1153// event_sp->Dump (&s);
1154// s.EOL();
1155// }
1156//#endif
1157 // We have to be very careful here as the m_private_state_listener might
1158 // contain events that have ProcessSP values in them which can keep this
1159 // process around forever. These events need to be cleared out.
1160 m_private_state_listener.Clear();
Greg Claytonaa49c832013-05-03 22:25:56 +00001161 m_public_run_lock.WriteTryLock(); // This will do nothing if already locked
Greg Clayton96249852013-04-18 16:57:27 +00001162 m_public_run_lock.WriteUnlock();
Greg Claytonaa49c832013-05-03 22:25:56 +00001163 m_private_run_lock.WriteTryLock(); // This will do nothing if already locked
Greg Clayton96249852013-04-18 16:57:27 +00001164 m_private_run_lock.WriteUnlock();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001165 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166}
1167
1168void
1169Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1170{
1171 m_notifications.push_back(callbacks);
1172 if (callbacks.initialize != NULL)
1173 callbacks.initialize (callbacks.baton, this);
1174}
1175
1176bool
1177Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1178{
1179 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1180 for (pos = m_notifications.begin(); pos != end; ++pos)
1181 {
1182 if (pos->baton == callbacks.baton &&
1183 pos->initialize == callbacks.initialize &&
1184 pos->process_state_changed == callbacks.process_state_changed)
1185 {
1186 m_notifications.erase(pos);
1187 return true;
1188 }
1189 }
1190 return false;
1191}
1192
1193void
1194Process::SynchronouslyNotifyStateChanged (StateType state)
1195{
1196 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1197 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1198 {
1199 if (notification_pos->process_state_changed)
1200 notification_pos->process_state_changed (notification_pos->baton, this, state);
1201 }
1202}
1203
1204// FIXME: We need to do some work on events before the general Listener sees them.
1205// For instance if we are continuing from a breakpoint, we need to ensure that we do
1206// the little "insert real insn, step & stop" trick. But we can't do that when the
1207// event is delivered by the broadcaster - since that is done on the thread that is
1208// waiting for new events, so if we needed more than one event for our handling, we would
1209// stall. So instead we do it when we fetch the event off of the queue.
1210//
1211
1212StateType
1213Process::GetNextEvent (EventSP &event_sp)
1214{
1215 StateType state = eStateInvalid;
1216
1217 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1218 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1219
1220 return state;
1221}
1222
1223
1224StateType
Greg Clayton85fb1b92012-09-11 02:33:37 +00001225Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001226{
Jim Ingham4b536182011-08-09 02:12:22 +00001227 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1228 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1229 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001230 if (event_sp_ptr)
1231 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001232 StateType state = GetState();
1233 // If we are exited or detached, we won't ever get back to any
1234 // other valid state...
1235 if (state == eStateDetached || state == eStateExited)
1236 return state;
1237
1238 while (state != eStateInvalid)
1239 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001240 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001241 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001242 if (event_sp_ptr && event_sp)
1243 *event_sp_ptr = event_sp;
1244
Jim Ingham4b536182011-08-09 02:12:22 +00001245 switch (state)
1246 {
1247 case eStateCrashed:
1248 case eStateDetached:
1249 case eStateExited:
1250 case eStateUnloaded:
1251 return state;
1252 case eStateStopped:
1253 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1254 continue;
1255 else
1256 return state;
1257 default:
1258 continue;
1259 }
1260 }
1261 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001262}
1263
1264
1265StateType
1266Process::WaitForState
1267(
1268 const TimeValue *timeout,
1269 const StateType *match_states, const uint32_t num_match_states
1270)
1271{
1272 EventSP event_sp;
1273 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001274 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001275 while (state != eStateInvalid)
1276 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001277 // If we are exited or detached, we won't ever get back to any
1278 // other valid state...
1279 if (state == eStateDetached || state == eStateExited)
1280 return state;
1281
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001282 state = WaitForStateChangedEvents (timeout, event_sp);
1283
1284 for (i=0; i<num_match_states; ++i)
1285 {
1286 if (match_states[i] == state)
1287 return state;
1288 }
1289 }
1290 return state;
1291}
1292
Jim Ingham30f9b212010-10-11 23:53:14 +00001293bool
1294Process::HijackProcessEvents (Listener *listener)
1295{
1296 if (listener != NULL)
1297 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001298 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001299 }
1300 else
1301 return false;
1302}
1303
1304void
1305Process::RestoreProcessEvents ()
1306{
1307 RestoreBroadcaster();
1308}
1309
Jim Ingham0f16e732011-02-08 05:20:59 +00001310bool
1311Process::HijackPrivateProcessEvents (Listener *listener)
1312{
1313 if (listener != NULL)
1314 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001315 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001316 }
1317 else
1318 return false;
1319}
1320
1321void
1322Process::RestorePrivateProcessEvents ()
1323{
1324 m_private_state_broadcaster.RestoreBroadcaster();
1325}
1326
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001327StateType
1328Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1329{
Greg Clayton5160ce52013-03-27 23:08:40 +00001330 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001331
1332 if (log)
1333 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1334
1335 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001336 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1337 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001338 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001339 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001340 {
1341 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1342 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1343 else if (log)
1344 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1345 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346
1347 if (log)
1348 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1349 __FUNCTION__,
1350 timeout,
1351 StateAsCString(state));
1352 return state;
1353}
1354
1355Event *
1356Process::PeekAtStateChangedEvents ()
1357{
Greg Clayton5160ce52013-03-27 23:08:40 +00001358 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001359
1360 if (log)
1361 log->Printf ("Process::%s...", __FUNCTION__);
1362
1363 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001364 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1365 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001366 if (log)
1367 {
1368 if (event_ptr)
1369 {
1370 log->Printf ("Process::%s (event_ptr) => %s",
1371 __FUNCTION__,
1372 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1373 }
1374 else
1375 {
1376 log->Printf ("Process::%s no events found",
1377 __FUNCTION__);
1378 }
1379 }
1380 return event_ptr;
1381}
1382
1383StateType
1384Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1385{
Greg Clayton5160ce52013-03-27 23:08:40 +00001386 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387
1388 if (log)
1389 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1390
1391 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001392 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1393 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001394 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001395 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001396 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1397 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001398
1399 // This is a bit of a hack, but when we wait here we could very well return
1400 // to the command-line, and that could disable the log, which would render the
1401 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001402 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001403 {
1404 if (state == eStateInvalid)
1405 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1406 else
1407 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1408 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001409 return state;
1410}
1411
1412bool
1413Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1414{
Greg Clayton5160ce52013-03-27 23:08:40 +00001415 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001416
1417 if (log)
1418 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1419
1420 if (control_only)
1421 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1422 else
1423 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1424}
1425
1426bool
1427Process::IsRunning () const
1428{
1429 return StateIsRunningState (m_public_state.GetValue());
1430}
1431
1432int
1433Process::GetExitStatus ()
1434{
1435 if (m_public_state.GetValue() == eStateExited)
1436 return m_exit_status;
1437 return -1;
1438}
1439
Greg Clayton85851dd2010-12-04 00:10:17 +00001440
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001441const char *
1442Process::GetExitDescription ()
1443{
1444 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1445 return m_exit_string.c_str();
1446 return NULL;
1447}
1448
Greg Clayton6779606a2011-01-22 23:43:18 +00001449bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001450Process::SetExitStatus (int status, const char *cstr)
1451{
Greg Clayton5160ce52013-03-27 23:08:40 +00001452 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001453 if (log)
1454 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1455 status, status,
1456 cstr ? "\"" : "",
1457 cstr ? cstr : "NULL",
1458 cstr ? "\"" : "");
1459
Greg Clayton6779606a2011-01-22 23:43:18 +00001460 // We were already in the exited state
1461 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001462 {
Greg Clayton385d6032011-01-26 23:47:29 +00001463 if (log)
1464 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001465 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001466 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001467
1468 m_exit_status = status;
1469 if (cstr)
1470 m_exit_string = cstr;
1471 else
1472 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001473
Greg Clayton6779606a2011-01-22 23:43:18 +00001474 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001475
Greg Clayton6779606a2011-01-22 23:43:18 +00001476 SetPrivateState (eStateExited);
1477 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001478}
1479
1480// This static callback can be used to watch for local child processes on
1481// the current host. The the child process exits, the process will be
1482// found in the global target list (we want to be completely sure that the
1483// lldb_private::Process doesn't go away before we can deliver the signal.
1484bool
Greg Claytone4e45922011-11-16 05:37:56 +00001485Process::SetProcessExitStatus (void *callback_baton,
1486 lldb::pid_t pid,
1487 bool exited,
1488 int signo, // Zero for no signal
1489 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490)
1491{
Greg Clayton5160ce52013-03-27 23:08:40 +00001492 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001493 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001494 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001495 callback_baton,
1496 pid,
1497 exited,
1498 signo,
1499 exit_status);
1500
1501 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001502 {
Greg Clayton66111032010-06-23 01:19:29 +00001503 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504 if (target_sp)
1505 {
1506 ProcessSP process_sp (target_sp->GetProcessSP());
1507 if (process_sp)
1508 {
1509 const char *signal_cstr = NULL;
1510 if (signo)
1511 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1512
1513 process_sp->SetExitStatus (exit_status, signal_cstr);
1514 }
1515 }
1516 return true;
1517 }
1518 return false;
1519}
1520
1521
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001522void
1523Process::UpdateThreadListIfNeeded ()
1524{
1525 const uint32_t stop_id = GetStopID();
1526 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1527 {
Greg Clayton2637f822011-11-17 01:23:07 +00001528 const StateType state = GetPrivateState();
1529 if (StateIsStoppedState (state, true))
1530 {
1531 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001532 // m_thread_list does have its own mutex, but we need to
1533 // hold onto the mutex between the call to UpdateThreadList(...)
1534 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001535 ThreadList &old_thread_list = m_thread_list;
1536 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001537 ThreadList new_thread_list(this);
1538 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001539 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001540 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001541 {
Jim Ingham09437922013-03-01 20:04:25 +00001542 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1543 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1544 // shutting us down, causing a deadlock.
1545 if (!m_destroy_in_process)
1546 {
1547 OperatingSystem *os = GetOperatingSystem ();
1548 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001549 {
1550 // Clear any old backing threads where memory threads might have been
1551 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001552 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001553 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001554 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001555
1556 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001557 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1558 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1559 new_thread_list); // The new thread list that we will show to the user that gets filled in
Greg Claytonb3ae8762013-04-12 20:07:46 +00001560 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001561 else
1562 {
1563 // No OS plug-in, the new thread list is the same as the real thread list
1564 new_thread_list = real_thread_list;
1565 }
Jim Ingham09437922013-03-01 20:04:25 +00001566 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001567 m_thread_list.Update (new_thread_list);
1568 m_thread_list.SetStopID (stop_id);
Greg Clayton9fc13552012-04-10 00:18:59 +00001569 }
Greg Clayton2637f822011-11-17 01:23:07 +00001570 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001571 }
1572}
1573
Greg Claytona4d87472013-01-18 23:41:08 +00001574ThreadSP
1575Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1576{
1577 OperatingSystem *os = GetOperatingSystem ();
1578 if (os)
1579 return os->CreateThread(tid, context);
1580 return ThreadSP();
1581}
1582
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001583uint32_t
1584Process::GetNextThreadIndexID (uint64_t thread_id)
1585{
1586 return AssignIndexIDToThread(thread_id);
1587}
1588
1589bool
1590Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1591{
1592 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1593 if (iterator == m_thread_id_to_index_id_map.end())
1594 {
1595 return false;
1596 }
1597 else
1598 {
1599 return true;
1600 }
1601}
1602
1603uint32_t
1604Process::AssignIndexIDToThread(uint64_t thread_id)
1605{
1606 uint32_t result = 0;
1607 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1608 if (iterator == m_thread_id_to_index_id_map.end())
1609 {
1610 result = ++m_thread_index_id;
1611 m_thread_id_to_index_id_map[thread_id] = result;
1612 }
1613 else
1614 {
1615 result = iterator->second;
1616 }
1617
1618 return result;
1619}
1620
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001621StateType
1622Process::GetState()
1623{
1624 // If any other threads access this we will need a mutex for it
1625 return m_public_state.GetValue ();
1626}
1627
1628void
Jim Ingham221d51c2013-05-08 00:35:16 +00001629Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001630{
Greg Clayton5160ce52013-03-27 23:08:40 +00001631 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001632 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001633 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001634 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001635 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001636
1637 // On the transition from Run to Stopped, we unlock the writer end of the
1638 // run lock. The lock gets locked in Resume, which is the public API
1639 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001640 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1641 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001642 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001643 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001644 if (log)
1645 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Greg Clayton96249852013-04-18 16:57:27 +00001646 m_public_run_lock.WriteUnlock();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001647 }
1648 else
1649 {
1650 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1651 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001652 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001653 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001654 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001655 {
1656 if (log)
1657 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Greg Clayton96249852013-04-18 16:57:27 +00001658 m_public_run_lock.WriteUnlock();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001659 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001660 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001661 }
1662 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001663}
1664
Jim Ingham3b8285d2012-04-19 01:40:33 +00001665Error
1666Process::Resume ()
1667{
Greg Clayton5160ce52013-03-27 23:08:40 +00001668 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001669 if (log)
1670 log->Printf("Process::Resume -- locking run lock");
Greg Clayton96249852013-04-18 16:57:27 +00001671 if (!m_public_run_lock.WriteTryLock())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001672 {
1673 Error error("Resume request failed - process still running.");
1674 if (log)
1675 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1676 return error;
1677 }
1678 return PrivateResume();
1679}
1680
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001681StateType
1682Process::GetPrivateState ()
1683{
1684 return m_private_state.GetValue();
1685}
1686
1687void
1688Process::SetPrivateState (StateType new_state)
1689{
Greg Clayton5160ce52013-03-27 23:08:40 +00001690 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001691 bool state_changed = false;
1692
1693 if (log)
1694 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1695
Andrew Kaylor29d65742013-05-10 17:19:04 +00001696 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001697 Mutex::Locker locker(m_private_state.GetMutex());
1698
1699 const StateType old_state = m_private_state.GetValueNoLock ();
1700 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001701 // This code is left commented out in case we ever need to control
1702 // the private process state with another run lock. Right now it doesn't
1703 // seem like we need to do this, but if we ever do, we can uncomment and
1704 // use this code.
Greg Claytonaa49c832013-05-03 22:25:56 +00001705 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1706 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1707 if (old_state_is_stopped != new_state_is_stopped)
1708 {
1709 if (new_state_is_stopped)
1710 m_private_run_lock.WriteUnlock();
1711 else
1712 m_private_run_lock.WriteLock();
1713 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001714
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001715 if (state_changed)
1716 {
1717 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001718 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001719 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001720 // Note, this currently assumes that all threads in the list
1721 // stop when the process stops. In the future we will want to
1722 // support a debugging model where some threads continue to run
1723 // while others are stopped. When that happens we will either need
1724 // a way for the thread list to identify which threads are stopping
1725 // or create a special thread list containing only threads which
1726 // actually stopped.
1727 //
1728 // The process plugin is responsible for managing the actual
1729 // behavior of the threads and should have stopped any threads
1730 // that are going to stop before we get here.
1731 m_thread_list.DidStop();
1732
Jim Ingham4b536182011-08-09 02:12:22 +00001733 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001734 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001735 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001736 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001737 }
1738 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001739 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1740 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1741 else
1742 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001743 }
1744 else
1745 {
1746 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001747 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001748 }
1749}
1750
Jim Ingham0faa43f2011-11-08 03:00:11 +00001751void
1752Process::SetRunningUserExpression (bool on)
1753{
1754 m_mod_id.SetRunningUserExpression (on);
1755}
1756
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001757addr_t
1758Process::GetImageInfoAddress()
1759{
1760 return LLDB_INVALID_ADDRESS;
1761}
1762
Greg Clayton8f343b02010-11-04 01:54:29 +00001763//----------------------------------------------------------------------
1764// LoadImage
1765//
1766// This function provides a default implementation that works for most
1767// unix variants. Any Process subclasses that need to do shared library
1768// loading differently should override LoadImage and UnloadImage and
1769// do what is needed.
1770//----------------------------------------------------------------------
1771uint32_t
1772Process::LoadImage (const FileSpec &image_spec, Error &error)
1773{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001774 char path[PATH_MAX];
1775 image_spec.GetPath(path, sizeof(path));
1776
Greg Clayton8f343b02010-11-04 01:54:29 +00001777 DynamicLoader *loader = GetDynamicLoader();
1778 if (loader)
1779 {
1780 error = loader->CanLoadImage();
1781 if (error.Fail())
1782 return LLDB_INVALID_IMAGE_TOKEN;
1783 }
1784
1785 if (error.Success())
1786 {
1787 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001788
1789 if (thread_sp)
1790 {
1791 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1792
1793 if (frame_sp)
1794 {
1795 ExecutionContext exe_ctx;
1796 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham184e9812013-01-15 02:47:48 +00001797 const bool unwind_on_error = true;
1798 const bool ignore_breakpoints = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001799 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001800 expr.Printf("dlopen (\"%s\", 2)", path);
1801 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001802 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001803 ClangUserExpression::Evaluate (exe_ctx,
1804 eExecutionPolicyAlways,
1805 lldb::eLanguageTypeUnknown,
1806 ClangUserExpression::eResultTypeAny,
1807 unwind_on_error,
Jim Ingham184e9812013-01-15 02:47:48 +00001808 ignore_breakpoints,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001809 expr.GetData(),
1810 prefix,
1811 result_valobj_sp,
1812 true,
1813 ClangUserExpression::kDefaultTimeout);
Johnny Chene92aa432011-09-09 00:01:43 +00001814 error = result_valobj_sp->GetError();
1815 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001816 {
1817 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001818 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001819 {
1820 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1821 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1822 {
1823 uint32_t image_token = m_image_tokens.size();
1824 m_image_tokens.push_back (image_ptr);
1825 return image_token;
1826 }
1827 }
1828 }
1829 }
1830 }
1831 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001832 if (!error.AsCString())
1833 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001834 return LLDB_INVALID_IMAGE_TOKEN;
1835}
1836
1837//----------------------------------------------------------------------
1838// UnloadImage
1839//
1840// This function provides a default implementation that works for most
1841// unix variants. Any Process subclasses that need to do shared library
1842// loading differently should override LoadImage and UnloadImage and
1843// do what is needed.
1844//----------------------------------------------------------------------
1845Error
1846Process::UnloadImage (uint32_t image_token)
1847{
1848 Error error;
1849 if (image_token < m_image_tokens.size())
1850 {
1851 const addr_t image_addr = m_image_tokens[image_token];
1852 if (image_addr == LLDB_INVALID_ADDRESS)
1853 {
1854 error.SetErrorString("image already unloaded");
1855 }
1856 else
1857 {
1858 DynamicLoader *loader = GetDynamicLoader();
1859 if (loader)
1860 error = loader->CanLoadImage();
1861
1862 if (error.Success())
1863 {
1864 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001865
1866 if (thread_sp)
1867 {
1868 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1869
1870 if (frame_sp)
1871 {
1872 ExecutionContext exe_ctx;
1873 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham184e9812013-01-15 02:47:48 +00001874 const bool unwind_on_error = true;
1875 const bool ignore_breakpoints = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001876 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001877 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001878 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001879 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001880 ClangUserExpression::Evaluate (exe_ctx,
1881 eExecutionPolicyAlways,
1882 lldb::eLanguageTypeUnknown,
1883 ClangUserExpression::eResultTypeAny,
1884 unwind_on_error,
Jim Ingham184e9812013-01-15 02:47:48 +00001885 ignore_breakpoints,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001886 expr.GetData(),
1887 prefix,
1888 result_valobj_sp,
1889 true,
1890 ClangUserExpression::kDefaultTimeout);
Greg Clayton8f343b02010-11-04 01:54:29 +00001891 if (result_valobj_sp->GetError().Success())
1892 {
1893 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001894 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001895 {
1896 if (scalar.UInt(1))
1897 {
1898 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1899 }
1900 else
1901 {
1902 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1903 }
1904 }
1905 }
1906 else
1907 {
1908 error = result_valobj_sp->GetError();
1909 }
1910 }
1911 }
1912 }
1913 }
1914 }
1915 else
1916 {
1917 error.SetErrorString("invalid image token");
1918 }
1919 return error;
1920}
1921
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001922const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001923Process::GetABI()
1924{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001925 if (!m_abi_sp)
1926 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1927 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001928}
1929
Jim Ingham22777012010-09-23 02:01:19 +00001930LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001931Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001932{
1933 LanguageRuntimeCollection::iterator pos;
1934 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001935 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001936 {
Jim Inghamab175242012-03-10 00:22:19 +00001937 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001938
Jim Inghamab175242012-03-10 00:22:19 +00001939 m_language_runtimes[language] = runtime_sp;
1940 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001941 }
1942 else
1943 return (*pos).second.get();
1944}
1945
1946CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001947Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001948{
Jim Inghamab175242012-03-10 00:22:19 +00001949 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001950 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1951 return static_cast<CPPLanguageRuntime *> (runtime);
1952 return NULL;
1953}
1954
1955ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001956Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001957{
Jim Inghamab175242012-03-10 00:22:19 +00001958 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001959 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1960 return static_cast<ObjCLanguageRuntime *> (runtime);
1961 return NULL;
1962}
1963
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001964bool
1965Process::IsPossibleDynamicValue (ValueObject& in_value)
1966{
1967 if (in_value.IsDynamic())
1968 return false;
1969 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1970
1971 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1972 {
1973 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1974 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1975 }
1976
1977 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1978 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1979 return true;
1980
1981 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1982 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1983}
1984
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001985BreakpointSiteList &
1986Process::GetBreakpointSiteList()
1987{
1988 return m_breakpoint_site_list;
1989}
1990
1991const BreakpointSiteList &
1992Process::GetBreakpointSiteList() const
1993{
1994 return m_breakpoint_site_list;
1995}
1996
1997
1998void
1999Process::DisableAllBreakpointSites ()
2000{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002001 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2002// bp_site->SetEnabled(true);
2003 DisableBreakpointSite(bp_site);
2004 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002005}
2006
2007Error
2008Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2009{
2010 Error error (DisableBreakpointSiteByID (break_id));
2011
2012 if (error.Success())
2013 m_breakpoint_site_list.Remove(break_id);
2014
2015 return error;
2016}
2017
2018Error
2019Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2020{
2021 Error error;
2022 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2023 if (bp_site_sp)
2024 {
2025 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002026 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002027 }
2028 else
2029 {
Daniel Malead01b2952012-11-29 21:49:15 +00002030 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002031 }
2032
2033 return error;
2034}
2035
2036Error
2037Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2038{
2039 Error error;
2040 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2041 if (bp_site_sp)
2042 {
2043 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002044 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002045 }
2046 else
2047 {
Daniel Malead01b2952012-11-29 21:49:15 +00002048 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002049 }
2050 return error;
2051}
2052
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002053lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002054Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002055{
Greg Clayton92bb12c2011-05-19 18:17:41 +00002056 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002057 if (load_addr != LLDB_INVALID_ADDRESS)
2058 {
2059 BreakpointSiteSP bp_site_sp;
2060
2061 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2062 // create a new breakpoint site and add it.
2063
2064 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2065
2066 if (bp_site_sp)
2067 {
2068 bp_site_sp->AddOwner (owner);
2069 owner->SetBreakpointSite (bp_site_sp);
2070 return bp_site_sp->GetID();
2071 }
2072 else
2073 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002074 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002075 if (bp_site_sp)
2076 {
Jim Ingham299c0c12013-02-15 02:06:30 +00002077 if (EnableBreakpointSite (bp_site_sp.get()).Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002078 {
2079 owner->SetBreakpointSite (bp_site_sp);
2080 return m_breakpoint_site_list.Add (bp_site_sp);
2081 }
2082 }
2083 }
2084 }
2085 // We failed to enable the breakpoint
2086 return LLDB_INVALID_BREAK_ID;
2087
2088}
2089
2090void
2091Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2092{
2093 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2094 if (num_owners == 0)
2095 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002096 // Don't try to disable the site if we don't have a live process anymore.
2097 if (IsAlive())
2098 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002099 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2100 }
2101}
2102
2103
2104size_t
2105Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2106{
2107 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002108 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002109
Jim Ingham20c77192011-06-29 19:42:28 +00002110 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002112 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2113 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002114 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002115 addr_t intersect_addr;
2116 size_t intersect_size;
2117 size_t opcode_offset;
2118 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002119 {
2120 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2121 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002122 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002123 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002124 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002125 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002127 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002128 }
2129 return bytes_removed;
2130}
2131
2132
Greg Claytonded470d2011-03-19 01:12:21 +00002133
2134size_t
2135Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2136{
2137 PlatformSP platform_sp (m_target.GetPlatform());
2138 if (platform_sp)
2139 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2140 return 0;
2141}
2142
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002143Error
2144Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2145{
2146 Error error;
2147 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002148 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002149 const addr_t bp_addr = bp_site->GetLoadAddress();
2150 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002151 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002152 if (bp_site->IsEnabled())
2153 {
2154 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002155 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002156 return error;
2157 }
2158
2159 if (bp_addr == LLDB_INVALID_ADDRESS)
2160 {
2161 error.SetErrorString("BreakpointSite contains an invalid load address.");
2162 return error;
2163 }
2164 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2165 // trap for the breakpoint site
2166 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2167
2168 if (bp_opcode_size == 0)
2169 {
Daniel Malead01b2952012-11-29 21:49:15 +00002170 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002171 }
2172 else
2173 {
2174 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2175
2176 if (bp_opcode_bytes == NULL)
2177 {
2178 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2179 return error;
2180 }
2181
2182 // Save the original opcode by reading it
2183 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2184 {
2185 // Write a software breakpoint in place of the original opcode
2186 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2187 {
2188 uint8_t verify_bp_opcode_bytes[64];
2189 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2190 {
2191 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2192 {
2193 bp_site->SetEnabled(true);
2194 bp_site->SetType (BreakpointSite::eSoftware);
2195 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002196 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002197 bp_site->GetID(),
2198 (uint64_t)bp_addr);
2199 }
2200 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002201 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002202 }
2203 else
2204 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2205 }
2206 else
2207 error.SetErrorString("Unable to write breakpoint trap to memory.");
2208 }
2209 else
2210 error.SetErrorString("Unable to read memory at breakpoint address.");
2211 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002212 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002213 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002214 bp_site->GetID(),
2215 (uint64_t)bp_addr,
2216 error.AsCString());
2217 return error;
2218}
2219
2220Error
2221Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2222{
2223 Error error;
2224 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002225 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002226 addr_t bp_addr = bp_site->GetLoadAddress();
2227 lldb::user_id_t breakID = bp_site->GetID();
2228 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002229 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002230
2231 if (bp_site->IsHardware())
2232 {
2233 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2234 }
2235 else if (bp_site->IsEnabled())
2236 {
2237 const size_t break_op_size = bp_site->GetByteSize();
2238 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2239 if (break_op_size > 0)
2240 {
2241 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002242 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002243 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002244 bool break_op_found = false;
2245
2246 // Read the breakpoint opcode
2247 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2248 {
2249 bool verify = false;
2250 // Make sure we have the a breakpoint opcode exists at this address
2251 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2252 {
2253 break_op_found = true;
2254 // We found a valid breakpoint opcode at this address, now restore
2255 // the saved opcode.
2256 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2257 {
2258 verify = true;
2259 }
2260 else
2261 error.SetErrorString("Memory write failed when restoring original opcode.");
2262 }
2263 else
2264 {
2265 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2266 // Set verify to true and so we can check if the original opcode has already been restored
2267 verify = true;
2268 }
2269
2270 if (verify)
2271 {
Greg Claytonc982c762010-07-09 20:39:50 +00002272 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002273 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002274 // Verify that our original opcode made it back to the inferior
2275 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2276 {
2277 // compare the memory we just read with the original opcode
2278 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2279 {
2280 // SUCCESS
2281 bp_site->SetEnabled(false);
2282 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002283 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002284 return error;
2285 }
2286 else
2287 {
2288 if (break_op_found)
2289 error.SetErrorString("Failed to restore original opcode.");
2290 }
2291 }
2292 else
2293 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2294 }
2295 }
2296 else
2297 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2298 }
2299 }
2300 else
2301 {
2302 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002303 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002304 return error;
2305 }
2306
2307 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002308 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002309 bp_site->GetID(),
2310 (uint64_t)bp_addr,
2311 error.AsCString());
2312 return error;
2313
2314}
2315
Greg Clayton58be07b2011-01-07 06:08:19 +00002316// Uncomment to verify memory caching works after making changes to caching code
2317//#define VERIFY_MEMORY_READS
2318
Sean Callanan64c0cf22012-06-07 22:26:42 +00002319size_t
2320Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2321{
2322 if (!GetDisableMemoryCache())
2323 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002324#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002325 // Memory caching is enabled, with debug verification
2326
2327 if (buf && size)
2328 {
2329 // Uncomment the line below to make sure memory caching is working.
2330 // I ran this through the test suite and got no assertions, so I am
2331 // pretty confident this is working well. If any changes are made to
2332 // memory caching, uncomment the line below and test your changes!
2333
2334 // Verify all memory reads by using the cache first, then redundantly
2335 // reading the same memory from the inferior and comparing to make sure
2336 // everything is exactly the same.
2337 std::string verify_buf (size, '\0');
2338 assert (verify_buf.size() == size);
2339 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2340 Error verify_error;
2341 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2342 assert (cache_bytes_read == verify_bytes_read);
2343 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2344 assert (verify_error.Success() == error.Success());
2345 return cache_bytes_read;
2346 }
2347 return 0;
2348#else // !defined(VERIFY_MEMORY_READS)
2349 // Memory caching is enabled, without debug verification
2350
2351 return m_memory_cache.Read (addr, buf, size, error);
2352#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002353 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002354 else
2355 {
2356 // Memory caching is disabled
2357
2358 return ReadMemoryFromInferior (addr, buf, size, error);
2359 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002360}
Greg Clayton58be07b2011-01-07 06:08:19 +00002361
Greg Clayton4c82d422012-05-18 23:20:01 +00002362size_t
2363Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2364{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002365 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002366 out_str.clear();
2367 addr_t curr_addr = addr;
2368 while (1)
2369 {
2370 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2371 if (length == 0)
2372 break;
2373 out_str.append(buf, length);
2374 // If we got "length - 1" bytes, we didn't get the whole C string, we
2375 // need to read some more characters
2376 if (length == sizeof(buf) - 1)
2377 curr_addr += length;
2378 else
2379 break;
2380 }
2381 return out_str.size();
2382}
2383
Greg Clayton58be07b2011-01-07 06:08:19 +00002384
2385size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002386Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2387 size_t type_width)
2388{
2389 size_t total_bytes_read = 0;
2390 if (dst && max_bytes && type_width && max_bytes >= type_width)
2391 {
2392 // Ensure a null terminator independent of the number of bytes that is read.
2393 memset (dst, 0, max_bytes);
2394 size_t bytes_left = max_bytes - type_width;
2395
2396 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2397 assert(sizeof(terminator) >= type_width &&
2398 "Attempting to validate a string with more than 4 bytes per character!");
2399
2400 addr_t curr_addr = addr;
2401 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2402 char *curr_dst = dst;
2403
2404 error.Clear();
2405 while (bytes_left > 0 && error.Success())
2406 {
2407 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2408 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2409 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2410
2411 if (bytes_read == 0)
2412 break;
2413
2414 // Search for a null terminator of correct size and alignment in bytes_read
2415 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2416 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2417 if (::strncmp(&dst[i], terminator, type_width) == 0)
2418 {
2419 error.Clear();
2420 return i;
2421 }
2422
2423 total_bytes_read += bytes_read;
2424 curr_dst += bytes_read;
2425 curr_addr += bytes_read;
2426 bytes_left -= bytes_read;
2427 }
2428 }
2429 else
2430 {
2431 if (max_bytes)
2432 error.SetErrorString("invalid arguments");
2433 }
2434 return total_bytes_read;
2435}
2436
2437// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2438// null terminators.
2439size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002440Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002441{
2442 size_t total_cstr_len = 0;
2443 if (dst && dst_max_len)
2444 {
Greg Claytone91b7952011-12-15 03:14:23 +00002445 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002446 // NULL out everything just to be safe
2447 memset (dst, 0, dst_max_len);
2448 Error error;
2449 addr_t curr_addr = addr;
2450 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2451 size_t bytes_left = dst_max_len - 1;
2452 char *curr_dst = dst;
2453
2454 while (bytes_left > 0)
2455 {
2456 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2457 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2458 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2459
2460 if (bytes_read == 0)
2461 {
Greg Claytone91b7952011-12-15 03:14:23 +00002462 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002463 dst[total_cstr_len] = '\0';
2464 break;
2465 }
2466 const size_t len = strlen(curr_dst);
2467
2468 total_cstr_len += len;
2469
2470 if (len < bytes_to_read)
2471 break;
2472
2473 curr_dst += bytes_read;
2474 curr_addr += bytes_read;
2475 bytes_left -= bytes_read;
2476 }
2477 }
Greg Claytone91b7952011-12-15 03:14:23 +00002478 else
2479 {
2480 if (dst == NULL)
2481 result_error.SetErrorString("invalid arguments");
2482 else
2483 result_error.Clear();
2484 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002485 return total_cstr_len;
2486}
2487
2488size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002489Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2490{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002491 if (buf == NULL || size == 0)
2492 return 0;
2493
2494 size_t bytes_read = 0;
2495 uint8_t *bytes = (uint8_t *)buf;
2496
2497 while (bytes_read < size)
2498 {
2499 const size_t curr_size = size - bytes_read;
2500 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2501 bytes + bytes_read,
2502 curr_size,
2503 error);
2504 bytes_read += curr_bytes_read;
2505 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2506 break;
2507 }
2508
2509 // Replace any software breakpoint opcodes that fall into this range back
2510 // into "buf" before we return
2511 if (bytes_read > 0)
2512 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2513 return bytes_read;
2514}
2515
Greg Clayton58a4c462010-12-16 20:01:20 +00002516uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002517Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002518{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002519 Scalar scalar;
2520 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2521 return scalar.ULongLong(fail_value);
2522 return fail_value;
2523}
2524
2525addr_t
2526Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2527{
2528 Scalar scalar;
2529 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2530 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2531 return LLDB_INVALID_ADDRESS;
2532}
2533
2534
2535bool
2536Process::WritePointerToMemory (lldb::addr_t vm_addr,
2537 lldb::addr_t ptr_value,
2538 Error &error)
2539{
2540 Scalar scalar;
2541 const uint32_t addr_byte_size = GetAddressByteSize();
2542 if (addr_byte_size <= 4)
2543 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002544 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002545 scalar = ptr_value;
2546 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002547}
2548
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002549size_t
2550Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2551{
2552 size_t bytes_written = 0;
2553 const uint8_t *bytes = (const uint8_t *)buf;
2554
2555 while (bytes_written < size)
2556 {
2557 const size_t curr_size = size - bytes_written;
2558 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2559 bytes + bytes_written,
2560 curr_size,
2561 error);
2562 bytes_written += curr_bytes_written;
2563 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2564 break;
2565 }
2566 return bytes_written;
2567}
2568
2569size_t
2570Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2571{
Greg Clayton58be07b2011-01-07 06:08:19 +00002572#if defined (ENABLE_MEMORY_CACHING)
2573 m_memory_cache.Flush (addr, size);
2574#endif
2575
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002576 if (buf == NULL || size == 0)
2577 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002578
Jim Ingham4b536182011-08-09 02:12:22 +00002579 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002580
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002581 // We need to write any data that would go where any current software traps
2582 // (enabled software breakpoints) any software traps (breakpoints) that we
2583 // may have placed in our tasks memory.
2584
Greg Claytond8cf1a12013-06-12 00:46:38 +00002585 BreakpointSiteList bp_sites_in_range;
2586
2587 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002588 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002589 // No breakpoint sites overlap
2590 if (bp_sites_in_range.IsEmpty())
2591 return WriteMemoryPrivate (addr, buf, size, error);
2592 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002593 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002594 const uint8_t *ubuf = (const uint8_t *)buf;
2595 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002596
Greg Claytond8cf1a12013-06-12 00:46:38 +00002597 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2598
2599 if (error.Success())
2600 {
2601 addr_t intersect_addr;
2602 size_t intersect_size;
2603 size_t opcode_offset;
2604 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2605 assert(intersects);
2606 assert(addr <= intersect_addr && intersect_addr < addr + size);
2607 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2608 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2609
2610 // Check for bytes before this breakpoint
2611 const addr_t curr_addr = addr + bytes_written;
2612 if (intersect_addr > curr_addr)
2613 {
2614 // There are some bytes before this breakpoint that we need to
2615 // just write to memory
2616 size_t curr_size = intersect_addr - curr_addr;
2617 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2618 ubuf + bytes_written,
2619 curr_size,
2620 error);
2621 bytes_written += curr_bytes_written;
2622 if (curr_bytes_written != curr_size)
2623 {
2624 // We weren't able to write all of the requested bytes, we
2625 // are done looping and will return the number of bytes that
2626 // we have written so far.
2627 if (error.Success())
2628 error.SetErrorToGenericError();
2629 }
2630 }
2631 // Now write any bytes that would cover up any software breakpoints
2632 // directly into the breakpoint opcode buffer
2633 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2634 bytes_written += intersect_size;
2635 }
2636 });
2637
2638 if (bytes_written < size)
2639 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2640 ubuf + bytes_written,
2641 size - bytes_written,
2642 error);
2643 }
2644 }
2645 else
2646 {
2647 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002648 }
2649
2650 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002651 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002652}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002653
2654size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002655Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002656{
2657 if (byte_size == UINT32_MAX)
2658 byte_size = scalar.GetByteSize();
2659 if (byte_size > 0)
2660 {
2661 uint8_t buf[32];
2662 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2663 if (mem_size > 0)
2664 return WriteMemory(addr, buf, mem_size, error);
2665 else
2666 error.SetErrorString ("failed to get scalar as memory data");
2667 }
2668 else
2669 {
2670 error.SetErrorString ("invalid scalar value");
2671 }
2672 return 0;
2673}
2674
2675size_t
2676Process::ReadScalarIntegerFromMemory (addr_t addr,
2677 uint32_t byte_size,
2678 bool is_signed,
2679 Scalar &scalar,
2680 Error &error)
2681{
Greg Clayton7060f892013-05-01 23:41:30 +00002682 uint64_t uval = 0;
2683 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002684 {
Greg Clayton7060f892013-05-01 23:41:30 +00002685 error.SetErrorString ("byte size is zero");
2686 }
2687 else if (byte_size & (byte_size - 1))
2688 {
2689 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2690 }
2691 else if (byte_size <= sizeof(uval))
2692 {
2693 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002694 if (bytes_read == byte_size)
2695 {
2696 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002697 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002698 if (byte_size <= 4)
2699 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002700 else
Greg Clayton7060f892013-05-01 23:41:30 +00002701 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002702 if (is_signed)
2703 scalar.SignExtend(byte_size * 8);
2704 return bytes_read;
2705 }
2706 }
2707 else
2708 {
2709 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2710 }
2711 return 0;
2712}
2713
Greg Claytond495c532011-05-17 03:37:42 +00002714#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002715addr_t
2716Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2717{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002718 if (GetPrivateState() != eStateStopped)
2719 return LLDB_INVALID_ADDRESS;
2720
Greg Claytond495c532011-05-17 03:37:42 +00002721#if defined (USE_ALLOCATE_MEMORY_CACHE)
2722 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2723#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002724 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002725 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002726 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002727 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002728 size,
Greg Claytond495c532011-05-17 03:37:42 +00002729 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002730 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002731 m_mod_id.GetStopID(),
2732 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002733 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002734#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002735}
2736
Sean Callanan90539452011-09-20 23:01:51 +00002737bool
2738Process::CanJIT ()
2739{
Sean Callanana7b443a2012-02-14 22:50:38 +00002740 if (m_can_jit == eCanJITDontKnow)
2741 {
2742 Error err;
2743
2744 uint64_t allocated_memory = AllocateMemory(8,
2745 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2746 err);
2747
2748 if (err.Success())
2749 m_can_jit = eCanJITYes;
2750 else
2751 m_can_jit = eCanJITNo;
2752
2753 DeallocateMemory (allocated_memory);
2754 }
2755
Sean Callanan90539452011-09-20 23:01:51 +00002756 return m_can_jit == eCanJITYes;
2757}
2758
2759void
2760Process::SetCanJIT (bool can_jit)
2761{
2762 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2763}
2764
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002765Error
2766Process::DeallocateMemory (addr_t ptr)
2767{
Greg Claytond495c532011-05-17 03:37:42 +00002768 Error error;
2769#if defined (USE_ALLOCATE_MEMORY_CACHE)
2770 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2771 {
Daniel Malead01b2952012-11-29 21:49:15 +00002772 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002773 }
2774#else
2775 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002776
Greg Clayton5160ce52013-03-27 23:08:40 +00002777 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002778 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002779 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002780 ptr,
2781 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002782 m_mod_id.GetStopID(),
2783 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002784#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002785 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002786}
2787
Han Ming Ongc811d382012-11-17 00:33:14 +00002788
Greg Claytonc9660542012-02-05 02:38:54 +00002789ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002790Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton39f7ee82013-02-01 21:38:35 +00002791 lldb::addr_t header_addr)
Greg Claytonc9660542012-02-05 02:38:54 +00002792{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002793 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002794 if (module_sp)
2795 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002796 Error error;
2797 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2798 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002799 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002800 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002801 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002802}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002803
2804Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002805Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002806{
2807 Error error;
2808 error.SetErrorString("watchpoints are not supported");
2809 return error;
2810}
2811
2812Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002813Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002814{
2815 Error error;
2816 error.SetErrorString("watchpoints are not supported");
2817 return error;
2818}
2819
2820StateType
2821Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2822{
2823 StateType state;
2824 // Now wait for the process to launch and return control to us, and then
2825 // call DidLaunch:
2826 while (1)
2827 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002828 event_sp.reset();
2829 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2830
Greg Clayton2637f822011-11-17 01:23:07 +00002831 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002832 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002833
2834 // If state is invalid, then we timed out
2835 if (state == eStateInvalid)
2836 break;
2837
2838 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839 HandlePrivateEvent (event_sp);
2840 }
2841 return state;
2842}
2843
2844Error
Greg Clayton982c9762011-11-03 21:22:33 +00002845Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002846{
2847 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002848 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002849 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002850 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002851 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852
Greg Claytonaa149cb2011-08-11 02:48:45 +00002853 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002854 if (exe_module)
2855 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002856 char local_exec_file_path[PATH_MAX];
2857 char platform_exec_file_path[PATH_MAX];
2858 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2859 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002860 if (exe_module->GetFileSpec().Exists())
2861 {
Greg Clayton71337622011-02-24 22:24:29 +00002862 if (PrivateStateThreadIsValid ())
2863 PausePrivateStateThread ();
2864
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002865 error = WillLaunch (exe_module);
2866 if (error.Success())
2867 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002868 const bool restarted = false;
2869 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002870 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002871
Greg Clayton96249852013-04-18 16:57:27 +00002872 if (m_public_run_lock.WriteTryLock())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002873 {
2874 // Now launch using these arguments.
2875 error = DoLaunch (exe_module, launch_info);
2876 }
2877 else
2878 {
2879 // This shouldn't happen
2880 error.SetErrorString("failed to acquire process run lock");
2881 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002882
2883 if (error.Fail())
2884 {
2885 if (GetID() != LLDB_INVALID_PROCESS_ID)
2886 {
2887 SetID (LLDB_INVALID_PROCESS_ID);
2888 const char *error_string = error.AsCString();
2889 if (error_string == NULL)
2890 error_string = "launch failed";
2891 SetExitStatus (-1, error_string);
2892 }
2893 }
2894 else
2895 {
2896 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002897 TimeValue timeout_time;
2898 timeout_time = TimeValue::Now();
2899 timeout_time.OffsetWithSeconds(10);
2900 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002901
Greg Clayton1a38ea72011-06-22 01:42:17 +00002902 if (state == eStateInvalid || event_sp.get() == NULL)
2903 {
2904 // We were able to launch the process, but we failed to
2905 // catch the initial stop.
2906 SetExitStatus (0, "failed to catch stop after launch");
2907 Destroy();
2908 }
2909 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002910 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002911
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002912 DidLaunch ();
2913
Greg Claytonc859e2d2012-02-13 23:10:39 +00002914 DynamicLoader *dyld = GetDynamicLoader ();
2915 if (dyld)
2916 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002917
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002918 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919 // This delays passing the stopped event to listeners till DidLaunch gets
2920 // a chance to complete...
2921 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002922
2923 if (PrivateStateThreadIsValid ())
2924 ResumePrivateStateThread ();
2925 else
2926 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002927 }
2928 else if (state == eStateExited)
2929 {
2930 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2931 // not likely to work, and return an invalid pid.
2932 HandlePrivateEvent (event_sp);
2933 }
2934 }
2935 }
2936 }
2937 else
2938 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002939 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002940 }
2941 }
2942 return error;
2943}
2944
Greg Claytonc3776bf2012-02-09 06:16:32 +00002945
2946Error
2947Process::LoadCore ()
2948{
2949 Error error = DoLoadCore();
2950 if (error.Success())
2951 {
2952 if (PrivateStateThreadIsValid ())
2953 ResumePrivateStateThread ();
2954 else
2955 StartPrivateStateThread ();
2956
Greg Claytonc859e2d2012-02-13 23:10:39 +00002957 DynamicLoader *dyld = GetDynamicLoader ();
2958 if (dyld)
2959 dyld->DidAttach();
2960
2961 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002962 // We successfully loaded a core file, now pretend we stopped so we can
2963 // show all of the threads in the core file and explore the crashed
2964 // state.
2965 SetPrivateState (eStateStopped);
2966
2967 }
2968 return error;
2969}
2970
Greg Claytonc859e2d2012-02-13 23:10:39 +00002971DynamicLoader *
2972Process::GetDynamicLoader ()
2973{
2974 if (m_dyld_ap.get() == NULL)
2975 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2976 return m_dyld_ap.get();
2977}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002978
2979
Jim Inghambb3a2832011-01-29 01:49:25 +00002980Process::NextEventAction::EventActionResult
2981Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002982{
Jim Inghambb3a2832011-01-29 01:49:25 +00002983 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2984 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002985 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002986 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002987 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002988 return eEventActionRetry;
2989
2990 case eStateStopped:
2991 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002992 {
2993 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002994 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002995 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002996 // We don't want these events to be reported, so go set the ShouldReportStop here:
2997 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
2998
Greg Claytonc9ed4782011-11-12 02:10:56 +00002999 if (m_exec_count > 0)
3000 {
3001 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00003002 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003003 return eEventActionRetry;
3004 }
3005 else
3006 {
3007 m_process->CompleteAttach ();
3008 return eEventActionSuccess;
3009 }
3010 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003011 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003012
Greg Clayton513c26c2011-01-29 07:10:55 +00003013 default:
3014 case eStateExited:
3015 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003016 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003017 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003018
3019 m_exit_string.assign ("No valid Process");
3020 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003021}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003022
Jim Inghambb3a2832011-01-29 01:49:25 +00003023Process::NextEventAction::EventActionResult
3024Process::AttachCompletionHandler::HandleBeingInterrupted()
3025{
3026 return eEventActionSuccess;
3027}
3028
3029const char *
3030Process::AttachCompletionHandler::GetExitString ()
3031{
3032 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003033}
3034
3035Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003036Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003037{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003038 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003039 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003040 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003041 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003042
Greg Clayton144f3a92011-11-15 03:53:30 +00003043 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003044 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003045 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003046 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003047 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003048
Greg Clayton144f3a92011-11-15 03:53:30 +00003049 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003050 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003051 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3052
3053 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003054 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003055 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3056 if (error.Success())
3057 {
Greg Clayton96249852013-04-18 16:57:27 +00003058 if (m_public_run_lock.WriteTryLock())
Greg Clayton926cce72012-10-12 16:10:12 +00003059 {
3060 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003061 const bool restarted = false;
3062 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003063 // Now attach using these arguments.
3064 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
3065 }
3066 else
3067 {
3068 // This shouldn't happen
3069 error.SetErrorString("failed to acquire process run lock");
3070 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003071
Greg Clayton144f3a92011-11-15 03:53:30 +00003072 if (error.Fail())
3073 {
3074 if (GetID() != LLDB_INVALID_PROCESS_ID)
3075 {
3076 SetID (LLDB_INVALID_PROCESS_ID);
3077 if (error.AsCString() == NULL)
3078 error.SetErrorString("attach failed");
3079
3080 SetExitStatus(-1, error.AsCString());
3081 }
3082 }
3083 else
3084 {
3085 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3086 StartPrivateStateThread();
3087 }
3088 return error;
3089 }
Greg Claytone996fd32011-03-08 22:40:15 +00003090 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003091 else
Greg Claytone996fd32011-03-08 22:40:15 +00003092 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003093 ProcessInstanceInfoList process_infos;
3094 PlatformSP platform_sp (m_target.GetPlatform ());
3095
3096 if (platform_sp)
3097 {
3098 ProcessInstanceInfoMatch match_info;
3099 match_info.GetProcessInfo() = attach_info;
3100 match_info.SetNameMatchType (eNameMatchEquals);
3101 platform_sp->FindProcesses (match_info, process_infos);
3102 const uint32_t num_matches = process_infos.GetSize();
3103 if (num_matches == 1)
3104 {
3105 attach_pid = process_infos.GetProcessIDAtIndex(0);
3106 // Fall through and attach using the above process ID
3107 }
3108 else
3109 {
3110 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3111 if (num_matches > 1)
3112 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3113 else
3114 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3115 }
3116 }
3117 else
3118 {
3119 error.SetErrorString ("invalid platform, can't find processes by name");
3120 return error;
3121 }
Greg Claytone996fd32011-03-08 22:40:15 +00003122 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003123 }
3124 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003125 {
3126 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003127 }
3128 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003129
3130 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003131 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003132 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003133 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003134 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003135
Greg Clayton96249852013-04-18 16:57:27 +00003136 if (m_public_run_lock.WriteTryLock())
Greg Clayton926cce72012-10-12 16:10:12 +00003137 {
3138 // Now attach using these arguments.
3139 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003140 const bool restarted = false;
3141 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003142 error = DoAttachToProcessWithID (attach_pid, attach_info);
3143 }
3144 else
3145 {
3146 // This shouldn't happen
3147 error.SetErrorString("failed to acquire process run lock");
3148 }
3149
Greg Clayton144f3a92011-11-15 03:53:30 +00003150 if (error.Success())
3151 {
3152
3153 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3154 StartPrivateStateThread();
3155 }
3156 else
Greg Claytone996fd32011-03-08 22:40:15 +00003157 {
3158 if (GetID() != LLDB_INVALID_PROCESS_ID)
3159 {
3160 SetID (LLDB_INVALID_PROCESS_ID);
3161 const char *error_string = error.AsCString();
3162 if (error_string == NULL)
3163 error_string = "attach failed";
3164
3165 SetExitStatus(-1, error_string);
3166 }
3167 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003168 }
3169 }
3170 return error;
3171}
3172
Greg Clayton93d3c8332011-02-16 04:46:07 +00003173void
3174Process::CompleteAttach ()
3175{
3176 // Let the process subclass figure out at much as it can about the process
3177 // before we go looking for a dynamic loader plug-in.
3178 DidAttach();
3179
Jim Ingham4299fdb2011-09-15 01:10:17 +00003180 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3181 // the same as the one we've already set, switch architectures.
3182 PlatformSP platform_sp (m_target.GetPlatform ());
3183 assert (platform_sp.get());
3184 if (platform_sp)
3185 {
Greg Clayton70512312012-05-08 01:45:38 +00003186 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003187 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003188 {
3189 ArchSpec platform_arch;
3190 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3191 if (platform_sp)
3192 {
3193 m_target.SetPlatform (platform_sp);
3194 m_target.SetArchitecture(platform_arch);
3195 }
3196 }
3197 else
3198 {
3199 ProcessInstanceInfo process_info;
3200 platform_sp->GetProcessInfo (GetID(), process_info);
3201 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003202 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003203 m_target.SetArchitecture (process_arch);
3204 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003205 }
3206
3207 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003208 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003209 DynamicLoader *dyld = GetDynamicLoader ();
3210 if (dyld)
3211 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003212
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003213 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003214 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003215 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003216 Mutex::Locker modules_locker(target_modules.GetMutex());
3217 size_t num_modules = target_modules.GetSize();
3218 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003219
Andy Gibbsa297a972013-06-19 19:04:53 +00003220 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003221 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003222 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003223 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003224 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003225 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003226 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003227 break;
3228 }
3229 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003230 if (new_executable_module_sp)
3231 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003232}
3233
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003234Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003235Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003236{
Greg Claytonb766a732011-02-04 01:58:07 +00003237 m_abi_sp.reset();
3238 m_process_input_reader.reset();
3239
3240 // Find the process and its architecture. Make sure it matches the architecture
3241 // of the current Target, and if not adjust it.
3242
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003243 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003244 if (error.Success())
3245 {
Greg Clayton71337622011-02-24 22:24:29 +00003246 if (GetID() != LLDB_INVALID_PROCESS_ID)
3247 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003248 EventSP event_sp;
3249 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3250
3251 if (state == eStateStopped || state == eStateCrashed)
3252 {
3253 // If we attached and actually have a process on the other end, then
3254 // this ended up being the equivalent of an attach.
3255 CompleteAttach ();
3256
3257 // This delays passing the stopped event to listeners till
3258 // CompleteAttach gets a chance to complete...
3259 HandlePrivateEvent (event_sp);
3260
3261 }
Greg Clayton71337622011-02-24 22:24:29 +00003262 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003263
3264 if (PrivateStateThreadIsValid ())
3265 ResumePrivateStateThread ();
3266 else
3267 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003268 }
3269 return error;
3270}
3271
3272
3273Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003274Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003275{
Greg Clayton5160ce52013-03-27 23:08:40 +00003276 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003277 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003278 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003279 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003280 StateAsCString(m_public_state.GetValue()),
3281 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003282
3283 Error error (WillResume());
3284 // Tell the process it is about to resume before the thread list
3285 if (error.Success())
3286 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003287 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003288 // can let all of our threads know that they are about to be
3289 // resumed. Threads will each be called with
3290 // Thread::WillResume(StateType) where StateType contains the state
3291 // that they are supposed to have when the process is resumed
3292 // (suspended/running/stepping). Threads should also check
3293 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003294 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003295 if (m_thread_list.WillResume())
3296 {
Jim Ingham372787f2012-04-07 00:00:41 +00003297 // Last thing, do the PreResumeActions.
3298 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003299 {
Jim Ingham0161b492013-02-09 01:29:05 +00003300 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003301 }
3302 else
3303 {
3304 m_mod_id.BumpResumeID();
3305 error = DoResume();
3306 if (error.Success())
3307 {
3308 DidResume();
3309 m_thread_list.DidResume();
3310 if (log)
3311 log->Printf ("Process thinks the process has resumed.");
3312 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003313 }
3314 }
3315 else
3316 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003317 // Somebody wanted to run without running. So generate a continue & a stopped event,
3318 // and let the world handle them.
3319 if (log)
3320 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3321
3322 SetPrivateState(eStateRunning);
3323 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003324 }
3325 }
Jim Ingham444586b2011-01-24 06:34:17 +00003326 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003327 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003328 return error;
3329}
3330
3331Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003332Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003333{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003334 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3335 // in case it was already set and some thread plan logic calls halt on its
3336 // own.
3337 m_clear_thread_plans_on_stop |= clear_thread_plans;
3338
Jim Inghamaacc3182012-06-06 00:29:30 +00003339 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3340 // we could just straightaway get another event. It just narrows the window...
3341 m_currently_handling_event.WaitForValueEqualTo(false);
3342
3343
Jim Inghambb3a2832011-01-29 01:49:25 +00003344 // Pause our private state thread so we can ensure no one else eats
3345 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003346 Listener halt_listener ("lldb.process.halt_listener");
3347 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003348
Jim Inghambb3a2832011-01-29 01:49:25 +00003349 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003350 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003351
Greg Clayton513c26c2011-01-29 07:10:55 +00003352 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003353 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003354
Greg Clayton513c26c2011-01-29 07:10:55 +00003355 bool caused_stop = false;
3356
3357 // Ask the process subclass to actually halt our process
3358 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003359 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003360 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003361 if (m_public_state.GetValue() == eStateAttaching)
3362 {
3363 SetExitStatus(SIGKILL, "Cancelled async attach.");
3364 Destroy ();
3365 }
3366 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003367 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003368 // If "caused_stop" is true, then DoHalt stopped the process. If
3369 // "caused_stop" is false, the process was already stopped.
3370 // If the DoHalt caused the process to stop, then we want to catch
3371 // this event and set the interrupted bool to true before we pass
3372 // this along so clients know that the process was interrupted by
3373 // a halt command.
3374 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003375 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003376 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003377 TimeValue timeout_time;
3378 timeout_time = TimeValue::Now();
3379 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003380 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3381 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003382
Jim Ingham0f16e732011-02-08 05:20:59 +00003383 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003384 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003385 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003386 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003387 }
3388 else
3389 {
Greg Clayton2637f822011-11-17 01:23:07 +00003390 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003391 {
3392 // We caused the process to interrupt itself, so mark this
3393 // as such in the stop event so clients can tell an interrupted
3394 // process from a natural stop
3395 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3396 }
3397 else
3398 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003399 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003400 if (log)
3401 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3402 error.SetErrorString ("Did not get stopped event after halt.");
3403 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003404 }
3405 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003406 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003407 }
3408 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003409 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003410 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003411 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003412
3413 // Post any event we might have consumed. If all goes well, we will have
3414 // stopped the process, intercepted the event and set the interrupted
3415 // bool in the event. Post it to the private event queue and that will end up
3416 // correctly setting the state.
3417 if (event_sp)
3418 m_private_state_broadcaster.BroadcastEvent(event_sp);
3419
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003420 return error;
3421}
3422
3423Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003424Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3425{
3426 Error error;
3427 if (m_public_state.GetValue() == eStateRunning)
3428 {
3429 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3430 if (log)
3431 log->Printf("Process::Destroy() About to halt.");
3432 error = Halt();
3433 if (error.Success())
3434 {
3435 // Consume the halt event.
3436 TimeValue timeout (TimeValue::Now());
3437 timeout.OffsetWithSeconds(1);
3438 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3439
3440 // If the process exited while we were waiting for it to stop, put the exited event into
3441 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3442 // they don't have a process anymore...
3443
3444 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3445 {
3446 if (log)
3447 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3448 return error;
3449 }
3450 else
3451 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3452
3453 if (state != eStateStopped)
3454 {
3455 if (log)
3456 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3457 // If we really couldn't stop the process then we should just error out here, but if the
3458 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3459 StateType private_state = m_private_state.GetValue();
3460 if (private_state != eStateStopped)
3461 {
3462 return error;
3463 }
3464 }
3465 }
3466 else
3467 {
3468 if (log)
3469 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3470 }
3471 }
3472 return error;
3473}
3474
3475Error
Jim Inghamacff8952013-05-02 00:27:30 +00003476Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003477{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003478 EventSP exit_event_sp;
3479 Error error;
3480 m_destroy_in_process = true;
3481
3482 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003483
3484 if (error.Success())
3485 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003486 if (DetachRequiresHalt())
3487 {
3488 error = HaltForDestroyOrDetach (exit_event_sp);
3489 if (!error.Success())
3490 {
3491 m_destroy_in_process = false;
3492 return error;
3493 }
3494 else if (exit_event_sp)
3495 {
3496 // We shouldn't need to do anything else here. There's no process left to detach from...
3497 StopPrivateStateThread();
3498 m_destroy_in_process = false;
3499 return error;
3500 }
3501 }
3502
Jim Inghamacff8952013-05-02 00:27:30 +00003503 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003504 if (error.Success())
3505 {
3506 DidDetach();
3507 StopPrivateStateThread();
3508 }
Jim Inghamacff8952013-05-02 00:27:30 +00003509 else
3510 {
3511 return error;
3512 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003513 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003514 m_destroy_in_process = false;
3515
3516 // If we exited when we were waiting for a process to stop, then
3517 // forward the event here so we don't lose the event
3518 if (exit_event_sp)
3519 {
3520 // Directly broadcast our exited event because we shut down our
3521 // private state thread above
3522 BroadcastEvent(exit_event_sp);
3523 }
3524
3525 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3526 // the last events through the event system, in which case we might strand the write lock. Unlock
3527 // it here so when we do to tear down the process we don't get an error destroying the lock.
3528
Greg Clayton96249852013-04-18 16:57:27 +00003529 m_public_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003530 return error;
3531}
3532
3533Error
3534Process::Destroy ()
3535{
Jim Ingham09437922013-03-01 20:04:25 +00003536
3537 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3538 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3539 // failed and the process stays around for some reason it won't be in a confused state.
3540
3541 m_destroy_in_process = true;
3542
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003543 Error error (WillDestroy());
3544 if (error.Success())
3545 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003546 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003547 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003548 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003549 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003550 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003551
Jim Inghamaacc3182012-06-06 00:29:30 +00003552 if (m_public_state.GetValue() != eStateRunning)
3553 {
3554 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3555 // kill it, we don't want it hitting a breakpoint...
3556 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3557 // we're not going to have much luck doing this now.
3558 m_thread_list.DiscardThreadPlans();
3559 DisableAllBreakpointSites();
3560 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003561
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003562 error = DoDestroy();
3563 if (error.Success())
3564 {
3565 DidDestroy();
3566 StopPrivateStateThread();
3567 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003568 m_stdio_communication.StopReadThread();
3569 m_stdio_communication.Disconnect();
3570 if (m_process_input_reader && m_process_input_reader->IsActive())
3571 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3572 if (m_process_input_reader)
3573 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003574
3575 // If we exited when we were waiting for a process to stop, then
3576 // forward the event here so we don't lose the event
3577 if (exit_event_sp)
3578 {
3579 // Directly broadcast our exited event because we shut down our
3580 // private state thread above
3581 BroadcastEvent(exit_event_sp);
3582 }
3583
Jim Inghamb1e2e842012-04-12 18:49:31 +00003584 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3585 // the last events through the event system, in which case we might strand the write lock. Unlock
3586 // it here so when we do to tear down the process we don't get an error destroying the lock.
Greg Clayton96249852013-04-18 16:57:27 +00003587 m_public_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003588 }
Jim Ingham09437922013-03-01 20:04:25 +00003589
3590 m_destroy_in_process = false;
3591
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003592 return error;
3593}
3594
3595Error
3596Process::Signal (int signal)
3597{
3598 Error error (WillSignal());
3599 if (error.Success())
3600 {
3601 error = DoSignal(signal);
3602 if (error.Success())
3603 DidSignal();
3604 }
3605 return error;
3606}
3607
Greg Clayton514487e2011-02-15 21:59:32 +00003608lldb::ByteOrder
3609Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003610{
Greg Clayton514487e2011-02-15 21:59:32 +00003611 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003612}
3613
3614uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003615Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003616{
Greg Clayton514487e2011-02-15 21:59:32 +00003617 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003618}
3619
Greg Clayton514487e2011-02-15 21:59:32 +00003620
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003621bool
3622Process::ShouldBroadcastEvent (Event *event_ptr)
3623{
3624 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3625 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003626 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003627
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003628 switch (state)
3629 {
Greg Claytonb766a732011-02-04 01:58:07 +00003630 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003631 case eStateAttaching:
3632 case eStateLaunching:
3633 case eStateDetached:
3634 case eStateExited:
3635 case eStateUnloaded:
3636 // These events indicate changes in the state of the debugging session, always report them.
3637 return_value = true;
3638 break;
3639 case eStateInvalid:
3640 // We stopped for no apparent reason, don't report it.
3641 return_value = false;
3642 break;
3643 case eStateRunning:
3644 case eStateStepping:
3645 // If we've started the target running, we handle the cases where we
3646 // are already running and where there is a transition from stopped to
3647 // running differently.
3648 // running -> running: Automatically suppress extra running events
3649 // stopped -> running: Report except when there is one or more no votes
3650 // and no yes votes.
3651 SynchronouslyNotifyStateChanged (state);
Jim Ingham0161b492013-02-09 01:29:05 +00003652 switch (m_last_broadcast_state)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003653 {
3654 case eStateRunning:
3655 case eStateStepping:
3656 // We always suppress multiple runnings with no PUBLIC stop in between.
3657 return_value = false;
3658 break;
3659 default:
3660 // TODO: make this work correctly. For now always report
3661 // run if we aren't running so we don't miss any runnning
3662 // events. If I run the lldb/test/thread/a.out file and
3663 // break at main.cpp:58, run and hit the breakpoints on
3664 // multiple threads, then somehow during the stepping over
3665 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003666
3667 // This is a transition from stop to run.
3668 switch (m_thread_list.ShouldReportRun (event_ptr))
3669 {
3670 case eVoteYes:
3671 case eVoteNoOpinion:
3672 return_value = true;
3673 break;
3674 case eVoteNo:
3675 return_value = false;
3676 break;
3677 }
3678 break;
3679 }
3680 break;
3681 case eStateStopped:
3682 case eStateCrashed:
3683 case eStateSuspended:
3684 {
3685 // We've stopped. First see if we're going to restart the target.
3686 // If we are going to stop, then we always broadcast the event.
3687 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00003688 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003689
Jim Inghamcb4ca112012-05-16 01:32:14 +00003690 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003691 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003692 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003693 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003694 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3695 event_ptr,
3696 StateAsCString(state));
3697 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003698 }
3699 else
3700 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003701 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3702 bool should_resume = false;
3703
Jim Ingham0161b492013-02-09 01:29:05 +00003704 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3705 // Asking the thread list is also not likely to go well, since we are running again.
3706 // So in that case just report the event.
3707
Jim Ingham0161b492013-02-09 01:29:05 +00003708 if (!was_restarted)
3709 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Jim Ingham221d51c2013-05-08 00:35:16 +00003710
3711 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003712 {
Jim Ingham0161b492013-02-09 01:29:05 +00003713 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3714 if (log)
3715 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3716 should_resume,
3717 StateAsCString(state),
3718 was_restarted,
3719 stop_vote);
3720
3721 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003722 {
3723 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003724 return_value = true;
3725 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003727 case eVoteNo:
3728 return_value = false;
3729 break;
3730 }
Jim Ingham0161b492013-02-09 01:29:05 +00003731
Jim Inghamcb95f342012-09-05 21:13:56 +00003732 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003733 {
3734 if (log)
3735 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3736 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003737 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003738 }
3739
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003740 }
3741 else
3742 {
3743 return_value = true;
3744 SynchronouslyNotifyStateChanged (state);
3745 }
3746 }
3747 }
Jim Ingham0161b492013-02-09 01:29:05 +00003748 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003749 }
Jim Ingham0161b492013-02-09 01:29:05 +00003750
3751 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3752 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3753 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3754 // because the PublicState reflects the last event pulled off the queue, and there may be several
3755 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3756 // yet. m_last_broadcast_state gets updated here.
3757
3758 if (return_value)
3759 m_last_broadcast_state = state;
3760
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003761 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003762 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3763 event_ptr,
3764 StateAsCString(state),
3765 StateAsCString(m_last_broadcast_state),
3766 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003767 return return_value;
3768}
3769
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003770
3771bool
Jim Ingham372787f2012-04-07 00:00:41 +00003772Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003773{
Greg Clayton5160ce52013-03-27 23:08:40 +00003774 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003775
Greg Clayton8b82f082011-04-12 05:54:46 +00003776 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003777 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003778 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3779
Jim Ingham372787f2012-04-07 00:00:41 +00003780 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003781 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003782
3783 // Create a thread that watches our internal state and controls which
3784 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003785 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003786 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003787 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00003788 else
Daniel Malead01b2952012-11-29 21:49:15 +00003789 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003790
3791 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003792 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003793 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3794 if (success)
3795 {
3796 ResumePrivateStateThread();
3797 return true;
3798 }
3799 else
3800 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003801}
3802
3803void
3804Process::PausePrivateStateThread ()
3805{
3806 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3807}
3808
3809void
3810Process::ResumePrivateStateThread ()
3811{
3812 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3813}
3814
3815void
3816Process::StopPrivateStateThread ()
3817{
Greg Clayton8b82f082011-04-12 05:54:46 +00003818 if (PrivateStateThreadIsValid ())
3819 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003820 else
3821 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003822 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003823 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003824 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003825 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003826}
3827
3828void
3829Process::ControlPrivateStateThread (uint32_t signal)
3830{
Greg Clayton5160ce52013-03-27 23:08:40 +00003831 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003832
3833 assert (signal == eBroadcastInternalStateControlStop ||
3834 signal == eBroadcastInternalStateControlPause ||
3835 signal == eBroadcastInternalStateControlResume);
3836
3837 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003838 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003839
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003840 // Signal the private state thread. First we should copy this is case the
3841 // thread starts exiting since the private state thread will NULL this out
3842 // when it exits
3843 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003844 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003845 {
3846 TimeValue timeout_time;
3847 bool timed_out;
3848
3849 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3850
3851 timeout_time = TimeValue::Now();
3852 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003853 if (log)
3854 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003855 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3856 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3857
3858 if (signal == eBroadcastInternalStateControlStop)
3859 {
3860 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003861 {
3862 Error error;
3863 Host::ThreadCancel (private_state_thread, &error);
3864 if (log)
3865 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3866 }
3867 else
3868 {
3869 if (log)
3870 log->Printf ("The control event killed the private state thread without having to cancel.");
3871 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003872
3873 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003874 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003875 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003876 }
3877 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003878 else
3879 {
3880 if (log)
3881 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3882 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003883}
3884
3885void
Jim Inghamcfc09352012-07-27 23:57:19 +00003886Process::SendAsyncInterrupt ()
3887{
3888 if (PrivateStateThreadIsValid())
3889 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3890 else
3891 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3892}
3893
3894void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003895Process::HandlePrivateEvent (EventSP &event_sp)
3896{
Greg Clayton5160ce52013-03-27 23:08:40 +00003897 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003898 m_resume_requested = false;
3899
Jim Inghamaacc3182012-06-06 00:29:30 +00003900 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003901
Greg Clayton414f5d32011-01-25 02:58:48 +00003902 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003903
3904 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003905 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003906 {
Jim Ingham754ab982011-01-29 04:05:41 +00003907 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003908 if (log)
3909 log->Printf ("Ran next event action, result was %d.", action_result);
3910
Jim Inghambb3a2832011-01-29 01:49:25 +00003911 switch (action_result)
3912 {
3913 case NextEventAction::eEventActionSuccess:
3914 SetNextEventAction(NULL);
3915 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003916
Jim Inghambb3a2832011-01-29 01:49:25 +00003917 case NextEventAction::eEventActionRetry:
3918 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003919
Jim Inghambb3a2832011-01-29 01:49:25 +00003920 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003921 // Handle Exiting Here. If we already got an exited event,
3922 // we should just propagate it. Otherwise, swallow this event,
3923 // and set our state to exit so the next event will kill us.
3924 if (new_state != eStateExited)
3925 {
3926 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003927 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003928 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003929 SetNextEventAction(NULL);
3930 return;
3931 }
3932 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003933 break;
3934 }
3935 }
3936
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003937 // See if we should broadcast this state to external clients?
3938 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003939
3940 if (should_broadcast)
3941 {
3942 if (log)
3943 {
Daniel Malead01b2952012-11-29 21:49:15 +00003944 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003945 __FUNCTION__,
3946 GetID(),
3947 StateAsCString(new_state),
3948 StateAsCString (GetState ()),
3949 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003950 }
Jim Ingham9575d842011-03-11 03:53:59 +00003951 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003952 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003953 PushProcessInputReader ();
Jim Inghamb78d73f2013-05-15 01:21:48 +00003954 else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003955 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003956
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003957 BroadcastEvent (event_sp);
3958 }
3959 else
3960 {
3961 if (log)
3962 {
Daniel Malead01b2952012-11-29 21:49:15 +00003963 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003964 __FUNCTION__,
3965 GetID(),
3966 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003967 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003968 }
3969 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003970 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003971}
3972
3973void *
3974Process::PrivateStateThread (void *arg)
3975{
3976 Process *proc = static_cast<Process*> (arg);
3977 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003978 return result;
3979}
3980
3981void *
3982Process::RunPrivateStateThread ()
3983{
Jim Ingham076b3042012-04-10 01:21:57 +00003984 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003985 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003986
Greg Clayton5160ce52013-03-27 23:08:40 +00003987 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003988 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003989 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003990
3991 bool exit_now = false;
3992 while (!exit_now)
3993 {
3994 EventSP event_sp;
3995 WaitForEventsPrivate (NULL, event_sp, control_only);
3996 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3997 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003998 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003999 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Inghamb1e2e842012-04-12 18:49:31 +00004000
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004001 switch (event_sp->GetType())
4002 {
4003 case eBroadcastInternalStateControlStop:
4004 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004005 break; // doing any internal state managment below
4006
4007 case eBroadcastInternalStateControlPause:
4008 control_only = true;
4009 break;
4010
4011 case eBroadcastInternalStateControlResume:
4012 control_only = false;
4013 break;
4014 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004015
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004016 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004017 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004018 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004019 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4020 {
4021 if (m_public_state.GetValue() == eStateAttaching)
4022 {
4023 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004024 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004025 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4026 }
4027 else
4028 {
4029 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004030 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004031 Halt();
4032 }
4033 continue;
4034 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004035
4036 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4037
4038 if (internal_state != eStateInvalid)
4039 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004040 if (m_clear_thread_plans_on_stop &&
4041 StateIsStoppedState(internal_state, true))
4042 {
4043 m_clear_thread_plans_on_stop = false;
4044 m_thread_list.DiscardThreadPlans();
4045 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004046 HandlePrivateEvent (event_sp);
4047 }
4048
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004049 if (internal_state == eStateInvalid ||
4050 internal_state == eStateExited ||
4051 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004052 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004053 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004054 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004055
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004056 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004057 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004058 }
4059
Caroline Tice20ad3c42010-10-29 21:48:37 +00004060 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004061 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004062 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004063
Greg Clayton96249852013-04-18 16:57:27 +00004064 m_public_run_lock.WriteUnlock();
Greg Clayton6ed95942011-01-22 07:12:45 +00004065 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4066 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004067 return NULL;
4068}
4069
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004070//------------------------------------------------------------------
4071// Process Event Data
4072//------------------------------------------------------------------
4073
4074Process::ProcessEventData::ProcessEventData () :
4075 EventData (),
4076 m_process_sp (),
4077 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004078 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004079 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004080 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004081{
4082}
4083
4084Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4085 EventData (),
4086 m_process_sp (process_sp),
4087 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004088 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004089 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004090 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004091{
4092}
4093
4094Process::ProcessEventData::~ProcessEventData()
4095{
4096}
4097
4098const ConstString &
4099Process::ProcessEventData::GetFlavorString ()
4100{
4101 static ConstString g_flavor ("Process::ProcessEventData");
4102 return g_flavor;
4103}
4104
4105const ConstString &
4106Process::ProcessEventData::GetFlavor () const
4107{
4108 return ProcessEventData::GetFlavorString ();
4109}
4110
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004111void
4112Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4113{
4114 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004115 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4116 // the public event queue, then other times when we're pretending that this is where we stopped at the
4117 // end of expression evaluation. m_update_state is used to distinguish these
4118 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004119 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004120 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004121 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004122
Jim Ingham221d51c2013-05-08 00:35:16 +00004123 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004124
4125 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4126 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004127 {
4128 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004129 uint32_t num_threads = curr_thread_list.GetSize();
4130 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004131
Jim Ingham4b536182011-08-09 02:12:22 +00004132 // The actions might change one of the thread's stop_info's opinions about whether we should
4133 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004134
4135 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4136 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4137 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4138 // 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
4139 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004140 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004141 for (idx = 0; idx < num_threads; ++idx)
4142 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4143
Jim Inghamc7078c22012-12-13 22:24:15 +00004144 // Use this to track whether we should continue from here. We will only continue the target running if
4145 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4146 // then it doesn't matter what the other threads say...
4147
4148 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004149
Jim Ingham0ad7e052013-04-25 02:04:59 +00004150 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4151 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4152 // thing to do is, and it's better to let the user decide than continue behind their backs.
4153
4154 bool does_anybody_have_an_opinion = false;
4155
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004156 for (idx = 0; idx < num_threads; ++idx)
4157 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004158 curr_thread_list = m_process_sp->GetThreadList();
4159 if (curr_thread_list.GetSize() != num_threads)
4160 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004161 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004162 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004163 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004164 break;
4165 }
4166
4167 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4168
4169 if (thread_sp->GetIndexID() != thread_index_array[idx])
4170 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004171 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004172 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004173 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004174 idx,
4175 thread_index_array[idx],
4176 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004177 break;
4178 }
4179
Jim Inghamb15bfc72010-10-20 00:39:53 +00004180 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004181 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004182 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004183 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004184 bool this_thread_wants_to_stop;
4185 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004186 {
Jim Ingham0161b492013-02-09 01:29:05 +00004187 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4188 }
4189 else
4190 {
4191 stop_info_sp->PerformAction(event_ptr);
4192 // The stop action might restart the target. If it does, then we want to mark that in the
4193 // event so that whoever is receiving it will know to wait for the running event and reflect
4194 // that state appropriately.
4195 // We also need to stop processing actions, since they aren't expecting the target to be running.
4196
4197 // FIXME: we might have run.
4198 if (stop_info_sp->HasTargetRunSinceMe())
4199 {
4200 SetRestarted (true);
4201 break;
4202 }
4203
4204 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004205 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004206
Jim Inghamc7078c22012-12-13 22:24:15 +00004207 if (still_should_stop == false)
4208 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004209 }
4210 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004211
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004212
Jim Inghama8ca6e22013-05-03 23:04:37 +00004213 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004214 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004215 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004216 {
4217 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004218 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004219 // Use the public resume method here, since this is just
4220 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004221 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004222 }
4223 else
4224 {
4225 // If we didn't restart, run the Stop Hooks here:
4226 // They might also restart the target, so watch for that.
4227 m_process_sp->GetTarget().RunStopHooks();
4228 if (m_process_sp->GetPrivateState() == eStateRunning)
4229 SetRestarted(true);
4230 }
Jim Ingham9575d842011-03-11 03:53:59 +00004231 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004232 }
4233}
4234
4235void
4236Process::ProcessEventData::Dump (Stream *s) const
4237{
4238 if (m_process_sp)
Daniel Malead01b2952012-11-29 21:49:15 +00004239 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004240
Greg Clayton8b82f082011-04-12 05:54:46 +00004241 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004242}
4243
4244const Process::ProcessEventData *
4245Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4246{
4247 if (event_ptr)
4248 {
4249 const EventData *event_data = event_ptr->GetData();
4250 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4251 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4252 }
4253 return NULL;
4254}
4255
4256ProcessSP
4257Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4258{
4259 ProcessSP process_sp;
4260 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4261 if (data)
4262 process_sp = data->GetProcessSP();
4263 return process_sp;
4264}
4265
4266StateType
4267Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4268{
4269 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4270 if (data == NULL)
4271 return eStateInvalid;
4272 else
4273 return data->GetState();
4274}
4275
4276bool
4277Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4278{
4279 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4280 if (data == NULL)
4281 return false;
4282 else
4283 return data->GetRestarted();
4284}
4285
4286void
4287Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4288{
4289 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4290 if (data != NULL)
4291 data->SetRestarted(new_value);
4292}
4293
Jim Ingham0161b492013-02-09 01:29:05 +00004294size_t
4295Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4296{
4297 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4298 if (data != NULL)
4299 return data->GetNumRestartedReasons();
4300 else
4301 return 0;
4302}
4303
4304const char *
4305Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4306{
4307 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4308 if (data != NULL)
4309 return data->GetRestartedReasonAtIndex(idx);
4310 else
4311 return NULL;
4312}
4313
4314void
4315Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4316{
4317 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4318 if (data != NULL)
4319 data->AddRestartedReason(reason);
4320}
4321
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004322bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004323Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4324{
4325 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4326 if (data == NULL)
4327 return false;
4328 else
4329 return data->GetInterrupted ();
4330}
4331
4332void
4333Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4334{
4335 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4336 if (data != NULL)
4337 data->SetInterrupted(new_value);
4338}
4339
4340bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004341Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4342{
4343 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4344 if (data)
4345 {
4346 data->SetUpdateStateOnRemoval();
4347 return true;
4348 }
4349 return false;
4350}
4351
Greg Claytond9e416c2012-02-18 05:35:26 +00004352lldb::TargetSP
4353Process::CalculateTarget ()
4354{
4355 return m_target.shared_from_this();
4356}
4357
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004358void
Greg Clayton0603aa92010-10-04 01:05:56 +00004359Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004360{
Greg Claytonc14ee322011-09-22 04:58:26 +00004361 exe_ctx.SetTargetPtr (&m_target);
4362 exe_ctx.SetProcessPtr (this);
4363 exe_ctx.SetThreadPtr(NULL);
4364 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004365}
4366
Greg Claytone996fd32011-03-08 22:40:15 +00004367//uint32_t
4368//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4369//{
4370// return 0;
4371//}
4372//
4373//ArchSpec
4374//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4375//{
4376// return Host::GetArchSpecForExistingProcess (pid);
4377//}
4378//
4379//ArchSpec
4380//Process::GetArchSpecForExistingProcess (const char *process_name)
4381//{
4382// return Host::GetArchSpecForExistingProcess (process_name);
4383//}
4384//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004385void
4386Process::AppendSTDOUT (const char * s, size_t len)
4387{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004388 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004389 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004390 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004391}
4392
4393void
Greg Clayton93e86192011-11-13 04:45:22 +00004394Process::AppendSTDERR (const char * s, size_t len)
4395{
4396 Mutex::Locker locker (m_stdio_communication_mutex);
4397 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004398 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004399}
4400
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004401void
4402Process::BroadcastAsyncProfileData(const char *s, size_t len)
4403{
4404 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004405 m_profile_data.push_back(s);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004406 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4407}
4408
4409size_t
4410Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4411{
4412 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004413 if (m_profile_data.empty())
4414 return 0;
4415
4416 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004417 if (bytes_available > 0)
4418 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004419 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004420 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004421 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004422 if (bytes_available > buf_size)
4423 {
Han Ming Ong929a94f2012-11-29 22:14:45 +00004424 memcpy(buf, m_profile_data.front().data(), buf_size);
4425 m_profile_data.front().erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004426 bytes_available = buf_size;
4427 }
4428 else
4429 {
Han Ming Ong929a94f2012-11-29 22:14:45 +00004430 memcpy(buf, m_profile_data.front().data(), bytes_available);
4431 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004432 }
4433 }
4434 return bytes_available;
4435}
4436
4437
Greg Clayton93e86192011-11-13 04:45:22 +00004438//------------------------------------------------------------------
4439// Process STDIO
4440//------------------------------------------------------------------
4441
4442size_t
4443Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4444{
4445 Mutex::Locker locker(m_stdio_communication_mutex);
4446 size_t bytes_available = m_stdout_data.size();
4447 if (bytes_available > 0)
4448 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004449 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004450 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004451 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004452 if (bytes_available > buf_size)
4453 {
4454 memcpy(buf, m_stdout_data.c_str(), buf_size);
4455 m_stdout_data.erase(0, buf_size);
4456 bytes_available = buf_size;
4457 }
4458 else
4459 {
4460 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4461 m_stdout_data.clear();
4462 }
4463 }
4464 return bytes_available;
4465}
4466
4467
4468size_t
4469Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4470{
4471 Mutex::Locker locker(m_stdio_communication_mutex);
4472 size_t bytes_available = m_stderr_data.size();
4473 if (bytes_available > 0)
4474 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004475 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004476 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004477 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004478 if (bytes_available > buf_size)
4479 {
4480 memcpy(buf, m_stderr_data.c_str(), buf_size);
4481 m_stderr_data.erase(0, buf_size);
4482 bytes_available = buf_size;
4483 }
4484 else
4485 {
4486 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4487 m_stderr_data.clear();
4488 }
4489 }
4490 return bytes_available;
4491}
4492
4493void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004494Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4495{
4496 Process *process = (Process *) baton;
4497 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4498}
4499
4500size_t
4501Process::ProcessInputReaderCallback (void *baton,
4502 InputReader &reader,
4503 lldb::InputReaderAction notification,
4504 const char *bytes,
4505 size_t bytes_len)
4506{
4507 Process *process = (Process *) baton;
4508
4509 switch (notification)
4510 {
4511 case eInputReaderActivate:
4512 break;
4513
4514 case eInputReaderDeactivate:
4515 break;
4516
4517 case eInputReaderReactivate:
4518 break;
4519
Caroline Tice969ed3d2011-05-02 20:41:46 +00004520 case eInputReaderAsynchronousOutputWritten:
4521 break;
4522
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004523 case eInputReaderGotToken:
4524 {
4525 Error error;
4526 process->PutSTDIN (bytes, bytes_len, error);
4527 }
4528 break;
4529
Caroline Ticeefed6132010-11-19 20:47:54 +00004530 case eInputReaderInterrupt:
Jim Inghamfc65a502013-06-19 00:56:17 +00004531 process->SendAsyncInterrupt();
Caroline Ticeefed6132010-11-19 20:47:54 +00004532 break;
4533
4534 case eInputReaderEndOfFile:
4535 process->AppendSTDOUT ("^D", 2);
4536 break;
4537
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004538 case eInputReaderDone:
4539 break;
4540
4541 }
4542
4543 return bytes_len;
4544}
4545
4546void
4547Process::ResetProcessInputReader ()
4548{
4549 m_process_input_reader.reset();
4550}
4551
4552void
Greg Claytonee95ed52011-11-17 22:14:31 +00004553Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004554{
4555 // First set up the Read Thread for reading/handling process I/O
4556
Greg Clayton7b0992d2013-04-18 22:45:39 +00004557 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004558
4559 if (conn_ap.get())
4560 {
4561 m_stdio_communication.SetConnection (conn_ap.release());
4562 if (m_stdio_communication.IsConnected())
4563 {
4564 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4565 m_stdio_communication.StartReadThread();
4566
4567 // Now read thread is set up, set up input reader.
4568
4569 if (!m_process_input_reader.get())
4570 {
4571 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4572 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4573 this,
4574 eInputReaderGranularityByte,
4575 NULL,
4576 NULL,
4577 false));
4578
4579 if (err.Fail())
4580 m_process_input_reader.reset();
4581 }
4582 }
4583 }
4584}
4585
4586void
4587Process::PushProcessInputReader ()
4588{
4589 if (m_process_input_reader && !m_process_input_reader->IsActive())
4590 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4591}
4592
4593void
4594Process::PopProcessInputReader ()
4595{
4596 if (m_process_input_reader && m_process_input_reader->IsActive())
4597 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4598}
4599
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004600// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004601void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004602Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004603{
Greg Clayton67cc0632012-08-22 17:17:09 +00004604// static std::vector<OptionEnumValueElement> g_plugins;
4605//
4606// int i=0;
4607// const char *name;
4608// OptionEnumValueElement option_enum;
4609// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4610// {
4611// if (name)
4612// {
4613// option_enum.value = i;
4614// option_enum.string_value = name;
4615// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4616// g_plugins.push_back (option_enum);
4617// }
4618// ++i;
4619// }
4620// option_enum.value = 0;
4621// option_enum.string_value = NULL;
4622// option_enum.usage = NULL;
4623// g_plugins.push_back (option_enum);
4624//
4625// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4626// {
4627// if (::strcmp (name, "plugin") == 0)
4628// {
4629// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4630// break;
4631// }
4632// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004633//
Greg Clayton6920b522012-08-22 18:39:03 +00004634 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004635}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004636
Greg Clayton99d0faf2010-11-18 23:32:35 +00004637void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004638Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004639{
Greg Clayton6920b522012-08-22 18:39:03 +00004640 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004641}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004642
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004643ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004644Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004645 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00004646 bool stop_others,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004647 bool run_others,
Jim Ingham184e9812013-01-15 02:47:48 +00004648 bool unwind_on_error,
4649 bool ignore_breakpoints,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004650 uint32_t timeout_usec,
Jim Inghamf48169b2010-11-30 02:22:11 +00004651 Stream &errors)
4652{
4653 ExecutionResults return_value = eExecutionSetupError;
4654
Jim Ingham77787032011-01-20 02:03:18 +00004655 if (thread_plan_sp.get() == NULL)
4656 {
4657 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004658 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004659 }
Jim Ingham7d7931d2013-03-28 00:05:34 +00004660
4661 if (!thread_plan_sp->ValidatePlan(NULL))
4662 {
4663 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4664 return eExecutionSetupError;
4665 }
4666
Greg Claytonc14ee322011-09-22 04:58:26 +00004667 if (exe_ctx.GetProcessPtr() != this)
4668 {
4669 errors.Printf("RunThreadPlan called on wrong process.");
4670 return eExecutionSetupError;
4671 }
4672
4673 Thread *thread = exe_ctx.GetThreadPtr();
4674 if (thread == NULL)
4675 {
4676 errors.Printf("RunThreadPlan called with invalid thread.");
4677 return eExecutionSetupError;
4678 }
Jim Ingham77787032011-01-20 02:03:18 +00004679
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004680 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4681 // For that to be true the plan can't be private - since private plans suppress themselves in the
4682 // GetCompletedPlan call.
4683
4684 bool orig_plan_private = thread_plan_sp->GetPrivate();
4685 thread_plan_sp->SetPrivate(false);
4686
Jim Ingham444586b2011-01-24 06:34:17 +00004687 if (m_private_state.GetValue() != eStateStopped)
4688 {
4689 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004690 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004691 }
4692
Jim Ingham66243842011-08-13 00:56:10 +00004693 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004694 const uint32_t thread_idx_id = thread->GetIndexID();
Jim Ingham11b0e052013-02-19 23:22:45 +00004695 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4696 if (!selected_frame_sp)
4697 {
4698 thread->SetSelectedFrame(0);
4699 selected_frame_sp = thread->GetSelectedFrame();
4700 if (!selected_frame_sp)
4701 {
4702 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4703 return eExecutionSetupError;
4704 }
4705 }
4706
4707 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004708
4709 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4710 // so we should arrange to reset them as well.
4711
Greg Claytonc14ee322011-09-22 04:58:26 +00004712 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004713
Jim Ingham66243842011-08-13 00:56:10 +00004714 uint32_t selected_tid;
4715 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004716 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004717 {
4718 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004719 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004720 }
4721 else
4722 {
4723 selected_tid = LLDB_INVALID_THREAD_ID;
4724 }
4725
Jim Ingham372787f2012-04-07 00:00:41 +00004726 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004727 lldb::StateType old_state;
4728 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004729
Greg Clayton5160ce52013-03-27 23:08:40 +00004730 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004731 if (Host::GetCurrentThread() == m_private_state_thread)
4732 {
Jim Ingham076b3042012-04-10 01:21:57 +00004733 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4734 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004735 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Ingham076b3042012-04-10 01:21:57 +00004736 // we are fielding public events here.
4737 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004738 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
Jim Ingham076b3042012-04-10 01:21:57 +00004739
4740
Jim Ingham372787f2012-04-07 00:00:41 +00004741 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004742
4743 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4744 // returning control here.
4745 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4746 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4747 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4748 // do just what we want.
4749 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4750 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4751 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4752 old_state = m_public_state.GetValue();
4753 m_public_state.SetValueNoLock(eStateStopped);
4754
4755 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004756 StartPrivateStateThread(true);
4757 }
4758
4759 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004760
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004761 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004762
Sean Callanana46ec452012-07-11 21:31:24 +00004763 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004764
Jim Ingham77787032011-01-20 02:03:18 +00004765 {
Sean Callanana46ec452012-07-11 21:31:24 +00004766 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4767 // restored on exit to the function.
4768 //
4769 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4770 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004771
Sean Callanana46ec452012-07-11 21:31:24 +00004772 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004773
Jim Inghamf48169b2010-11-30 02:22:11 +00004774 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004775 {
4776 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004777 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004778 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004779 thread->GetIndexID(),
4780 thread->GetID(),
4781 s.GetData());
4782 }
4783
4784 bool got_event;
4785 lldb::EventSP event_sp;
4786 lldb::StateType stop_state = lldb::eStateInvalid;
4787
4788 TimeValue* timeout_ptr = NULL;
4789 TimeValue real_timeout;
4790
Jim Ingham0161b492013-02-09 01:29:05 +00004791 bool before_first_timeout = true; // This is set to false the first time that we have to halt the target.
Sean Callanana46ec452012-07-11 21:31:24 +00004792 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004793 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004794 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanana46ec452012-07-11 21:31:24 +00004795
Jim Ingham0161b492013-02-09 01:29:05 +00004796 // This is just for accounting:
4797 uint32_t num_resumes = 0;
4798
4799 TimeValue one_thread_timeout = TimeValue::Now();
4800 TimeValue final_timeout = one_thread_timeout;
4801
4802 if (run_others)
4803 {
4804 // If we are running all threads then we take half the time to run all threads, bounded by
4805 // .25 sec.
4806 if (timeout_usec == 0)
4807 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4808 else
4809 {
Greg Clayton03da4cc2013-04-19 21:31:16 +00004810 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham0161b492013-02-09 01:29:05 +00004811 if (computed_timeout > default_one_thread_timeout_usec)
4812 computed_timeout = default_one_thread_timeout_usec;
4813 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4814 }
4815 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4816 }
4817 else
4818 {
4819 if (timeout_usec != 0)
4820 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4821 }
4822
Jim Ingham8559a352012-11-26 23:52:18 +00004823 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4824 // So don't call return anywhere within it.
4825
Sean Callanana46ec452012-07-11 21:31:24 +00004826 while (1)
4827 {
4828 // We usually want to resume the process if we get to the top of the loop.
4829 // The only exception is if we get two running events with no intervening
4830 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00004831 if (log)
4832 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4833 do_resume,
4834 handle_running_event,
4835 before_first_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00004836
Jim Ingham184e9812013-01-15 02:47:48 +00004837 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00004838 {
4839 // Do the initial resume and wait for the running event before going further.
4840
Jim Ingham184e9812013-01-15 02:47:48 +00004841 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00004842 {
Jim Ingham0161b492013-02-09 01:29:05 +00004843 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00004844 Error resume_error = PrivateResume ();
4845 if (!resume_error.Success())
4846 {
Jim Ingham0161b492013-02-09 01:29:05 +00004847 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4848 num_resumes,
4849 resume_error.AsCString());
Jim Ingham184e9812013-01-15 02:47:48 +00004850 return_value = eExecutionSetupError;
4851 break;
4852 }
Sean Callanana46ec452012-07-11 21:31:24 +00004853 }
Sean Callanana46ec452012-07-11 21:31:24 +00004854
Jim Ingham0161b492013-02-09 01:29:05 +00004855 TimeValue resume_timeout = TimeValue::Now();
4856 resume_timeout.OffsetWithMicroSeconds(500000);
4857
4858 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00004859 if (!got_event)
4860 {
4861 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004862 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4863 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004864
Jim Ingham0161b492013-02-09 01:29:05 +00004865 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004866 return_value = eExecutionSetupError;
4867 break;
4868 }
4869
4870 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00004871
Sean Callanana46ec452012-07-11 21:31:24 +00004872 if (stop_state != eStateRunning)
4873 {
Jim Ingham0161b492013-02-09 01:29:05 +00004874 bool restarted = false;
4875
4876 if (stop_state == eStateStopped)
4877 {
4878 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4879 if (log)
4880 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4881 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4882 num_resumes,
4883 StateAsCString(stop_state),
4884 restarted,
4885 do_resume,
4886 handle_running_event);
4887 }
4888
4889 if (restarted)
4890 {
4891 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4892 // event here. But if I do, the best thing is to Halt and then get out of here.
4893 Halt();
4894 }
4895
Jim Ingham35e1bda2012-10-16 21:41:58 +00004896 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4897 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004898 return_value = eExecutionSetupError;
4899 break;
4900 }
4901
4902 if (log)
4903 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4904 // We need to call the function synchronously, so spin waiting for it to return.
4905 // If we get interrupted while executing, we're going to lose our context, and
4906 // won't be able to gather the result at this point.
4907 // We set the timeout AFTER the resume, since the resume takes some time and we
4908 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00004909 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004910 else
4911 {
Sean Callanana46ec452012-07-11 21:31:24 +00004912 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004913 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004914 }
Jim Ingham0161b492013-02-09 01:29:05 +00004915
4916 if (before_first_timeout)
4917 {
4918 if (run_others)
4919 timeout_ptr = &one_thread_timeout;
4920 else
4921 {
4922 if (timeout_usec == 0)
4923 timeout_ptr = NULL;
4924 else
4925 timeout_ptr = &final_timeout;
4926 }
4927 }
4928 else
4929 {
4930 if (timeout_usec == 0)
4931 timeout_ptr = NULL;
4932 else
4933 timeout_ptr = &final_timeout;
4934 }
4935
4936 do_resume = true;
4937 handle_running_event = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00004938
Sean Callanana46ec452012-07-11 21:31:24 +00004939 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00004940 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00004941
Jim Ingham0f16e732011-02-08 05:20:59 +00004942 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004943 {
Sean Callanana46ec452012-07-11 21:31:24 +00004944 if (timeout_ptr)
4945 {
Matt Kopec676a4872013-02-21 23:55:31 +00004946 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00004947 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
4948 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00004949 }
Jim Ingham20829ac2011-08-09 22:24:33 +00004950 else
Sean Callanana46ec452012-07-11 21:31:24 +00004951 {
4952 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4953 }
4954 }
4955
4956 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4957
4958 if (got_event)
4959 {
4960 if (event_sp.get())
4961 {
4962 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00004963 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004964 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004965 Halt();
Jim Inghamcfc09352012-07-27 23:57:19 +00004966 return_value = eExecutionInterrupted;
4967 errors.Printf ("Execution halted by user interrupt.");
4968 if (log)
4969 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00004970 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00004971 }
4972 else
4973 {
4974 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4975 if (log)
4976 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4977
4978 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00004979 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004980 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00004981 {
Jim Ingham0161b492013-02-09 01:29:05 +00004982 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00004983 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4984 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004985 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004986 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00004987 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00004988 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4989 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00004990 }
4991 else
4992 {
Jim Ingham0161b492013-02-09 01:29:05 +00004993 // If we were restarted, we just need to go back up to fetch another event.
4994 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00004995 {
4996 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004997 {
4998 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
4999 }
5000 keep_going = true;
5001 do_resume = false;
5002 handle_running_event = true;
5003
Jim Inghamcfc09352012-07-27 23:57:19 +00005004 }
5005 else
5006 {
Jim Ingham0161b492013-02-09 01:29:05 +00005007
5008 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5009 StopReason stop_reason = eStopReasonInvalid;
5010 if (stop_info_sp)
5011 stop_reason = stop_info_sp->GetStopReason();
5012
5013
5014 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5015 // it is OUR plan that is complete?
5016 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005017 {
5018 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005019 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5020 // Now mark this plan as private so it doesn't get reported as the stop reason
5021 // after this point.
5022 if (thread_plan_sp)
5023 thread_plan_sp->SetPrivate (orig_plan_private);
5024 return_value = eExecutionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005025 }
5026 else
5027 {
Jim Ingham0161b492013-02-09 01:29:05 +00005028 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005029 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005030 {
5031 if (log)
5032 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham184e9812013-01-15 02:47:48 +00005033 return_value = eExecutionHitBreakpoint;
Jim Ingham0161b492013-02-09 01:29:05 +00005034 }
Jim Ingham184e9812013-01-15 02:47:48 +00005035 else
Jim Ingham0161b492013-02-09 01:29:05 +00005036 {
5037 if (log)
5038 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham184e9812013-01-15 02:47:48 +00005039 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005040 }
Jim Ingham184e9812013-01-15 02:47:48 +00005041 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005042 }
Sean Callanana46ec452012-07-11 21:31:24 +00005043 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005044 }
5045 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005046
Jim Inghamcfc09352012-07-27 23:57:19 +00005047 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005048 // This shouldn't really happen, but sometimes we do get two running events without an
5049 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005050 do_resume = false;
5051 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005052 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005053 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005054
Jim Inghamcfc09352012-07-27 23:57:19 +00005055 default:
5056 if (log)
5057 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5058
5059 if (stop_state == eStateExited)
5060 event_to_broadcast_sp = event_sp;
5061
Sean Callananbf154da2012-08-08 17:35:10 +00005062 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00005063 return_value = eExecutionInterrupted;
5064 break;
5065 }
Sean Callanana46ec452012-07-11 21:31:24 +00005066 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005067
Sean Callanana46ec452012-07-11 21:31:24 +00005068 if (keep_going)
5069 continue;
5070 else
5071 break;
5072 }
5073 else
5074 {
5075 if (log)
5076 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5077 return_value = eExecutionInterrupted;
5078 break;
5079 }
5080 }
5081 else
5082 {
5083 // If we didn't get an event that means we've timed out...
5084 // We will interrupt the process here. Depending on what we were asked to do we will
5085 // either exit, or try with all threads running for the same timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005086
5087 if (log) {
Jim Ingham35e1bda2012-10-16 21:41:58 +00005088 if (run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00005089 {
Jim Ingham0161b492013-02-09 01:29:05 +00005090 uint64_t remaining_time = final_timeout - TimeValue::Now();
5091 if (before_first_timeout)
5092 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
5093 "running till for %" PRId64 " usec with all threads enabled.",
5094 remaining_time);
Sean Callanana46ec452012-07-11 21:31:24 +00005095 else
5096 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005097 "and timeout: %d timed out, abandoning execution.",
5098 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005099 }
5100 else
5101 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005102 "abandoning execution.",
5103 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005104 }
5105
Jim Ingham0161b492013-02-09 01:29:05 +00005106 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5107 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5108 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5109 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5110 // stopped event. That's what this while loop does.
5111
5112 bool back_to_top = true;
5113 uint32_t try_halt_again = 0;
5114 bool do_halt = true;
5115 const uint32_t num_retries = 5;
5116 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005117 {
Jim Ingham0161b492013-02-09 01:29:05 +00005118 Error halt_error;
5119 if (do_halt)
5120 {
5121 if (log)
5122 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5123 halt_error = Halt();
5124 }
5125 if (halt_error.Success())
5126 {
5127 if (log)
5128 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5129
5130 real_timeout = TimeValue::Now();
5131 real_timeout.OffsetWithMicroSeconds(500000);
5132
5133 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005134
Jim Ingham0161b492013-02-09 01:29:05 +00005135 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005136 {
Jim Ingham0161b492013-02-09 01:29:05 +00005137 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5138 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005139 {
Jim Ingham0161b492013-02-09 01:29:05 +00005140 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5141 if (stop_state == lldb::eStateStopped
5142 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5143 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005144 }
5145
Jim Ingham0161b492013-02-09 01:29:05 +00005146 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005147 {
Jim Ingham0161b492013-02-09 01:29:05 +00005148 // Between the time we initiated the Halt and the time we delivered it, the process could have
5149 // already finished its job. Check that here:
5150
5151 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5152 {
5153 if (log)
5154 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5155 "Exiting wait loop.");
5156 return_value = eExecutionCompleted;
5157 back_to_top = false;
5158 break;
5159 }
5160
5161 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5162 {
5163 if (log)
5164 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5165 "Exiting wait loop.");
5166 try_halt_again++;
5167 do_halt = false;
5168 continue;
5169 }
Sean Callanana46ec452012-07-11 21:31:24 +00005170
Jim Ingham0161b492013-02-09 01:29:05 +00005171 if (!run_others)
5172 {
5173 if (log)
5174 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5175 return_value = eExecutionInterrupted;
5176 back_to_top = false;
5177 break;
5178 }
5179
5180 if (before_first_timeout)
5181 {
5182 // Set all the other threads to run, and return to the top of the loop, which will continue;
5183 before_first_timeout = false;
5184 thread_plan_sp->SetStopOthers (false);
5185 if (log)
5186 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005187
Jim Ingham0161b492013-02-09 01:29:05 +00005188 back_to_top = true;
5189 break;
5190 }
5191 else
5192 {
5193 // Running all threads failed, so return Interrupted.
5194 if (log)
5195 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5196 return_value = eExecutionInterrupted;
5197 back_to_top = false;
5198 break;
5199 }
Sean Callanana46ec452012-07-11 21:31:24 +00005200 }
5201 }
5202 else
Jim Ingham0161b492013-02-09 01:29:05 +00005203 { if (log)
5204 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5205 "I'm getting out of here passing Interrupted.");
Sean Callanana46ec452012-07-11 21:31:24 +00005206 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005207 back_to_top = false;
5208 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005209 }
5210 }
Jim Ingham0161b492013-02-09 01:29:05 +00005211 else
5212 {
5213 try_halt_again++;
5214 continue;
5215 }
Sean Callanana46ec452012-07-11 21:31:24 +00005216 }
Jim Ingham0161b492013-02-09 01:29:05 +00005217
5218 if (!back_to_top || try_halt_again > num_retries)
5219 break;
5220 else
5221 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005222 }
Sean Callanana46ec452012-07-11 21:31:24 +00005223 } // END WAIT LOOP
5224
5225 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5226 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5227 {
5228 StopPrivateStateThread();
5229 Error error;
5230 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005231 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005232 {
5233 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5234 }
5235 m_public_state.SetValueNoLock(old_state);
5236
5237 }
5238
Jim Ingham184e9812013-01-15 02:47:48 +00005239 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5240 // could happen:
5241 // 1) The execution successfully completed
5242 // 2) We hit a breakpoint, and ignore_breakpoints was true
5243 // 3) We got some other error, and discard_on_error was true
5244 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
5245 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham8559a352012-11-26 23:52:18 +00005246
Jim Ingham184e9812013-01-15 02:47:48 +00005247 if (return_value == eExecutionCompleted
5248 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005249 {
5250 thread_plan_sp->RestoreThreadState();
5251 }
Sean Callanana46ec452012-07-11 21:31:24 +00005252
5253 // Now do some processing on the results of the run:
Jim Ingham184e9812013-01-15 02:47:48 +00005254 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005255 {
5256 if (log)
5257 {
5258 StreamString s;
5259 if (event_sp)
5260 event_sp->Dump (&s);
5261 else
5262 {
5263 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5264 }
5265
5266 StreamString ts;
5267
5268 const char *event_explanation = NULL;
5269
5270 do
5271 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005272 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005273 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005274 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005275 break;
5276 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005277 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005278 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005279 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005280 break;
5281 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005282 else
Sean Callanana46ec452012-07-11 21:31:24 +00005283 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005284 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5285
5286 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005287 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005288 event_explanation = "<no event data>";
5289 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005290 }
5291
Jim Inghamcfc09352012-07-27 23:57:19 +00005292 Process *process = event_data->GetProcessSP().get();
5293
5294 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005295 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005296 event_explanation = "<no process>";
5297 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005298 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005299
5300 ThreadList &thread_list = process->GetThreadList();
5301
5302 uint32_t num_threads = thread_list.GetSize();
5303 uint32_t thread_index;
5304
5305 ts.Printf("<%u threads> ", num_threads);
5306
5307 for (thread_index = 0;
5308 thread_index < num_threads;
5309 ++thread_index)
5310 {
5311 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5312
5313 if (!thread)
5314 {
5315 ts.Printf("<?> ");
5316 continue;
5317 }
5318
Daniel Malead01b2952012-11-29 21:49:15 +00005319 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005320 RegisterContext *register_context = thread->GetRegisterContext().get();
5321
5322 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005323 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005324 else
5325 ts.Printf("[ip unknown] ");
5326
5327 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5328 if (stop_info_sp)
5329 {
5330 const char *stop_desc = stop_info_sp->GetDescription();
5331 if (stop_desc)
5332 ts.PutCString (stop_desc);
5333 }
5334 ts.Printf(">");
5335 }
5336
5337 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005338 }
Sean Callanana46ec452012-07-11 21:31:24 +00005339 } while (0);
5340
Jim Inghamcfc09352012-07-27 23:57:19 +00005341 if (event_explanation)
5342 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005343 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005344 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5345 }
5346
Jim Ingham184e9812013-01-15 02:47:48 +00005347 if (should_unwind && thread_plan_sp)
Jim Inghamcfc09352012-07-27 23:57:19 +00005348 {
5349 if (log)
5350 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5351 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5352 thread_plan_sp->SetPrivate (orig_plan_private);
5353 }
5354 else
5355 {
5356 if (log)
5357 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00005358 }
5359 }
5360 else if (return_value == eExecutionSetupError)
5361 {
5362 if (log)
5363 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005364
Jim Ingham184e9812013-01-15 02:47:48 +00005365 if (unwind_on_error && thread_plan_sp)
Jim Ingham0f16e732011-02-08 05:20:59 +00005366 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005367 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005368 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005369 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005370 }
5371 else
5372 {
Sean Callanana46ec452012-07-11 21:31:24 +00005373 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005374 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005375 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005376 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5377 return_value = eExecutionCompleted;
5378 }
5379 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5380 {
5381 if (log)
5382 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5383 return_value = eExecutionDiscarded;
5384 }
5385 else
5386 {
5387 if (log)
5388 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham184e9812013-01-15 02:47:48 +00005389 if (unwind_on_error && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005390 {
5391 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005392 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005393 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5394 thread_plan_sp->SetPrivate (orig_plan_private);
5395 }
5396 }
5397 }
5398
5399 // Thread we ran the function in may have gone away because we ran the target
5400 // Check that it's still there, and if it is put it back in the context. Also restore the
5401 // frame in the context if it is still present.
5402 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5403 if (thread)
5404 {
5405 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5406 }
5407
5408 // Also restore the current process'es selected frame & thread, since this function calling may
5409 // be done behind the user's back.
5410
5411 if (selected_tid != LLDB_INVALID_THREAD_ID)
5412 {
5413 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5414 {
5415 // We were able to restore the selected thread, now restore the frame:
5416 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5417 if (old_frame_sp)
5418 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005419 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005420 }
5421 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005422
Sean Callanana46ec452012-07-11 21:31:24 +00005423 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00005424
Sean Callanana46ec452012-07-11 21:31:24 +00005425 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005426 {
Sean Callanana46ec452012-07-11 21:31:24 +00005427 if (log)
5428 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5429 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005430 }
5431
5432 return return_value;
5433}
5434
5435const char *
5436Process::ExecutionResultAsCString (ExecutionResults result)
5437{
5438 const char *result_name;
5439
5440 switch (result)
5441 {
Greg Claytone0d378b2011-03-24 21:19:54 +00005442 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005443 result_name = "eExecutionCompleted";
5444 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005445 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00005446 result_name = "eExecutionDiscarded";
5447 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005448 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005449 result_name = "eExecutionInterrupted";
5450 break;
Jim Ingham184e9812013-01-15 02:47:48 +00005451 case eExecutionHitBreakpoint:
5452 result_name = "eExecutionHitBreakpoint";
5453 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005454 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00005455 result_name = "eExecutionSetupError";
5456 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005457 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005458 result_name = "eExecutionTimedOut";
5459 break;
5460 }
5461 return result_name;
5462}
5463
Greg Clayton7260f622011-04-18 08:33:37 +00005464void
5465Process::GetStatus (Stream &strm)
5466{
5467 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005468 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005469 {
5470 if (state == eStateExited)
5471 {
5472 int exit_status = GetExitStatus();
5473 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005474 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005475 GetID(),
5476 exit_status,
5477 exit_status,
5478 exit_description ? exit_description : "");
5479 }
5480 else
5481 {
5482 if (state == eStateConnected)
5483 strm.Printf ("Connected to remote target.\n");
5484 else
Daniel Malead01b2952012-11-29 21:49:15 +00005485 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005486 }
5487 }
5488 else
5489 {
Daniel Malead01b2952012-11-29 21:49:15 +00005490 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005491 }
5492}
5493
5494size_t
5495Process::GetThreadStatus (Stream &strm,
5496 bool only_threads_with_stop_reason,
5497 uint32_t start_frame,
5498 uint32_t num_frames,
5499 uint32_t num_frames_with_source)
5500{
5501 size_t num_thread_infos_dumped = 0;
5502
Jim Ingham41f2b942012-09-10 20:50:15 +00005503 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005504 const size_t num_threads = GetThreadList().GetSize();
5505 for (uint32_t i = 0; i < num_threads; i++)
5506 {
5507 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5508 if (thread)
5509 {
5510 if (only_threads_with_stop_reason)
5511 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005512 StopInfoSP stop_info_sp = thread->GetStopInfo();
5513 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005514 continue;
5515 }
5516 thread->GetStatus (strm,
5517 start_frame,
5518 num_frames,
5519 num_frames_with_source);
5520 ++num_thread_infos_dumped;
5521 }
5522 }
5523 return num_thread_infos_dumped;
5524}
5525
Greg Claytona9f40ad2012-02-22 04:37:26 +00005526void
5527Process::AddInvalidMemoryRegion (const LoadRange &region)
5528{
5529 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5530}
5531
5532bool
5533Process::RemoveInvalidMemoryRange (const LoadRange &region)
5534{
5535 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5536}
5537
Jim Ingham372787f2012-04-07 00:00:41 +00005538void
5539Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5540{
5541 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5542}
5543
5544bool
5545Process::RunPreResumeActions ()
5546{
5547 bool result = true;
5548 while (!m_pre_resume_actions.empty())
5549 {
5550 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5551 m_pre_resume_actions.pop_back();
5552 bool this_result = action.callback (action.baton);
5553 if (result == true) result = this_result;
5554 }
5555 return result;
5556}
5557
5558void
5559Process::ClearPreResumeActions ()
5560{
5561 m_pre_resume_actions.clear();
5562}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005563
Greg Claytonfa559e52012-05-18 02:38:05 +00005564void
5565Process::Flush ()
5566{
5567 m_thread_list.Flush();
5568}
Greg Clayton90ba8112012-12-05 00:16:59 +00005569
5570void
5571Process::DidExec ()
5572{
5573 Target &target = GetTarget();
5574 target.CleanupProcess ();
5575 ModuleList unloaded_modules (target.GetImages());
5576 target.ModulesDidUnload (unloaded_modules);
5577 target.GetSectionLoadList().Clear();
5578 m_dynamic_checkers_ap.reset();
5579 m_abi_sp.reset();
5580 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005581 m_dyld_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005582 m_image_tokens.clear();
5583 m_allocated_memory_cache.Clear();
5584 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005585 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005586 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005587 DoDidExec();
5588 CompleteAttach ();
5589}
Sean Callananbb777042013-05-16 17:30:37 +00005590
5591Process::ReservationCache::ReservationCache (Process &process) : m_process(process)
5592{
5593 m_mod_id = process.GetModID();
5594}
5595
5596void
5597Process::ReservationCache::Reserve (lldb::addr_t addr, size_t size)
5598{
5599 CheckModID();
5600 m_reserved_cache[addr] = size;
5601}
5602
5603void
5604Process::ReservationCache::Unreserve (lldb::addr_t addr)
5605{
5606 CheckModID();
5607 ReservedMap::iterator iter = m_reserved_cache.find(addr);
5608
5609 if (iter != m_reserved_cache.end())
5610 {
5611 size_t size = iter->second;
5612 m_reserved_cache.erase(iter);
5613 m_free_cache[size].push_back(addr);
5614 }
5615}
5616
5617lldb::addr_t
5618Process::ReservationCache::Find (size_t size)
5619{
5620 CheckModID();
5621 lldb::addr_t ret = LLDB_INVALID_ADDRESS;
5622 FreeMap::iterator map_iter = m_free_cache.find(size);
5623 if (map_iter != m_free_cache.end())
5624 {
5625 if (!map_iter->second.empty())
5626 {
5627 ret = map_iter->second.back();
5628 map_iter->second.pop_back();
5629 m_reserved_cache[ret] = size;
5630 }
5631 }
5632
5633 return ret;
5634}
5635
5636void
5637Process::ReservationCache::CheckModID()
5638{
5639 if (m_mod_id != m_process.GetModID())
5640 {
5641 // wipe all our caches, they're invalid
5642 m_reserved_cache.clear();
5643 m_free_cache.clear();
5644 m_mod_id = m_process.GetModID();
5645 }
5646}