blob: f4733c38d768f064a505fc39f5145e274a98a654 [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"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000999 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000 m_public_state (eStateUnloaded),
1001 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001002 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1003 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001004 m_private_state_listener ("lldb.process.internal_state_listener"),
1005 m_private_state_control_wait(),
1006 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +00001007 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +00001008 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009 m_thread_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001010 m_thread_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001011 m_exit_status (-1),
1012 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001013 m_thread_mutex (Mutex::eMutexTypeRecursive),
1014 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015 m_thread_list (this),
1016 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001017 m_image_tokens (),
1018 m_listener (listener),
1019 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001020 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001021 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001022 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001023 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +00001024 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001025 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +00001026 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +00001027 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001028 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1029 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +00001030 m_memory_cache (*this),
1031 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +00001032 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +00001033 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +00001034 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +00001035 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +00001036 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001037 m_finalize_called(false),
Jim Ingham0161b492013-02-09 01:29:05 +00001038 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +00001039 m_destroy_in_process (false),
1040 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001041{
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001042 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +00001043
Greg Clayton5160ce52013-03-27 23:08:40 +00001044 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045 if (log)
1046 log->Printf ("%p Process::Process()", this);
1047
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001048 SetEventName (eBroadcastBitStateChanged, "state-changed");
1049 SetEventName (eBroadcastBitInterrupt, "interrupt");
1050 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1051 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001052 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001053
Greg Clayton35a4cc52012-10-29 20:52:08 +00001054 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1055 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1056 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1057
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058 listener.StartListeningForEvents (this,
1059 eBroadcastBitStateChanged |
1060 eBroadcastBitInterrupt |
1061 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001062 eBroadcastBitSTDERR |
1063 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001064
1065 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001066 eBroadcastBitStateChanged |
1067 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001068
1069 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1070 eBroadcastInternalStateControlStop |
1071 eBroadcastInternalStateControlPause |
1072 eBroadcastInternalStateControlResume);
1073}
1074
1075//----------------------------------------------------------------------
1076// Destructor
1077//----------------------------------------------------------------------
1078Process::~Process()
1079{
Greg Clayton5160ce52013-03-27 23:08:40 +00001080 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001081 if (log)
1082 log->Printf ("%p Process::~Process()", this);
1083 StopPrivateStateThread();
1084}
1085
Greg Clayton67cc0632012-08-22 17:17:09 +00001086const ProcessPropertiesSP &
1087Process::GetGlobalProperties()
1088{
1089 static ProcessPropertiesSP g_settings_sp;
1090 if (!g_settings_sp)
1091 g_settings_sp.reset (new ProcessProperties (true));
1092 return g_settings_sp;
1093}
1094
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001095void
1096Process::Finalize()
1097{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001098 switch (GetPrivateState())
1099 {
1100 case eStateConnected:
1101 case eStateAttaching:
1102 case eStateLaunching:
1103 case eStateStopped:
1104 case eStateRunning:
1105 case eStateStepping:
1106 case eStateCrashed:
1107 case eStateSuspended:
1108 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +00001109 {
1110 // FIXME: This will have to be a process setting:
1111 bool keep_stopped = false;
1112 Detach(keep_stopped);
1113 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00001114 else
1115 Destroy();
1116 break;
1117
1118 case eStateInvalid:
1119 case eStateUnloaded:
1120 case eStateDetached:
1121 case eStateExited:
1122 break;
1123 }
1124
Greg Clayton1ed54f52011-10-01 00:45:15 +00001125 // Clear our broadcaster before we proceed with destroying
1126 Broadcaster::Clear();
1127
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001128 // Do any cleanup needed prior to being destructed... Subclasses
1129 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001130
1131 // We need to destroy the loader before the derived Process class gets destroyed
1132 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001133 m_dynamic_checkers_ap.reset();
1134 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001135 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001136 m_dyld_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001137 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001138 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +00001139 std::vector<Notifications> empty_notifications;
1140 m_notifications.swap(empty_notifications);
1141 m_image_tokens.clear();
1142 m_memory_cache.Clear();
1143 m_allocated_memory_cache.Clear();
1144 m_language_runtimes.clear();
1145 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001146//#ifdef LLDB_CONFIGURATION_DEBUG
1147// StreamFile s(stdout, false);
1148// EventSP event_sp;
1149// while (m_private_state_listener.GetNextEvent(event_sp))
1150// {
1151// event_sp->Dump (&s);
1152// s.EOL();
1153// }
1154//#endif
1155 // We have to be very careful here as the m_private_state_listener might
1156 // contain events that have ProcessSP values in them which can keep this
1157 // process around forever. These events need to be cleared out.
1158 m_private_state_listener.Clear();
Greg Claytonaa49c832013-05-03 22:25:56 +00001159 m_public_run_lock.WriteTryLock(); // This will do nothing if already locked
Greg Clayton96249852013-04-18 16:57:27 +00001160 m_public_run_lock.WriteUnlock();
Greg Claytonaa49c832013-05-03 22:25:56 +00001161 m_private_run_lock.WriteTryLock(); // This will do nothing if already locked
Greg Clayton96249852013-04-18 16:57:27 +00001162 m_private_run_lock.WriteUnlock();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001163 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164}
1165
1166void
1167Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1168{
1169 m_notifications.push_back(callbacks);
1170 if (callbacks.initialize != NULL)
1171 callbacks.initialize (callbacks.baton, this);
1172}
1173
1174bool
1175Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1176{
1177 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1178 for (pos = m_notifications.begin(); pos != end; ++pos)
1179 {
1180 if (pos->baton == callbacks.baton &&
1181 pos->initialize == callbacks.initialize &&
1182 pos->process_state_changed == callbacks.process_state_changed)
1183 {
1184 m_notifications.erase(pos);
1185 return true;
1186 }
1187 }
1188 return false;
1189}
1190
1191void
1192Process::SynchronouslyNotifyStateChanged (StateType state)
1193{
1194 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1195 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1196 {
1197 if (notification_pos->process_state_changed)
1198 notification_pos->process_state_changed (notification_pos->baton, this, state);
1199 }
1200}
1201
1202// FIXME: We need to do some work on events before the general Listener sees them.
1203// For instance if we are continuing from a breakpoint, we need to ensure that we do
1204// the little "insert real insn, step & stop" trick. But we can't do that when the
1205// event is delivered by the broadcaster - since that is done on the thread that is
1206// waiting for new events, so if we needed more than one event for our handling, we would
1207// stall. So instead we do it when we fetch the event off of the queue.
1208//
1209
1210StateType
1211Process::GetNextEvent (EventSP &event_sp)
1212{
1213 StateType state = eStateInvalid;
1214
1215 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1216 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1217
1218 return state;
1219}
1220
1221
1222StateType
Greg Clayton85fb1b92012-09-11 02:33:37 +00001223Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001224{
Jim Ingham4b536182011-08-09 02:12:22 +00001225 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1226 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1227 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001228 if (event_sp_ptr)
1229 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001230 StateType state = GetState();
1231 // If we are exited or detached, we won't ever get back to any
1232 // other valid state...
1233 if (state == eStateDetached || state == eStateExited)
1234 return state;
1235
1236 while (state != eStateInvalid)
1237 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001238 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001239 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001240 if (event_sp_ptr && event_sp)
1241 *event_sp_ptr = event_sp;
1242
Jim Ingham4b536182011-08-09 02:12:22 +00001243 switch (state)
1244 {
1245 case eStateCrashed:
1246 case eStateDetached:
1247 case eStateExited:
1248 case eStateUnloaded:
1249 return state;
1250 case eStateStopped:
1251 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1252 continue;
1253 else
1254 return state;
1255 default:
1256 continue;
1257 }
1258 }
1259 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001260}
1261
1262
1263StateType
1264Process::WaitForState
1265(
1266 const TimeValue *timeout,
1267 const StateType *match_states, const uint32_t num_match_states
1268)
1269{
1270 EventSP event_sp;
1271 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001272 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001273 while (state != eStateInvalid)
1274 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001275 // If we are exited or detached, we won't ever get back to any
1276 // other valid state...
1277 if (state == eStateDetached || state == eStateExited)
1278 return state;
1279
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001280 state = WaitForStateChangedEvents (timeout, event_sp);
1281
1282 for (i=0; i<num_match_states; ++i)
1283 {
1284 if (match_states[i] == state)
1285 return state;
1286 }
1287 }
1288 return state;
1289}
1290
Jim Ingham30f9b212010-10-11 23:53:14 +00001291bool
1292Process::HijackProcessEvents (Listener *listener)
1293{
1294 if (listener != NULL)
1295 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001296 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001297 }
1298 else
1299 return false;
1300}
1301
1302void
1303Process::RestoreProcessEvents ()
1304{
1305 RestoreBroadcaster();
1306}
1307
Jim Ingham0f16e732011-02-08 05:20:59 +00001308bool
1309Process::HijackPrivateProcessEvents (Listener *listener)
1310{
1311 if (listener != NULL)
1312 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001313 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001314 }
1315 else
1316 return false;
1317}
1318
1319void
1320Process::RestorePrivateProcessEvents ()
1321{
1322 m_private_state_broadcaster.RestoreBroadcaster();
1323}
1324
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001325StateType
1326Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1327{
Greg Clayton5160ce52013-03-27 23:08:40 +00001328 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001329
1330 if (log)
1331 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1332
1333 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001334 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1335 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001336 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001337 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001338 {
1339 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1340 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1341 else if (log)
1342 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1343 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001344
1345 if (log)
1346 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1347 __FUNCTION__,
1348 timeout,
1349 StateAsCString(state));
1350 return state;
1351}
1352
1353Event *
1354Process::PeekAtStateChangedEvents ()
1355{
Greg Clayton5160ce52013-03-27 23:08:40 +00001356 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001357
1358 if (log)
1359 log->Printf ("Process::%s...", __FUNCTION__);
1360
1361 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001362 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1363 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364 if (log)
1365 {
1366 if (event_ptr)
1367 {
1368 log->Printf ("Process::%s (event_ptr) => %s",
1369 __FUNCTION__,
1370 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1371 }
1372 else
1373 {
1374 log->Printf ("Process::%s no events found",
1375 __FUNCTION__);
1376 }
1377 }
1378 return event_ptr;
1379}
1380
1381StateType
1382Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1383{
Greg Clayton5160ce52013-03-27 23:08:40 +00001384 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001385
1386 if (log)
1387 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1388
1389 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001390 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1391 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001392 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001393 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001394 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1395 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001396
1397 // This is a bit of a hack, but when we wait here we could very well return
1398 // to the command-line, and that could disable the log, which would render the
1399 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001401 {
1402 if (state == eStateInvalid)
1403 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1404 else
1405 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1406 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001407 return state;
1408}
1409
1410bool
1411Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1412{
Greg Clayton5160ce52013-03-27 23:08:40 +00001413 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001414
1415 if (log)
1416 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1417
1418 if (control_only)
1419 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1420 else
1421 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1422}
1423
1424bool
1425Process::IsRunning () const
1426{
1427 return StateIsRunningState (m_public_state.GetValue());
1428}
1429
1430int
1431Process::GetExitStatus ()
1432{
1433 if (m_public_state.GetValue() == eStateExited)
1434 return m_exit_status;
1435 return -1;
1436}
1437
Greg Clayton85851dd2010-12-04 00:10:17 +00001438
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001439const char *
1440Process::GetExitDescription ()
1441{
1442 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1443 return m_exit_string.c_str();
1444 return NULL;
1445}
1446
Greg Clayton6779606a2011-01-22 23:43:18 +00001447bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001448Process::SetExitStatus (int status, const char *cstr)
1449{
Greg Clayton5160ce52013-03-27 23:08:40 +00001450 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001451 if (log)
1452 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1453 status, status,
1454 cstr ? "\"" : "",
1455 cstr ? cstr : "NULL",
1456 cstr ? "\"" : "");
1457
Greg Clayton6779606a2011-01-22 23:43:18 +00001458 // We were already in the exited state
1459 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001460 {
Greg Clayton385d6032011-01-26 23:47:29 +00001461 if (log)
1462 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001463 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001464 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001465
1466 m_exit_status = status;
1467 if (cstr)
1468 m_exit_string = cstr;
1469 else
1470 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001471
Greg Clayton6779606a2011-01-22 23:43:18 +00001472 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001473
Greg Clayton6779606a2011-01-22 23:43:18 +00001474 SetPrivateState (eStateExited);
1475 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001476}
1477
1478// This static callback can be used to watch for local child processes on
1479// the current host. The the child process exits, the process will be
1480// found in the global target list (we want to be completely sure that the
1481// lldb_private::Process doesn't go away before we can deliver the signal.
1482bool
Greg Claytone4e45922011-11-16 05:37:56 +00001483Process::SetProcessExitStatus (void *callback_baton,
1484 lldb::pid_t pid,
1485 bool exited,
1486 int signo, // Zero for no signal
1487 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001488)
1489{
Greg Clayton5160ce52013-03-27 23:08:40 +00001490 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001491 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001492 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001493 callback_baton,
1494 pid,
1495 exited,
1496 signo,
1497 exit_status);
1498
1499 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001500 {
Greg Clayton66111032010-06-23 01:19:29 +00001501 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001502 if (target_sp)
1503 {
1504 ProcessSP process_sp (target_sp->GetProcessSP());
1505 if (process_sp)
1506 {
1507 const char *signal_cstr = NULL;
1508 if (signo)
1509 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1510
1511 process_sp->SetExitStatus (exit_status, signal_cstr);
1512 }
1513 }
1514 return true;
1515 }
1516 return false;
1517}
1518
1519
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001520void
1521Process::UpdateThreadListIfNeeded ()
1522{
1523 const uint32_t stop_id = GetStopID();
1524 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1525 {
Greg Clayton2637f822011-11-17 01:23:07 +00001526 const StateType state = GetPrivateState();
1527 if (StateIsStoppedState (state, true))
1528 {
1529 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001530 // m_thread_list does have its own mutex, but we need to
1531 // hold onto the mutex between the call to UpdateThreadList(...)
1532 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001533 ThreadList &old_thread_list = m_thread_list;
1534 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001535 ThreadList new_thread_list(this);
1536 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001537 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001538 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001539 {
Jim Ingham09437922013-03-01 20:04:25 +00001540 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1541 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1542 // shutting us down, causing a deadlock.
1543 if (!m_destroy_in_process)
1544 {
1545 OperatingSystem *os = GetOperatingSystem ();
1546 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001547 {
1548 // Clear any old backing threads where memory threads might have been
1549 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001550 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001551 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001552 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001553
1554 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001555 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1556 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1557 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 +00001558 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001559 else
1560 {
1561 // No OS plug-in, the new thread list is the same as the real thread list
1562 new_thread_list = real_thread_list;
1563 }
Jim Ingham09437922013-03-01 20:04:25 +00001564 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001565 m_thread_list.Update (new_thread_list);
1566 m_thread_list.SetStopID (stop_id);
Greg Clayton9fc13552012-04-10 00:18:59 +00001567 }
Greg Clayton2637f822011-11-17 01:23:07 +00001568 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001569 }
1570}
1571
Greg Claytona4d87472013-01-18 23:41:08 +00001572ThreadSP
1573Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1574{
1575 OperatingSystem *os = GetOperatingSystem ();
1576 if (os)
1577 return os->CreateThread(tid, context);
1578 return ThreadSP();
1579}
1580
1581
1582
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001583// This is obsoleted. Staged removal for Xcode.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001584uint32_t
1585Process::GetNextThreadIndexID ()
1586{
1587 return ++m_thread_index_id;
1588}
1589
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001590uint32_t
1591Process::GetNextThreadIndexID (uint64_t thread_id)
1592{
1593 return AssignIndexIDToThread(thread_id);
1594}
1595
1596bool
1597Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1598{
1599 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1600 if (iterator == m_thread_id_to_index_id_map.end())
1601 {
1602 return false;
1603 }
1604 else
1605 {
1606 return true;
1607 }
1608}
1609
1610uint32_t
1611Process::AssignIndexIDToThread(uint64_t thread_id)
1612{
1613 uint32_t result = 0;
1614 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1615 if (iterator == m_thread_id_to_index_id_map.end())
1616 {
1617 result = ++m_thread_index_id;
1618 m_thread_id_to_index_id_map[thread_id] = result;
1619 }
1620 else
1621 {
1622 result = iterator->second;
1623 }
1624
1625 return result;
1626}
1627
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001628StateType
1629Process::GetState()
1630{
1631 // If any other threads access this we will need a mutex for it
1632 return m_public_state.GetValue ();
1633}
1634
1635void
Jim Ingham221d51c2013-05-08 00:35:16 +00001636Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001637{
Greg Clayton5160ce52013-03-27 23:08:40 +00001638 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001639 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001640 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001641 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001642 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001643
1644 // On the transition from Run to Stopped, we unlock the writer end of the
1645 // run lock. The lock gets locked in Resume, which is the public API
1646 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001647 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1648 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001649 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001650 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001651 if (log)
1652 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Greg Clayton96249852013-04-18 16:57:27 +00001653 m_public_run_lock.WriteUnlock();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001654 }
1655 else
1656 {
1657 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1658 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001659 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001660 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001661 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001662 {
1663 if (log)
1664 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Greg Clayton96249852013-04-18 16:57:27 +00001665 m_public_run_lock.WriteUnlock();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001666 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001667 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001668 }
1669 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001670}
1671
Jim Ingham3b8285d2012-04-19 01:40:33 +00001672Error
1673Process::Resume ()
1674{
Greg Clayton5160ce52013-03-27 23:08:40 +00001675 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001676 if (log)
1677 log->Printf("Process::Resume -- locking run lock");
Greg Clayton96249852013-04-18 16:57:27 +00001678 if (!m_public_run_lock.WriteTryLock())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001679 {
1680 Error error("Resume request failed - process still running.");
1681 if (log)
1682 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1683 return error;
1684 }
1685 return PrivateResume();
1686}
1687
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001688StateType
1689Process::GetPrivateState ()
1690{
1691 return m_private_state.GetValue();
1692}
1693
1694void
1695Process::SetPrivateState (StateType new_state)
1696{
Greg Clayton5160ce52013-03-27 23:08:40 +00001697 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001698 bool state_changed = false;
1699
1700 if (log)
1701 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1702
Andrew Kaylor29d65742013-05-10 17:19:04 +00001703 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001704 Mutex::Locker locker(m_private_state.GetMutex());
1705
1706 const StateType old_state = m_private_state.GetValueNoLock ();
1707 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001708 // This code is left commented out in case we ever need to control
1709 // the private process state with another run lock. Right now it doesn't
1710 // seem like we need to do this, but if we ever do, we can uncomment and
1711 // use this code.
Greg Claytonaa49c832013-05-03 22:25:56 +00001712 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1713 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1714 if (old_state_is_stopped != new_state_is_stopped)
1715 {
1716 if (new_state_is_stopped)
1717 m_private_run_lock.WriteUnlock();
1718 else
1719 m_private_run_lock.WriteLock();
1720 }
Greg Claytonaa49c832013-05-03 22:25:56 +00001721
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001722 if (state_changed)
1723 {
1724 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001725 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001726 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001727 // Note, this currently assumes that all threads in the list
1728 // stop when the process stops. In the future we will want to
1729 // support a debugging model where some threads continue to run
1730 // while others are stopped. When that happens we will either need
1731 // a way for the thread list to identify which threads are stopping
1732 // or create a special thread list containing only threads which
1733 // actually stopped.
1734 //
1735 // The process plugin is responsible for managing the actual
1736 // behavior of the threads and should have stopped any threads
1737 // that are going to stop before we get here.
1738 m_thread_list.DidStop();
1739
Jim Ingham4b536182011-08-09 02:12:22 +00001740 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001741 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001742 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001743 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001744 }
1745 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001746 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1747 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1748 else
1749 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001750 }
1751 else
1752 {
1753 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001754 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001755 }
1756}
1757
Jim Ingham0faa43f2011-11-08 03:00:11 +00001758void
1759Process::SetRunningUserExpression (bool on)
1760{
1761 m_mod_id.SetRunningUserExpression (on);
1762}
1763
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001764addr_t
1765Process::GetImageInfoAddress()
1766{
1767 return LLDB_INVALID_ADDRESS;
1768}
1769
Greg Clayton8f343b02010-11-04 01:54:29 +00001770//----------------------------------------------------------------------
1771// LoadImage
1772//
1773// This function provides a default implementation that works for most
1774// unix variants. Any Process subclasses that need to do shared library
1775// loading differently should override LoadImage and UnloadImage and
1776// do what is needed.
1777//----------------------------------------------------------------------
1778uint32_t
1779Process::LoadImage (const FileSpec &image_spec, Error &error)
1780{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001781 char path[PATH_MAX];
1782 image_spec.GetPath(path, sizeof(path));
1783
Greg Clayton8f343b02010-11-04 01:54:29 +00001784 DynamicLoader *loader = GetDynamicLoader();
1785 if (loader)
1786 {
1787 error = loader->CanLoadImage();
1788 if (error.Fail())
1789 return LLDB_INVALID_IMAGE_TOKEN;
1790 }
1791
1792 if (error.Success())
1793 {
1794 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001795
1796 if (thread_sp)
1797 {
1798 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1799
1800 if (frame_sp)
1801 {
1802 ExecutionContext exe_ctx;
1803 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham184e9812013-01-15 02:47:48 +00001804 const bool unwind_on_error = true;
1805 const bool ignore_breakpoints = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001806 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001807 expr.Printf("dlopen (\"%s\", 2)", path);
1808 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001809 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001810 ClangUserExpression::Evaluate (exe_ctx,
1811 eExecutionPolicyAlways,
1812 lldb::eLanguageTypeUnknown,
1813 ClangUserExpression::eResultTypeAny,
1814 unwind_on_error,
Jim Ingham184e9812013-01-15 02:47:48 +00001815 ignore_breakpoints,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001816 expr.GetData(),
1817 prefix,
1818 result_valobj_sp,
1819 true,
1820 ClangUserExpression::kDefaultTimeout);
Johnny Chene92aa432011-09-09 00:01:43 +00001821 error = result_valobj_sp->GetError();
1822 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001823 {
1824 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001825 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001826 {
1827 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1828 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1829 {
1830 uint32_t image_token = m_image_tokens.size();
1831 m_image_tokens.push_back (image_ptr);
1832 return image_token;
1833 }
1834 }
1835 }
1836 }
1837 }
1838 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001839 if (!error.AsCString())
1840 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001841 return LLDB_INVALID_IMAGE_TOKEN;
1842}
1843
1844//----------------------------------------------------------------------
1845// UnloadImage
1846//
1847// This function provides a default implementation that works for most
1848// unix variants. Any Process subclasses that need to do shared library
1849// loading differently should override LoadImage and UnloadImage and
1850// do what is needed.
1851//----------------------------------------------------------------------
1852Error
1853Process::UnloadImage (uint32_t image_token)
1854{
1855 Error error;
1856 if (image_token < m_image_tokens.size())
1857 {
1858 const addr_t image_addr = m_image_tokens[image_token];
1859 if (image_addr == LLDB_INVALID_ADDRESS)
1860 {
1861 error.SetErrorString("image already unloaded");
1862 }
1863 else
1864 {
1865 DynamicLoader *loader = GetDynamicLoader();
1866 if (loader)
1867 error = loader->CanLoadImage();
1868
1869 if (error.Success())
1870 {
1871 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001872
1873 if (thread_sp)
1874 {
1875 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1876
1877 if (frame_sp)
1878 {
1879 ExecutionContext exe_ctx;
1880 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham184e9812013-01-15 02:47:48 +00001881 const bool unwind_on_error = true;
1882 const bool ignore_breakpoints = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001883 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001884 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001885 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001886 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001887 ClangUserExpression::Evaluate (exe_ctx,
1888 eExecutionPolicyAlways,
1889 lldb::eLanguageTypeUnknown,
1890 ClangUserExpression::eResultTypeAny,
1891 unwind_on_error,
Jim Ingham184e9812013-01-15 02:47:48 +00001892 ignore_breakpoints,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001893 expr.GetData(),
1894 prefix,
1895 result_valobj_sp,
1896 true,
1897 ClangUserExpression::kDefaultTimeout);
Greg Clayton8f343b02010-11-04 01:54:29 +00001898 if (result_valobj_sp->GetError().Success())
1899 {
1900 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001901 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001902 {
1903 if (scalar.UInt(1))
1904 {
1905 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1906 }
1907 else
1908 {
1909 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1910 }
1911 }
1912 }
1913 else
1914 {
1915 error = result_valobj_sp->GetError();
1916 }
1917 }
1918 }
1919 }
1920 }
1921 }
1922 else
1923 {
1924 error.SetErrorString("invalid image token");
1925 }
1926 return error;
1927}
1928
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001929const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001930Process::GetABI()
1931{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001932 if (!m_abi_sp)
1933 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1934 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001935}
1936
Jim Ingham22777012010-09-23 02:01:19 +00001937LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001938Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001939{
1940 LanguageRuntimeCollection::iterator pos;
1941 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001942 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001943 {
Jim Inghamab175242012-03-10 00:22:19 +00001944 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001945
Jim Inghamab175242012-03-10 00:22:19 +00001946 m_language_runtimes[language] = runtime_sp;
1947 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001948 }
1949 else
1950 return (*pos).second.get();
1951}
1952
1953CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001954Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001955{
Jim Inghamab175242012-03-10 00:22:19 +00001956 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001957 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1958 return static_cast<CPPLanguageRuntime *> (runtime);
1959 return NULL;
1960}
1961
1962ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001963Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001964{
Jim Inghamab175242012-03-10 00:22:19 +00001965 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001966 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1967 return static_cast<ObjCLanguageRuntime *> (runtime);
1968 return NULL;
1969}
1970
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001971bool
1972Process::IsPossibleDynamicValue (ValueObject& in_value)
1973{
1974 if (in_value.IsDynamic())
1975 return false;
1976 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1977
1978 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1979 {
1980 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1981 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1982 }
1983
1984 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1985 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1986 return true;
1987
1988 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1989 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1990}
1991
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001992BreakpointSiteList &
1993Process::GetBreakpointSiteList()
1994{
1995 return m_breakpoint_site_list;
1996}
1997
1998const BreakpointSiteList &
1999Process::GetBreakpointSiteList() const
2000{
2001 return m_breakpoint_site_list;
2002}
2003
2004
2005void
2006Process::DisableAllBreakpointSites ()
2007{
2008 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham43c555d2012-07-04 00:35:43 +00002009 size_t num_sites = m_breakpoint_site_list.GetSize();
2010 for (size_t i = 0; i < num_sites; i++)
2011 {
Jim Ingham299c0c12013-02-15 02:06:30 +00002012 DisableBreakpointSite (m_breakpoint_site_list.GetByIndex(i).get());
Jim Ingham43c555d2012-07-04 00:35:43 +00002013 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002014}
2015
2016Error
2017Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2018{
2019 Error error (DisableBreakpointSiteByID (break_id));
2020
2021 if (error.Success())
2022 m_breakpoint_site_list.Remove(break_id);
2023
2024 return error;
2025}
2026
2027Error
2028Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2029{
2030 Error error;
2031 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2032 if (bp_site_sp)
2033 {
2034 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002035 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002036 }
2037 else
2038 {
Daniel Malead01b2952012-11-29 21:49:15 +00002039 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002040 }
2041
2042 return error;
2043}
2044
2045Error
2046Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2047{
2048 Error error;
2049 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2050 if (bp_site_sp)
2051 {
2052 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002053 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002054 }
2055 else
2056 {
Daniel Malead01b2952012-11-29 21:49:15 +00002057 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002058 }
2059 return error;
2060}
2061
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002062lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002063Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002064{
Greg Clayton92bb12c2011-05-19 18:17:41 +00002065 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 if (load_addr != LLDB_INVALID_ADDRESS)
2067 {
2068 BreakpointSiteSP bp_site_sp;
2069
2070 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2071 // create a new breakpoint site and add it.
2072
2073 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2074
2075 if (bp_site_sp)
2076 {
2077 bp_site_sp->AddOwner (owner);
2078 owner->SetBreakpointSite (bp_site_sp);
2079 return bp_site_sp->GetID();
2080 }
2081 else
2082 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002083 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002084 if (bp_site_sp)
2085 {
Jim Ingham299c0c12013-02-15 02:06:30 +00002086 if (EnableBreakpointSite (bp_site_sp.get()).Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002087 {
2088 owner->SetBreakpointSite (bp_site_sp);
2089 return m_breakpoint_site_list.Add (bp_site_sp);
2090 }
2091 }
2092 }
2093 }
2094 // We failed to enable the breakpoint
2095 return LLDB_INVALID_BREAK_ID;
2096
2097}
2098
2099void
2100Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2101{
2102 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2103 if (num_owners == 0)
2104 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002105 // Don't try to disable the site if we don't have a live process anymore.
2106 if (IsAlive())
2107 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2109 }
2110}
2111
2112
2113size_t
2114Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2115{
2116 size_t bytes_removed = 0;
2117 addr_t intersect_addr;
2118 size_t intersect_size;
2119 size_t opcode_offset;
2120 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00002121 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00002122 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002123
Jim Ingham20c77192011-06-29 19:42:28 +00002124 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002125 {
Greg Clayton4d122c42011-09-17 08:33:22 +00002126 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002127 {
Greg Clayton4d122c42011-09-17 08:33:22 +00002128 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002129 {
Greg Clayton4d122c42011-09-17 08:33:22 +00002130 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002131 {
2132 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2133 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00002134 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002135 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00002136 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002137 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138 }
2139 }
2140 }
2141 return bytes_removed;
2142}
2143
2144
Greg Claytonded470d2011-03-19 01:12:21 +00002145
2146size_t
2147Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2148{
2149 PlatformSP platform_sp (m_target.GetPlatform());
2150 if (platform_sp)
2151 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2152 return 0;
2153}
2154
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002155Error
2156Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2157{
2158 Error error;
2159 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002160 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002161 const addr_t bp_addr = bp_site->GetLoadAddress();
2162 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002163 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002164 if (bp_site->IsEnabled())
2165 {
2166 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002167 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 +00002168 return error;
2169 }
2170
2171 if (bp_addr == LLDB_INVALID_ADDRESS)
2172 {
2173 error.SetErrorString("BreakpointSite contains an invalid load address.");
2174 return error;
2175 }
2176 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2177 // trap for the breakpoint site
2178 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2179
2180 if (bp_opcode_size == 0)
2181 {
Daniel Malead01b2952012-11-29 21:49:15 +00002182 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002183 }
2184 else
2185 {
2186 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2187
2188 if (bp_opcode_bytes == NULL)
2189 {
2190 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2191 return error;
2192 }
2193
2194 // Save the original opcode by reading it
2195 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2196 {
2197 // Write a software breakpoint in place of the original opcode
2198 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2199 {
2200 uint8_t verify_bp_opcode_bytes[64];
2201 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2202 {
2203 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2204 {
2205 bp_site->SetEnabled(true);
2206 bp_site->SetType (BreakpointSite::eSoftware);
2207 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002208 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002209 bp_site->GetID(),
2210 (uint64_t)bp_addr);
2211 }
2212 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002213 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002214 }
2215 else
2216 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2217 }
2218 else
2219 error.SetErrorString("Unable to write breakpoint trap to memory.");
2220 }
2221 else
2222 error.SetErrorString("Unable to read memory at breakpoint address.");
2223 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002224 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002225 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002226 bp_site->GetID(),
2227 (uint64_t)bp_addr,
2228 error.AsCString());
2229 return error;
2230}
2231
2232Error
2233Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2234{
2235 Error error;
2236 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002237 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002238 addr_t bp_addr = bp_site->GetLoadAddress();
2239 lldb::user_id_t breakID = bp_site->GetID();
2240 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002241 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002242
2243 if (bp_site->IsHardware())
2244 {
2245 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2246 }
2247 else if (bp_site->IsEnabled())
2248 {
2249 const size_t break_op_size = bp_site->GetByteSize();
2250 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2251 if (break_op_size > 0)
2252 {
2253 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002254 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002255 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002256 bool break_op_found = false;
2257
2258 // Read the breakpoint opcode
2259 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2260 {
2261 bool verify = false;
2262 // Make sure we have the a breakpoint opcode exists at this address
2263 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2264 {
2265 break_op_found = true;
2266 // We found a valid breakpoint opcode at this address, now restore
2267 // the saved opcode.
2268 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2269 {
2270 verify = true;
2271 }
2272 else
2273 error.SetErrorString("Memory write failed when restoring original opcode.");
2274 }
2275 else
2276 {
2277 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2278 // Set verify to true and so we can check if the original opcode has already been restored
2279 verify = true;
2280 }
2281
2282 if (verify)
2283 {
Greg Claytonc982c762010-07-09 20:39:50 +00002284 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002285 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002286 // Verify that our original opcode made it back to the inferior
2287 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2288 {
2289 // compare the memory we just read with the original opcode
2290 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2291 {
2292 // SUCCESS
2293 bp_site->SetEnabled(false);
2294 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002295 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 +00002296 return error;
2297 }
2298 else
2299 {
2300 if (break_op_found)
2301 error.SetErrorString("Failed to restore original opcode.");
2302 }
2303 }
2304 else
2305 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2306 }
2307 }
2308 else
2309 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2310 }
2311 }
2312 else
2313 {
2314 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002315 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 +00002316 return error;
2317 }
2318
2319 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002320 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321 bp_site->GetID(),
2322 (uint64_t)bp_addr,
2323 error.AsCString());
2324 return error;
2325
2326}
2327
Greg Clayton58be07b2011-01-07 06:08:19 +00002328// Uncomment to verify memory caching works after making changes to caching code
2329//#define VERIFY_MEMORY_READS
2330
Sean Callanan64c0cf22012-06-07 22:26:42 +00002331size_t
2332Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2333{
2334 if (!GetDisableMemoryCache())
2335 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002336#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002337 // Memory caching is enabled, with debug verification
2338
2339 if (buf && size)
2340 {
2341 // Uncomment the line below to make sure memory caching is working.
2342 // I ran this through the test suite and got no assertions, so I am
2343 // pretty confident this is working well. If any changes are made to
2344 // memory caching, uncomment the line below and test your changes!
2345
2346 // Verify all memory reads by using the cache first, then redundantly
2347 // reading the same memory from the inferior and comparing to make sure
2348 // everything is exactly the same.
2349 std::string verify_buf (size, '\0');
2350 assert (verify_buf.size() == size);
2351 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2352 Error verify_error;
2353 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2354 assert (cache_bytes_read == verify_bytes_read);
2355 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2356 assert (verify_error.Success() == error.Success());
2357 return cache_bytes_read;
2358 }
2359 return 0;
2360#else // !defined(VERIFY_MEMORY_READS)
2361 // Memory caching is enabled, without debug verification
2362
2363 return m_memory_cache.Read (addr, buf, size, error);
2364#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002365 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002366 else
2367 {
2368 // Memory caching is disabled
2369
2370 return ReadMemoryFromInferior (addr, buf, size, error);
2371 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002372}
Greg Clayton58be07b2011-01-07 06:08:19 +00002373
Greg Clayton4c82d422012-05-18 23:20:01 +00002374size_t
2375Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2376{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002377 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002378 out_str.clear();
2379 addr_t curr_addr = addr;
2380 while (1)
2381 {
2382 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2383 if (length == 0)
2384 break;
2385 out_str.append(buf, length);
2386 // If we got "length - 1" bytes, we didn't get the whole C string, we
2387 // need to read some more characters
2388 if (length == sizeof(buf) - 1)
2389 curr_addr += length;
2390 else
2391 break;
2392 }
2393 return out_str.size();
2394}
2395
Greg Clayton58be07b2011-01-07 06:08:19 +00002396
2397size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002398Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2399 size_t type_width)
2400{
2401 size_t total_bytes_read = 0;
2402 if (dst && max_bytes && type_width && max_bytes >= type_width)
2403 {
2404 // Ensure a null terminator independent of the number of bytes that is read.
2405 memset (dst, 0, max_bytes);
2406 size_t bytes_left = max_bytes - type_width;
2407
2408 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2409 assert(sizeof(terminator) >= type_width &&
2410 "Attempting to validate a string with more than 4 bytes per character!");
2411
2412 addr_t curr_addr = addr;
2413 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2414 char *curr_dst = dst;
2415
2416 error.Clear();
2417 while (bytes_left > 0 && error.Success())
2418 {
2419 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2420 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2421 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2422
2423 if (bytes_read == 0)
2424 break;
2425
2426 // Search for a null terminator of correct size and alignment in bytes_read
2427 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2428 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2429 if (::strncmp(&dst[i], terminator, type_width) == 0)
2430 {
2431 error.Clear();
2432 return i;
2433 }
2434
2435 total_bytes_read += bytes_read;
2436 curr_dst += bytes_read;
2437 curr_addr += bytes_read;
2438 bytes_left -= bytes_read;
2439 }
2440 }
2441 else
2442 {
2443 if (max_bytes)
2444 error.SetErrorString("invalid arguments");
2445 }
2446 return total_bytes_read;
2447}
2448
2449// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2450// null terminators.
2451size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002452Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002453{
2454 size_t total_cstr_len = 0;
2455 if (dst && dst_max_len)
2456 {
Greg Claytone91b7952011-12-15 03:14:23 +00002457 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002458 // NULL out everything just to be safe
2459 memset (dst, 0, dst_max_len);
2460 Error error;
2461 addr_t curr_addr = addr;
2462 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2463 size_t bytes_left = dst_max_len - 1;
2464 char *curr_dst = dst;
2465
2466 while (bytes_left > 0)
2467 {
2468 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2469 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2470 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2471
2472 if (bytes_read == 0)
2473 {
Greg Claytone91b7952011-12-15 03:14:23 +00002474 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002475 dst[total_cstr_len] = '\0';
2476 break;
2477 }
2478 const size_t len = strlen(curr_dst);
2479
2480 total_cstr_len += len;
2481
2482 if (len < bytes_to_read)
2483 break;
2484
2485 curr_dst += bytes_read;
2486 curr_addr += bytes_read;
2487 bytes_left -= bytes_read;
2488 }
2489 }
Greg Claytone91b7952011-12-15 03:14:23 +00002490 else
2491 {
2492 if (dst == NULL)
2493 result_error.SetErrorString("invalid arguments");
2494 else
2495 result_error.Clear();
2496 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002497 return total_cstr_len;
2498}
2499
2500size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002501Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2502{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002503 if (buf == NULL || size == 0)
2504 return 0;
2505
2506 size_t bytes_read = 0;
2507 uint8_t *bytes = (uint8_t *)buf;
2508
2509 while (bytes_read < size)
2510 {
2511 const size_t curr_size = size - bytes_read;
2512 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2513 bytes + bytes_read,
2514 curr_size,
2515 error);
2516 bytes_read += curr_bytes_read;
2517 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2518 break;
2519 }
2520
2521 // Replace any software breakpoint opcodes that fall into this range back
2522 // into "buf" before we return
2523 if (bytes_read > 0)
2524 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2525 return bytes_read;
2526}
2527
Greg Clayton58a4c462010-12-16 20:01:20 +00002528uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002529Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002530{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002531 Scalar scalar;
2532 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2533 return scalar.ULongLong(fail_value);
2534 return fail_value;
2535}
2536
2537addr_t
2538Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2539{
2540 Scalar scalar;
2541 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2542 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2543 return LLDB_INVALID_ADDRESS;
2544}
2545
2546
2547bool
2548Process::WritePointerToMemory (lldb::addr_t vm_addr,
2549 lldb::addr_t ptr_value,
2550 Error &error)
2551{
2552 Scalar scalar;
2553 const uint32_t addr_byte_size = GetAddressByteSize();
2554 if (addr_byte_size <= 4)
2555 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002556 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002557 scalar = ptr_value;
2558 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002559}
2560
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002561size_t
2562Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2563{
2564 size_t bytes_written = 0;
2565 const uint8_t *bytes = (const uint8_t *)buf;
2566
2567 while (bytes_written < size)
2568 {
2569 const size_t curr_size = size - bytes_written;
2570 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2571 bytes + bytes_written,
2572 curr_size,
2573 error);
2574 bytes_written += curr_bytes_written;
2575 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2576 break;
2577 }
2578 return bytes_written;
2579}
2580
2581size_t
2582Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2583{
Greg Clayton58be07b2011-01-07 06:08:19 +00002584#if defined (ENABLE_MEMORY_CACHING)
2585 m_memory_cache.Flush (addr, size);
2586#endif
2587
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002588 if (buf == NULL || size == 0)
2589 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002590
Jim Ingham4b536182011-08-09 02:12:22 +00002591 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002592
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002593 // We need to write any data that would go where any current software traps
2594 // (enabled software breakpoints) any software traps (breakpoints) that we
2595 // may have placed in our tasks memory.
2596
2597 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2598 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2599
2600 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002601 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002602
2603 BreakpointSiteList::collection::const_iterator pos;
2604 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002605 addr_t intersect_addr = 0;
2606 size_t intersect_size = 0;
2607 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002608 const uint8_t *ubuf = (const uint8_t *)buf;
2609
2610 for (pos = iter; pos != end; ++pos)
2611 {
2612 BreakpointSiteSP bp;
2613 bp = pos->second;
2614
2615 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2616 assert(addr <= intersect_addr && intersect_addr < addr + size);
2617 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2618 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2619
2620 // Check for bytes before this breakpoint
2621 const addr_t curr_addr = addr + bytes_written;
2622 if (intersect_addr > curr_addr)
2623 {
2624 // There are some bytes before this breakpoint that we need to
2625 // just write to memory
2626 size_t curr_size = intersect_addr - curr_addr;
2627 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2628 ubuf + bytes_written,
2629 curr_size,
2630 error);
2631 bytes_written += curr_bytes_written;
2632 if (curr_bytes_written != curr_size)
2633 {
2634 // We weren't able to write all of the requested bytes, we
2635 // are done looping and will return the number of bytes that
2636 // we have written so far.
2637 break;
2638 }
2639 }
2640
2641 // Now write any bytes that would cover up any software breakpoints
2642 // directly into the breakpoint opcode buffer
2643 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2644 bytes_written += intersect_size;
2645 }
2646
2647 // Write any remaining bytes after the last breakpoint if we have any left
2648 if (bytes_written < size)
2649 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2650 ubuf + bytes_written,
2651 size - bytes_written,
2652 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002653
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002654 return bytes_written;
2655}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002656
2657size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002658Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002659{
2660 if (byte_size == UINT32_MAX)
2661 byte_size = scalar.GetByteSize();
2662 if (byte_size > 0)
2663 {
2664 uint8_t buf[32];
2665 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2666 if (mem_size > 0)
2667 return WriteMemory(addr, buf, mem_size, error);
2668 else
2669 error.SetErrorString ("failed to get scalar as memory data");
2670 }
2671 else
2672 {
2673 error.SetErrorString ("invalid scalar value");
2674 }
2675 return 0;
2676}
2677
2678size_t
2679Process::ReadScalarIntegerFromMemory (addr_t addr,
2680 uint32_t byte_size,
2681 bool is_signed,
2682 Scalar &scalar,
2683 Error &error)
2684{
Greg Clayton7060f892013-05-01 23:41:30 +00002685 uint64_t uval = 0;
2686 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002687 {
Greg Clayton7060f892013-05-01 23:41:30 +00002688 error.SetErrorString ("byte size is zero");
2689 }
2690 else if (byte_size & (byte_size - 1))
2691 {
2692 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2693 }
2694 else if (byte_size <= sizeof(uval))
2695 {
2696 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002697 if (bytes_read == byte_size)
2698 {
2699 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002700 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002701 if (byte_size <= 4)
2702 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002703 else
Greg Clayton7060f892013-05-01 23:41:30 +00002704 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002705 if (is_signed)
2706 scalar.SignExtend(byte_size * 8);
2707 return bytes_read;
2708 }
2709 }
2710 else
2711 {
2712 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2713 }
2714 return 0;
2715}
2716
Greg Claytond495c532011-05-17 03:37:42 +00002717#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002718addr_t
2719Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2720{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002721 if (GetPrivateState() != eStateStopped)
2722 return LLDB_INVALID_ADDRESS;
2723
Greg Claytond495c532011-05-17 03:37:42 +00002724#if defined (USE_ALLOCATE_MEMORY_CACHE)
2725 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2726#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002727 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002728 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002729 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002730 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 +00002731 size,
Greg Claytond495c532011-05-17 03:37:42 +00002732 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002733 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002734 m_mod_id.GetStopID(),
2735 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002736 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002737#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738}
2739
Sean Callanan90539452011-09-20 23:01:51 +00002740bool
2741Process::CanJIT ()
2742{
Sean Callanana7b443a2012-02-14 22:50:38 +00002743 if (m_can_jit == eCanJITDontKnow)
2744 {
2745 Error err;
2746
2747 uint64_t allocated_memory = AllocateMemory(8,
2748 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2749 err);
2750
2751 if (err.Success())
2752 m_can_jit = eCanJITYes;
2753 else
2754 m_can_jit = eCanJITNo;
2755
2756 DeallocateMemory (allocated_memory);
2757 }
2758
Sean Callanan90539452011-09-20 23:01:51 +00002759 return m_can_jit == eCanJITYes;
2760}
2761
2762void
2763Process::SetCanJIT (bool can_jit)
2764{
2765 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2766}
2767
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002768Error
2769Process::DeallocateMemory (addr_t ptr)
2770{
Greg Claytond495c532011-05-17 03:37:42 +00002771 Error error;
2772#if defined (USE_ALLOCATE_MEMORY_CACHE)
2773 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2774 {
Daniel Malead01b2952012-11-29 21:49:15 +00002775 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002776 }
2777#else
2778 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002779
Greg Clayton5160ce52013-03-27 23:08:40 +00002780 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002781 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002782 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 +00002783 ptr,
2784 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002785 m_mod_id.GetStopID(),
2786 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002787#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002788 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002789}
2790
Han Ming Ongc811d382012-11-17 00:33:14 +00002791
Greg Claytonc9660542012-02-05 02:38:54 +00002792ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002793Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton39f7ee82013-02-01 21:38:35 +00002794 lldb::addr_t header_addr)
Greg Claytonc9660542012-02-05 02:38:54 +00002795{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002796 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002797 if (module_sp)
2798 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002799 Error error;
2800 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2801 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002802 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002803 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002804 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002805}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002806
2807Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002808Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002809{
2810 Error error;
2811 error.SetErrorString("watchpoints are not supported");
2812 return error;
2813}
2814
2815Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002816Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002817{
2818 Error error;
2819 error.SetErrorString("watchpoints are not supported");
2820 return error;
2821}
2822
2823StateType
2824Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2825{
2826 StateType state;
2827 // Now wait for the process to launch and return control to us, and then
2828 // call DidLaunch:
2829 while (1)
2830 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002831 event_sp.reset();
2832 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2833
Greg Clayton2637f822011-11-17 01:23:07 +00002834 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002835 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002836
2837 // If state is invalid, then we timed out
2838 if (state == eStateInvalid)
2839 break;
2840
2841 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002842 HandlePrivateEvent (event_sp);
2843 }
2844 return state;
2845}
2846
2847Error
Greg Clayton982c9762011-11-03 21:22:33 +00002848Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002849{
2850 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002851 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002852 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002853 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002854 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002855
Greg Claytonaa149cb2011-08-11 02:48:45 +00002856 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002857 if (exe_module)
2858 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002859 char local_exec_file_path[PATH_MAX];
2860 char platform_exec_file_path[PATH_MAX];
2861 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2862 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002863 if (exe_module->GetFileSpec().Exists())
2864 {
Greg Clayton71337622011-02-24 22:24:29 +00002865 if (PrivateStateThreadIsValid ())
2866 PausePrivateStateThread ();
2867
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002868 error = WillLaunch (exe_module);
2869 if (error.Success())
2870 {
Jim Ingham221d51c2013-05-08 00:35:16 +00002871 const bool restarted = false;
2872 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002873 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002874
Greg Clayton96249852013-04-18 16:57:27 +00002875 if (m_public_run_lock.WriteTryLock())
Greg Clayton69fd4be2012-09-04 20:29:05 +00002876 {
2877 // Now launch using these arguments.
2878 error = DoLaunch (exe_module, launch_info);
2879 }
2880 else
2881 {
2882 // This shouldn't happen
2883 error.SetErrorString("failed to acquire process run lock");
2884 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002885
2886 if (error.Fail())
2887 {
2888 if (GetID() != LLDB_INVALID_PROCESS_ID)
2889 {
2890 SetID (LLDB_INVALID_PROCESS_ID);
2891 const char *error_string = error.AsCString();
2892 if (error_string == NULL)
2893 error_string = "launch failed";
2894 SetExitStatus (-1, error_string);
2895 }
2896 }
2897 else
2898 {
2899 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002900 TimeValue timeout_time;
2901 timeout_time = TimeValue::Now();
2902 timeout_time.OffsetWithSeconds(10);
2903 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002904
Greg Clayton1a38ea72011-06-22 01:42:17 +00002905 if (state == eStateInvalid || event_sp.get() == NULL)
2906 {
2907 // We were able to launch the process, but we failed to
2908 // catch the initial stop.
2909 SetExitStatus (0, "failed to catch stop after launch");
2910 Destroy();
2911 }
2912 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002913 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002914
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002915 DidLaunch ();
2916
Greg Claytonc859e2d2012-02-13 23:10:39 +00002917 DynamicLoader *dyld = GetDynamicLoader ();
2918 if (dyld)
2919 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002920
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002921 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002922 // This delays passing the stopped event to listeners till DidLaunch gets
2923 // a chance to complete...
2924 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002925
2926 if (PrivateStateThreadIsValid ())
2927 ResumePrivateStateThread ();
2928 else
2929 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002930 }
2931 else if (state == eStateExited)
2932 {
2933 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2934 // not likely to work, and return an invalid pid.
2935 HandlePrivateEvent (event_sp);
2936 }
2937 }
2938 }
2939 }
2940 else
2941 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002942 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002943 }
2944 }
2945 return error;
2946}
2947
Greg Claytonc3776bf2012-02-09 06:16:32 +00002948
2949Error
2950Process::LoadCore ()
2951{
2952 Error error = DoLoadCore();
2953 if (error.Success())
2954 {
2955 if (PrivateStateThreadIsValid ())
2956 ResumePrivateStateThread ();
2957 else
2958 StartPrivateStateThread ();
2959
Greg Claytonc859e2d2012-02-13 23:10:39 +00002960 DynamicLoader *dyld = GetDynamicLoader ();
2961 if (dyld)
2962 dyld->DidAttach();
2963
2964 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002965 // We successfully loaded a core file, now pretend we stopped so we can
2966 // show all of the threads in the core file and explore the crashed
2967 // state.
2968 SetPrivateState (eStateStopped);
2969
2970 }
2971 return error;
2972}
2973
Greg Claytonc859e2d2012-02-13 23:10:39 +00002974DynamicLoader *
2975Process::GetDynamicLoader ()
2976{
2977 if (m_dyld_ap.get() == NULL)
2978 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2979 return m_dyld_ap.get();
2980}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002981
2982
Jim Inghambb3a2832011-01-29 01:49:25 +00002983Process::NextEventAction::EventActionResult
2984Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002985{
Jim Inghambb3a2832011-01-29 01:49:25 +00002986 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2987 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002988 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002989 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002990 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002991 return eEventActionRetry;
2992
2993 case eStateStopped:
2994 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002995 {
2996 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002997 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002998 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00002999 // We don't want these events to be reported, so go set the ShouldReportStop here:
3000 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3001
Greg Claytonc9ed4782011-11-12 02:10:56 +00003002 if (m_exec_count > 0)
3003 {
3004 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00003005 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003006 return eEventActionRetry;
3007 }
3008 else
3009 {
3010 m_process->CompleteAttach ();
3011 return eEventActionSuccess;
3012 }
3013 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003014 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003015
Greg Clayton513c26c2011-01-29 07:10:55 +00003016 default:
3017 case eStateExited:
3018 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003019 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003020 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003021
3022 m_exit_string.assign ("No valid Process");
3023 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003024}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003025
Jim Inghambb3a2832011-01-29 01:49:25 +00003026Process::NextEventAction::EventActionResult
3027Process::AttachCompletionHandler::HandleBeingInterrupted()
3028{
3029 return eEventActionSuccess;
3030}
3031
3032const char *
3033Process::AttachCompletionHandler::GetExitString ()
3034{
3035 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036}
3037
3038Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003039Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003040{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003041 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003042 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003043 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003044 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003045
Greg Clayton144f3a92011-11-15 03:53:30 +00003046 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003047 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003048 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003049 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003050 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003051
Greg Clayton144f3a92011-11-15 03:53:30 +00003052 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003053 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003054 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3055
3056 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003057 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003058 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3059 if (error.Success())
3060 {
Greg Clayton96249852013-04-18 16:57:27 +00003061 if (m_public_run_lock.WriteTryLock())
Greg Clayton926cce72012-10-12 16:10:12 +00003062 {
3063 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003064 const bool restarted = false;
3065 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003066 // Now attach using these arguments.
3067 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
3068 }
3069 else
3070 {
3071 // This shouldn't happen
3072 error.SetErrorString("failed to acquire process run lock");
3073 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003074
Greg Clayton144f3a92011-11-15 03:53:30 +00003075 if (error.Fail())
3076 {
3077 if (GetID() != LLDB_INVALID_PROCESS_ID)
3078 {
3079 SetID (LLDB_INVALID_PROCESS_ID);
3080 if (error.AsCString() == NULL)
3081 error.SetErrorString("attach failed");
3082
3083 SetExitStatus(-1, error.AsCString());
3084 }
3085 }
3086 else
3087 {
3088 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3089 StartPrivateStateThread();
3090 }
3091 return error;
3092 }
Greg Claytone996fd32011-03-08 22:40:15 +00003093 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003094 else
Greg Claytone996fd32011-03-08 22:40:15 +00003095 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003096 ProcessInstanceInfoList process_infos;
3097 PlatformSP platform_sp (m_target.GetPlatform ());
3098
3099 if (platform_sp)
3100 {
3101 ProcessInstanceInfoMatch match_info;
3102 match_info.GetProcessInfo() = attach_info;
3103 match_info.SetNameMatchType (eNameMatchEquals);
3104 platform_sp->FindProcesses (match_info, process_infos);
3105 const uint32_t num_matches = process_infos.GetSize();
3106 if (num_matches == 1)
3107 {
3108 attach_pid = process_infos.GetProcessIDAtIndex(0);
3109 // Fall through and attach using the above process ID
3110 }
3111 else
3112 {
3113 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3114 if (num_matches > 1)
3115 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3116 else
3117 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3118 }
3119 }
3120 else
3121 {
3122 error.SetErrorString ("invalid platform, can't find processes by name");
3123 return error;
3124 }
Greg Claytone996fd32011-03-08 22:40:15 +00003125 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003126 }
3127 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003128 {
3129 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003130 }
3131 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003132
3133 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003134 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003135 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003136 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003138
Greg Clayton96249852013-04-18 16:57:27 +00003139 if (m_public_run_lock.WriteTryLock())
Greg Clayton926cce72012-10-12 16:10:12 +00003140 {
3141 // Now attach using these arguments.
3142 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003143 const bool restarted = false;
3144 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003145 error = DoAttachToProcessWithID (attach_pid, attach_info);
3146 }
3147 else
3148 {
3149 // This shouldn't happen
3150 error.SetErrorString("failed to acquire process run lock");
3151 }
3152
Greg Clayton144f3a92011-11-15 03:53:30 +00003153 if (error.Success())
3154 {
3155
3156 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3157 StartPrivateStateThread();
3158 }
3159 else
Greg Claytone996fd32011-03-08 22:40:15 +00003160 {
3161 if (GetID() != LLDB_INVALID_PROCESS_ID)
3162 {
3163 SetID (LLDB_INVALID_PROCESS_ID);
3164 const char *error_string = error.AsCString();
3165 if (error_string == NULL)
3166 error_string = "attach failed";
3167
3168 SetExitStatus(-1, error_string);
3169 }
3170 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003171 }
3172 }
3173 return error;
3174}
3175
Greg Clayton93d3c8332011-02-16 04:46:07 +00003176void
3177Process::CompleteAttach ()
3178{
3179 // Let the process subclass figure out at much as it can about the process
3180 // before we go looking for a dynamic loader plug-in.
3181 DidAttach();
3182
Jim Ingham4299fdb2011-09-15 01:10:17 +00003183 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3184 // the same as the one we've already set, switch architectures.
3185 PlatformSP platform_sp (m_target.GetPlatform ());
3186 assert (platform_sp.get());
3187 if (platform_sp)
3188 {
Greg Clayton70512312012-05-08 01:45:38 +00003189 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003190 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003191 {
3192 ArchSpec platform_arch;
3193 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3194 if (platform_sp)
3195 {
3196 m_target.SetPlatform (platform_sp);
3197 m_target.SetArchitecture(platform_arch);
3198 }
3199 }
3200 else
3201 {
3202 ProcessInstanceInfo process_info;
3203 platform_sp->GetProcessInfo (GetID(), process_info);
3204 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003205 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003206 m_target.SetArchitecture (process_arch);
3207 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003208 }
3209
3210 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003211 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003212 DynamicLoader *dyld = GetDynamicLoader ();
3213 if (dyld)
3214 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003215
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003216 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003217 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003218 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003219 Mutex::Locker modules_locker(target_modules.GetMutex());
3220 size_t num_modules = target_modules.GetSize();
3221 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003222
Greg Clayton93d3c8332011-02-16 04:46:07 +00003223 for (int i = 0; i < num_modules; i++)
3224 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003225 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003226 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003227 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003228 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003229 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003230 break;
3231 }
3232 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003233 if (new_executable_module_sp)
3234 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003235}
3236
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003237Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003238Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003239{
Greg Claytonb766a732011-02-04 01:58:07 +00003240 m_abi_sp.reset();
3241 m_process_input_reader.reset();
3242
3243 // Find the process and its architecture. Make sure it matches the architecture
3244 // of the current Target, and if not adjust it.
3245
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003246 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003247 if (error.Success())
3248 {
Greg Clayton71337622011-02-24 22:24:29 +00003249 if (GetID() != LLDB_INVALID_PROCESS_ID)
3250 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003251 EventSP event_sp;
3252 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3253
3254 if (state == eStateStopped || state == eStateCrashed)
3255 {
3256 // If we attached and actually have a process on the other end, then
3257 // this ended up being the equivalent of an attach.
3258 CompleteAttach ();
3259
3260 // This delays passing the stopped event to listeners till
3261 // CompleteAttach gets a chance to complete...
3262 HandlePrivateEvent (event_sp);
3263
3264 }
Greg Clayton71337622011-02-24 22:24:29 +00003265 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003266
3267 if (PrivateStateThreadIsValid ())
3268 ResumePrivateStateThread ();
3269 else
3270 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003271 }
3272 return error;
3273}
3274
3275
3276Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003277Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003278{
Greg Clayton5160ce52013-03-27 23:08:40 +00003279 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003280 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003281 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003282 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003283 StateAsCString(m_public_state.GetValue()),
3284 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003285
3286 Error error (WillResume());
3287 // Tell the process it is about to resume before the thread list
3288 if (error.Success())
3289 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003290 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003291 // can let all of our threads know that they are about to be
3292 // resumed. Threads will each be called with
3293 // Thread::WillResume(StateType) where StateType contains the state
3294 // that they are supposed to have when the process is resumed
3295 // (suspended/running/stepping). Threads should also check
3296 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003297 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003298 if (m_thread_list.WillResume())
3299 {
Jim Ingham372787f2012-04-07 00:00:41 +00003300 // Last thing, do the PreResumeActions.
3301 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003302 {
Jim Ingham0161b492013-02-09 01:29:05 +00003303 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003304 }
3305 else
3306 {
3307 m_mod_id.BumpResumeID();
3308 error = DoResume();
3309 if (error.Success())
3310 {
3311 DidResume();
3312 m_thread_list.DidResume();
3313 if (log)
3314 log->Printf ("Process thinks the process has resumed.");
3315 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003316 }
3317 }
3318 else
3319 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003320 // Somebody wanted to run without running. So generate a continue & a stopped event,
3321 // and let the world handle them.
3322 if (log)
3323 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3324
3325 SetPrivateState(eStateRunning);
3326 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003327 }
3328 }
Jim Ingham444586b2011-01-24 06:34:17 +00003329 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003330 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003331 return error;
3332}
3333
3334Error
3335Process::Halt ()
3336{
Jim Inghamaacc3182012-06-06 00:29:30 +00003337 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3338 // we could just straightaway get another event. It just narrows the window...
3339 m_currently_handling_event.WaitForValueEqualTo(false);
3340
3341
Jim Inghambb3a2832011-01-29 01:49:25 +00003342 // Pause our private state thread so we can ensure no one else eats
3343 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003344 Listener halt_listener ("lldb.process.halt_listener");
3345 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003346
Jim Inghambb3a2832011-01-29 01:49:25 +00003347 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003348 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003349
Greg Clayton513c26c2011-01-29 07:10:55 +00003350 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003351 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003352
Greg Clayton513c26c2011-01-29 07:10:55 +00003353 bool caused_stop = false;
3354
3355 // Ask the process subclass to actually halt our process
3356 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003357 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003358 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003359 if (m_public_state.GetValue() == eStateAttaching)
3360 {
3361 SetExitStatus(SIGKILL, "Cancelled async attach.");
3362 Destroy ();
3363 }
3364 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003365 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003366 // If "caused_stop" is true, then DoHalt stopped the process. If
3367 // "caused_stop" is false, the process was already stopped.
3368 // If the DoHalt caused the process to stop, then we want to catch
3369 // this event and set the interrupted bool to true before we pass
3370 // this along so clients know that the process was interrupted by
3371 // a halt command.
3372 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003373 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003374 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003375 TimeValue timeout_time;
3376 timeout_time = TimeValue::Now();
3377 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003378 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3379 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003380
Jim Ingham0f16e732011-02-08 05:20:59 +00003381 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003382 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003383 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003384 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003385 }
3386 else
3387 {
Greg Clayton2637f822011-11-17 01:23:07 +00003388 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003389 {
3390 // We caused the process to interrupt itself, so mark this
3391 // as such in the stop event so clients can tell an interrupted
3392 // process from a natural stop
3393 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3394 }
3395 else
3396 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003397 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003398 if (log)
3399 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3400 error.SetErrorString ("Did not get stopped event after halt.");
3401 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003402 }
3403 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003404 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003405 }
3406 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003407 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003408 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003409 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003410
3411 // Post any event we might have consumed. If all goes well, we will have
3412 // stopped the process, intercepted the event and set the interrupted
3413 // bool in the event. Post it to the private event queue and that will end up
3414 // correctly setting the state.
3415 if (event_sp)
3416 m_private_state_broadcaster.BroadcastEvent(event_sp);
3417
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003418 return error;
3419}
3420
3421Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003422Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3423{
3424 Error error;
3425 if (m_public_state.GetValue() == eStateRunning)
3426 {
3427 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3428 if (log)
3429 log->Printf("Process::Destroy() About to halt.");
3430 error = Halt();
3431 if (error.Success())
3432 {
3433 // Consume the halt event.
3434 TimeValue timeout (TimeValue::Now());
3435 timeout.OffsetWithSeconds(1);
3436 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3437
3438 // If the process exited while we were waiting for it to stop, put the exited event into
3439 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3440 // they don't have a process anymore...
3441
3442 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3443 {
3444 if (log)
3445 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3446 return error;
3447 }
3448 else
3449 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3450
3451 if (state != eStateStopped)
3452 {
3453 if (log)
3454 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3455 // If we really couldn't stop the process then we should just error out here, but if the
3456 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3457 StateType private_state = m_private_state.GetValue();
3458 if (private_state != eStateStopped)
3459 {
3460 return error;
3461 }
3462 }
3463 }
3464 else
3465 {
3466 if (log)
3467 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3468 }
3469 }
3470 return error;
3471}
3472
3473Error
Jim Inghamacff8952013-05-02 00:27:30 +00003474Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003475{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003476 EventSP exit_event_sp;
3477 Error error;
3478 m_destroy_in_process = true;
3479
3480 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003481
3482 if (error.Success())
3483 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003484 if (DetachRequiresHalt())
3485 {
3486 error = HaltForDestroyOrDetach (exit_event_sp);
3487 if (!error.Success())
3488 {
3489 m_destroy_in_process = false;
3490 return error;
3491 }
3492 else if (exit_event_sp)
3493 {
3494 // We shouldn't need to do anything else here. There's no process left to detach from...
3495 StopPrivateStateThread();
3496 m_destroy_in_process = false;
3497 return error;
3498 }
3499 }
3500
Jim Inghamacff8952013-05-02 00:27:30 +00003501 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003502 if (error.Success())
3503 {
3504 DidDetach();
3505 StopPrivateStateThread();
3506 }
Jim Inghamacff8952013-05-02 00:27:30 +00003507 else
3508 {
3509 return error;
3510 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003511 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003512 m_destroy_in_process = false;
3513
3514 // If we exited when we were waiting for a process to stop, then
3515 // forward the event here so we don't lose the event
3516 if (exit_event_sp)
3517 {
3518 // Directly broadcast our exited event because we shut down our
3519 // private state thread above
3520 BroadcastEvent(exit_event_sp);
3521 }
3522
3523 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3524 // the last events through the event system, in which case we might strand the write lock. Unlock
3525 // it here so when we do to tear down the process we don't get an error destroying the lock.
3526
Greg Clayton96249852013-04-18 16:57:27 +00003527 m_public_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003528 return error;
3529}
3530
3531Error
3532Process::Destroy ()
3533{
Jim Ingham09437922013-03-01 20:04:25 +00003534
3535 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3536 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3537 // failed and the process stays around for some reason it won't be in a confused state.
3538
3539 m_destroy_in_process = true;
3540
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003541 Error error (WillDestroy());
3542 if (error.Success())
3543 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003544 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003545 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003546 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003547 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003548 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003549
Jim Inghamaacc3182012-06-06 00:29:30 +00003550 if (m_public_state.GetValue() != eStateRunning)
3551 {
3552 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3553 // kill it, we don't want it hitting a breakpoint...
3554 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3555 // we're not going to have much luck doing this now.
3556 m_thread_list.DiscardThreadPlans();
3557 DisableAllBreakpointSites();
3558 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003559
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003560 error = DoDestroy();
3561 if (error.Success())
3562 {
3563 DidDestroy();
3564 StopPrivateStateThread();
3565 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003566 m_stdio_communication.StopReadThread();
3567 m_stdio_communication.Disconnect();
3568 if (m_process_input_reader && m_process_input_reader->IsActive())
3569 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3570 if (m_process_input_reader)
3571 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003572
3573 // If we exited when we were waiting for a process to stop, then
3574 // forward the event here so we don't lose the event
3575 if (exit_event_sp)
3576 {
3577 // Directly broadcast our exited event because we shut down our
3578 // private state thread above
3579 BroadcastEvent(exit_event_sp);
3580 }
3581
Jim Inghamb1e2e842012-04-12 18:49:31 +00003582 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3583 // the last events through the event system, in which case we might strand the write lock. Unlock
3584 // 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 +00003585 m_public_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003586 }
Jim Ingham09437922013-03-01 20:04:25 +00003587
3588 m_destroy_in_process = false;
3589
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003590 return error;
3591}
3592
3593Error
3594Process::Signal (int signal)
3595{
3596 Error error (WillSignal());
3597 if (error.Success())
3598 {
3599 error = DoSignal(signal);
3600 if (error.Success())
3601 DidSignal();
3602 }
3603 return error;
3604}
3605
Greg Clayton514487e2011-02-15 21:59:32 +00003606lldb::ByteOrder
3607Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003608{
Greg Clayton514487e2011-02-15 21:59:32 +00003609 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003610}
3611
3612uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003613Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003614{
Greg Clayton514487e2011-02-15 21:59:32 +00003615 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003616}
3617
Greg Clayton514487e2011-02-15 21:59:32 +00003618
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003619bool
3620Process::ShouldBroadcastEvent (Event *event_ptr)
3621{
3622 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3623 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003624 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003625
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626 switch (state)
3627 {
Greg Claytonb766a732011-02-04 01:58:07 +00003628 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003629 case eStateAttaching:
3630 case eStateLaunching:
3631 case eStateDetached:
3632 case eStateExited:
3633 case eStateUnloaded:
3634 // These events indicate changes in the state of the debugging session, always report them.
3635 return_value = true;
3636 break;
3637 case eStateInvalid:
3638 // We stopped for no apparent reason, don't report it.
3639 return_value = false;
3640 break;
3641 case eStateRunning:
3642 case eStateStepping:
3643 // If we've started the target running, we handle the cases where we
3644 // are already running and where there is a transition from stopped to
3645 // running differently.
3646 // running -> running: Automatically suppress extra running events
3647 // stopped -> running: Report except when there is one or more no votes
3648 // and no yes votes.
3649 SynchronouslyNotifyStateChanged (state);
Jim Ingham0161b492013-02-09 01:29:05 +00003650 switch (m_last_broadcast_state)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003651 {
3652 case eStateRunning:
3653 case eStateStepping:
3654 // We always suppress multiple runnings with no PUBLIC stop in between.
3655 return_value = false;
3656 break;
3657 default:
3658 // TODO: make this work correctly. For now always report
3659 // run if we aren't running so we don't miss any runnning
3660 // events. If I run the lldb/test/thread/a.out file and
3661 // break at main.cpp:58, run and hit the breakpoints on
3662 // multiple threads, then somehow during the stepping over
3663 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003664
3665 // This is a transition from stop to run.
3666 switch (m_thread_list.ShouldReportRun (event_ptr))
3667 {
3668 case eVoteYes:
3669 case eVoteNoOpinion:
3670 return_value = true;
3671 break;
3672 case eVoteNo:
3673 return_value = false;
3674 break;
3675 }
3676 break;
3677 }
3678 break;
3679 case eStateStopped:
3680 case eStateCrashed:
3681 case eStateSuspended:
3682 {
3683 // We've stopped. First see if we're going to restart the target.
3684 // If we are going to stop, then we always broadcast the event.
3685 // 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 +00003686 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003687
Jim Inghamcb4ca112012-05-16 01:32:14 +00003688 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003689 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003690 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003691 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003692 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3693 event_ptr,
3694 StateAsCString(state));
3695 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003696 }
3697 else
3698 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003699 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3700 bool should_resume = false;
3701
Jim Ingham0161b492013-02-09 01:29:05 +00003702 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3703 // Asking the thread list is also not likely to go well, since we are running again.
3704 // So in that case just report the event.
3705
Jim Ingham0161b492013-02-09 01:29:05 +00003706 if (!was_restarted)
3707 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Jim Ingham221d51c2013-05-08 00:35:16 +00003708
3709 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003710 {
Jim Ingham0161b492013-02-09 01:29:05 +00003711 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3712 if (log)
3713 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3714 should_resume,
3715 StateAsCString(state),
3716 was_restarted,
3717 stop_vote);
3718
3719 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003720 {
3721 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003722 return_value = true;
3723 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003724 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003725 case eVoteNo:
3726 return_value = false;
3727 break;
3728 }
Jim Ingham0161b492013-02-09 01:29:05 +00003729
Jim Inghamcb95f342012-09-05 21:13:56 +00003730 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003731 {
3732 if (log)
3733 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3734 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003735 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003736 }
3737
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003738 }
3739 else
3740 {
3741 return_value = true;
3742 SynchronouslyNotifyStateChanged (state);
3743 }
3744 }
3745 }
Jim Ingham0161b492013-02-09 01:29:05 +00003746 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003747 }
Jim Ingham0161b492013-02-09 01:29:05 +00003748
3749 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3750 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3751 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3752 // because the PublicState reflects the last event pulled off the queue, and there may be several
3753 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3754 // yet. m_last_broadcast_state gets updated here.
3755
3756 if (return_value)
3757 m_last_broadcast_state = state;
3758
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003759 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003760 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3761 event_ptr,
3762 StateAsCString(state),
3763 StateAsCString(m_last_broadcast_state),
3764 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003765 return return_value;
3766}
3767
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003768
3769bool
Jim Ingham372787f2012-04-07 00:00:41 +00003770Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003771{
Greg Clayton5160ce52013-03-27 23:08:40 +00003772 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003773
Greg Clayton8b82f082011-04-12 05:54:46 +00003774 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003775 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003776 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3777
Jim Ingham372787f2012-04-07 00:00:41 +00003778 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003779 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003780
3781 // Create a thread that watches our internal state and controls which
3782 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003783 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003784 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003785 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00003786 else
Daniel Malead01b2952012-11-29 21:49:15 +00003787 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003788
3789 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003790 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003791 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3792 if (success)
3793 {
3794 ResumePrivateStateThread();
3795 return true;
3796 }
3797 else
3798 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003799}
3800
3801void
3802Process::PausePrivateStateThread ()
3803{
3804 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3805}
3806
3807void
3808Process::ResumePrivateStateThread ()
3809{
3810 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3811}
3812
3813void
3814Process::StopPrivateStateThread ()
3815{
Greg Clayton8b82f082011-04-12 05:54:46 +00003816 if (PrivateStateThreadIsValid ())
3817 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003818 else
3819 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003820 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00003821 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003822 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00003823 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003824}
3825
3826void
3827Process::ControlPrivateStateThread (uint32_t signal)
3828{
Greg Clayton5160ce52013-03-27 23:08:40 +00003829 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003830
3831 assert (signal == eBroadcastInternalStateControlStop ||
3832 signal == eBroadcastInternalStateControlPause ||
3833 signal == eBroadcastInternalStateControlResume);
3834
3835 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003836 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003837
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003838 // Signal the private state thread. First we should copy this is case the
3839 // thread starts exiting since the private state thread will NULL this out
3840 // when it exits
3841 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003842 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003843 {
3844 TimeValue timeout_time;
3845 bool timed_out;
3846
3847 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3848
3849 timeout_time = TimeValue::Now();
3850 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003851 if (log)
3852 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003853 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3854 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3855
3856 if (signal == eBroadcastInternalStateControlStop)
3857 {
3858 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003859 {
3860 Error error;
3861 Host::ThreadCancel (private_state_thread, &error);
3862 if (log)
3863 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3864 }
3865 else
3866 {
3867 if (log)
3868 log->Printf ("The control event killed the private state thread without having to cancel.");
3869 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003870
3871 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003872 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003873 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003874 }
3875 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003876 else
3877 {
3878 if (log)
3879 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3880 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003881}
3882
3883void
Jim Inghamcfc09352012-07-27 23:57:19 +00003884Process::SendAsyncInterrupt ()
3885{
3886 if (PrivateStateThreadIsValid())
3887 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3888 else
3889 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3890}
3891
3892void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003893Process::HandlePrivateEvent (EventSP &event_sp)
3894{
Greg Clayton5160ce52013-03-27 23:08:40 +00003895 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00003896 m_resume_requested = false;
3897
Jim Inghamaacc3182012-06-06 00:29:30 +00003898 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003899
Greg Clayton414f5d32011-01-25 02:58:48 +00003900 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003901
3902 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003903 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003904 {
Jim Ingham754ab982011-01-29 04:05:41 +00003905 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00003906 if (log)
3907 log->Printf ("Ran next event action, result was %d.", action_result);
3908
Jim Inghambb3a2832011-01-29 01:49:25 +00003909 switch (action_result)
3910 {
3911 case NextEventAction::eEventActionSuccess:
3912 SetNextEventAction(NULL);
3913 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003914
Jim Inghambb3a2832011-01-29 01:49:25 +00003915 case NextEventAction::eEventActionRetry:
3916 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003917
Jim Inghambb3a2832011-01-29 01:49:25 +00003918 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003919 // Handle Exiting Here. If we already got an exited event,
3920 // we should just propagate it. Otherwise, swallow this event,
3921 // and set our state to exit so the next event will kill us.
3922 if (new_state != eStateExited)
3923 {
3924 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003925 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00003926 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003927 SetNextEventAction(NULL);
3928 return;
3929 }
3930 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003931 break;
3932 }
3933 }
3934
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003935 // See if we should broadcast this state to external clients?
3936 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003937
3938 if (should_broadcast)
3939 {
3940 if (log)
3941 {
Daniel Malead01b2952012-11-29 21:49:15 +00003942 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003943 __FUNCTION__,
3944 GetID(),
3945 StateAsCString(new_state),
3946 StateAsCString (GetState ()),
3947 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003948 }
Jim Ingham9575d842011-03-11 03:53:59 +00003949 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003950 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003951 PushProcessInputReader ();
3952 else
3953 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003954
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003955 BroadcastEvent (event_sp);
3956 }
3957 else
3958 {
3959 if (log)
3960 {
Daniel Malead01b2952012-11-29 21:49:15 +00003961 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003962 __FUNCTION__,
3963 GetID(),
3964 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003965 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003966 }
3967 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003968 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003969}
3970
3971void *
3972Process::PrivateStateThread (void *arg)
3973{
3974 Process *proc = static_cast<Process*> (arg);
3975 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003976 return result;
3977}
3978
3979void *
3980Process::RunPrivateStateThread ()
3981{
Jim Ingham076b3042012-04-10 01:21:57 +00003982 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003983 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003984
Greg Clayton5160ce52013-03-27 23:08:40 +00003985 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003986 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003987 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003988
3989 bool exit_now = false;
3990 while (!exit_now)
3991 {
3992 EventSP event_sp;
3993 WaitForEventsPrivate (NULL, event_sp, control_only);
3994 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3995 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003996 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00003997 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 +00003998
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003999 switch (event_sp->GetType())
4000 {
4001 case eBroadcastInternalStateControlStop:
4002 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004003 break; // doing any internal state managment below
4004
4005 case eBroadcastInternalStateControlPause:
4006 control_only = true;
4007 break;
4008
4009 case eBroadcastInternalStateControlResume:
4010 control_only = false;
4011 break;
4012 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004013
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004014 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004015 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004016 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004017 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4018 {
4019 if (m_public_state.GetValue() == eStateAttaching)
4020 {
4021 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004022 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 +00004023 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4024 }
4025 else
4026 {
4027 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004028 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004029 Halt();
4030 }
4031 continue;
4032 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004033
4034 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4035
4036 if (internal_state != eStateInvalid)
4037 {
4038 HandlePrivateEvent (event_sp);
4039 }
4040
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004041 if (internal_state == eStateInvalid ||
4042 internal_state == eStateExited ||
4043 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004044 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004045 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004046 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 +00004047
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004048 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004049 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004050 }
4051
Caroline Tice20ad3c42010-10-29 21:48:37 +00004052 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004053 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004054 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004055
Greg Clayton96249852013-04-18 16:57:27 +00004056 m_public_run_lock.WriteUnlock();
Greg Clayton6ed95942011-01-22 07:12:45 +00004057 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4058 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004059 return NULL;
4060}
4061
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004062//------------------------------------------------------------------
4063// Process Event Data
4064//------------------------------------------------------------------
4065
4066Process::ProcessEventData::ProcessEventData () :
4067 EventData (),
4068 m_process_sp (),
4069 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004070 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004071 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004072 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004073{
4074}
4075
4076Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4077 EventData (),
4078 m_process_sp (process_sp),
4079 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004080 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004081 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004082 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004083{
4084}
4085
4086Process::ProcessEventData::~ProcessEventData()
4087{
4088}
4089
4090const ConstString &
4091Process::ProcessEventData::GetFlavorString ()
4092{
4093 static ConstString g_flavor ("Process::ProcessEventData");
4094 return g_flavor;
4095}
4096
4097const ConstString &
4098Process::ProcessEventData::GetFlavor () const
4099{
4100 return ProcessEventData::GetFlavorString ();
4101}
4102
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004103void
4104Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4105{
4106 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004107 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4108 // the public event queue, then other times when we're pretending that this is where we stopped at the
4109 // end of expression evaluation. m_update_state is used to distinguish these
4110 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004111 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004112 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004113 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004114
Jim Ingham221d51c2013-05-08 00:35:16 +00004115 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004116
4117 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4118 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004119 {
4120 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004121 uint32_t num_threads = curr_thread_list.GetSize();
4122 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004123
Jim Ingham4b536182011-08-09 02:12:22 +00004124 // The actions might change one of the thread's stop_info's opinions about whether we should
4125 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004126
4127 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4128 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4129 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4130 // 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
4131 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004132 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004133 for (idx = 0; idx < num_threads; ++idx)
4134 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4135
Jim Inghamc7078c22012-12-13 22:24:15 +00004136 // Use this to track whether we should continue from here. We will only continue the target running if
4137 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4138 // then it doesn't matter what the other threads say...
4139
4140 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004141
Jim Ingham0ad7e052013-04-25 02:04:59 +00004142 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4143 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4144 // thing to do is, and it's better to let the user decide than continue behind their backs.
4145
4146 bool does_anybody_have_an_opinion = false;
4147
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004148 for (idx = 0; idx < num_threads; ++idx)
4149 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004150 curr_thread_list = m_process_sp->GetThreadList();
4151 if (curr_thread_list.GetSize() != num_threads)
4152 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004153 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004154 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004155 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 +00004156 break;
4157 }
4158
4159 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4160
4161 if (thread_sp->GetIndexID() != thread_index_array[idx])
4162 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004163 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004164 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004165 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004166 idx,
4167 thread_index_array[idx],
4168 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004169 break;
4170 }
4171
Jim Inghamb15bfc72010-10-20 00:39:53 +00004172 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004173 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004174 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004175 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004176 bool this_thread_wants_to_stop;
4177 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004178 {
Jim Ingham0161b492013-02-09 01:29:05 +00004179 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4180 }
4181 else
4182 {
4183 stop_info_sp->PerformAction(event_ptr);
4184 // The stop action might restart the target. If it does, then we want to mark that in the
4185 // event so that whoever is receiving it will know to wait for the running event and reflect
4186 // that state appropriately.
4187 // We also need to stop processing actions, since they aren't expecting the target to be running.
4188
4189 // FIXME: we might have run.
4190 if (stop_info_sp->HasTargetRunSinceMe())
4191 {
4192 SetRestarted (true);
4193 break;
4194 }
4195
4196 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004197 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004198
Jim Inghamc7078c22012-12-13 22:24:15 +00004199 if (still_should_stop == false)
4200 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004201 }
4202 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004203
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004204
Jim Inghama8ca6e22013-05-03 23:04:37 +00004205 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004206 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004207 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004208 {
4209 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004210 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004211 // Use the public resume method here, since this is just
4212 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004213 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004214 }
4215 else
4216 {
4217 // If we didn't restart, run the Stop Hooks here:
4218 // They might also restart the target, so watch for that.
4219 m_process_sp->GetTarget().RunStopHooks();
4220 if (m_process_sp->GetPrivateState() == eStateRunning)
4221 SetRestarted(true);
4222 }
Jim Ingham9575d842011-03-11 03:53:59 +00004223 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004224 }
4225}
4226
4227void
4228Process::ProcessEventData::Dump (Stream *s) const
4229{
4230 if (m_process_sp)
Daniel Malead01b2952012-11-29 21:49:15 +00004231 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004232
Greg Clayton8b82f082011-04-12 05:54:46 +00004233 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004234}
4235
4236const Process::ProcessEventData *
4237Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4238{
4239 if (event_ptr)
4240 {
4241 const EventData *event_data = event_ptr->GetData();
4242 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4243 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4244 }
4245 return NULL;
4246}
4247
4248ProcessSP
4249Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4250{
4251 ProcessSP process_sp;
4252 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4253 if (data)
4254 process_sp = data->GetProcessSP();
4255 return process_sp;
4256}
4257
4258StateType
4259Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4260{
4261 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4262 if (data == NULL)
4263 return eStateInvalid;
4264 else
4265 return data->GetState();
4266}
4267
4268bool
4269Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4270{
4271 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4272 if (data == NULL)
4273 return false;
4274 else
4275 return data->GetRestarted();
4276}
4277
4278void
4279Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4280{
4281 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4282 if (data != NULL)
4283 data->SetRestarted(new_value);
4284}
4285
Jim Ingham0161b492013-02-09 01:29:05 +00004286size_t
4287Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4288{
4289 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4290 if (data != NULL)
4291 return data->GetNumRestartedReasons();
4292 else
4293 return 0;
4294}
4295
4296const char *
4297Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4298{
4299 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4300 if (data != NULL)
4301 return data->GetRestartedReasonAtIndex(idx);
4302 else
4303 return NULL;
4304}
4305
4306void
4307Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4308{
4309 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4310 if (data != NULL)
4311 data->AddRestartedReason(reason);
4312}
4313
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004314bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004315Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4316{
4317 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4318 if (data == NULL)
4319 return false;
4320 else
4321 return data->GetInterrupted ();
4322}
4323
4324void
4325Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4326{
4327 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4328 if (data != NULL)
4329 data->SetInterrupted(new_value);
4330}
4331
4332bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004333Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4334{
4335 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4336 if (data)
4337 {
4338 data->SetUpdateStateOnRemoval();
4339 return true;
4340 }
4341 return false;
4342}
4343
Greg Claytond9e416c2012-02-18 05:35:26 +00004344lldb::TargetSP
4345Process::CalculateTarget ()
4346{
4347 return m_target.shared_from_this();
4348}
4349
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004350void
Greg Clayton0603aa92010-10-04 01:05:56 +00004351Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004352{
Greg Claytonc14ee322011-09-22 04:58:26 +00004353 exe_ctx.SetTargetPtr (&m_target);
4354 exe_ctx.SetProcessPtr (this);
4355 exe_ctx.SetThreadPtr(NULL);
4356 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004357}
4358
Greg Claytone996fd32011-03-08 22:40:15 +00004359//uint32_t
4360//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4361//{
4362// return 0;
4363//}
4364//
4365//ArchSpec
4366//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4367//{
4368// return Host::GetArchSpecForExistingProcess (pid);
4369//}
4370//
4371//ArchSpec
4372//Process::GetArchSpecForExistingProcess (const char *process_name)
4373//{
4374// return Host::GetArchSpecForExistingProcess (process_name);
4375//}
4376//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004377void
4378Process::AppendSTDOUT (const char * s, size_t len)
4379{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004380 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004381 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004382 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004383}
4384
4385void
Greg Clayton93e86192011-11-13 04:45:22 +00004386Process::AppendSTDERR (const char * s, size_t len)
4387{
4388 Mutex::Locker locker (m_stdio_communication_mutex);
4389 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004390 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004391}
4392
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004393void
4394Process::BroadcastAsyncProfileData(const char *s, size_t len)
4395{
4396 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004397 m_profile_data.push_back(s);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004398 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4399}
4400
4401size_t
4402Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4403{
4404 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004405 if (m_profile_data.empty())
4406 return 0;
4407
4408 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004409 if (bytes_available > 0)
4410 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004411 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004412 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004413 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004414 if (bytes_available > buf_size)
4415 {
Han Ming Ong929a94f2012-11-29 22:14:45 +00004416 memcpy(buf, m_profile_data.front().data(), buf_size);
4417 m_profile_data.front().erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004418 bytes_available = buf_size;
4419 }
4420 else
4421 {
Han Ming Ong929a94f2012-11-29 22:14:45 +00004422 memcpy(buf, m_profile_data.front().data(), bytes_available);
4423 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004424 }
4425 }
4426 return bytes_available;
4427}
4428
4429
Greg Clayton93e86192011-11-13 04:45:22 +00004430//------------------------------------------------------------------
4431// Process STDIO
4432//------------------------------------------------------------------
4433
4434size_t
4435Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4436{
4437 Mutex::Locker locker(m_stdio_communication_mutex);
4438 size_t bytes_available = m_stdout_data.size();
4439 if (bytes_available > 0)
4440 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004441 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004442 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004443 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004444 if (bytes_available > buf_size)
4445 {
4446 memcpy(buf, m_stdout_data.c_str(), buf_size);
4447 m_stdout_data.erase(0, buf_size);
4448 bytes_available = buf_size;
4449 }
4450 else
4451 {
4452 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4453 m_stdout_data.clear();
4454 }
4455 }
4456 return bytes_available;
4457}
4458
4459
4460size_t
4461Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4462{
4463 Mutex::Locker locker(m_stdio_communication_mutex);
4464 size_t bytes_available = m_stderr_data.size();
4465 if (bytes_available > 0)
4466 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004467 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004468 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004469 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004470 if (bytes_available > buf_size)
4471 {
4472 memcpy(buf, m_stderr_data.c_str(), buf_size);
4473 m_stderr_data.erase(0, buf_size);
4474 bytes_available = buf_size;
4475 }
4476 else
4477 {
4478 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4479 m_stderr_data.clear();
4480 }
4481 }
4482 return bytes_available;
4483}
4484
4485void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004486Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4487{
4488 Process *process = (Process *) baton;
4489 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4490}
4491
4492size_t
4493Process::ProcessInputReaderCallback (void *baton,
4494 InputReader &reader,
4495 lldb::InputReaderAction notification,
4496 const char *bytes,
4497 size_t bytes_len)
4498{
4499 Process *process = (Process *) baton;
4500
4501 switch (notification)
4502 {
4503 case eInputReaderActivate:
4504 break;
4505
4506 case eInputReaderDeactivate:
4507 break;
4508
4509 case eInputReaderReactivate:
4510 break;
4511
Caroline Tice969ed3d2011-05-02 20:41:46 +00004512 case eInputReaderAsynchronousOutputWritten:
4513 break;
4514
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004515 case eInputReaderGotToken:
4516 {
4517 Error error;
4518 process->PutSTDIN (bytes, bytes_len, error);
4519 }
4520 break;
4521
Caroline Ticeefed6132010-11-19 20:47:54 +00004522 case eInputReaderInterrupt:
4523 process->Halt ();
4524 break;
4525
4526 case eInputReaderEndOfFile:
4527 process->AppendSTDOUT ("^D", 2);
4528 break;
4529
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004530 case eInputReaderDone:
4531 break;
4532
4533 }
4534
4535 return bytes_len;
4536}
4537
4538void
4539Process::ResetProcessInputReader ()
4540{
4541 m_process_input_reader.reset();
4542}
4543
4544void
Greg Claytonee95ed52011-11-17 22:14:31 +00004545Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004546{
4547 // First set up the Read Thread for reading/handling process I/O
4548
Greg Clayton7b0992d2013-04-18 22:45:39 +00004549 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004550
4551 if (conn_ap.get())
4552 {
4553 m_stdio_communication.SetConnection (conn_ap.release());
4554 if (m_stdio_communication.IsConnected())
4555 {
4556 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4557 m_stdio_communication.StartReadThread();
4558
4559 // Now read thread is set up, set up input reader.
4560
4561 if (!m_process_input_reader.get())
4562 {
4563 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4564 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4565 this,
4566 eInputReaderGranularityByte,
4567 NULL,
4568 NULL,
4569 false));
4570
4571 if (err.Fail())
4572 m_process_input_reader.reset();
4573 }
4574 }
4575 }
4576}
4577
4578void
4579Process::PushProcessInputReader ()
4580{
4581 if (m_process_input_reader && !m_process_input_reader->IsActive())
4582 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4583}
4584
4585void
4586Process::PopProcessInputReader ()
4587{
4588 if (m_process_input_reader && m_process_input_reader->IsActive())
4589 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4590}
4591
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004592// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004593void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004594Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004595{
Greg Clayton67cc0632012-08-22 17:17:09 +00004596// static std::vector<OptionEnumValueElement> g_plugins;
4597//
4598// int i=0;
4599// const char *name;
4600// OptionEnumValueElement option_enum;
4601// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4602// {
4603// if (name)
4604// {
4605// option_enum.value = i;
4606// option_enum.string_value = name;
4607// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4608// g_plugins.push_back (option_enum);
4609// }
4610// ++i;
4611// }
4612// option_enum.value = 0;
4613// option_enum.string_value = NULL;
4614// option_enum.usage = NULL;
4615// g_plugins.push_back (option_enum);
4616//
4617// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4618// {
4619// if (::strcmp (name, "plugin") == 0)
4620// {
4621// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4622// break;
4623// }
4624// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004625//
Greg Clayton6920b522012-08-22 18:39:03 +00004626 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004627}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004628
Greg Clayton99d0faf2010-11-18 23:32:35 +00004629void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004630Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004631{
Greg Clayton6920b522012-08-22 18:39:03 +00004632 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004633}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004634
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004635ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004636Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004637 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00004638 bool stop_others,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004639 bool run_others,
Jim Ingham184e9812013-01-15 02:47:48 +00004640 bool unwind_on_error,
4641 bool ignore_breakpoints,
Jim Ingham35e1bda2012-10-16 21:41:58 +00004642 uint32_t timeout_usec,
Jim Inghamf48169b2010-11-30 02:22:11 +00004643 Stream &errors)
4644{
4645 ExecutionResults return_value = eExecutionSetupError;
4646
Jim Ingham77787032011-01-20 02:03:18 +00004647 if (thread_plan_sp.get() == NULL)
4648 {
4649 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004650 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004651 }
Jim Ingham7d7931d2013-03-28 00:05:34 +00004652
4653 if (!thread_plan_sp->ValidatePlan(NULL))
4654 {
4655 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4656 return eExecutionSetupError;
4657 }
4658
Greg Claytonc14ee322011-09-22 04:58:26 +00004659 if (exe_ctx.GetProcessPtr() != this)
4660 {
4661 errors.Printf("RunThreadPlan called on wrong process.");
4662 return eExecutionSetupError;
4663 }
4664
4665 Thread *thread = exe_ctx.GetThreadPtr();
4666 if (thread == NULL)
4667 {
4668 errors.Printf("RunThreadPlan called with invalid thread.");
4669 return eExecutionSetupError;
4670 }
Jim Ingham77787032011-01-20 02:03:18 +00004671
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004672 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4673 // For that to be true the plan can't be private - since private plans suppress themselves in the
4674 // GetCompletedPlan call.
4675
4676 bool orig_plan_private = thread_plan_sp->GetPrivate();
4677 thread_plan_sp->SetPrivate(false);
4678
Jim Ingham444586b2011-01-24 06:34:17 +00004679 if (m_private_state.GetValue() != eStateStopped)
4680 {
4681 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004682 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004683 }
4684
Jim Ingham66243842011-08-13 00:56:10 +00004685 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004686 const uint32_t thread_idx_id = thread->GetIndexID();
Jim Ingham11b0e052013-02-19 23:22:45 +00004687 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4688 if (!selected_frame_sp)
4689 {
4690 thread->SetSelectedFrame(0);
4691 selected_frame_sp = thread->GetSelectedFrame();
4692 if (!selected_frame_sp)
4693 {
4694 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4695 return eExecutionSetupError;
4696 }
4697 }
4698
4699 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004700
4701 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4702 // so we should arrange to reset them as well.
4703
Greg Claytonc14ee322011-09-22 04:58:26 +00004704 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004705
Jim Ingham66243842011-08-13 00:56:10 +00004706 uint32_t selected_tid;
4707 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004708 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004709 {
4710 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004711 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004712 }
4713 else
4714 {
4715 selected_tid = LLDB_INVALID_THREAD_ID;
4716 }
4717
Jim Ingham372787f2012-04-07 00:00:41 +00004718 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004719 lldb::StateType old_state;
4720 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004721
Greg Clayton5160ce52013-03-27 23:08:40 +00004722 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004723 if (Host::GetCurrentThread() == m_private_state_thread)
4724 {
Jim Ingham076b3042012-04-10 01:21:57 +00004725 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4726 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004727 // 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 +00004728 // we are fielding public events here.
4729 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004730 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 +00004731
4732
Jim Ingham372787f2012-04-07 00:00:41 +00004733 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004734
4735 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4736 // returning control here.
4737 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4738 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4739 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4740 // do just what we want.
4741 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4742 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4743 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4744 old_state = m_public_state.GetValue();
4745 m_public_state.SetValueNoLock(eStateStopped);
4746
4747 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004748 StartPrivateStateThread(true);
4749 }
4750
4751 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004752
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004753 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004754
Sean Callanana46ec452012-07-11 21:31:24 +00004755 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004756
Jim Ingham77787032011-01-20 02:03:18 +00004757 {
Sean Callanana46ec452012-07-11 21:31:24 +00004758 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4759 // restored on exit to the function.
4760 //
4761 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4762 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004763
Sean Callanana46ec452012-07-11 21:31:24 +00004764 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004765
Jim Inghamf48169b2010-11-30 02:22:11 +00004766 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004767 {
4768 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004769 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004770 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004771 thread->GetIndexID(),
4772 thread->GetID(),
4773 s.GetData());
4774 }
4775
4776 bool got_event;
4777 lldb::EventSP event_sp;
4778 lldb::StateType stop_state = lldb::eStateInvalid;
4779
4780 TimeValue* timeout_ptr = NULL;
4781 TimeValue real_timeout;
4782
Jim Ingham0161b492013-02-09 01:29:05 +00004783 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 +00004784 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004785 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004786 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanana46ec452012-07-11 21:31:24 +00004787
Jim Ingham0161b492013-02-09 01:29:05 +00004788 // This is just for accounting:
4789 uint32_t num_resumes = 0;
4790
4791 TimeValue one_thread_timeout = TimeValue::Now();
4792 TimeValue final_timeout = one_thread_timeout;
4793
4794 if (run_others)
4795 {
4796 // If we are running all threads then we take half the time to run all threads, bounded by
4797 // .25 sec.
4798 if (timeout_usec == 0)
4799 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4800 else
4801 {
Greg Clayton03da4cc2013-04-19 21:31:16 +00004802 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham0161b492013-02-09 01:29:05 +00004803 if (computed_timeout > default_one_thread_timeout_usec)
4804 computed_timeout = default_one_thread_timeout_usec;
4805 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4806 }
4807 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4808 }
4809 else
4810 {
4811 if (timeout_usec != 0)
4812 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4813 }
4814
Jim Ingham8559a352012-11-26 23:52:18 +00004815 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4816 // So don't call return anywhere within it.
4817
Sean Callanana46ec452012-07-11 21:31:24 +00004818 while (1)
4819 {
4820 // We usually want to resume the process if we get to the top of the loop.
4821 // The only exception is if we get two running events with no intervening
4822 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00004823 if (log)
4824 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4825 do_resume,
4826 handle_running_event,
4827 before_first_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00004828
Jim Ingham184e9812013-01-15 02:47:48 +00004829 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00004830 {
4831 // Do the initial resume and wait for the running event before going further.
4832
Jim Ingham184e9812013-01-15 02:47:48 +00004833 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00004834 {
Jim Ingham0161b492013-02-09 01:29:05 +00004835 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00004836 Error resume_error = PrivateResume ();
4837 if (!resume_error.Success())
4838 {
Jim Ingham0161b492013-02-09 01:29:05 +00004839 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4840 num_resumes,
4841 resume_error.AsCString());
Jim Ingham184e9812013-01-15 02:47:48 +00004842 return_value = eExecutionSetupError;
4843 break;
4844 }
Sean Callanana46ec452012-07-11 21:31:24 +00004845 }
Sean Callanana46ec452012-07-11 21:31:24 +00004846
Jim Ingham0161b492013-02-09 01:29:05 +00004847 TimeValue resume_timeout = TimeValue::Now();
4848 resume_timeout.OffsetWithMicroSeconds(500000);
4849
4850 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00004851 if (!got_event)
4852 {
4853 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004854 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4855 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004856
Jim Ingham0161b492013-02-09 01:29:05 +00004857 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00004858 return_value = eExecutionSetupError;
4859 break;
4860 }
4861
4862 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00004863
Sean Callanana46ec452012-07-11 21:31:24 +00004864 if (stop_state != eStateRunning)
4865 {
Jim Ingham0161b492013-02-09 01:29:05 +00004866 bool restarted = false;
4867
4868 if (stop_state == eStateStopped)
4869 {
4870 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4871 if (log)
4872 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4873 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4874 num_resumes,
4875 StateAsCString(stop_state),
4876 restarted,
4877 do_resume,
4878 handle_running_event);
4879 }
4880
4881 if (restarted)
4882 {
4883 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4884 // event here. But if I do, the best thing is to Halt and then get out of here.
4885 Halt();
4886 }
4887
Jim Ingham35e1bda2012-10-16 21:41:58 +00004888 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4889 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00004890 return_value = eExecutionSetupError;
4891 break;
4892 }
4893
4894 if (log)
4895 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4896 // We need to call the function synchronously, so spin waiting for it to return.
4897 // If we get interrupted while executing, we're going to lose our context, and
4898 // won't be able to gather the result at this point.
4899 // We set the timeout AFTER the resume, since the resume takes some time and we
4900 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00004901 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004902 else
4903 {
Sean Callanana46ec452012-07-11 21:31:24 +00004904 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004905 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004906 }
Jim Ingham0161b492013-02-09 01:29:05 +00004907
4908 if (before_first_timeout)
4909 {
4910 if (run_others)
4911 timeout_ptr = &one_thread_timeout;
4912 else
4913 {
4914 if (timeout_usec == 0)
4915 timeout_ptr = NULL;
4916 else
4917 timeout_ptr = &final_timeout;
4918 }
4919 }
4920 else
4921 {
4922 if (timeout_usec == 0)
4923 timeout_ptr = NULL;
4924 else
4925 timeout_ptr = &final_timeout;
4926 }
4927
4928 do_resume = true;
4929 handle_running_event = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00004930
Sean Callanana46ec452012-07-11 21:31:24 +00004931 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00004932 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00004933
Jim Ingham0f16e732011-02-08 05:20:59 +00004934 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004935 {
Sean Callanana46ec452012-07-11 21:31:24 +00004936 if (timeout_ptr)
4937 {
Matt Kopec676a4872013-02-21 23:55:31 +00004938 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00004939 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
4940 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00004941 }
Jim Ingham20829ac2011-08-09 22:24:33 +00004942 else
Sean Callanana46ec452012-07-11 21:31:24 +00004943 {
4944 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4945 }
4946 }
4947
4948 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4949
4950 if (got_event)
4951 {
4952 if (event_sp.get())
4953 {
4954 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00004955 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004956 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004957 Halt();
Jim Inghamcfc09352012-07-27 23:57:19 +00004958 return_value = eExecutionInterrupted;
4959 errors.Printf ("Execution halted by user interrupt.");
4960 if (log)
4961 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00004962 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00004963 }
4964 else
4965 {
4966 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4967 if (log)
4968 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4969
4970 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00004971 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004972 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00004973 {
Jim Ingham0161b492013-02-09 01:29:05 +00004974 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00004975 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4976 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004977 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004978 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00004979 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00004980 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4981 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00004982 }
4983 else
4984 {
Jim Ingham0161b492013-02-09 01:29:05 +00004985 // If we were restarted, we just need to go back up to fetch another event.
4986 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00004987 {
4988 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004989 {
4990 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
4991 }
4992 keep_going = true;
4993 do_resume = false;
4994 handle_running_event = true;
4995
Jim Inghamcfc09352012-07-27 23:57:19 +00004996 }
4997 else
4998 {
Jim Ingham0161b492013-02-09 01:29:05 +00004999
5000 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5001 StopReason stop_reason = eStopReasonInvalid;
5002 if (stop_info_sp)
5003 stop_reason = stop_info_sp->GetStopReason();
5004
5005
5006 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5007 // it is OUR plan that is complete?
5008 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005009 {
5010 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005011 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5012 // Now mark this plan as private so it doesn't get reported as the stop reason
5013 // after this point.
5014 if (thread_plan_sp)
5015 thread_plan_sp->SetPrivate (orig_plan_private);
5016 return_value = eExecutionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005017 }
5018 else
5019 {
Jim Ingham0161b492013-02-09 01:29:05 +00005020 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005021 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005022 {
5023 if (log)
5024 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham184e9812013-01-15 02:47:48 +00005025 return_value = eExecutionHitBreakpoint;
Jim Ingham0161b492013-02-09 01:29:05 +00005026 }
Jim Ingham184e9812013-01-15 02:47:48 +00005027 else
Jim Ingham0161b492013-02-09 01:29:05 +00005028 {
5029 if (log)
5030 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham184e9812013-01-15 02:47:48 +00005031 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005032 }
Jim Ingham184e9812013-01-15 02:47:48 +00005033 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005034 }
Sean Callanana46ec452012-07-11 21:31:24 +00005035 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005036 }
5037 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005038
Jim Inghamcfc09352012-07-27 23:57:19 +00005039 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005040 // This shouldn't really happen, but sometimes we do get two running events without an
5041 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005042 do_resume = false;
5043 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005044 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005045 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005046
Jim Inghamcfc09352012-07-27 23:57:19 +00005047 default:
5048 if (log)
5049 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5050
5051 if (stop_state == eStateExited)
5052 event_to_broadcast_sp = event_sp;
5053
Sean Callananbf154da2012-08-08 17:35:10 +00005054 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00005055 return_value = eExecutionInterrupted;
5056 break;
5057 }
Sean Callanana46ec452012-07-11 21:31:24 +00005058 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005059
Sean Callanana46ec452012-07-11 21:31:24 +00005060 if (keep_going)
5061 continue;
5062 else
5063 break;
5064 }
5065 else
5066 {
5067 if (log)
5068 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5069 return_value = eExecutionInterrupted;
5070 break;
5071 }
5072 }
5073 else
5074 {
5075 // If we didn't get an event that means we've timed out...
5076 // We will interrupt the process here. Depending on what we were asked to do we will
5077 // either exit, or try with all threads running for the same timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005078
5079 if (log) {
Jim Ingham35e1bda2012-10-16 21:41:58 +00005080 if (run_others)
Sean Callanana46ec452012-07-11 21:31:24 +00005081 {
Jim Ingham0161b492013-02-09 01:29:05 +00005082 uint64_t remaining_time = final_timeout - TimeValue::Now();
5083 if (before_first_timeout)
5084 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
5085 "running till for %" PRId64 " usec with all threads enabled.",
5086 remaining_time);
Sean Callanana46ec452012-07-11 21:31:24 +00005087 else
5088 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005089 "and timeout: %d timed out, abandoning execution.",
5090 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005091 }
5092 else
5093 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005094 "abandoning execution.",
5095 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005096 }
5097
Jim Ingham0161b492013-02-09 01:29:05 +00005098 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5099 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5100 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5101 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5102 // stopped event. That's what this while loop does.
5103
5104 bool back_to_top = true;
5105 uint32_t try_halt_again = 0;
5106 bool do_halt = true;
5107 const uint32_t num_retries = 5;
5108 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005109 {
Jim Ingham0161b492013-02-09 01:29:05 +00005110 Error halt_error;
5111 if (do_halt)
5112 {
5113 if (log)
5114 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5115 halt_error = Halt();
5116 }
5117 if (halt_error.Success())
5118 {
5119 if (log)
5120 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5121
5122 real_timeout = TimeValue::Now();
5123 real_timeout.OffsetWithMicroSeconds(500000);
5124
5125 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005126
Jim Ingham0161b492013-02-09 01:29:05 +00005127 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005128 {
Jim Ingham0161b492013-02-09 01:29:05 +00005129 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5130 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005131 {
Jim Ingham0161b492013-02-09 01:29:05 +00005132 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5133 if (stop_state == lldb::eStateStopped
5134 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5135 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005136 }
5137
Jim Ingham0161b492013-02-09 01:29:05 +00005138 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005139 {
Jim Ingham0161b492013-02-09 01:29:05 +00005140 // Between the time we initiated the Halt and the time we delivered it, the process could have
5141 // already finished its job. Check that here:
5142
5143 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5144 {
5145 if (log)
5146 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5147 "Exiting wait loop.");
5148 return_value = eExecutionCompleted;
5149 back_to_top = false;
5150 break;
5151 }
5152
5153 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5154 {
5155 if (log)
5156 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5157 "Exiting wait loop.");
5158 try_halt_again++;
5159 do_halt = false;
5160 continue;
5161 }
Sean Callanana46ec452012-07-11 21:31:24 +00005162
Jim Ingham0161b492013-02-09 01:29:05 +00005163 if (!run_others)
5164 {
5165 if (log)
5166 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5167 return_value = eExecutionInterrupted;
5168 back_to_top = false;
5169 break;
5170 }
5171
5172 if (before_first_timeout)
5173 {
5174 // Set all the other threads to run, and return to the top of the loop, which will continue;
5175 before_first_timeout = false;
5176 thread_plan_sp->SetStopOthers (false);
5177 if (log)
5178 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005179
Jim Ingham0161b492013-02-09 01:29:05 +00005180 back_to_top = true;
5181 break;
5182 }
5183 else
5184 {
5185 // Running all threads failed, so return Interrupted.
5186 if (log)
5187 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5188 return_value = eExecutionInterrupted;
5189 back_to_top = false;
5190 break;
5191 }
Sean Callanana46ec452012-07-11 21:31:24 +00005192 }
5193 }
5194 else
Jim Ingham0161b492013-02-09 01:29:05 +00005195 { if (log)
5196 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5197 "I'm getting out of here passing Interrupted.");
Sean Callanana46ec452012-07-11 21:31:24 +00005198 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005199 back_to_top = false;
5200 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005201 }
5202 }
Jim Ingham0161b492013-02-09 01:29:05 +00005203 else
5204 {
5205 try_halt_again++;
5206 continue;
5207 }
Sean Callanana46ec452012-07-11 21:31:24 +00005208 }
Jim Ingham0161b492013-02-09 01:29:05 +00005209
5210 if (!back_to_top || try_halt_again > num_retries)
5211 break;
5212 else
5213 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005214 }
Sean Callanana46ec452012-07-11 21:31:24 +00005215 } // END WAIT LOOP
5216
5217 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5218 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5219 {
5220 StopPrivateStateThread();
5221 Error error;
5222 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005223 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005224 {
5225 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5226 }
5227 m_public_state.SetValueNoLock(old_state);
5228
5229 }
5230
Jim Ingham184e9812013-01-15 02:47:48 +00005231 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5232 // could happen:
5233 // 1) The execution successfully completed
5234 // 2) We hit a breakpoint, and ignore_breakpoints was true
5235 // 3) We got some other error, and discard_on_error was true
5236 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
5237 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham8559a352012-11-26 23:52:18 +00005238
Jim Ingham184e9812013-01-15 02:47:48 +00005239 if (return_value == eExecutionCompleted
5240 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005241 {
5242 thread_plan_sp->RestoreThreadState();
5243 }
Sean Callanana46ec452012-07-11 21:31:24 +00005244
5245 // Now do some processing on the results of the run:
Jim Ingham184e9812013-01-15 02:47:48 +00005246 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005247 {
5248 if (log)
5249 {
5250 StreamString s;
5251 if (event_sp)
5252 event_sp->Dump (&s);
5253 else
5254 {
5255 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5256 }
5257
5258 StreamString ts;
5259
5260 const char *event_explanation = NULL;
5261
5262 do
5263 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005264 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005265 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005266 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005267 break;
5268 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005269 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005270 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005271 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005272 break;
5273 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005274 else
Sean Callanana46ec452012-07-11 21:31:24 +00005275 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005276 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5277
5278 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005279 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005280 event_explanation = "<no event data>";
5281 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005282 }
5283
Jim Inghamcfc09352012-07-27 23:57:19 +00005284 Process *process = event_data->GetProcessSP().get();
5285
5286 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005287 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005288 event_explanation = "<no process>";
5289 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005290 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005291
5292 ThreadList &thread_list = process->GetThreadList();
5293
5294 uint32_t num_threads = thread_list.GetSize();
5295 uint32_t thread_index;
5296
5297 ts.Printf("<%u threads> ", num_threads);
5298
5299 for (thread_index = 0;
5300 thread_index < num_threads;
5301 ++thread_index)
5302 {
5303 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5304
5305 if (!thread)
5306 {
5307 ts.Printf("<?> ");
5308 continue;
5309 }
5310
Daniel Malead01b2952012-11-29 21:49:15 +00005311 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005312 RegisterContext *register_context = thread->GetRegisterContext().get();
5313
5314 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005315 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005316 else
5317 ts.Printf("[ip unknown] ");
5318
5319 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5320 if (stop_info_sp)
5321 {
5322 const char *stop_desc = stop_info_sp->GetDescription();
5323 if (stop_desc)
5324 ts.PutCString (stop_desc);
5325 }
5326 ts.Printf(">");
5327 }
5328
5329 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005330 }
Sean Callanana46ec452012-07-11 21:31:24 +00005331 } while (0);
5332
Jim Inghamcfc09352012-07-27 23:57:19 +00005333 if (event_explanation)
5334 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005335 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005336 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5337 }
5338
Jim Ingham184e9812013-01-15 02:47:48 +00005339 if (should_unwind && thread_plan_sp)
Jim Inghamcfc09352012-07-27 23:57:19 +00005340 {
5341 if (log)
5342 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5343 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5344 thread_plan_sp->SetPrivate (orig_plan_private);
5345 }
5346 else
5347 {
5348 if (log)
5349 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00005350 }
5351 }
5352 else if (return_value == eExecutionSetupError)
5353 {
5354 if (log)
5355 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005356
Jim Ingham184e9812013-01-15 02:47:48 +00005357 if (unwind_on_error && thread_plan_sp)
Jim Ingham0f16e732011-02-08 05:20:59 +00005358 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005359 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005360 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005361 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005362 }
5363 else
5364 {
Sean Callanana46ec452012-07-11 21:31:24 +00005365 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005366 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005367 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005368 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5369 return_value = eExecutionCompleted;
5370 }
5371 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5372 {
5373 if (log)
5374 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5375 return_value = eExecutionDiscarded;
5376 }
5377 else
5378 {
5379 if (log)
5380 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham184e9812013-01-15 02:47:48 +00005381 if (unwind_on_error && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005382 {
5383 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005384 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005385 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5386 thread_plan_sp->SetPrivate (orig_plan_private);
5387 }
5388 }
5389 }
5390
5391 // Thread we ran the function in may have gone away because we ran the target
5392 // Check that it's still there, and if it is put it back in the context. Also restore the
5393 // frame in the context if it is still present.
5394 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5395 if (thread)
5396 {
5397 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5398 }
5399
5400 // Also restore the current process'es selected frame & thread, since this function calling may
5401 // be done behind the user's back.
5402
5403 if (selected_tid != LLDB_INVALID_THREAD_ID)
5404 {
5405 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5406 {
5407 // We were able to restore the selected thread, now restore the frame:
5408 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5409 if (old_frame_sp)
5410 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005411 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005412 }
5413 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005414
Sean Callanana46ec452012-07-11 21:31:24 +00005415 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00005416
Sean Callanana46ec452012-07-11 21:31:24 +00005417 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005418 {
Sean Callanana46ec452012-07-11 21:31:24 +00005419 if (log)
5420 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5421 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005422 }
5423
5424 return return_value;
5425}
5426
5427const char *
5428Process::ExecutionResultAsCString (ExecutionResults result)
5429{
5430 const char *result_name;
5431
5432 switch (result)
5433 {
Greg Claytone0d378b2011-03-24 21:19:54 +00005434 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005435 result_name = "eExecutionCompleted";
5436 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005437 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00005438 result_name = "eExecutionDiscarded";
5439 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005440 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005441 result_name = "eExecutionInterrupted";
5442 break;
Jim Ingham184e9812013-01-15 02:47:48 +00005443 case eExecutionHitBreakpoint:
5444 result_name = "eExecutionHitBreakpoint";
5445 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005446 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00005447 result_name = "eExecutionSetupError";
5448 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005449 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005450 result_name = "eExecutionTimedOut";
5451 break;
5452 }
5453 return result_name;
5454}
5455
Greg Clayton7260f622011-04-18 08:33:37 +00005456void
5457Process::GetStatus (Stream &strm)
5458{
5459 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005460 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005461 {
5462 if (state == eStateExited)
5463 {
5464 int exit_status = GetExitStatus();
5465 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005466 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005467 GetID(),
5468 exit_status,
5469 exit_status,
5470 exit_description ? exit_description : "");
5471 }
5472 else
5473 {
5474 if (state == eStateConnected)
5475 strm.Printf ("Connected to remote target.\n");
5476 else
Daniel Malead01b2952012-11-29 21:49:15 +00005477 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005478 }
5479 }
5480 else
5481 {
Daniel Malead01b2952012-11-29 21:49:15 +00005482 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005483 }
5484}
5485
5486size_t
5487Process::GetThreadStatus (Stream &strm,
5488 bool only_threads_with_stop_reason,
5489 uint32_t start_frame,
5490 uint32_t num_frames,
5491 uint32_t num_frames_with_source)
5492{
5493 size_t num_thread_infos_dumped = 0;
5494
Jim Ingham41f2b942012-09-10 20:50:15 +00005495 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005496 const size_t num_threads = GetThreadList().GetSize();
5497 for (uint32_t i = 0; i < num_threads; i++)
5498 {
5499 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5500 if (thread)
5501 {
5502 if (only_threads_with_stop_reason)
5503 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005504 StopInfoSP stop_info_sp = thread->GetStopInfo();
5505 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005506 continue;
5507 }
5508 thread->GetStatus (strm,
5509 start_frame,
5510 num_frames,
5511 num_frames_with_source);
5512 ++num_thread_infos_dumped;
5513 }
5514 }
5515 return num_thread_infos_dumped;
5516}
5517
Greg Claytona9f40ad2012-02-22 04:37:26 +00005518void
5519Process::AddInvalidMemoryRegion (const LoadRange &region)
5520{
5521 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5522}
5523
5524bool
5525Process::RemoveInvalidMemoryRange (const LoadRange &region)
5526{
5527 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5528}
5529
Jim Ingham372787f2012-04-07 00:00:41 +00005530void
5531Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5532{
5533 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5534}
5535
5536bool
5537Process::RunPreResumeActions ()
5538{
5539 bool result = true;
5540 while (!m_pre_resume_actions.empty())
5541 {
5542 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5543 m_pre_resume_actions.pop_back();
5544 bool this_result = action.callback (action.baton);
5545 if (result == true) result = this_result;
5546 }
5547 return result;
5548}
5549
5550void
5551Process::ClearPreResumeActions ()
5552{
5553 m_pre_resume_actions.clear();
5554}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005555
Greg Claytonfa559e52012-05-18 02:38:05 +00005556void
5557Process::Flush ()
5558{
5559 m_thread_list.Flush();
5560}
Greg Clayton90ba8112012-12-05 00:16:59 +00005561
5562void
5563Process::DidExec ()
5564{
5565 Target &target = GetTarget();
5566 target.CleanupProcess ();
5567 ModuleList unloaded_modules (target.GetImages());
5568 target.ModulesDidUnload (unloaded_modules);
5569 target.GetSectionLoadList().Clear();
5570 m_dynamic_checkers_ap.reset();
5571 m_abi_sp.reset();
5572 m_os_ap.reset();
5573 m_dyld_ap.reset();
5574 m_image_tokens.clear();
5575 m_allocated_memory_cache.Clear();
5576 m_language_runtimes.clear();
5577 DoDidExec();
5578 CompleteAttach ();
5579}