blob: a5ef629e5eb202f9da4d10785ad8bf28a64a1440 [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"
Jim Ingham1460e4b2014-01-10 23:46:59 +000024#include "lldb/Symbol/Symbol.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Core/PluginManager.h"
26#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000027#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000028#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029#include "lldb/Host/Host.h"
30#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000031#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000032#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000033#include "lldb/Target/LanguageRuntime.h"
34#include "lldb/Target/CPPLanguageRuntime.h"
35#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000036#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000038#include "lldb/Target/StopInfo.h"
Jason Molendaeef51062013-11-05 03:57:19 +000039#include "lldb/Target/SystemRuntime.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040#include "lldb/Target/Target.h"
41#include "lldb/Target/TargetList.h"
42#include "lldb/Target/Thread.h"
43#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000044#include "lldb/Target/ThreadPlanBase.h"
Jim Ingham1460e4b2014-01-10 23:46:59 +000045#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046
Charles Davis510938e2013-08-27 05:04:57 +000047#ifndef LLDB_DISABLE_POSIX
48#include <spawn.h>
49#endif
50
Chris Lattner30fdc8d2010-06-08 16:52:24 +000051using namespace lldb;
52using namespace lldb_private;
53
Greg Clayton67cc0632012-08-22 17:17:09 +000054
55// Comment out line below to disable memory caching, overriding the process setting
56// target.process.disable-memory-cache
57#define ENABLE_MEMORY_CACHING
58
59#ifdef ENABLE_MEMORY_CACHING
60#define DISABLE_MEM_CACHE_DEFAULT false
61#else
62#define DISABLE_MEM_CACHE_DEFAULT true
63#endif
64
65class ProcessOptionValueProperties : public OptionValueProperties
66{
67public:
68 ProcessOptionValueProperties (const ConstString &name) :
69 OptionValueProperties (name)
70 {
71 }
72
73 // This constructor is used when creating ProcessOptionValueProperties when it
74 // is part of a new lldb_private::Process instance. It will copy all current
75 // global property values as needed
76 ProcessOptionValueProperties (ProcessProperties *global_properties) :
77 OptionValueProperties(*global_properties->GetValueProperties())
78 {
79 }
80
81 virtual const Property *
82 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
83 {
84 // When gettings the value for a key from the process options, we will always
85 // try and grab the setting from the current process if there is one. Else we just
86 // use the one from this instance.
87 if (exe_ctx)
88 {
89 Process *process = exe_ctx->GetProcessPtr();
90 if (process)
91 {
92 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
93 if (this != instance_properties)
94 return instance_properties->ProtectedGetPropertyAtIndex (idx);
95 }
96 }
97 return ProtectedGetPropertyAtIndex (idx);
98 }
99};
100
101static PropertyDefinition
102g_properties[] =
103{
104 { "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 +0000105 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
106 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Inghamafc1b122013-01-31 19:48:57 +0000107 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
108 { "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 +0000109 { "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 +0000110 { "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 +0000111 { "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 +0000112 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
113};
114
115enum {
116 ePropertyDisableMemCache,
Greg Claytonc9d645d2012-10-18 22:40:37 +0000117 ePropertyExtraStartCommand,
Jim Ingham184e9812013-01-15 02:47:48 +0000118 ePropertyIgnoreBreakpointsInExpressions,
119 ePropertyUnwindOnErrorInExpressions,
Jim Ingham29950772013-01-26 02:19:28 +0000120 ePropertyPythonOSPluginPath,
Jim Inghamacff8952013-05-02 00:27:30 +0000121 ePropertyStopOnSharedLibraryEvents,
122 ePropertyDetachKeepsStopped
Greg Clayton67cc0632012-08-22 17:17:09 +0000123};
124
125ProcessProperties::ProcessProperties (bool is_global) :
126 Properties ()
127{
128 if (is_global)
129 {
130 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
131 m_collection_sp->Initialize(g_properties);
132 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham29950772013-01-26 02:19:28 +0000133 ConstString("Settings specific to threads."),
Greg Clayton67cc0632012-08-22 17:17:09 +0000134 true,
135 Thread::GetGlobalProperties()->GetValueProperties());
136 }
137 else
138 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
139}
140
141ProcessProperties::~ProcessProperties()
142{
143}
144
145bool
146ProcessProperties::GetDisableMemoryCache() const
147{
148 const uint32_t idx = ePropertyDisableMemCache;
149 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
150}
151
152Args
153ProcessProperties::GetExtraStartupCommands () const
154{
155 Args args;
156 const uint32_t idx = ePropertyExtraStartCommand;
157 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
158 return args;
159}
160
161void
162ProcessProperties::SetExtraStartupCommands (const Args &args)
163{
164 const uint32_t idx = ePropertyExtraStartCommand;
165 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
166}
167
Greg Claytonc9d645d2012-10-18 22:40:37 +0000168FileSpec
169ProcessProperties::GetPythonOSPluginPath () const
170{
171 const uint32_t idx = ePropertyPythonOSPluginPath;
172 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
173}
174
175void
176ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
177{
178 const uint32_t idx = ePropertyPythonOSPluginPath;
179 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
180}
181
Jim Ingham184e9812013-01-15 02:47:48 +0000182
183bool
184ProcessProperties::GetIgnoreBreakpointsInExpressions () const
185{
186 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
187 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
188}
189
190void
191ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
192{
193 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
194 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
195}
196
197bool
198ProcessProperties::GetUnwindOnErrorInExpressions () const
199{
200 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
201 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
202}
203
204void
205ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
206{
207 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
208 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
209}
210
Jim Ingham29950772013-01-26 02:19:28 +0000211bool
212ProcessProperties::GetStopOnSharedLibraryEvents () const
213{
214 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
215 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
216}
217
218void
219ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
220{
221 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
222 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
223}
224
Jim Inghamacff8952013-05-02 00:27:30 +0000225bool
226ProcessProperties::GetDetachKeepsStopped () const
227{
228 const uint32_t idx = ePropertyDetachKeepsStopped;
229 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
230}
231
232void
233ProcessProperties::SetDetachKeepsStopped (bool stop)
234{
235 const uint32_t idx = ePropertyDetachKeepsStopped;
236 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
237}
238
Greg Clayton32e0a752011-03-30 18:16:51 +0000239void
Greg Clayton8b82f082011-04-12 05:54:46 +0000240ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000241{
242 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000243 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000244 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000245
246 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malead01b2952012-11-29 21:49:15 +0000247 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000248
249 if (m_executable)
250 {
251 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
252 s.PutCString (" file = ");
253 m_executable.Dump(&s);
254 s.EOL();
255 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000256 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000257 if (argc > 0)
258 {
259 for (uint32_t i=0; i<argc; i++)
260 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000261 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000262 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000263 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000264 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000265 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000266 }
267 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000268
269 const uint32_t envc = m_environment.GetArgumentCount();
270 if (envc > 0)
271 {
272 for (uint32_t i=0; i<envc; i++)
273 {
274 const char *env = m_environment.GetArgumentAtIndex(i);
275 if (i < 10)
276 s.Printf (" env[%u] = %s\n", i, env);
277 else
278 s.Printf ("env[%u] = %s\n", i, env);
279 }
280 }
281
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000282 if (m_arch.IsValid())
283 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
284
Greg Clayton8b82f082011-04-12 05:54:46 +0000285 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000286 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000287 cstr = platform->GetUserName (m_uid);
288 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000289 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000290 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000291 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000292 cstr = platform->GetGroupName (m_gid);
293 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000294 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000295 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000296 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000297 cstr = platform->GetUserName (m_euid);
298 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000299 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000300 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000301 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000302 cstr = platform->GetGroupName (m_egid);
303 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000304 }
305}
306
307void
Greg Clayton8b82f082011-04-12 05:54:46 +0000308ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000309{
Greg Clayton8b82f082011-04-12 05:54:46 +0000310 const char *label;
311 if (show_args || verbose)
312 label = "ARGUMENTS";
313 else
314 label = "NAME";
315
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000316 if (verbose)
317 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000318 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000319 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
320 }
321 else
322 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000323 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000324 s.PutCString ("====== ====== ========== ======= ============================\n");
325 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000326}
327
328void
Greg Clayton8b82f082011-04-12 05:54:46 +0000329ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000330{
331 if (m_pid != LLDB_INVALID_PROCESS_ID)
332 {
333 const char *cstr;
Daniel Malead01b2952012-11-29 21:49:15 +0000334 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000335
Greg Clayton32e0a752011-03-30 18:16:51 +0000336
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000337 if (verbose)
338 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000339 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000340 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
341 s.Printf ("%-10s ", cstr);
342 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000343 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000344
Greg Clayton8b82f082011-04-12 05:54:46 +0000345 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000346 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
347 s.Printf ("%-10s ", cstr);
348 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000349 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000350
Greg Clayton8b82f082011-04-12 05:54:46 +0000351 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000352 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
353 s.Printf ("%-10s ", cstr);
354 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000355 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000356
Greg Clayton8b82f082011-04-12 05:54:46 +0000357 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000358 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
359 s.Printf ("%-10s ", cstr);
360 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000361 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000362 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
363 }
364 else
365 {
Jason Molendafd54b362011-09-20 21:44:10 +0000366 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000367 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000368 (int)m_arch.GetTriple().getArchName().size(),
369 m_arch.GetTriple().getArchName().data());
370 }
371
Greg Clayton8b82f082011-04-12 05:54:46 +0000372 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000373 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000374 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000375 if (argc > 0)
376 {
377 for (uint32_t i=0; i<argc; i++)
378 {
379 if (i > 0)
380 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000381 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000382 }
383 }
384 }
385 else
386 {
387 s.PutCString (GetName());
388 }
389
390 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000391 }
392}
393
Greg Clayton8b82f082011-04-12 05:54:46 +0000394
395void
Greg Clayton45392552012-10-17 22:57:12 +0000396ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton982c9762011-11-03 21:22:33 +0000397{
398 m_arguments.SetArguments (argv);
399
400 // Is the first argument the executable?
401 if (first_arg_is_executable)
402 {
403 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
404 if (first_arg)
405 {
406 // Yes the first argument is an executable, set it as the executable
407 // in the launch options. Don't resolve the file path as the path
408 // could be a remote platform path
409 const bool resolve = false;
410 m_executable.SetFile(first_arg, resolve);
Greg Clayton982c9762011-11-03 21:22:33 +0000411 }
412 }
413}
414void
Greg Clayton45392552012-10-17 22:57:12 +0000415ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Clayton8b82f082011-04-12 05:54:46 +0000416{
417 // Copy all arguments
418 m_arguments = args;
419
420 // Is the first argument the executable?
421 if (first_arg_is_executable)
422 {
Greg Clayton982c9762011-11-03 21:22:33 +0000423 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000424 if (first_arg)
425 {
426 // Yes the first argument is an executable, set it as the executable
427 // in the launch options. Don't resolve the file path as the path
428 // could be a remote platform path
429 const bool resolve = false;
430 m_executable.SetFile(first_arg, resolve);
Greg Clayton8b82f082011-04-12 05:54:46 +0000431 }
432 }
433}
434
Greg Clayton1d885962011-11-08 02:43:13 +0000435void
Greg Claytonee95ed52011-11-17 22:14:31 +0000436ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-11-08 02:43:13 +0000437{
438 // If notthing was specified, then check the process for any default
439 // settings that were set with "settings set"
440 if (m_file_actions.empty())
441 {
Greg Clayton1d885962011-11-08 02:43:13 +0000442 if (m_flags.Test(eLaunchFlagDisableSTDIO))
443 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000444 AppendSuppressFileAction (STDIN_FILENO , true, false);
445 AppendSuppressFileAction (STDOUT_FILENO, false, true);
446 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000447 }
448 else
449 {
450 // Check for any values that might have gotten set with any of:
451 // (lldb) settings set target.input-path
452 // (lldb) settings set target.output-path
453 // (lldb) settings set target.error-path
Greg Clayton67cc0632012-08-22 17:17:09 +0000454 FileSpec in_path;
455 FileSpec out_path;
456 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000457 if (target)
458 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000459 in_path = target->GetStandardInputPath();
460 out_path = target->GetStandardOutputPath();
461 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000462 }
463
Greg Clayton67cc0632012-08-22 17:17:09 +0000464 if (in_path || out_path || err_path)
465 {
466 char path[PATH_MAX];
467 if (in_path && in_path.GetPath(path, sizeof(path)))
468 AppendOpenFileAction(STDIN_FILENO, path, true, false);
469
470 if (out_path && out_path.GetPath(path, sizeof(path)))
471 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
472
473 if (err_path && err_path.GetPath(path, sizeof(path)))
474 AppendOpenFileAction(STDERR_FILENO, path, false, true);
475 }
476 else if (default_to_use_pty)
Greg Claytonee95ed52011-11-17 22:14:31 +0000477 {
478 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000479 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000480 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
481 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
482 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
483 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000484 }
485 }
Greg Clayton1d885962011-11-08 02:43:13 +0000486 }
487 }
488}
489
Greg Clayton144f3a92011-11-15 03:53:30 +0000490
491bool
Greg Claytond1cf11a2012-04-14 01:42:46 +0000492ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
493 bool localhost,
494 bool will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +0000495 bool first_arg_is_full_shell_command,
496 int32_t num_resumes)
Greg Clayton144f3a92011-11-15 03:53:30 +0000497{
498 error.Clear();
499
500 if (GetFlags().Test (eLaunchFlagLaunchInShell))
501 {
502 const char *shell_executable = GetShell();
503 if (shell_executable)
504 {
505 char shell_resolved_path[PATH_MAX];
506
507 if (localhost)
508 {
509 FileSpec shell_filespec (shell_executable, true);
510
511 if (!shell_filespec.Exists())
512 {
513 // Resolve the path in case we just got "bash", "sh" or "tcsh"
514 if (!shell_filespec.ResolveExecutableLocation ())
515 {
516 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
517 return false;
518 }
519 }
520 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
521 shell_executable = shell_resolved_path;
522 }
523
Greg Clayton45392552012-10-17 22:57:12 +0000524 const char **argv = GetArguments().GetConstArgumentVector ();
525 if (argv == NULL || argv[0] == NULL)
526 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000527 Args shell_arguments;
528 std::string safe_arg;
529 shell_arguments.AppendArgument (shell_executable);
Greg Clayton144f3a92011-11-15 03:53:30 +0000530 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000531 StreamString shell_command;
532 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000533 {
Greg Clayton45392552012-10-17 22:57:12 +0000534 // Add a modified PATH environment variable in case argv[0]
535 // is a relative path
536 const char *argv0 = argv[0];
537 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
538 {
539 // We have a relative path to our executable which may not work if
540 // we just try to run "a.out" (without it being converted to "./a.out")
541 const char *working_dir = GetWorkingDirectory();
Greg Clayton8938f8d2013-02-14 03:54:39 +0000542 // Be sure to put quotes around PATH's value in case any paths have spaces...
543 std::string new_path("PATH=\"");
Greg Clayton45392552012-10-17 22:57:12 +0000544 const size_t empty_path_len = new_path.size();
545
546 if (working_dir && working_dir[0])
547 {
548 new_path += working_dir;
549 }
550 else
551 {
552 char current_working_dir[PATH_MAX];
553 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
554 if (cwd && cwd[0])
555 new_path += cwd;
556 }
557 const char *curr_path = getenv("PATH");
558 if (curr_path)
559 {
560 if (new_path.size() > empty_path_len)
561 new_path += ':';
562 new_path += curr_path;
563 }
Greg Clayton8938f8d2013-02-14 03:54:39 +0000564 new_path += "\" ";
Greg Clayton45392552012-10-17 22:57:12 +0000565 shell_command.PutCString(new_path.c_str());
566 }
567
Greg Claytond1cf11a2012-04-14 01:42:46 +0000568 shell_command.PutCString ("exec");
Greg Clayton45392552012-10-17 22:57:12 +0000569
Greg Clayton45392552012-10-17 22:57:12 +0000570 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Claytond1cf11a2012-04-14 01:42:46 +0000571 if (GetArchitecture().IsValid())
572 {
573 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton45392552012-10-17 22:57:12 +0000574 // Set the resume count to 2:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000575 // 1 - stop in shell
576 // 2 - stop in /usr/bin/arch
577 // 3 - then we will stop in our program
Jim Inghamdf0ae222013-09-10 02:09:47 +0000578 SetResumeCount(num_resumes + 1);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000579 }
580 else
581 {
Greg Clayton45392552012-10-17 22:57:12 +0000582 // Set the resume count to 1:
Greg Claytond1cf11a2012-04-14 01:42:46 +0000583 // 1 - stop in shell
584 // 2 - then we will stop in our program
Jim Inghamdf0ae222013-09-10 02:09:47 +0000585 SetResumeCount(num_resumes);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000586 }
Greg Clayton144f3a92011-11-15 03:53:30 +0000587 }
Greg Clayton45392552012-10-17 22:57:12 +0000588
589 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000590 {
Greg Clayton45392552012-10-17 22:57:12 +0000591 // There should only be one argument that is the shell command itself to be used as is
592 if (argv[0] && !argv[1])
593 shell_command.Printf("%s", argv[0]);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000594 else
Greg Clayton45392552012-10-17 22:57:12 +0000595 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000596 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000597 else
598 {
Greg Clayton45392552012-10-17 22:57:12 +0000599 for (size_t i=0; argv[i] != NULL; ++i)
600 {
601 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
602 shell_command.Printf(" %s", arg);
603 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000604 }
Greg Clayton45392552012-10-17 22:57:12 +0000605 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton144f3a92011-11-15 03:53:30 +0000606 m_executable.SetFile(shell_executable, false);
607 m_arguments = shell_arguments;
608 return true;
609 }
610 else
611 {
612 error.SetErrorString ("invalid shell path");
613 }
614 }
615 else
616 {
617 error.SetErrorString ("not launching in shell");
618 }
619 return false;
620}
621
622
Greg Clayton32e0a752011-03-30 18:16:51 +0000623bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000624ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
625{
626 if ((read || write) && fd >= 0 && path && path[0])
627 {
628 m_action = eFileActionOpen;
629 m_fd = fd;
630 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000631 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000632 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000633 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000634 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000635 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000636 m_path.assign (path);
637 return true;
638 }
639 else
640 {
641 Clear();
642 }
643 return false;
644}
645
646bool
647ProcessLaunchInfo::FileAction::Close (int fd)
648{
649 Clear();
650 if (fd >= 0)
651 {
652 m_action = eFileActionClose;
653 m_fd = fd;
654 }
655 return m_fd >= 0;
656}
657
658
659bool
660ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
661{
662 Clear();
663 if (fd >= 0 && dup_fd >= 0)
664 {
665 m_action = eFileActionDuplicate;
666 m_fd = fd;
667 m_arg = dup_fd;
668 }
669 return m_fd >= 0;
670}
671
672
673
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000674#ifndef LLDB_DISABLE_POSIX
Greg Clayton8b82f082011-04-12 05:54:46 +0000675bool
Charles Davis510938e2013-08-27 05:04:57 +0000676ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (void *_file_actions,
Greg Clayton8b82f082011-04-12 05:54:46 +0000677 const FileAction *info,
678 Log *log,
679 Error& error)
680{
681 if (info == NULL)
682 return false;
683
Charles Davis510938e2013-08-27 05:04:57 +0000684 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
685
Greg Clayton8b82f082011-04-12 05:54:46 +0000686 switch (info->m_action)
687 {
688 case eFileActionNone:
689 error.Clear();
690 break;
691
692 case eFileActionClose:
693 if (info->m_fd == -1)
694 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
695 else
696 {
697 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
698 eErrorTypePOSIX);
699 if (log && (error.Fail() || log))
700 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
701 file_actions, info->m_fd);
702 }
703 break;
704
705 case eFileActionDuplicate:
706 if (info->m_fd == -1)
707 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
708 else if (info->m_arg == -1)
709 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
710 else
711 {
712 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
713 eErrorTypePOSIX);
714 if (log && (error.Fail() || log))
715 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
716 file_actions, info->m_fd, info->m_arg);
717 }
718 break;
719
720 case eFileActionOpen:
721 if (info->m_fd == -1)
722 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
723 else
724 {
725 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000726
Greg Clayton8b82f082011-04-12 05:54:46 +0000727 mode_t mode = 0;
728
Greg Clayton144f3a92011-11-15 03:53:30 +0000729 if (oflag & O_CREAT)
730 mode = 0640;
731
Greg Clayton8b82f082011-04-12 05:54:46 +0000732 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
733 info->m_fd,
734 info->m_path.c_str(),
735 oflag,
736 mode),
737 eErrorTypePOSIX);
738 if (error.Fail() || log)
739 error.PutToLog(log,
740 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
741 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
742 }
743 break;
Greg Clayton8b82f082011-04-12 05:54:46 +0000744 }
745 return error.Success();
746}
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000747#endif
Greg Clayton8b82f082011-04-12 05:54:46 +0000748
749Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000750ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000751{
752 Error error;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000753 const int short_option = m_getopt_table[option_idx].val;
Greg Clayton8b82f082011-04-12 05:54:46 +0000754
755 switch (short_option)
756 {
757 case 's': // Stop at program entry point
758 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
759 break;
760
Greg Clayton8b82f082011-04-12 05:54:46 +0000761 case 'i': // STDIN for read only
762 {
763 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000764 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000765 launch_info.AppendFileAction (action);
766 }
767 break;
768
769 case 'o': // Open STDOUT for write only
770 {
771 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000772 if (action.Open (STDOUT_FILENO, option_arg, false, true))
773 launch_info.AppendFileAction (action);
774 }
775 break;
776
777 case 'e': // STDERR for write only
778 {
779 ProcessLaunchInfo::FileAction action;
780 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000781 launch_info.AppendFileAction (action);
782 }
783 break;
784
Greg Clayton9845a8d2012-03-06 04:01:04 +0000785
Greg Clayton8b82f082011-04-12 05:54:46 +0000786 case 'p': // Process plug-in name
787 launch_info.SetProcessPluginName (option_arg);
788 break;
789
790 case 'n': // Disable STDIO
791 {
792 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000793 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000794 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000795 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000796 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000797 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000798 launch_info.AppendFileAction (action);
799 }
800 break;
801
802 case 'w':
803 launch_info.SetWorkingDirectory (option_arg);
804 break;
805
806 case 't': // Open process in new terminal window
807 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
808 break;
809
810 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000811 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
812 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000813 break;
814
815 case 'A':
816 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
817 break;
818
Greg Clayton982c9762011-11-03 21:22:33 +0000819 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000820 if (option_arg && option_arg[0])
821 launch_info.SetShell (option_arg);
822 else
Ed Masteb8ca4a22013-09-03 23:04:53 +0000823 launch_info.SetShell (LLDB_DEFAULT_SHELL);
Greg Clayton982c9762011-11-03 21:22:33 +0000824 break;
825
Greg Clayton8b82f082011-04-12 05:54:46 +0000826 case 'v':
827 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
828 break;
829
830 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000831 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000832 break;
833
834 }
835 return error;
836}
837
838OptionDefinition
839ProcessLaunchCommandOptions::g_option_table[] =
840{
Virgile Belloe2607b52013-09-05 16:42:23 +0000841{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
842{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
843{ LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
844{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', OptionParser::eRequiredArgument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
845{ LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
846{ LLDB_OPT_SET_ALL, false, "environment", 'v', OptionParser::eRequiredArgument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value string (--environment NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
847{ LLDB_OPT_SET_ALL, false, "shell", 'c', OptionParser::eOptionalArgument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000848
Virgile Belloe2607b52013-09-05 16:42:23 +0000849{ LLDB_OPT_SET_1 , false, "stdin", 'i', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
850{ LLDB_OPT_SET_1 , false, "stdout", 'o', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
851{ LLDB_OPT_SET_1 , false, "stderr", 'e', OptionParser::eRequiredArgument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000852
Virgile Belloe2607b52013-09-05 16:42:23 +0000853{ LLDB_OPT_SET_2 , false, "tty", 't', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000854
Virgile Belloe2607b52013-09-05 16:42:23 +0000855{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', OptionParser::eNoArgument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000856
857{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
858};
859
860
861
862bool
863ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000864{
865 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
866 return true;
867 const char *match_name = m_match_info.GetName();
868 if (!match_name)
869 return true;
870
871 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
872}
873
874bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000875ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000876{
877 if (!NameMatches (proc_info.GetName()))
878 return false;
879
880 if (m_match_info.ProcessIDIsValid() &&
881 m_match_info.GetProcessID() != proc_info.GetProcessID())
882 return false;
883
884 if (m_match_info.ParentProcessIDIsValid() &&
885 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
886 return false;
887
Greg Clayton8b82f082011-04-12 05:54:46 +0000888 if (m_match_info.UserIDIsValid () &&
889 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000890 return false;
891
Greg Clayton8b82f082011-04-12 05:54:46 +0000892 if (m_match_info.GroupIDIsValid () &&
893 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000894 return false;
895
896 if (m_match_info.EffectiveUserIDIsValid () &&
897 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
898 return false;
899
900 if (m_match_info.EffectiveGroupIDIsValid () &&
901 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
902 return false;
903
904 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callananbf4b7be2012-12-13 22:07:14 +0000905 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton32e0a752011-03-30 18:16:51 +0000906 return false;
907 return true;
908}
909
910bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000911ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000912{
913 if (m_name_match_type != eNameMatchIgnore)
914 return false;
915
916 if (m_match_info.ProcessIDIsValid())
917 return false;
918
919 if (m_match_info.ParentProcessIDIsValid())
920 return false;
921
Greg Clayton8b82f082011-04-12 05:54:46 +0000922 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000923 return false;
924
Greg Clayton8b82f082011-04-12 05:54:46 +0000925 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000926 return false;
927
928 if (m_match_info.EffectiveUserIDIsValid ())
929 return false;
930
931 if (m_match_info.EffectiveGroupIDIsValid ())
932 return false;
933
934 if (m_match_info.GetArchitecture().IsValid())
935 return false;
936
937 if (m_match_all_users)
938 return false;
939
940 return true;
941
942}
943
944void
Greg Clayton8b82f082011-04-12 05:54:46 +0000945ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000946{
947 m_match_info.Clear();
948 m_name_match_type = eNameMatchIgnore;
949 m_match_all_users = false;
950}
Greg Clayton58be07b2011-01-07 06:08:19 +0000951
Greg Claytonc3776bf2012-02-09 06:16:32 +0000952ProcessSP
953Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000954{
Greg Clayton949e8222013-01-16 17:29:04 +0000955 static uint32_t g_process_unique_id = 0;
956
Greg Claytonc3776bf2012-02-09 06:16:32 +0000957 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000958 ProcessCreateInstance create_callback = NULL;
959 if (plugin_name)
960 {
Greg Clayton57abc5d2013-05-10 21:47:16 +0000961 ConstString const_plugin_name(plugin_name);
962 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (const_plugin_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000963 if (create_callback)
964 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000965 process_sp = create_callback(target, listener, crash_file_path);
966 if (process_sp)
967 {
Greg Clayton949e8222013-01-16 17:29:04 +0000968 if (process_sp->CanDebug(target, true))
969 {
970 process_sp->m_process_unique_id = ++g_process_unique_id;
971 }
972 else
Greg Claytonc3776bf2012-02-09 06:16:32 +0000973 process_sp.reset();
974 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000975 }
976 }
977 else
978 {
Greg Claytonc982c762010-07-09 20:39:50 +0000979 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000980 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000981 process_sp = create_callback(target, listener, crash_file_path);
982 if (process_sp)
983 {
Greg Clayton949e8222013-01-16 17:29:04 +0000984 if (process_sp->CanDebug(target, false))
985 {
986 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Claytonc3776bf2012-02-09 06:16:32 +0000987 break;
Greg Clayton949e8222013-01-16 17:29:04 +0000988 }
989 else
990 process_sp.reset();
Greg Claytonc3776bf2012-02-09 06:16:32 +0000991 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000992 }
993 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000994 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000995}
996
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000997ConstString &
998Process::GetStaticBroadcasterClass ()
999{
1000 static ConstString class_name ("lldb.process");
1001 return class_name;
1002}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001003
1004//----------------------------------------------------------------------
1005// Process constructor
1006//----------------------------------------------------------------------
1007Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +00001008 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001009 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001010 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001011 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001012 m_public_state (eStateUnloaded),
1013 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001014 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
1015 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016 m_private_state_listener ("lldb.process.internal_state_listener"),
1017 m_private_state_control_wait(),
1018 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +00001019 m_mod_id (),
Greg Clayton949e8222013-01-16 17:29:04 +00001020 m_process_unique_id(0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021 m_thread_index_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +00001022 m_queue_index_id (0),
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001023 m_thread_id_to_index_id_map (),
Jason Molenda5e8dce42013-12-13 00:29:16 +00001024 m_queue_id_to_index_id_map (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001025 m_exit_status (-1),
1026 m_exit_string (),
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001027 m_thread_mutex (Mutex::eMutexTypeRecursive),
1028 m_thread_list_real (this),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001029 m_thread_list (this),
Jason Molenda864f1cc2013-11-11 05:20:44 +00001030 m_extended_thread_list (this),
Jason Molenda4ff13262013-11-20 00:31:38 +00001031 m_extended_thread_stop_id (0),
Jason Molenda5e8dce42013-12-13 00:29:16 +00001032 m_queue_list (this),
1033 m_queue_list_stop_id (0),
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001035 m_image_tokens (),
1036 m_listener (listener),
1037 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001038 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001039 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001040 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +00001041 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +00001042 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +00001043 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +00001044 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +00001045 m_stderr_data (),
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001046 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1047 m_profile_data (),
Greg Claytond495c532011-05-17 03:37:42 +00001048 m_memory_cache (*this),
1049 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +00001050 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +00001051 m_next_event_action_ap(),
Greg Clayton96249852013-04-18 16:57:27 +00001052 m_public_run_lock (),
Greg Clayton96249852013-04-18 16:57:27 +00001053 m_private_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +00001054 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001055 m_finalize_called(false),
Greg Claytonf9b57b92013-05-10 23:48:10 +00001056 m_clear_thread_plans_on_stop (false),
Jim Ingham1460e4b2014-01-10 23:46:59 +00001057 m_force_next_event_delivery(false),
Jim Ingham0161b492013-02-09 01:29:05 +00001058 m_last_broadcast_state (eStateInvalid),
Jason Molenda69b6b632013-03-05 03:33:59 +00001059 m_destroy_in_process (false),
1060 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001061{
Jim Ingham4bddaeb2012-02-16 06:50:00 +00001062 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +00001063
Greg Clayton5160ce52013-03-27 23:08:40 +00001064 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001065 if (log)
1066 log->Printf ("%p Process::Process()", this);
1067
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001068 SetEventName (eBroadcastBitStateChanged, "state-changed");
1069 SetEventName (eBroadcastBitInterrupt, "interrupt");
1070 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1071 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001072 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Claytoncfd1ace2010-10-31 03:01:06 +00001073
Greg Clayton35a4cc52012-10-29 20:52:08 +00001074 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1075 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1076 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1077
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078 listener.StartListeningForEvents (this,
1079 eBroadcastBitStateChanged |
1080 eBroadcastBitInterrupt |
1081 eBroadcastBitSTDOUT |
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001082 eBroadcastBitSTDERR |
1083 eBroadcastBitProfileData);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084
1085 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001086 eBroadcastBitStateChanged |
1087 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001088
1089 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1090 eBroadcastInternalStateControlStop |
1091 eBroadcastInternalStateControlPause |
1092 eBroadcastInternalStateControlResume);
1093}
1094
1095//----------------------------------------------------------------------
1096// Destructor
1097//----------------------------------------------------------------------
1098Process::~Process()
1099{
Greg Clayton5160ce52013-03-27 23:08:40 +00001100 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001101 if (log)
1102 log->Printf ("%p Process::~Process()", this);
1103 StopPrivateStateThread();
1104}
1105
Greg Clayton67cc0632012-08-22 17:17:09 +00001106const ProcessPropertiesSP &
1107Process::GetGlobalProperties()
1108{
1109 static ProcessPropertiesSP g_settings_sp;
1110 if (!g_settings_sp)
1111 g_settings_sp.reset (new ProcessProperties (true));
1112 return g_settings_sp;
1113}
1114
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115void
1116Process::Finalize()
1117{
Greg Claytone24c4ac2011-11-17 04:46:02 +00001118 switch (GetPrivateState())
1119 {
1120 case eStateConnected:
1121 case eStateAttaching:
1122 case eStateLaunching:
1123 case eStateStopped:
1124 case eStateRunning:
1125 case eStateStepping:
1126 case eStateCrashed:
1127 case eStateSuspended:
1128 if (GetShouldDetach())
Jim Inghamacff8952013-05-02 00:27:30 +00001129 {
1130 // FIXME: This will have to be a process setting:
1131 bool keep_stopped = false;
1132 Detach(keep_stopped);
1133 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00001134 else
1135 Destroy();
1136 break;
1137
1138 case eStateInvalid:
1139 case eStateUnloaded:
1140 case eStateDetached:
1141 case eStateExited:
1142 break;
1143 }
1144
Greg Clayton1ed54f52011-10-01 00:45:15 +00001145 // Clear our broadcaster before we proceed with destroying
1146 Broadcaster::Clear();
1147
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001148 // Do any cleanup needed prior to being destructed... Subclasses
1149 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001150
1151 // We need to destroy the loader before the derived Process class gets destroyed
1152 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001153 m_dynamic_checkers_ap.reset();
1154 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001155 m_os_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00001156 m_system_runtime_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001157 m_dyld_ap.reset();
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001158 m_thread_list_real.Destroy();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001159 m_thread_list.Destroy();
Jason Molenda864f1cc2013-11-11 05:20:44 +00001160 m_extended_thread_list.Destroy();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001161 m_queue_list.Clear();
1162 m_queue_list_stop_id = 0;
Greg Clayton894f82f2012-01-20 23:08:34 +00001163 std::vector<Notifications> empty_notifications;
1164 m_notifications.swap(empty_notifications);
1165 m_image_tokens.clear();
1166 m_memory_cache.Clear();
1167 m_allocated_memory_cache.Clear();
1168 m_language_runtimes.clear();
1169 m_next_event_action_ap.reset();
Greg Clayton35a4cc52012-10-29 20:52:08 +00001170//#ifdef LLDB_CONFIGURATION_DEBUG
1171// StreamFile s(stdout, false);
1172// EventSP event_sp;
1173// while (m_private_state_listener.GetNextEvent(event_sp))
1174// {
1175// event_sp->Dump (&s);
1176// s.EOL();
1177// }
1178//#endif
1179 // We have to be very careful here as the m_private_state_listener might
1180 // contain events that have ProcessSP values in them which can keep this
1181 // process around forever. These events need to be cleared out.
1182 m_private_state_listener.Clear();
Ed Maste64fad602013-07-29 20:58:06 +00001183 m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
1184 m_public_run_lock.SetStopped();
1185 m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
1186 m_private_run_lock.SetStopped();
Jim Ingham4fc6cb92012-08-22 21:34:33 +00001187 m_finalize_called = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001188}
1189
1190void
1191Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1192{
1193 m_notifications.push_back(callbacks);
1194 if (callbacks.initialize != NULL)
1195 callbacks.initialize (callbacks.baton, this);
1196}
1197
1198bool
1199Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1200{
1201 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1202 for (pos = m_notifications.begin(); pos != end; ++pos)
1203 {
1204 if (pos->baton == callbacks.baton &&
1205 pos->initialize == callbacks.initialize &&
1206 pos->process_state_changed == callbacks.process_state_changed)
1207 {
1208 m_notifications.erase(pos);
1209 return true;
1210 }
1211 }
1212 return false;
1213}
1214
1215void
1216Process::SynchronouslyNotifyStateChanged (StateType state)
1217{
1218 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1219 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1220 {
1221 if (notification_pos->process_state_changed)
1222 notification_pos->process_state_changed (notification_pos->baton, this, state);
1223 }
1224}
1225
1226// FIXME: We need to do some work on events before the general Listener sees them.
1227// For instance if we are continuing from a breakpoint, we need to ensure that we do
1228// the little "insert real insn, step & stop" trick. But we can't do that when the
1229// event is delivered by the broadcaster - since that is done on the thread that is
1230// waiting for new events, so if we needed more than one event for our handling, we would
1231// stall. So instead we do it when we fetch the event off of the queue.
1232//
1233
1234StateType
1235Process::GetNextEvent (EventSP &event_sp)
1236{
1237 StateType state = eStateInvalid;
1238
1239 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1240 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1241
1242 return state;
1243}
1244
1245
1246StateType
Daniel Malea9e9919f2013-10-09 16:56:28 +00001247Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr, bool wait_always)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001248{
Jim Ingham4b536182011-08-09 02:12:22 +00001249 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1250 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1251 // on the event.
Greg Clayton85fb1b92012-09-11 02:33:37 +00001252 if (event_sp_ptr)
1253 event_sp_ptr->reset();
Jim Ingham4b536182011-08-09 02:12:22 +00001254 StateType state = GetState();
1255 // If we are exited or detached, we won't ever get back to any
1256 // other valid state...
1257 if (state == eStateDetached || state == eStateExited)
1258 return state;
1259
Daniel Malea9e9919f2013-10-09 16:56:28 +00001260 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1261 if (log)
1262 log->Printf ("Process::%s (timeout = %p)", __FUNCTION__, timeout);
1263
1264 if (!wait_always &&
1265 StateIsStoppedState(state, true) &&
1266 StateIsStoppedState(GetPrivateState(), true)) {
1267 if (log)
1268 log->Printf("Process::%s returning without waiting for events; process private and public states are already 'stopped'.",
1269 __FUNCTION__);
1270 return state;
1271 }
1272
Jim Ingham4b536182011-08-09 02:12:22 +00001273 while (state != eStateInvalid)
1274 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00001275 EventSP event_sp;
Jim Ingham4b536182011-08-09 02:12:22 +00001276 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Clayton85fb1b92012-09-11 02:33:37 +00001277 if (event_sp_ptr && event_sp)
1278 *event_sp_ptr = event_sp;
1279
Jim Ingham4b536182011-08-09 02:12:22 +00001280 switch (state)
1281 {
1282 case eStateCrashed:
1283 case eStateDetached:
1284 case eStateExited:
1285 case eStateUnloaded:
1286 return state;
1287 case eStateStopped:
1288 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1289 continue;
1290 else
1291 return state;
1292 default:
1293 continue;
1294 }
1295 }
1296 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001297}
1298
1299
1300StateType
1301Process::WaitForState
1302(
1303 const TimeValue *timeout,
1304 const StateType *match_states, const uint32_t num_match_states
1305)
1306{
1307 EventSP event_sp;
1308 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001309 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001310 while (state != eStateInvalid)
1311 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001312 // If we are exited or detached, we won't ever get back to any
1313 // other valid state...
1314 if (state == eStateDetached || state == eStateExited)
1315 return state;
1316
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001317 state = WaitForStateChangedEvents (timeout, event_sp);
1318
1319 for (i=0; i<num_match_states; ++i)
1320 {
1321 if (match_states[i] == state)
1322 return state;
1323 }
1324 }
1325 return state;
1326}
1327
Jim Ingham30f9b212010-10-11 23:53:14 +00001328bool
1329Process::HijackProcessEvents (Listener *listener)
1330{
1331 if (listener != NULL)
1332 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001333 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001334 }
1335 else
1336 return false;
1337}
1338
1339void
1340Process::RestoreProcessEvents ()
1341{
1342 RestoreBroadcaster();
1343}
1344
Jim Ingham0f16e732011-02-08 05:20:59 +00001345bool
1346Process::HijackPrivateProcessEvents (Listener *listener)
1347{
1348 if (listener != NULL)
1349 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001350 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001351 }
1352 else
1353 return false;
1354}
1355
1356void
1357Process::RestorePrivateProcessEvents ()
1358{
1359 m_private_state_broadcaster.RestoreBroadcaster();
1360}
1361
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001362StateType
1363Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1364{
Greg Clayton5160ce52013-03-27 23:08:40 +00001365 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001366
1367 if (log)
1368 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1369
1370 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001371 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1372 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001373 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001374 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001375 {
1376 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1377 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1378 else if (log)
1379 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1380 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001381
1382 if (log)
1383 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1384 __FUNCTION__,
1385 timeout,
1386 StateAsCString(state));
1387 return state;
1388}
1389
1390Event *
1391Process::PeekAtStateChangedEvents ()
1392{
Greg Clayton5160ce52013-03-27 23:08:40 +00001393 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001394
1395 if (log)
1396 log->Printf ("Process::%s...", __FUNCTION__);
1397
1398 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001399 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1400 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401 if (log)
1402 {
1403 if (event_ptr)
1404 {
1405 log->Printf ("Process::%s (event_ptr) => %s",
1406 __FUNCTION__,
1407 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1408 }
1409 else
1410 {
1411 log->Printf ("Process::%s no events found",
1412 __FUNCTION__);
1413 }
1414 }
1415 return event_ptr;
1416}
1417
1418StateType
1419Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1420{
Greg Clayton5160ce52013-03-27 23:08:40 +00001421 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001422
1423 if (log)
1424 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1425
1426 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001427 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1428 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001429 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001430 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001431 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1432 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001433
1434 // This is a bit of a hack, but when we wait here we could very well return
1435 // to the command-line, and that could disable the log, which would render the
1436 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001438 {
1439 if (state == eStateInvalid)
1440 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1441 else
1442 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1443 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001444 return state;
1445}
1446
1447bool
1448Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1449{
Greg Clayton5160ce52013-03-27 23:08:40 +00001450 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001451
1452 if (log)
1453 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1454
1455 if (control_only)
1456 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1457 else
1458 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1459}
1460
1461bool
1462Process::IsRunning () const
1463{
1464 return StateIsRunningState (m_public_state.GetValue());
1465}
1466
1467int
1468Process::GetExitStatus ()
1469{
1470 if (m_public_state.GetValue() == eStateExited)
1471 return m_exit_status;
1472 return -1;
1473}
1474
Greg Clayton85851dd2010-12-04 00:10:17 +00001475
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001476const char *
1477Process::GetExitDescription ()
1478{
1479 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1480 return m_exit_string.c_str();
1481 return NULL;
1482}
1483
Greg Clayton6779606a2011-01-22 23:43:18 +00001484bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001485Process::SetExitStatus (int status, const char *cstr)
1486{
Greg Clayton5160ce52013-03-27 23:08:40 +00001487 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton414f5d32011-01-25 02:58:48 +00001488 if (log)
1489 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1490 status, status,
1491 cstr ? "\"" : "",
1492 cstr ? cstr : "NULL",
1493 cstr ? "\"" : "");
1494
Greg Clayton6779606a2011-01-22 23:43:18 +00001495 // We were already in the exited state
1496 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001497 {
Greg Clayton385d6032011-01-26 23:47:29 +00001498 if (log)
1499 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001500 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001501 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001502
1503 m_exit_status = status;
1504 if (cstr)
1505 m_exit_string = cstr;
1506 else
1507 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001508
Greg Clayton6779606a2011-01-22 23:43:18 +00001509 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001510
Greg Clayton6779606a2011-01-22 23:43:18 +00001511 SetPrivateState (eStateExited);
1512 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001513}
1514
1515// This static callback can be used to watch for local child processes on
1516// the current host. The the child process exits, the process will be
1517// found in the global target list (we want to be completely sure that the
1518// lldb_private::Process doesn't go away before we can deliver the signal.
1519bool
Greg Claytone4e45922011-11-16 05:37:56 +00001520Process::SetProcessExitStatus (void *callback_baton,
1521 lldb::pid_t pid,
1522 bool exited,
1523 int signo, // Zero for no signal
1524 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001525)
1526{
Greg Clayton5160ce52013-03-27 23:08:40 +00001527 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytone4e45922011-11-16 05:37:56 +00001528 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00001529 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001530 callback_baton,
1531 pid,
1532 exited,
1533 signo,
1534 exit_status);
1535
1536 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001537 {
Greg Clayton66111032010-06-23 01:19:29 +00001538 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001539 if (target_sp)
1540 {
1541 ProcessSP process_sp (target_sp->GetProcessSP());
1542 if (process_sp)
1543 {
1544 const char *signal_cstr = NULL;
1545 if (signo)
1546 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1547
1548 process_sp->SetExitStatus (exit_status, signal_cstr);
1549 }
1550 }
1551 return true;
1552 }
1553 return false;
1554}
1555
1556
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001557void
1558Process::UpdateThreadListIfNeeded ()
1559{
1560 const uint32_t stop_id = GetStopID();
1561 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1562 {
Greg Clayton2637f822011-11-17 01:23:07 +00001563 const StateType state = GetPrivateState();
1564 if (StateIsStoppedState (state, true))
1565 {
1566 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001567 // m_thread_list does have its own mutex, but we need to
1568 // hold onto the mutex between the call to UpdateThreadList(...)
1569 // and the os->UpdateThreadList(...) so it doesn't change on us
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001570 ThreadList &old_thread_list = m_thread_list;
1571 ThreadList real_thread_list(this);
Greg Clayton2637f822011-11-17 01:23:07 +00001572 ThreadList new_thread_list(this);
1573 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001574 // thread list, but only update if "true" is returned
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001575 if (UpdateThreadList (m_thread_list_real, real_thread_list))
Greg Clayton9fc13552012-04-10 00:18:59 +00001576 {
Jim Ingham09437922013-03-01 20:04:25 +00001577 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1578 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1579 // shutting us down, causing a deadlock.
1580 if (!m_destroy_in_process)
1581 {
1582 OperatingSystem *os = GetOperatingSystem ();
1583 if (os)
Greg Claytonb3ae8762013-04-12 20:07:46 +00001584 {
1585 // Clear any old backing threads where memory threads might have been
1586 // backed by actual threads from the lldb_private::Process subclass
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001587 size_t num_old_threads = old_thread_list.GetSize(false);
Greg Claytonb3ae8762013-04-12 20:07:46 +00001588 for (size_t i=0; i<num_old_threads; ++i)
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001589 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
Greg Claytonb3ae8762013-04-12 20:07:46 +00001590
1591 // Now let the OperatingSystem plug-in update the thread list
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001592 os->UpdateThreadList (old_thread_list, // Old list full of threads created by OS plug-in
1593 real_thread_list, // The actual thread list full of threads created by each lldb_private::Process subclass
1594 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 +00001595 }
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001596 else
1597 {
1598 // No OS plug-in, the new thread list is the same as the real thread list
1599 new_thread_list = real_thread_list;
1600 }
Jim Ingham09437922013-03-01 20:04:25 +00001601 }
Jim Ingham02ff8e02013-06-22 00:55:02 +00001602
1603 m_thread_list_real.Update(real_thread_list);
Andrew Kaylorba4e61d2013-05-07 18:35:34 +00001604 m_thread_list.Update (new_thread_list);
1605 m_thread_list.SetStopID (stop_id);
Jason Molendaa6e91302013-11-19 05:44:41 +00001606
Jason Molenda4ff13262013-11-20 00:31:38 +00001607 if (GetLastNaturalStopID () != m_extended_thread_stop_id)
1608 {
1609 // Clear any extended threads that we may have accumulated previously
1610 m_extended_thread_list.Clear();
1611 m_extended_thread_stop_id = GetLastNaturalStopID ();
Jason Molenda5e8dce42013-12-13 00:29:16 +00001612
1613 m_queue_list.Clear();
1614 m_queue_list_stop_id = GetLastNaturalStopID ();
Jason Molenda4ff13262013-11-20 00:31:38 +00001615 }
Greg Clayton9fc13552012-04-10 00:18:59 +00001616 }
Greg Clayton2637f822011-11-17 01:23:07 +00001617 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001618 }
1619}
1620
Jason Molenda5e8dce42013-12-13 00:29:16 +00001621void
1622Process::UpdateQueueListIfNeeded ()
1623{
1624 if (m_system_runtime_ap.get())
1625 {
1626 if (m_queue_list.GetSize() == 0 || m_queue_list_stop_id != GetLastNaturalStopID())
1627 {
1628 const StateType state = GetPrivateState();
1629 if (StateIsStoppedState (state, true))
1630 {
1631 m_system_runtime_ap->PopulateQueueList (m_queue_list);
1632 m_queue_list_stop_id = GetLastNaturalStopID();
1633 }
1634 }
1635 }
1636}
1637
Greg Claytona4d87472013-01-18 23:41:08 +00001638ThreadSP
1639Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1640{
1641 OperatingSystem *os = GetOperatingSystem ();
1642 if (os)
1643 return os->CreateThread(tid, context);
1644 return ThreadSP();
1645}
1646
Han Ming Ongc2c423e2013-01-08 22:10:01 +00001647uint32_t
1648Process::GetNextThreadIndexID (uint64_t thread_id)
1649{
1650 return AssignIndexIDToThread(thread_id);
1651}
1652
1653bool
1654Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1655{
1656 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1657 if (iterator == m_thread_id_to_index_id_map.end())
1658 {
1659 return false;
1660 }
1661 else
1662 {
1663 return true;
1664 }
1665}
1666
1667uint32_t
1668Process::AssignIndexIDToThread(uint64_t thread_id)
1669{
1670 uint32_t result = 0;
1671 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1672 if (iterator == m_thread_id_to_index_id_map.end())
1673 {
1674 result = ++m_thread_index_id;
1675 m_thread_id_to_index_id_map[thread_id] = result;
1676 }
1677 else
1678 {
1679 result = iterator->second;
1680 }
1681
1682 return result;
1683}
1684
Jason Molenda5e8dce42013-12-13 00:29:16 +00001685bool
1686Process::HasAssignedIndexIDToQueue(queue_id_t queue_id)
1687{
1688 std::map<uint64_t, uint32_t>::iterator iterator = m_queue_id_to_index_id_map.find(queue_id);
1689 if (iterator == m_queue_id_to_index_id_map.end())
1690 {
1691 return false;
1692 }
1693 else
1694 {
1695 return true;
1696 }
1697}
1698
1699uint32_t
1700Process::AssignIndexIDToQueue(queue_id_t queue_id)
1701{
1702 uint32_t result = 0;
1703 std::map<uint64_t, uint32_t>::iterator iterator = m_queue_id_to_index_id_map.find(queue_id);
1704 if (iterator == m_queue_id_to_index_id_map.end())
1705 {
1706 result = ++m_queue_index_id;
1707 m_queue_id_to_index_id_map[queue_id] = result;
1708 }
1709 else
1710 {
1711 result = iterator->second;
1712 }
1713
1714 return result;
1715}
1716
1717
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001718StateType
1719Process::GetState()
1720{
1721 // If any other threads access this we will need a mutex for it
1722 return m_public_state.GetValue ();
1723}
1724
1725void
Jim Ingham221d51c2013-05-08 00:35:16 +00001726Process::SetPublicState (StateType new_state, bool restarted)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001727{
Greg Clayton5160ce52013-03-27 23:08:40 +00001728 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001729 if (log)
Jim Ingham221d51c2013-05-08 00:35:16 +00001730 log->Printf("Process::SetPublicState (state = %s, restarted = %i)", StateAsCString(new_state), restarted);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001731 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001732 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001733
1734 // On the transition from Run to Stopped, we unlock the writer end of the
1735 // run lock. The lock gets locked in Resume, which is the public API
1736 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001737 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1738 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001739 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001740 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001741 if (log)
1742 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001743 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001744 }
1745 else
1746 {
1747 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1748 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
Jim Ingham221d51c2013-05-08 00:35:16 +00001749 if ((old_state_is_stopped != new_state_is_stopped))
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001750 {
Jim Ingham221d51c2013-05-08 00:35:16 +00001751 if (new_state_is_stopped && !restarted)
Sean Callanan8b0737f2012-06-02 01:16:20 +00001752 {
1753 if (log)
1754 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ed Maste64fad602013-07-29 20:58:06 +00001755 m_public_run_lock.SetStopped();
Sean Callanan8b0737f2012-06-02 01:16:20 +00001756 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001757 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001758 }
1759 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001760}
1761
Jim Ingham3b8285d2012-04-19 01:40:33 +00001762Error
1763Process::Resume ()
1764{
Greg Clayton5160ce52013-03-27 23:08:40 +00001765 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham3b8285d2012-04-19 01:40:33 +00001766 if (log)
1767 log->Printf("Process::Resume -- locking run lock");
Ed Maste64fad602013-07-29 20:58:06 +00001768 if (!m_public_run_lock.TrySetRunning())
Jim Ingham3b8285d2012-04-19 01:40:33 +00001769 {
1770 Error error("Resume request failed - process still running.");
1771 if (log)
Ed Maste64fad602013-07-29 20:58:06 +00001772 log->Printf ("Process::Resume: -- TrySetRunning failed, not resuming.");
Jim Ingham3b8285d2012-04-19 01:40:33 +00001773 return error;
1774 }
1775 return PrivateResume();
1776}
1777
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001778StateType
1779Process::GetPrivateState ()
1780{
1781 return m_private_state.GetValue();
1782}
1783
1784void
1785Process::SetPrivateState (StateType new_state)
1786{
Greg Clayton5160ce52013-03-27 23:08:40 +00001787 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001788 bool state_changed = false;
1789
1790 if (log)
1791 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1792
Andrew Kaylor29d65742013-05-10 17:19:04 +00001793 Mutex::Locker thread_locker(m_thread_list.GetMutex());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001794 Mutex::Locker locker(m_private_state.GetMutex());
1795
1796 const StateType old_state = m_private_state.GetValueNoLock ();
1797 state_changed = old_state != new_state;
Ed Mastec29693f2013-07-02 16:35:47 +00001798
Greg Claytonaa49c832013-05-03 22:25:56 +00001799 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1800 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1801 if (old_state_is_stopped != new_state_is_stopped)
1802 {
1803 if (new_state_is_stopped)
Ed Maste64fad602013-07-29 20:58:06 +00001804 m_private_run_lock.SetStopped();
Greg Claytonaa49c832013-05-03 22:25:56 +00001805 else
Ed Maste64fad602013-07-29 20:58:06 +00001806 m_private_run_lock.SetRunning();
Greg Claytonaa49c832013-05-03 22:25:56 +00001807 }
Andrew Kaylor93132f52013-05-28 23:04:25 +00001808
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001809 if (state_changed)
1810 {
1811 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001812 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001813 {
Andrew Kaylor29d65742013-05-10 17:19:04 +00001814 // Note, this currently assumes that all threads in the list
1815 // stop when the process stops. In the future we will want to
1816 // support a debugging model where some threads continue to run
1817 // while others are stopped. When that happens we will either need
1818 // a way for the thread list to identify which threads are stopping
1819 // or create a special thread list containing only threads which
1820 // actually stopped.
1821 //
1822 // The process plugin is responsible for managing the actual
1823 // behavior of the threads and should have stopped any threads
1824 // that are going to stop before we get here.
1825 m_thread_list.DidStop();
1826
Jim Ingham4b536182011-08-09 02:12:22 +00001827 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001828 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001829 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001830 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001831 }
1832 // Use our target to get a shared pointer to ourselves...
Greg Clayton35a4cc52012-10-29 20:52:08 +00001833 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1834 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1835 else
1836 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837 }
1838 else
1839 {
1840 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001841 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001842 }
1843}
1844
Jim Ingham0faa43f2011-11-08 03:00:11 +00001845void
1846Process::SetRunningUserExpression (bool on)
1847{
1848 m_mod_id.SetRunningUserExpression (on);
1849}
1850
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001851addr_t
1852Process::GetImageInfoAddress()
1853{
1854 return LLDB_INVALID_ADDRESS;
1855}
1856
Greg Clayton8f343b02010-11-04 01:54:29 +00001857//----------------------------------------------------------------------
1858// LoadImage
1859//
1860// This function provides a default implementation that works for most
1861// unix variants. Any Process subclasses that need to do shared library
1862// loading differently should override LoadImage and UnloadImage and
1863// do what is needed.
1864//----------------------------------------------------------------------
1865uint32_t
1866Process::LoadImage (const FileSpec &image_spec, Error &error)
1867{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001868 char path[PATH_MAX];
1869 image_spec.GetPath(path, sizeof(path));
1870
Greg Clayton8f343b02010-11-04 01:54:29 +00001871 DynamicLoader *loader = GetDynamicLoader();
1872 if (loader)
1873 {
1874 error = loader->CanLoadImage();
1875 if (error.Fail())
1876 return LLDB_INVALID_IMAGE_TOKEN;
1877 }
1878
1879 if (error.Success())
1880 {
1881 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001882
1883 if (thread_sp)
1884 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001885 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001886
1887 if (frame_sp)
1888 {
1889 ExecutionContext exe_ctx;
1890 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001891 EvaluateExpressionOptions expr_options;
1892 expr_options.SetUnwindOnError(true);
1893 expr_options.SetIgnoreBreakpoints(true);
1894 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001895 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001896 expr.Printf("dlopen (\"%s\", 2)", path);
1897 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001898 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001899 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001900 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001901 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001902 expr.GetData(),
1903 prefix,
1904 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001905 expr_error);
1906 if (expr_error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001907 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001908 error = result_valobj_sp->GetError();
1909 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001910 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001911 Scalar scalar;
1912 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001913 {
Greg Clayton62afb9f2013-11-04 19:35:17 +00001914 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1915 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1916 {
1917 uint32_t image_token = m_image_tokens.size();
1918 m_image_tokens.push_back (image_ptr);
1919 return image_token;
1920 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001921 }
1922 }
1923 }
1924 }
1925 }
1926 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001927 if (!error.AsCString())
1928 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001929 return LLDB_INVALID_IMAGE_TOKEN;
1930}
1931
1932//----------------------------------------------------------------------
1933// UnloadImage
1934//
1935// This function provides a default implementation that works for most
1936// unix variants. Any Process subclasses that need to do shared library
1937// loading differently should override LoadImage and UnloadImage and
1938// do what is needed.
1939//----------------------------------------------------------------------
1940Error
1941Process::UnloadImage (uint32_t image_token)
1942{
1943 Error error;
1944 if (image_token < m_image_tokens.size())
1945 {
1946 const addr_t image_addr = m_image_tokens[image_token];
1947 if (image_addr == LLDB_INVALID_ADDRESS)
1948 {
1949 error.SetErrorString("image already unloaded");
1950 }
1951 else
1952 {
1953 DynamicLoader *loader = GetDynamicLoader();
1954 if (loader)
1955 error = loader->CanLoadImage();
1956
1957 if (error.Success())
1958 {
1959 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001960
1961 if (thread_sp)
1962 {
Jason Molendab57e4a12013-11-04 09:33:30 +00001963 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
Greg Clayton8f343b02010-11-04 01:54:29 +00001964
1965 if (frame_sp)
1966 {
1967 ExecutionContext exe_ctx;
1968 frame_sp->CalculateExecutionContext (exe_ctx);
Greg Clayton62afb9f2013-11-04 19:35:17 +00001969 EvaluateExpressionOptions expr_options;
1970 expr_options.SetUnwindOnError(true);
1971 expr_options.SetIgnoreBreakpoints(true);
1972 expr_options.SetExecutionPolicy(eExecutionPolicyAlways);
Greg Clayton8f343b02010-11-04 01:54:29 +00001973 StreamString expr;
Daniel Malead01b2952012-11-29 21:49:15 +00001974 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton8f343b02010-11-04 01:54:29 +00001975 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001976 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton62afb9f2013-11-04 19:35:17 +00001977 Error expr_error;
Greg Clayton26ab83d2012-10-31 20:49:04 +00001978 ClangUserExpression::Evaluate (exe_ctx,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001979 expr_options,
Greg Clayton26ab83d2012-10-31 20:49:04 +00001980 expr.GetData(),
1981 prefix,
1982 result_valobj_sp,
Greg Clayton62afb9f2013-11-04 19:35:17 +00001983 expr_error);
Greg Clayton8f343b02010-11-04 01:54:29 +00001984 if (result_valobj_sp->GetError().Success())
1985 {
1986 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001987 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001988 {
1989 if (scalar.UInt(1))
1990 {
1991 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1992 }
1993 else
1994 {
1995 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1996 }
1997 }
1998 }
1999 else
2000 {
2001 error = result_valobj_sp->GetError();
2002 }
2003 }
2004 }
2005 }
2006 }
2007 }
2008 else
2009 {
2010 error.SetErrorString("invalid image token");
2011 }
2012 return error;
2013}
2014
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002015const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002016Process::GetABI()
2017{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00002018 if (!m_abi_sp)
2019 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
2020 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002021}
2022
Jim Ingham22777012010-09-23 02:01:19 +00002023LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002024Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002025{
2026 LanguageRuntimeCollection::iterator pos;
2027 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00002028 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00002029 {
Jim Inghamab175242012-03-10 00:22:19 +00002030 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00002031
Jim Inghamab175242012-03-10 00:22:19 +00002032 m_language_runtimes[language] = runtime_sp;
2033 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00002034 }
2035 else
2036 return (*pos).second.get();
2037}
2038
2039CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002040Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002041{
Jim Inghamab175242012-03-10 00:22:19 +00002042 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002043 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
2044 return static_cast<CPPLanguageRuntime *> (runtime);
2045 return NULL;
2046}
2047
2048ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00002049Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00002050{
Jim Inghamab175242012-03-10 00:22:19 +00002051 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00002052 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
2053 return static_cast<ObjCLanguageRuntime *> (runtime);
2054 return NULL;
2055}
2056
Enrico Granatafd4c84e2012-05-21 16:51:35 +00002057bool
2058Process::IsPossibleDynamicValue (ValueObject& in_value)
2059{
2060 if (in_value.IsDynamic())
2061 return false;
2062 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
2063
2064 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
2065 {
2066 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
2067 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
2068 }
2069
2070 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
2071 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
2072 return true;
2073
2074 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
2075 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
2076}
2077
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002078BreakpointSiteList &
2079Process::GetBreakpointSiteList()
2080{
2081 return m_breakpoint_site_list;
2082}
2083
2084const BreakpointSiteList &
2085Process::GetBreakpointSiteList() const
2086{
2087 return m_breakpoint_site_list;
2088}
2089
2090
2091void
2092Process::DisableAllBreakpointSites ()
2093{
Greg Claytond8cf1a12013-06-12 00:46:38 +00002094 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
2095// bp_site->SetEnabled(true);
2096 DisableBreakpointSite(bp_site);
2097 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002098}
2099
2100Error
2101Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
2102{
2103 Error error (DisableBreakpointSiteByID (break_id));
2104
2105 if (error.Success())
2106 m_breakpoint_site_list.Remove(break_id);
2107
2108 return error;
2109}
2110
2111Error
2112Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
2113{
2114 Error error;
2115 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2116 if (bp_site_sp)
2117 {
2118 if (bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002119 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002120 }
2121 else
2122 {
Daniel Malead01b2952012-11-29 21:49:15 +00002123 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002124 }
2125
2126 return error;
2127}
2128
2129Error
2130Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2131{
2132 Error error;
2133 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2134 if (bp_site_sp)
2135 {
2136 if (!bp_site_sp->IsEnabled())
Jim Ingham299c0c12013-02-15 02:06:30 +00002137 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138 }
2139 else
2140 {
Daniel Malead01b2952012-11-29 21:49:15 +00002141 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142 }
2143 return error;
2144}
2145
Stephen Wilson50bd94f2010-07-17 00:56:13 +00002146lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00002147Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002148{
Jim Ingham1460e4b2014-01-10 23:46:59 +00002149 addr_t load_addr = LLDB_INVALID_ADDRESS;
2150
2151 bool show_error = true;
2152 switch (GetState())
2153 {
2154 case eStateInvalid:
2155 case eStateUnloaded:
2156 case eStateConnected:
2157 case eStateAttaching:
2158 case eStateLaunching:
2159 case eStateDetached:
2160 case eStateExited:
2161 show_error = false;
2162 break;
2163
2164 case eStateStopped:
2165 case eStateRunning:
2166 case eStateStepping:
2167 case eStateCrashed:
2168 case eStateSuspended:
2169 show_error = IsAlive();
2170 break;
2171 }
2172
2173 // Reset the IsIndirect flag here, in case the location changes from
2174 // pointing to a indirect symbol to a regular symbol.
2175 owner->SetIsIndirect (false);
2176
2177 if (owner->ShouldResolveIndirectFunctions())
2178 {
2179 Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
2180 if (symbol && symbol->IsIndirect())
2181 {
2182 Error error;
2183 load_addr = ResolveIndirectFunction (&symbol->GetAddress(), error);
2184 if (!error.Success() && show_error)
2185 {
2186 m_target.GetDebugger().GetErrorFile().Printf ("warning: failed to resolve indirect function at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2187 symbol->GetAddress().GetLoadAddress(&m_target),
2188 owner->GetBreakpoint().GetID(),
2189 owner->GetID(),
2190 error.AsCString() ? error.AsCString() : "unkown error");
2191 return LLDB_INVALID_BREAK_ID;
2192 }
2193 Address resolved_address(load_addr);
2194 load_addr = resolved_address.GetOpcodeLoadAddress (&m_target);
2195 owner->SetIsIndirect(true);
2196 }
2197 else
2198 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2199 }
2200 else
2201 load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
2202
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002203 if (load_addr != LLDB_INVALID_ADDRESS)
2204 {
2205 BreakpointSiteSP bp_site_sp;
2206
2207 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2208 // create a new breakpoint site and add it.
2209
2210 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2211
2212 if (bp_site_sp)
2213 {
2214 bp_site_sp->AddOwner (owner);
2215 owner->SetBreakpointSite (bp_site_sp);
2216 return bp_site_sp->GetID();
2217 }
2218 else
2219 {
Greg Claytonc7bece562013-01-25 18:06:21 +00002220 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002221 if (bp_site_sp)
2222 {
Greg Claytoneb023e72013-10-11 19:48:25 +00002223 Error error = EnableBreakpointSite (bp_site_sp.get());
2224 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002225 {
2226 owner->SetBreakpointSite (bp_site_sp);
2227 return m_breakpoint_site_list.Add (bp_site_sp);
2228 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002229 else
2230 {
Greg Claytonfbb76342013-11-20 21:07:01 +00002231 if (show_error)
2232 {
2233 // Report error for setting breakpoint...
2234 m_target.GetDebugger().GetErrorFile().Printf ("warning: failed to set breakpoint site at 0x%" PRIx64 " for breakpoint %i.%i: %s\n",
2235 load_addr,
2236 owner->GetBreakpoint().GetID(),
2237 owner->GetID(),
2238 error.AsCString() ? error.AsCString() : "unkown error");
2239 }
Greg Claytoneb023e72013-10-11 19:48:25 +00002240 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002241 }
2242 }
2243 }
2244 // We failed to enable the breakpoint
2245 return LLDB_INVALID_BREAK_ID;
2246
2247}
2248
2249void
2250Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2251{
2252 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2253 if (num_owners == 0)
2254 {
Jim Inghamf1ff3bb2013-04-06 00:16:39 +00002255 // Don't try to disable the site if we don't have a live process anymore.
2256 if (IsAlive())
2257 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002258 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2259 }
2260}
2261
2262
2263size_t
2264Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2265{
2266 size_t bytes_removed = 0;
Jim Ingham20c77192011-06-29 19:42:28 +00002267 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268
Jim Ingham20c77192011-06-29 19:42:28 +00002269 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002270 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002271 bp_sites_in_range.ForEach([bp_addr, size, buf, &bytes_removed](BreakpointSite *bp_site) -> void {
2272 if (bp_site->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002273 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002274 addr_t intersect_addr;
2275 size_t intersect_size;
2276 size_t opcode_offset;
2277 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00002278 {
2279 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2280 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Claytond8cf1a12013-06-12 00:46:38 +00002281 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00002282 size_t buf_offset = intersect_addr - bp_addr;
Greg Claytond8cf1a12013-06-12 00:46:38 +00002283 ::memcpy(buf + buf_offset, bp_site->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00002284 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002285 }
Greg Claytond8cf1a12013-06-12 00:46:38 +00002286 });
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002287 }
2288 return bytes_removed;
2289}
2290
2291
Greg Claytonded470d2011-03-19 01:12:21 +00002292
2293size_t
2294Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2295{
2296 PlatformSP platform_sp (m_target.GetPlatform());
2297 if (platform_sp)
2298 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2299 return 0;
2300}
2301
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002302Error
2303Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2304{
2305 Error error;
2306 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002307 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002308 const addr_t bp_addr = bp_site->GetLoadAddress();
2309 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002310 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002311 if (bp_site->IsEnabled())
2312 {
2313 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002314 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 +00002315 return error;
2316 }
2317
2318 if (bp_addr == LLDB_INVALID_ADDRESS)
2319 {
2320 error.SetErrorString("BreakpointSite contains an invalid load address.");
2321 return error;
2322 }
2323 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2324 // trap for the breakpoint site
2325 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2326
2327 if (bp_opcode_size == 0)
2328 {
Daniel Malead01b2952012-11-29 21:49:15 +00002329 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 }
2331 else
2332 {
2333 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2334
2335 if (bp_opcode_bytes == NULL)
2336 {
2337 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2338 return error;
2339 }
2340
2341 // Save the original opcode by reading it
2342 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2343 {
2344 // Write a software breakpoint in place of the original opcode
2345 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2346 {
2347 uint8_t verify_bp_opcode_bytes[64];
2348 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2349 {
2350 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2351 {
2352 bp_site->SetEnabled(true);
2353 bp_site->SetType (BreakpointSite::eSoftware);
2354 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002355 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356 bp_site->GetID(),
2357 (uint64_t)bp_addr);
2358 }
2359 else
Greg Clayton86edbf42011-10-26 00:56:27 +00002360 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002361 }
2362 else
2363 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2364 }
2365 else
2366 error.SetErrorString("Unable to write breakpoint trap to memory.");
2367 }
2368 else
2369 error.SetErrorString("Unable to read memory at breakpoint address.");
2370 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00002371 if (log && error.Fail())
Daniel Malead01b2952012-11-29 21:49:15 +00002372 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002373 bp_site->GetID(),
2374 (uint64_t)bp_addr,
2375 error.AsCString());
2376 return error;
2377}
2378
2379Error
2380Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2381{
2382 Error error;
2383 assert (bp_site != NULL);
Greg Clayton5160ce52013-03-27 23:08:40 +00002384 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002385 addr_t bp_addr = bp_site->GetLoadAddress();
2386 lldb::user_id_t breakID = bp_site->GetID();
2387 if (log)
Jim Ingham299c0c12013-02-15 02:06:30 +00002388 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002389
2390 if (bp_site->IsHardware())
2391 {
2392 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2393 }
2394 else if (bp_site->IsEnabled())
2395 {
2396 const size_t break_op_size = bp_site->GetByteSize();
2397 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2398 if (break_op_size > 0)
2399 {
2400 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00002401 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002402 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002403 bool break_op_found = false;
2404
2405 // Read the breakpoint opcode
2406 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2407 {
2408 bool verify = false;
2409 // Make sure we have the a breakpoint opcode exists at this address
2410 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2411 {
2412 break_op_found = true;
2413 // We found a valid breakpoint opcode at this address, now restore
2414 // the saved opcode.
2415 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2416 {
2417 verify = true;
2418 }
2419 else
2420 error.SetErrorString("Memory write failed when restoring original opcode.");
2421 }
2422 else
2423 {
2424 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2425 // Set verify to true and so we can check if the original opcode has already been restored
2426 verify = true;
2427 }
2428
2429 if (verify)
2430 {
Greg Claytonc982c762010-07-09 20:39:50 +00002431 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002432 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433 // Verify that our original opcode made it back to the inferior
2434 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2435 {
2436 // compare the memory we just read with the original opcode
2437 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2438 {
2439 // SUCCESS
2440 bp_site->SetEnabled(false);
2441 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002442 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 +00002443 return error;
2444 }
2445 else
2446 {
2447 if (break_op_found)
2448 error.SetErrorString("Failed to restore original opcode.");
2449 }
2450 }
2451 else
2452 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2453 }
2454 }
2455 else
2456 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2457 }
2458 }
2459 else
2460 {
2461 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002462 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 +00002463 return error;
2464 }
2465
2466 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002467 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002468 bp_site->GetID(),
2469 (uint64_t)bp_addr,
2470 error.AsCString());
2471 return error;
2472
2473}
2474
Greg Clayton58be07b2011-01-07 06:08:19 +00002475// Uncomment to verify memory caching works after making changes to caching code
2476//#define VERIFY_MEMORY_READS
2477
Sean Callanan64c0cf22012-06-07 22:26:42 +00002478size_t
2479Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2480{
Jason Molendaa7b5afa2013-11-15 00:17:32 +00002481 error.Clear();
Sean Callanan64c0cf22012-06-07 22:26:42 +00002482 if (!GetDisableMemoryCache())
2483 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002484#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002485 // Memory caching is enabled, with debug verification
2486
2487 if (buf && size)
2488 {
2489 // Uncomment the line below to make sure memory caching is working.
2490 // I ran this through the test suite and got no assertions, so I am
2491 // pretty confident this is working well. If any changes are made to
2492 // memory caching, uncomment the line below and test your changes!
2493
2494 // Verify all memory reads by using the cache first, then redundantly
2495 // reading the same memory from the inferior and comparing to make sure
2496 // everything is exactly the same.
2497 std::string verify_buf (size, '\0');
2498 assert (verify_buf.size() == size);
2499 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2500 Error verify_error;
2501 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2502 assert (cache_bytes_read == verify_bytes_read);
2503 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2504 assert (verify_error.Success() == error.Success());
2505 return cache_bytes_read;
2506 }
2507 return 0;
2508#else // !defined(VERIFY_MEMORY_READS)
2509 // Memory caching is enabled, without debug verification
2510
2511 return m_memory_cache.Read (addr, buf, size, error);
2512#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002513 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002514 else
2515 {
2516 // Memory caching is disabled
2517
2518 return ReadMemoryFromInferior (addr, buf, size, error);
2519 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002520}
Greg Clayton58be07b2011-01-07 06:08:19 +00002521
Greg Clayton4c82d422012-05-18 23:20:01 +00002522size_t
2523Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2524{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002525 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002526 out_str.clear();
2527 addr_t curr_addr = addr;
2528 while (1)
2529 {
2530 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2531 if (length == 0)
2532 break;
2533 out_str.append(buf, length);
2534 // If we got "length - 1" bytes, we didn't get the whole C string, we
2535 // need to read some more characters
2536 if (length == sizeof(buf) - 1)
2537 curr_addr += length;
2538 else
2539 break;
2540 }
2541 return out_str.size();
2542}
2543
Greg Clayton58be07b2011-01-07 06:08:19 +00002544
2545size_t
Ashok Thirumurthi6ac9d132013-04-19 15:58:38 +00002546Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2547 size_t type_width)
2548{
2549 size_t total_bytes_read = 0;
2550 if (dst && max_bytes && type_width && max_bytes >= type_width)
2551 {
2552 // Ensure a null terminator independent of the number of bytes that is read.
2553 memset (dst, 0, max_bytes);
2554 size_t bytes_left = max_bytes - type_width;
2555
2556 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2557 assert(sizeof(terminator) >= type_width &&
2558 "Attempting to validate a string with more than 4 bytes per character!");
2559
2560 addr_t curr_addr = addr;
2561 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2562 char *curr_dst = dst;
2563
2564 error.Clear();
2565 while (bytes_left > 0 && error.Success())
2566 {
2567 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2568 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2569 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2570
2571 if (bytes_read == 0)
2572 break;
2573
2574 // Search for a null terminator of correct size and alignment in bytes_read
2575 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2576 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2577 if (::strncmp(&dst[i], terminator, type_width) == 0)
2578 {
2579 error.Clear();
2580 return i;
2581 }
2582
2583 total_bytes_read += bytes_read;
2584 curr_dst += bytes_read;
2585 curr_addr += bytes_read;
2586 bytes_left -= bytes_read;
2587 }
2588 }
2589 else
2590 {
2591 if (max_bytes)
2592 error.SetErrorString("invalid arguments");
2593 }
2594 return total_bytes_read;
2595}
2596
2597// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2598// null terminators.
2599size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002600Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002601{
2602 size_t total_cstr_len = 0;
2603 if (dst && dst_max_len)
2604 {
Greg Claytone91b7952011-12-15 03:14:23 +00002605 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002606 // NULL out everything just to be safe
2607 memset (dst, 0, dst_max_len);
2608 Error error;
2609 addr_t curr_addr = addr;
2610 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2611 size_t bytes_left = dst_max_len - 1;
2612 char *curr_dst = dst;
2613
2614 while (bytes_left > 0)
2615 {
2616 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2617 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2618 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2619
2620 if (bytes_read == 0)
2621 {
Greg Claytone91b7952011-12-15 03:14:23 +00002622 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002623 dst[total_cstr_len] = '\0';
2624 break;
2625 }
2626 const size_t len = strlen(curr_dst);
2627
2628 total_cstr_len += len;
2629
2630 if (len < bytes_to_read)
2631 break;
2632
2633 curr_dst += bytes_read;
2634 curr_addr += bytes_read;
2635 bytes_left -= bytes_read;
2636 }
2637 }
Greg Claytone91b7952011-12-15 03:14:23 +00002638 else
2639 {
2640 if (dst == NULL)
2641 result_error.SetErrorString("invalid arguments");
2642 else
2643 result_error.Clear();
2644 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002645 return total_cstr_len;
2646}
2647
2648size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002649Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2650{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002651 if (buf == NULL || size == 0)
2652 return 0;
2653
2654 size_t bytes_read = 0;
2655 uint8_t *bytes = (uint8_t *)buf;
2656
2657 while (bytes_read < size)
2658 {
2659 const size_t curr_size = size - bytes_read;
2660 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2661 bytes + bytes_read,
2662 curr_size,
2663 error);
2664 bytes_read += curr_bytes_read;
2665 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2666 break;
2667 }
2668
2669 // Replace any software breakpoint opcodes that fall into this range back
2670 // into "buf" before we return
2671 if (bytes_read > 0)
2672 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2673 return bytes_read;
2674}
2675
Greg Clayton58a4c462010-12-16 20:01:20 +00002676uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002677Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002678{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002679 Scalar scalar;
2680 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2681 return scalar.ULongLong(fail_value);
2682 return fail_value;
2683}
2684
2685addr_t
2686Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2687{
2688 Scalar scalar;
2689 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2690 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2691 return LLDB_INVALID_ADDRESS;
2692}
2693
2694
2695bool
2696Process::WritePointerToMemory (lldb::addr_t vm_addr,
2697 lldb::addr_t ptr_value,
2698 Error &error)
2699{
2700 Scalar scalar;
2701 const uint32_t addr_byte_size = GetAddressByteSize();
2702 if (addr_byte_size <= 4)
2703 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002704 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002705 scalar = ptr_value;
2706 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002707}
2708
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002709size_t
2710Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2711{
2712 size_t bytes_written = 0;
2713 const uint8_t *bytes = (const uint8_t *)buf;
2714
2715 while (bytes_written < size)
2716 {
2717 const size_t curr_size = size - bytes_written;
2718 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2719 bytes + bytes_written,
2720 curr_size,
2721 error);
2722 bytes_written += curr_bytes_written;
2723 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2724 break;
2725 }
2726 return bytes_written;
2727}
2728
2729size_t
2730Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2731{
Greg Clayton58be07b2011-01-07 06:08:19 +00002732#if defined (ENABLE_MEMORY_CACHING)
2733 m_memory_cache.Flush (addr, size);
2734#endif
2735
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736 if (buf == NULL || size == 0)
2737 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002738
Jim Ingham4b536182011-08-09 02:12:22 +00002739 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002740
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002741 // We need to write any data that would go where any current software traps
2742 // (enabled software breakpoints) any software traps (breakpoints) that we
2743 // may have placed in our tasks memory.
2744
Greg Claytond8cf1a12013-06-12 00:46:38 +00002745 BreakpointSiteList bp_sites_in_range;
2746
2747 if (m_breakpoint_site_list.FindInRange (addr, addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002748 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002749 // No breakpoint sites overlap
2750 if (bp_sites_in_range.IsEmpty())
2751 return WriteMemoryPrivate (addr, buf, size, error);
2752 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002753 {
Greg Claytond8cf1a12013-06-12 00:46:38 +00002754 const uint8_t *ubuf = (const uint8_t *)buf;
2755 uint64_t bytes_written = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756
Greg Claytond8cf1a12013-06-12 00:46:38 +00002757 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, &error](BreakpointSite *bp) -> void {
2758
2759 if (error.Success())
2760 {
2761 addr_t intersect_addr;
2762 size_t intersect_size;
2763 size_t opcode_offset;
2764 const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2765 assert(intersects);
2766 assert(addr <= intersect_addr && intersect_addr < addr + size);
2767 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2768 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2769
2770 // Check for bytes before this breakpoint
2771 const addr_t curr_addr = addr + bytes_written;
2772 if (intersect_addr > curr_addr)
2773 {
2774 // There are some bytes before this breakpoint that we need to
2775 // just write to memory
2776 size_t curr_size = intersect_addr - curr_addr;
2777 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2778 ubuf + bytes_written,
2779 curr_size,
2780 error);
2781 bytes_written += curr_bytes_written;
2782 if (curr_bytes_written != curr_size)
2783 {
2784 // We weren't able to write all of the requested bytes, we
2785 // are done looping and will return the number of bytes that
2786 // we have written so far.
2787 if (error.Success())
2788 error.SetErrorToGenericError();
2789 }
2790 }
2791 // Now write any bytes that would cover up any software breakpoints
2792 // directly into the breakpoint opcode buffer
2793 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2794 bytes_written += intersect_size;
2795 }
2796 });
2797
2798 if (bytes_written < size)
2799 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2800 ubuf + bytes_written,
2801 size - bytes_written,
2802 error);
2803 }
2804 }
2805 else
2806 {
2807 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002808 }
2809
2810 // Write any remaining bytes after the last breakpoint if we have any left
Greg Claytond8cf1a12013-06-12 00:46:38 +00002811 return 0; //bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002812}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002813
2814size_t
Greg Claytonc7bece562013-01-25 18:06:21 +00002815Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002816{
2817 if (byte_size == UINT32_MAX)
2818 byte_size = scalar.GetByteSize();
2819 if (byte_size > 0)
2820 {
2821 uint8_t buf[32];
2822 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2823 if (mem_size > 0)
2824 return WriteMemory(addr, buf, mem_size, error);
2825 else
2826 error.SetErrorString ("failed to get scalar as memory data");
2827 }
2828 else
2829 {
2830 error.SetErrorString ("invalid scalar value");
2831 }
2832 return 0;
2833}
2834
2835size_t
2836Process::ReadScalarIntegerFromMemory (addr_t addr,
2837 uint32_t byte_size,
2838 bool is_signed,
2839 Scalar &scalar,
2840 Error &error)
2841{
Greg Clayton7060f892013-05-01 23:41:30 +00002842 uint64_t uval = 0;
2843 if (byte_size == 0)
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002844 {
Greg Clayton7060f892013-05-01 23:41:30 +00002845 error.SetErrorString ("byte size is zero");
2846 }
2847 else if (byte_size & (byte_size - 1))
2848 {
2849 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2850 }
2851 else if (byte_size <= sizeof(uval))
2852 {
2853 const size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002854 if (bytes_read == byte_size)
2855 {
2856 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Claytonc7bece562013-01-25 18:06:21 +00002857 lldb::offset_t offset = 0;
Greg Clayton7060f892013-05-01 23:41:30 +00002858 if (byte_size <= 4)
2859 scalar = data.GetMaxU32 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002860 else
Greg Clayton7060f892013-05-01 23:41:30 +00002861 scalar = data.GetMaxU64 (&offset, byte_size);
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002862 if (is_signed)
2863 scalar.SignExtend(byte_size * 8);
2864 return bytes_read;
2865 }
2866 }
2867 else
2868 {
2869 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2870 }
2871 return 0;
2872}
2873
Greg Claytond495c532011-05-17 03:37:42 +00002874#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002875addr_t
2876Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2877{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002878 if (GetPrivateState() != eStateStopped)
2879 return LLDB_INVALID_ADDRESS;
2880
Greg Claytond495c532011-05-17 03:37:42 +00002881#if defined (USE_ALLOCATE_MEMORY_CACHE)
2882 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2883#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002884 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton5160ce52013-03-27 23:08:40 +00002885 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002886 if (log)
Greg Clayton45989072013-10-23 18:24:30 +00002887 log->Printf("Process::AllocateMemory(size=%" PRIu64 ", permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
Deepak Panickald66b50c2013-10-22 12:27:43 +00002888 (uint64_t)size,
Greg Claytond495c532011-05-17 03:37:42 +00002889 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002890 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002891 m_mod_id.GetStopID(),
2892 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002893 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002894#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002895}
2896
Sean Callanan90539452011-09-20 23:01:51 +00002897bool
2898Process::CanJIT ()
2899{
Sean Callanana7b443a2012-02-14 22:50:38 +00002900 if (m_can_jit == eCanJITDontKnow)
2901 {
2902 Error err;
2903
2904 uint64_t allocated_memory = AllocateMemory(8,
2905 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2906 err);
2907
2908 if (err.Success())
2909 m_can_jit = eCanJITYes;
2910 else
2911 m_can_jit = eCanJITNo;
2912
2913 DeallocateMemory (allocated_memory);
2914 }
2915
Sean Callanan90539452011-09-20 23:01:51 +00002916 return m_can_jit == eCanJITYes;
2917}
2918
2919void
2920Process::SetCanJIT (bool can_jit)
2921{
2922 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2923}
2924
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002925Error
2926Process::DeallocateMemory (addr_t ptr)
2927{
Greg Claytond495c532011-05-17 03:37:42 +00002928 Error error;
2929#if defined (USE_ALLOCATE_MEMORY_CACHE)
2930 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2931 {
Daniel Malead01b2952012-11-29 21:49:15 +00002932 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Claytond495c532011-05-17 03:37:42 +00002933 }
2934#else
2935 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002936
Greg Clayton5160ce52013-03-27 23:08:40 +00002937 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonb2daec92011-01-23 19:58:49 +00002938 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00002939 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 +00002940 ptr,
2941 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002942 m_mod_id.GetStopID(),
2943 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002944#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002945 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946}
2947
Han Ming Ongc811d382012-11-17 00:33:14 +00002948
Greg Claytonc9660542012-02-05 02:38:54 +00002949ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002950Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton39f7ee82013-02-01 21:38:35 +00002951 lldb::addr_t header_addr)
Greg Claytonc9660542012-02-05 02:38:54 +00002952{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002953 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002954 if (module_sp)
2955 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002956 Error error;
2957 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2958 if (objfile)
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002959 return module_sp;
Greg Claytonc9660542012-02-05 02:38:54 +00002960 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002961 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002962}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002963
2964Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002965Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002966{
2967 Error error;
2968 error.SetErrorString("watchpoints are not supported");
2969 return error;
2970}
2971
2972Error
Jim Ingham1b5792e2012-12-18 02:03:49 +00002973Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002974{
2975 Error error;
2976 error.SetErrorString("watchpoints are not supported");
2977 return error;
2978}
2979
2980StateType
2981Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2982{
2983 StateType state;
2984 // Now wait for the process to launch and return control to us, and then
2985 // call DidLaunch:
2986 while (1)
2987 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002988 event_sp.reset();
2989 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2990
Greg Clayton2637f822011-11-17 01:23:07 +00002991 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002992 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002993
2994 // If state is invalid, then we timed out
2995 if (state == eStateInvalid)
2996 break;
2997
2998 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999 HandlePrivateEvent (event_sp);
3000 }
3001 return state;
3002}
3003
3004Error
Greg Claytonfbb76342013-11-20 21:07:01 +00003005Process::Launch (ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003006{
3007 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003008 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003009 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003010 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003011 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003012 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003013
Greg Claytonaa149cb2011-08-11 02:48:45 +00003014 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003015 if (exe_module)
3016 {
Greg Clayton2289fa42011-04-30 01:09:13 +00003017 char local_exec_file_path[PATH_MAX];
3018 char platform_exec_file_path[PATH_MAX];
3019 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
3020 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003021 if (exe_module->GetFileSpec().Exists())
3022 {
Greg Claytonfbb76342013-11-20 21:07:01 +00003023 // Install anything that might need to be installed prior to launching.
3024 // For host systems, this will do nothing, but if we are connected to a
3025 // remote platform it will install any needed binaries
3026 error = GetTarget().Install(&launch_info);
3027 if (error.Fail())
3028 return error;
3029
Greg Clayton71337622011-02-24 22:24:29 +00003030 if (PrivateStateThreadIsValid ())
3031 PausePrivateStateThread ();
3032
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003033 error = WillLaunch (exe_module);
3034 if (error.Success())
3035 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003036 const bool restarted = false;
3037 SetPublicState (eStateLaunching, restarted);
Greg Claytone24c4ac2011-11-17 04:46:02 +00003038 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003039
Ed Maste64fad602013-07-29 20:58:06 +00003040 if (m_public_run_lock.TrySetRunning())
Greg Clayton69fd4be2012-09-04 20:29:05 +00003041 {
3042 // Now launch using these arguments.
3043 error = DoLaunch (exe_module, launch_info);
3044 }
3045 else
3046 {
3047 // This shouldn't happen
3048 error.SetErrorString("failed to acquire process run lock");
3049 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050
3051 if (error.Fail())
3052 {
3053 if (GetID() != LLDB_INVALID_PROCESS_ID)
3054 {
3055 SetID (LLDB_INVALID_PROCESS_ID);
3056 const char *error_string = error.AsCString();
3057 if (error_string == NULL)
3058 error_string = "launch failed";
3059 SetExitStatus (-1, error_string);
3060 }
3061 }
3062 else
3063 {
3064 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00003065 TimeValue timeout_time;
3066 timeout_time = TimeValue::Now();
3067 timeout_time.OffsetWithSeconds(10);
3068 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003069
Greg Clayton1a38ea72011-06-22 01:42:17 +00003070 if (state == eStateInvalid || event_sp.get() == NULL)
3071 {
3072 // We were able to launch the process, but we failed to
3073 // catch the initial stop.
3074 SetExitStatus (0, "failed to catch stop after launch");
3075 Destroy();
3076 }
3077 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003078 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00003079
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003080 DidLaunch ();
3081
Greg Claytonc859e2d2012-02-13 23:10:39 +00003082 DynamicLoader *dyld = GetDynamicLoader ();
3083 if (dyld)
3084 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003085
Jason Molendaeef51062013-11-05 03:57:19 +00003086 SystemRuntime *system_runtime = GetSystemRuntime ();
3087 if (system_runtime)
3088 system_runtime->DidLaunch();
3089
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003090 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091 // This delays passing the stopped event to listeners till DidLaunch gets
3092 // a chance to complete...
3093 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00003094
3095 if (PrivateStateThreadIsValid ())
3096 ResumePrivateStateThread ();
3097 else
3098 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003099 }
3100 else if (state == eStateExited)
3101 {
3102 // We exited while trying to launch somehow. Don't call DidLaunch as that's
3103 // not likely to work, and return an invalid pid.
3104 HandlePrivateEvent (event_sp);
3105 }
3106 }
3107 }
3108 }
3109 else
3110 {
Greg Clayton86edbf42011-10-26 00:56:27 +00003111 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003112 }
3113 }
3114 return error;
3115}
3116
Greg Claytonc3776bf2012-02-09 06:16:32 +00003117
3118Error
3119Process::LoadCore ()
3120{
3121 Error error = DoLoadCore();
3122 if (error.Success())
3123 {
3124 if (PrivateStateThreadIsValid ())
3125 ResumePrivateStateThread ();
3126 else
3127 StartPrivateStateThread ();
3128
Greg Claytonc859e2d2012-02-13 23:10:39 +00003129 DynamicLoader *dyld = GetDynamicLoader ();
3130 if (dyld)
3131 dyld->DidAttach();
3132
Jason Molendaeef51062013-11-05 03:57:19 +00003133 SystemRuntime *system_runtime = GetSystemRuntime ();
3134 if (system_runtime)
3135 system_runtime->DidAttach();
3136
Greg Claytonc859e2d2012-02-13 23:10:39 +00003137 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00003138 // We successfully loaded a core file, now pretend we stopped so we can
3139 // show all of the threads in the core file and explore the crashed
3140 // state.
3141 SetPrivateState (eStateStopped);
3142
3143 }
3144 return error;
3145}
3146
Greg Claytonc859e2d2012-02-13 23:10:39 +00003147DynamicLoader *
3148Process::GetDynamicLoader ()
3149{
3150 if (m_dyld_ap.get() == NULL)
3151 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3152 return m_dyld_ap.get();
3153}
Greg Claytonc3776bf2012-02-09 06:16:32 +00003154
Jason Molendaeef51062013-11-05 03:57:19 +00003155SystemRuntime *
3156Process::GetSystemRuntime ()
3157{
3158 if (m_system_runtime_ap.get() == NULL)
3159 m_system_runtime_ap.reset (SystemRuntime::FindPlugin(this));
3160 return m_system_runtime_ap.get();
3161}
3162
Greg Claytonc3776bf2012-02-09 06:16:32 +00003163
Jim Inghambb3a2832011-01-29 01:49:25 +00003164Process::NextEventAction::EventActionResult
3165Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003166{
Jim Inghambb3a2832011-01-29 01:49:25 +00003167 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
3168 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00003169 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003170 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00003171 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00003172 return eEventActionRetry;
3173
3174 case eStateStopped:
3175 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00003176 {
3177 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00003178 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00003179 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Jim Ingham221d51c2013-05-08 00:35:16 +00003180 // We don't want these events to be reported, so go set the ShouldReportStop here:
3181 m_process->GetThreadList().SetShouldReportStop (eVoteNo);
3182
Greg Claytonc9ed4782011-11-12 02:10:56 +00003183 if (m_exec_count > 0)
3184 {
3185 --m_exec_count;
Jim Ingham221d51c2013-05-08 00:35:16 +00003186 RequestResume();
Greg Claytonc9ed4782011-11-12 02:10:56 +00003187 return eEventActionRetry;
3188 }
3189 else
3190 {
3191 m_process->CompleteAttach ();
3192 return eEventActionSuccess;
3193 }
3194 }
Greg Clayton513c26c2011-01-29 07:10:55 +00003195 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003196
Greg Clayton513c26c2011-01-29 07:10:55 +00003197 default:
3198 case eStateExited:
3199 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00003200 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00003201 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00003202
3203 m_exit_string.assign ("No valid Process");
3204 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00003205}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003206
Jim Inghambb3a2832011-01-29 01:49:25 +00003207Process::NextEventAction::EventActionResult
3208Process::AttachCompletionHandler::HandleBeingInterrupted()
3209{
3210 return eEventActionSuccess;
3211}
3212
3213const char *
3214Process::AttachCompletionHandler::GetExitString ()
3215{
3216 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003217}
3218
3219Error
Greg Clayton144f3a92011-11-15 03:53:30 +00003220Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003221{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003222 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003223 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003224 m_dyld_ap.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00003225 m_system_runtime_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003226 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00003227
Greg Clayton144f3a92011-11-15 03:53:30 +00003228 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00003229 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00003230 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00003231 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003232 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00003233
Greg Clayton144f3a92011-11-15 03:53:30 +00003234 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00003235 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003236 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3237
3238 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003239 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003240 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3241 if (error.Success())
3242 {
Ed Maste64fad602013-07-29 20:58:06 +00003243 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003244 {
3245 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003246 const bool restarted = false;
3247 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003248 // Now attach using these arguments.
Jean-Daniel Dupas9c517c02013-12-23 22:32:54 +00003249 error = DoAttachToProcessWithName (process_name, attach_info);
Greg Clayton926cce72012-10-12 16:10:12 +00003250 }
3251 else
3252 {
3253 // This shouldn't happen
3254 error.SetErrorString("failed to acquire process run lock");
3255 }
Greg Claytone24c4ac2011-11-17 04:46:02 +00003256
Greg Clayton144f3a92011-11-15 03:53:30 +00003257 if (error.Fail())
3258 {
3259 if (GetID() != LLDB_INVALID_PROCESS_ID)
3260 {
3261 SetID (LLDB_INVALID_PROCESS_ID);
3262 if (error.AsCString() == NULL)
3263 error.SetErrorString("attach failed");
3264
3265 SetExitStatus(-1, error.AsCString());
3266 }
3267 }
3268 else
3269 {
3270 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3271 StartPrivateStateThread();
3272 }
3273 return error;
3274 }
Greg Claytone996fd32011-03-08 22:40:15 +00003275 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003276 else
Greg Claytone996fd32011-03-08 22:40:15 +00003277 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003278 ProcessInstanceInfoList process_infos;
3279 PlatformSP platform_sp (m_target.GetPlatform ());
3280
3281 if (platform_sp)
3282 {
3283 ProcessInstanceInfoMatch match_info;
3284 match_info.GetProcessInfo() = attach_info;
3285 match_info.SetNameMatchType (eNameMatchEquals);
3286 platform_sp->FindProcesses (match_info, process_infos);
3287 const uint32_t num_matches = process_infos.GetSize();
3288 if (num_matches == 1)
3289 {
3290 attach_pid = process_infos.GetProcessIDAtIndex(0);
3291 // Fall through and attach using the above process ID
3292 }
3293 else
3294 {
3295 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3296 if (num_matches > 1)
3297 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3298 else
3299 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3300 }
3301 }
3302 else
3303 {
3304 error.SetErrorString ("invalid platform, can't find processes by name");
3305 return error;
3306 }
Greg Claytone996fd32011-03-08 22:40:15 +00003307 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003308 }
3309 else
Greg Clayton144f3a92011-11-15 03:53:30 +00003310 {
3311 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00003312 }
3313 }
Greg Clayton144f3a92011-11-15 03:53:30 +00003314
3315 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00003316 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003317 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00003318 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003319 {
Greg Clayton144f3a92011-11-15 03:53:30 +00003320
Ed Maste64fad602013-07-29 20:58:06 +00003321 if (m_public_run_lock.TrySetRunning())
Greg Clayton926cce72012-10-12 16:10:12 +00003322 {
3323 // Now attach using these arguments.
3324 m_should_detach = true;
Jim Ingham221d51c2013-05-08 00:35:16 +00003325 const bool restarted = false;
3326 SetPublicState (eStateAttaching, restarted);
Greg Clayton926cce72012-10-12 16:10:12 +00003327 error = DoAttachToProcessWithID (attach_pid, attach_info);
3328 }
3329 else
3330 {
3331 // This shouldn't happen
3332 error.SetErrorString("failed to acquire process run lock");
3333 }
3334
Greg Clayton144f3a92011-11-15 03:53:30 +00003335 if (error.Success())
3336 {
3337
3338 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3339 StartPrivateStateThread();
3340 }
3341 else
Greg Claytone996fd32011-03-08 22:40:15 +00003342 {
3343 if (GetID() != LLDB_INVALID_PROCESS_ID)
3344 {
3345 SetID (LLDB_INVALID_PROCESS_ID);
3346 const char *error_string = error.AsCString();
3347 if (error_string == NULL)
3348 error_string = "attach failed";
3349
3350 SetExitStatus(-1, error_string);
3351 }
3352 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003353 }
3354 }
3355 return error;
3356}
3357
Greg Clayton93d3c8332011-02-16 04:46:07 +00003358void
3359Process::CompleteAttach ()
3360{
3361 // Let the process subclass figure out at much as it can about the process
3362 // before we go looking for a dynamic loader plug-in.
3363 DidAttach();
3364
Jim Ingham4299fdb2011-09-15 01:10:17 +00003365 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3366 // the same as the one we've already set, switch architectures.
3367 PlatformSP platform_sp (m_target.GetPlatform ());
3368 assert (platform_sp.get());
3369 if (platform_sp)
3370 {
Greg Clayton70512312012-05-08 01:45:38 +00003371 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Clayton1e0c8842013-01-11 20:49:54 +00003372 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Clayton70512312012-05-08 01:45:38 +00003373 {
3374 ArchSpec platform_arch;
3375 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3376 if (platform_sp)
3377 {
3378 m_target.SetPlatform (platform_sp);
3379 m_target.SetArchitecture(platform_arch);
3380 }
3381 }
3382 else
3383 {
3384 ProcessInstanceInfo process_info;
3385 platform_sp->GetProcessInfo (GetID(), process_info);
3386 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callananbf4b7be2012-12-13 22:07:14 +00003387 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Clayton70512312012-05-08 01:45:38 +00003388 m_target.SetArchitecture (process_arch);
3389 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00003390 }
3391
3392 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00003393 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00003394 DynamicLoader *dyld = GetDynamicLoader ();
3395 if (dyld)
3396 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00003397
Jason Molendaeef51062013-11-05 03:57:19 +00003398 SystemRuntime *system_runtime = GetSystemRuntime ();
3399 if (system_runtime)
3400 system_runtime->DidAttach();
3401
Greg Clayton56d9a1b2011-08-22 02:49:39 +00003402 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00003403 // Figure out which one is the executable, and set that in our target:
Enrico Granata17598482012-11-08 02:22:02 +00003404 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003405 Mutex::Locker modules_locker(target_modules.GetMutex());
3406 size_t num_modules = target_modules.GetSize();
3407 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003408
Andy Gibbsa297a972013-06-19 19:04:53 +00003409 for (size_t i = 0; i < num_modules; i++)
Greg Clayton93d3c8332011-02-16 04:46:07 +00003410 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003411 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00003412 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00003413 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00003414 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003415 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00003416 break;
3417 }
3418 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00003419 if (new_executable_module_sp)
3420 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00003421}
3422
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003423Error
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003424Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytonb766a732011-02-04 01:58:07 +00003425{
Greg Claytonb766a732011-02-04 01:58:07 +00003426 m_abi_sp.reset();
3427 m_process_input_reader.reset();
3428
3429 // Find the process and its architecture. Make sure it matches the architecture
3430 // of the current Target, and if not adjust it.
3431
Jason Molenda4bd4e7e2012-09-29 04:02:01 +00003432 Error error (DoConnectRemote (strm, remote_url));
Greg Claytonb766a732011-02-04 01:58:07 +00003433 if (error.Success())
3434 {
Greg Clayton71337622011-02-24 22:24:29 +00003435 if (GetID() != LLDB_INVALID_PROCESS_ID)
3436 {
Greg Clayton32e0a752011-03-30 18:16:51 +00003437 EventSP event_sp;
3438 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3439
3440 if (state == eStateStopped || state == eStateCrashed)
3441 {
3442 // If we attached and actually have a process on the other end, then
3443 // this ended up being the equivalent of an attach.
3444 CompleteAttach ();
3445
3446 // This delays passing the stopped event to listeners till
3447 // CompleteAttach gets a chance to complete...
3448 HandlePrivateEvent (event_sp);
3449
3450 }
Greg Clayton71337622011-02-24 22:24:29 +00003451 }
Greg Clayton32e0a752011-03-30 18:16:51 +00003452
3453 if (PrivateStateThreadIsValid ())
3454 ResumePrivateStateThread ();
3455 else
3456 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00003457 }
3458 return error;
3459}
3460
3461
3462Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00003463Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003464{
Greg Clayton5160ce52013-03-27 23:08:40 +00003465 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003466 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003467 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00003468 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00003469 StateAsCString(m_public_state.GetValue()),
3470 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003471
3472 Error error (WillResume());
3473 // Tell the process it is about to resume before the thread list
3474 if (error.Success())
3475 {
Johnny Chenc4221e42010-12-02 20:53:05 +00003476 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003477 // can let all of our threads know that they are about to be
3478 // resumed. Threads will each be called with
3479 // Thread::WillResume(StateType) where StateType contains the state
3480 // that they are supposed to have when the process is resumed
3481 // (suspended/running/stepping). Threads should also check
3482 // their resume signal in lldb::Thread::GetResumeSignal()
Jim Ingham221d51c2013-05-08 00:35:16 +00003483 // to see if they are supposed to start back up with a signal.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003484 if (m_thread_list.WillResume())
3485 {
Jim Ingham372787f2012-04-07 00:00:41 +00003486 // Last thing, do the PreResumeActions.
3487 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003488 {
Jim Ingham0161b492013-02-09 01:29:05 +00003489 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham372787f2012-04-07 00:00:41 +00003490 }
3491 else
3492 {
3493 m_mod_id.BumpResumeID();
3494 error = DoResume();
3495 if (error.Success())
3496 {
3497 DidResume();
3498 m_thread_list.DidResume();
3499 if (log)
3500 log->Printf ("Process thinks the process has resumed.");
3501 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003502 }
3503 }
3504 else
3505 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00003506 // Somebody wanted to run without running. So generate a continue & a stopped event,
3507 // and let the world handle them.
3508 if (log)
3509 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3510
3511 SetPrivateState(eStateRunning);
3512 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003513 }
3514 }
Jim Ingham444586b2011-01-24 06:34:17 +00003515 else if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003516 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003517 return error;
3518}
3519
3520Error
Greg Claytonf9b57b92013-05-10 23:48:10 +00003521Process::Halt (bool clear_thread_plans)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003522{
Greg Claytonf9b57b92013-05-10 23:48:10 +00003523 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if
3524 // in case it was already set and some thread plan logic calls halt on its
3525 // own.
3526 m_clear_thread_plans_on_stop |= clear_thread_plans;
3527
Jim Inghamaacc3182012-06-06 00:29:30 +00003528 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3529 // we could just straightaway get another event. It just narrows the window...
3530 m_currently_handling_event.WaitForValueEqualTo(false);
3531
3532
Jim Inghambb3a2832011-01-29 01:49:25 +00003533 // Pause our private state thread so we can ensure no one else eats
3534 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003535 Listener halt_listener ("lldb.process.halt_listener");
3536 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003537
Jim Inghambb3a2832011-01-29 01:49:25 +00003538 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003539 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003540
Greg Clayton513c26c2011-01-29 07:10:55 +00003541 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003542 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003543
Greg Clayton513c26c2011-01-29 07:10:55 +00003544 bool caused_stop = false;
3545
3546 // Ask the process subclass to actually halt our process
3547 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003548 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003549 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003550 if (m_public_state.GetValue() == eStateAttaching)
3551 {
3552 SetExitStatus(SIGKILL, "Cancelled async attach.");
3553 Destroy ();
3554 }
3555 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003556 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003557 // If "caused_stop" is true, then DoHalt stopped the process. If
3558 // "caused_stop" is false, the process was already stopped.
3559 // If the DoHalt caused the process to stop, then we want to catch
3560 // this event and set the interrupted bool to true before we pass
3561 // this along so clients know that the process was interrupted by
3562 // a halt command.
3563 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003564 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003565 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003566 TimeValue timeout_time;
3567 timeout_time = TimeValue::Now();
3568 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003569 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3570 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003571
Jim Ingham0f16e732011-02-08 05:20:59 +00003572 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003573 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003574 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003575 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003576 }
3577 else
3578 {
Greg Clayton2637f822011-11-17 01:23:07 +00003579 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003580 {
3581 // We caused the process to interrupt itself, so mark this
3582 // as such in the stop event so clients can tell an interrupted
3583 // process from a natural stop
3584 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3585 }
3586 else
3587 {
Greg Clayton5160ce52013-03-27 23:08:40 +00003588 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003589 if (log)
3590 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3591 error.SetErrorString ("Did not get stopped event after halt.");
3592 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003593 }
3594 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003595 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003596 }
3597 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003598 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003599 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003600 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003601
3602 // Post any event we might have consumed. If all goes well, we will have
3603 // stopped the process, intercepted the event and set the interrupted
3604 // bool in the event. Post it to the private event queue and that will end up
3605 // correctly setting the state.
3606 if (event_sp)
3607 m_private_state_broadcaster.BroadcastEvent(event_sp);
3608
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003609 return error;
3610}
3611
3612Error
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003613Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3614{
3615 Error error;
3616 if (m_public_state.GetValue() == eStateRunning)
3617 {
3618 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3619 if (log)
3620 log->Printf("Process::Destroy() About to halt.");
3621 error = Halt();
3622 if (error.Success())
3623 {
3624 // Consume the halt event.
3625 TimeValue timeout (TimeValue::Now());
3626 timeout.OffsetWithSeconds(1);
3627 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3628
3629 // If the process exited while we were waiting for it to stop, put the exited event into
3630 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3631 // they don't have a process anymore...
3632
3633 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3634 {
3635 if (log)
3636 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3637 return error;
3638 }
3639 else
3640 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3641
3642 if (state != eStateStopped)
3643 {
3644 if (log)
3645 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3646 // If we really couldn't stop the process then we should just error out here, but if the
3647 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3648 StateType private_state = m_private_state.GetValue();
3649 if (private_state != eStateStopped)
3650 {
3651 return error;
3652 }
3653 }
3654 }
3655 else
3656 {
3657 if (log)
3658 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3659 }
3660 }
3661 return error;
3662}
3663
3664Error
Jim Inghamacff8952013-05-02 00:27:30 +00003665Process::Detach (bool keep_stopped)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003666{
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003667 EventSP exit_event_sp;
3668 Error error;
3669 m_destroy_in_process = true;
3670
3671 error = WillDetach();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003672
3673 if (error.Success())
3674 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003675 if (DetachRequiresHalt())
3676 {
3677 error = HaltForDestroyOrDetach (exit_event_sp);
3678 if (!error.Success())
3679 {
3680 m_destroy_in_process = false;
3681 return error;
3682 }
3683 else if (exit_event_sp)
3684 {
3685 // We shouldn't need to do anything else here. There's no process left to detach from...
3686 StopPrivateStateThread();
3687 m_destroy_in_process = false;
3688 return error;
3689 }
3690 }
3691
Jim Inghamacff8952013-05-02 00:27:30 +00003692 error = DoDetach(keep_stopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003693 if (error.Success())
3694 {
3695 DidDetach();
3696 StopPrivateStateThread();
3697 }
Jim Inghamacff8952013-05-02 00:27:30 +00003698 else
3699 {
3700 return error;
3701 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003702 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003703 m_destroy_in_process = false;
3704
3705 // If we exited when we were waiting for a process to stop, then
3706 // forward the event here so we don't lose the event
3707 if (exit_event_sp)
3708 {
3709 // Directly broadcast our exited event because we shut down our
3710 // private state thread above
3711 BroadcastEvent(exit_event_sp);
3712 }
3713
3714 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3715 // the last events through the event system, in which case we might strand the write lock. Unlock
3716 // it here so when we do to tear down the process we don't get an error destroying the lock.
3717
Ed Maste64fad602013-07-29 20:58:06 +00003718 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003719 return error;
3720}
3721
3722Error
3723Process::Destroy ()
3724{
Jim Ingham09437922013-03-01 20:04:25 +00003725
3726 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3727 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3728 // failed and the process stays around for some reason it won't be in a confused state.
3729
3730 m_destroy_in_process = true;
3731
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003732 Error error (WillDestroy());
3733 if (error.Success())
3734 {
Greg Clayton85fb1b92012-09-11 02:33:37 +00003735 EventSP exit_event_sp;
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003736 if (DestroyRequiresHalt())
Jim Ingham04e0a222012-05-23 15:46:31 +00003737 {
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003738 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Ingham04e0a222012-05-23 15:46:31 +00003739 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003740
Jim Inghamaacc3182012-06-06 00:29:30 +00003741 if (m_public_state.GetValue() != eStateRunning)
3742 {
3743 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3744 // kill it, we don't want it hitting a breakpoint...
3745 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3746 // we're not going to have much luck doing this now.
3747 m_thread_list.DiscardThreadPlans();
3748 DisableAllBreakpointSites();
3749 }
Jim Ingham8af3b9c2013-03-29 01:18:12 +00003750
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003751 error = DoDestroy();
3752 if (error.Success())
3753 {
3754 DidDestroy();
3755 StopPrivateStateThread();
3756 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003757 m_stdio_communication.StopReadThread();
3758 m_stdio_communication.Disconnect();
3759 if (m_process_input_reader && m_process_input_reader->IsActive())
3760 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3761 if (m_process_input_reader)
3762 m_process_input_reader.reset();
Greg Clayton85fb1b92012-09-11 02:33:37 +00003763
3764 // If we exited when we were waiting for a process to stop, then
3765 // forward the event here so we don't lose the event
3766 if (exit_event_sp)
3767 {
3768 // Directly broadcast our exited event because we shut down our
3769 // private state thread above
3770 BroadcastEvent(exit_event_sp);
3771 }
3772
Jim Inghamb1e2e842012-04-12 18:49:31 +00003773 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3774 // the last events through the event system, in which case we might strand the write lock. Unlock
3775 // it here so when we do to tear down the process we don't get an error destroying the lock.
Ed Maste64fad602013-07-29 20:58:06 +00003776 m_public_run_lock.SetStopped();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003777 }
Jim Ingham09437922013-03-01 20:04:25 +00003778
3779 m_destroy_in_process = false;
3780
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003781 return error;
3782}
3783
3784Error
3785Process::Signal (int signal)
3786{
3787 Error error (WillSignal());
3788 if (error.Success())
3789 {
3790 error = DoSignal(signal);
3791 if (error.Success())
3792 DidSignal();
3793 }
3794 return error;
3795}
3796
Greg Clayton514487e2011-02-15 21:59:32 +00003797lldb::ByteOrder
3798Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003799{
Greg Clayton514487e2011-02-15 21:59:32 +00003800 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003801}
3802
3803uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003804Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003805{
Greg Clayton514487e2011-02-15 21:59:32 +00003806 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003807}
3808
Greg Clayton514487e2011-02-15 21:59:32 +00003809
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003810bool
3811Process::ShouldBroadcastEvent (Event *event_ptr)
3812{
3813 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3814 bool return_value = true;
Greg Clayton5160ce52013-03-27 23:08:40 +00003815 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham0161b492013-02-09 01:29:05 +00003816
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003817 switch (state)
3818 {
Greg Claytonb766a732011-02-04 01:58:07 +00003819 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003820 case eStateAttaching:
3821 case eStateLaunching:
3822 case eStateDetached:
3823 case eStateExited:
3824 case eStateUnloaded:
3825 // These events indicate changes in the state of the debugging session, always report them.
3826 return_value = true;
3827 break;
3828 case eStateInvalid:
3829 // We stopped for no apparent reason, don't report it.
3830 return_value = false;
3831 break;
3832 case eStateRunning:
3833 case eStateStepping:
3834 // If we've started the target running, we handle the cases where we
3835 // are already running and where there is a transition from stopped to
3836 // running differently.
3837 // running -> running: Automatically suppress extra running events
3838 // stopped -> running: Report except when there is one or more no votes
3839 // and no yes votes.
3840 SynchronouslyNotifyStateChanged (state);
Jim Ingham1460e4b2014-01-10 23:46:59 +00003841 if (m_force_next_event_delivery)
3842 return_value = true;
3843 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003844 {
Jim Ingham1460e4b2014-01-10 23:46:59 +00003845 switch (m_last_broadcast_state)
3846 {
3847 case eStateRunning:
3848 case eStateStepping:
3849 // We always suppress multiple runnings with no PUBLIC stop in between.
3850 return_value = false;
3851 break;
3852 default:
3853 // TODO: make this work correctly. For now always report
3854 // run if we aren't running so we don't miss any runnning
3855 // events. If I run the lldb/test/thread/a.out file and
3856 // break at main.cpp:58, run and hit the breakpoints on
3857 // multiple threads, then somehow during the stepping over
3858 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003859
Jim Ingham1460e4b2014-01-10 23:46:59 +00003860 // This is a transition from stop to run.
3861 switch (m_thread_list.ShouldReportRun (event_ptr))
3862 {
3863 case eVoteYes:
3864 case eVoteNoOpinion:
3865 return_value = true;
3866 break;
3867 case eVoteNo:
3868 return_value = false;
3869 break;
3870 }
3871 break;
3872 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003873 }
3874 break;
3875 case eStateStopped:
3876 case eStateCrashed:
3877 case eStateSuspended:
3878 {
3879 // We've stopped. First see if we're going to restart the target.
3880 // If we are going to stop, then we always broadcast the event.
3881 // 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 +00003882 // If no thread has an opinion, we don't report it.
Jim Ingham221d51c2013-05-08 00:35:16 +00003883
Jim Inghamcb4ca112012-05-16 01:32:14 +00003884 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003885 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003886 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003887 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003888 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3889 event_ptr,
3890 StateAsCString(state));
3891 return_value = true;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003892 }
3893 else
3894 {
Jim Ingham221d51c2013-05-08 00:35:16 +00003895 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3896 bool should_resume = false;
3897
Jim Ingham0161b492013-02-09 01:29:05 +00003898 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3899 // Asking the thread list is also not likely to go well, since we are running again.
3900 // So in that case just report the event.
3901
Jim Ingham0161b492013-02-09 01:29:05 +00003902 if (!was_restarted)
3903 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
Jim Ingham221d51c2013-05-08 00:35:16 +00003904
3905 if (was_restarted || should_resume || m_resume_requested)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003906 {
Jim Ingham0161b492013-02-09 01:29:05 +00003907 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3908 if (log)
3909 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3910 should_resume,
3911 StateAsCString(state),
3912 was_restarted,
3913 stop_vote);
3914
3915 switch (stop_vote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003916 {
3917 case eVoteYes:
Jim Ingham0161b492013-02-09 01:29:05 +00003918 return_value = true;
3919 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003920 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003921 case eVoteNo:
3922 return_value = false;
3923 break;
3924 }
Jim Ingham0161b492013-02-09 01:29:05 +00003925
Jim Inghamcb95f342012-09-05 21:13:56 +00003926 if (!was_restarted)
Jim Ingham0161b492013-02-09 01:29:05 +00003927 {
3928 if (log)
3929 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3930 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Inghamcb95f342012-09-05 21:13:56 +00003931 PrivateResume ();
Jim Ingham0161b492013-02-09 01:29:05 +00003932 }
3933
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003934 }
3935 else
3936 {
3937 return_value = true;
3938 SynchronouslyNotifyStateChanged (state);
3939 }
3940 }
3941 }
Jim Ingham0161b492013-02-09 01:29:05 +00003942 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003943 }
Jim Ingham0161b492013-02-09 01:29:05 +00003944
Jim Ingham1460e4b2014-01-10 23:46:59 +00003945 // Forcing the next event delivery is a one shot deal. So reset it here.
3946 m_force_next_event_delivery = false;
3947
Jim Ingham0161b492013-02-09 01:29:05 +00003948 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3949 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3950 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3951 // because the PublicState reflects the last event pulled off the queue, and there may be several
3952 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3953 // yet. m_last_broadcast_state gets updated here.
3954
3955 if (return_value)
3956 m_last_broadcast_state = state;
3957
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003958 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00003959 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3960 event_ptr,
3961 StateAsCString(state),
3962 StateAsCString(m_last_broadcast_state),
3963 return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003964 return return_value;
3965}
3966
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003967
3968bool
Jim Ingham372787f2012-04-07 00:00:41 +00003969Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003970{
Greg Clayton5160ce52013-03-27 23:08:40 +00003971 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003972
Greg Clayton8b82f082011-04-12 05:54:46 +00003973 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003974 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003975 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3976
Jim Ingham372787f2012-04-07 00:00:41 +00003977 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003978 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003979
3980 // Create a thread that watches our internal state and controls which
3981 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003982 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003983 if (already_running)
Daniel Malead01b2952012-11-29 21:49:15 +00003984 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham372787f2012-04-07 00:00:41 +00003985 else
Daniel Malead01b2952012-11-29 21:49:15 +00003986 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003987
3988 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003989 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003990 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3991 if (success)
3992 {
3993 ResumePrivateStateThread();
3994 return true;
3995 }
3996 else
3997 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003998}
3999
4000void
4001Process::PausePrivateStateThread ()
4002{
4003 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
4004}
4005
4006void
4007Process::ResumePrivateStateThread ()
4008{
4009 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
4010}
4011
4012void
4013Process::StopPrivateStateThread ()
4014{
Greg Clayton8b82f082011-04-12 05:54:46 +00004015 if (PrivateStateThreadIsValid ())
4016 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004017 else
4018 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004019 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Inghamb1e2e842012-04-12 18:49:31 +00004020 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00004021 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Inghamb1e2e842012-04-12 18:49:31 +00004022 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004023}
4024
4025void
4026Process::ControlPrivateStateThread (uint32_t signal)
4027{
Greg Clayton5160ce52013-03-27 23:08:40 +00004028 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004029
4030 assert (signal == eBroadcastInternalStateControlStop ||
4031 signal == eBroadcastInternalStateControlPause ||
4032 signal == eBroadcastInternalStateControlResume);
4033
4034 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004035 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004036
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004037 // Signal the private state thread. First we should copy this is case the
4038 // thread starts exiting since the private state thread will NULL this out
4039 // when it exits
4040 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00004041 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004042 {
4043 TimeValue timeout_time;
4044 bool timed_out;
4045
4046 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
4047
4048 timeout_time = TimeValue::Now();
4049 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00004050 if (log)
4051 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004052 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
4053 m_private_state_control_wait.SetValue (false, eBroadcastNever);
4054
4055 if (signal == eBroadcastInternalStateControlStop)
4056 {
4057 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00004058 {
4059 Error error;
4060 Host::ThreadCancel (private_state_thread, &error);
4061 if (log)
4062 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
4063 }
4064 else
4065 {
4066 if (log)
4067 log->Printf ("The control event killed the private state thread without having to cancel.");
4068 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004069
4070 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00004071 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00004072 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004073 }
4074 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00004075 else
4076 {
4077 if (log)
4078 log->Printf ("Private state thread already dead, no need to signal it to stop.");
4079 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004080}
4081
4082void
Jim Inghamcfc09352012-07-27 23:57:19 +00004083Process::SendAsyncInterrupt ()
4084{
4085 if (PrivateStateThreadIsValid())
4086 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4087 else
4088 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
4089}
4090
4091void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004092Process::HandlePrivateEvent (EventSP &event_sp)
4093{
Greg Clayton5160ce52013-03-27 23:08:40 +00004094 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham221d51c2013-05-08 00:35:16 +00004095 m_resume_requested = false;
4096
Jim Inghamaacc3182012-06-06 00:29:30 +00004097 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00004098
Greg Clayton414f5d32011-01-25 02:58:48 +00004099 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00004100
4101 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00004102 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00004103 {
Jim Ingham754ab982011-01-29 04:05:41 +00004104 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham0161b492013-02-09 01:29:05 +00004105 if (log)
4106 log->Printf ("Ran next event action, result was %d.", action_result);
4107
Jim Inghambb3a2832011-01-29 01:49:25 +00004108 switch (action_result)
4109 {
4110 case NextEventAction::eEventActionSuccess:
4111 SetNextEventAction(NULL);
4112 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004113
Jim Inghambb3a2832011-01-29 01:49:25 +00004114 case NextEventAction::eEventActionRetry:
4115 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00004116
Jim Inghambb3a2832011-01-29 01:49:25 +00004117 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004118 // Handle Exiting Here. If we already got an exited event,
4119 // we should just propagate it. Otherwise, swallow this event,
4120 // and set our state to exit so the next event will kill us.
4121 if (new_state != eStateExited)
4122 {
4123 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00004124 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham221d51c2013-05-08 00:35:16 +00004125 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Jim Ingham2a5fdd42011-01-29 01:57:31 +00004126 SetNextEventAction(NULL);
4127 return;
4128 }
4129 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00004130 break;
4131 }
4132 }
4133
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004134 // See if we should broadcast this state to external clients?
4135 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004136
4137 if (should_broadcast)
4138 {
4139 if (log)
4140 {
Daniel Malead01b2952012-11-29 21:49:15 +00004141 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00004142 __FUNCTION__,
4143 GetID(),
4144 StateAsCString(new_state),
4145 StateAsCString (GetState ()),
4146 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004147 }
Jim Ingham9575d842011-03-11 03:53:59 +00004148 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00004149 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004150 PushProcessInputReader ();
Jim Inghamb78d73f2013-05-15 01:21:48 +00004151 else if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004152 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00004153
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004154 BroadcastEvent (event_sp);
4155 }
4156 else
4157 {
4158 if (log)
4159 {
Daniel Malead01b2952012-11-29 21:49:15 +00004160 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00004161 __FUNCTION__,
4162 GetID(),
4163 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00004164 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004165 }
4166 }
Jim Inghamaacc3182012-06-06 00:29:30 +00004167 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004168}
4169
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004170thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004171Process::PrivateStateThread (void *arg)
4172{
4173 Process *proc = static_cast<Process*> (arg);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004174 thread_result_t result = proc->RunPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004175 return result;
4176}
4177
Virgile Bellob2f1fb22013-08-23 12:44:05 +00004178thread_result_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004179Process::RunPrivateStateThread ()
4180{
Jim Ingham076b3042012-04-10 01:21:57 +00004181 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00004182 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004183
Greg Clayton5160ce52013-03-27 23:08:40 +00004184 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004185 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004186 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004187
4188 bool exit_now = false;
4189 while (!exit_now)
4190 {
4191 EventSP event_sp;
4192 WaitForEventsPrivate (NULL, event_sp, control_only);
4193 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
4194 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00004195 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004196 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 +00004197
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004198 switch (event_sp->GetType())
4199 {
4200 case eBroadcastInternalStateControlStop:
4201 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004202 break; // doing any internal state managment below
4203
4204 case eBroadcastInternalStateControlPause:
4205 control_only = true;
4206 break;
4207
4208 case eBroadcastInternalStateControlResume:
4209 control_only = false;
4210 break;
4211 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004212
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004213 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004214 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004215 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004216 else if (event_sp->GetType() == eBroadcastBitInterrupt)
4217 {
4218 if (m_public_state.GetValue() == eStateAttaching)
4219 {
4220 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004221 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 +00004222 BroadcastEvent (eBroadcastBitInterrupt, NULL);
4223 }
4224 else
4225 {
4226 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004227 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00004228 Halt();
4229 }
4230 continue;
4231 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004232
4233 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4234
4235 if (internal_state != eStateInvalid)
4236 {
Greg Claytonf9b57b92013-05-10 23:48:10 +00004237 if (m_clear_thread_plans_on_stop &&
4238 StateIsStoppedState(internal_state, true))
4239 {
4240 m_clear_thread_plans_on_stop = false;
4241 m_thread_list.DiscardThreadPlans();
4242 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004243 HandlePrivateEvent (event_sp);
4244 }
4245
Greg Clayton58d1c9a2010-10-18 04:14:23 +00004246 if (internal_state == eStateInvalid ||
4247 internal_state == eStateExited ||
4248 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004249 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004250 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004251 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 +00004252
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004253 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004254 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004255 }
4256
Caroline Tice20ad3c42010-10-29 21:48:37 +00004257 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004258 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004259 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004260
Ed Maste64fad602013-07-29 20:58:06 +00004261 m_public_run_lock.SetStopped();
Greg Clayton6ed95942011-01-22 07:12:45 +00004262 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4263 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004264 return NULL;
4265}
4266
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004267//------------------------------------------------------------------
4268// Process Event Data
4269//------------------------------------------------------------------
4270
4271Process::ProcessEventData::ProcessEventData () :
4272 EventData (),
4273 m_process_sp (),
4274 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00004275 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004276 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004277 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004278{
4279}
4280
4281Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4282 EventData (),
4283 m_process_sp (process_sp),
4284 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00004285 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00004286 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004287 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004288{
4289}
4290
4291Process::ProcessEventData::~ProcessEventData()
4292{
4293}
4294
4295const ConstString &
4296Process::ProcessEventData::GetFlavorString ()
4297{
4298 static ConstString g_flavor ("Process::ProcessEventData");
4299 return g_flavor;
4300}
4301
4302const ConstString &
4303Process::ProcessEventData::GetFlavor () const
4304{
4305 return ProcessEventData::GetFlavorString ();
4306}
4307
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004308void
4309Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4310{
4311 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00004312 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4313 // the public event queue, then other times when we're pretending that this is where we stopped at the
4314 // end of expression evaluation. m_update_state is used to distinguish these
4315 // three cases; it is 0 when we're just pulling it off for private handling,
Jim Ingham221d51c2013-05-08 00:35:16 +00004316 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Jim Inghama8604692011-05-22 21:45:01 +00004317 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004318 return;
Jim Ingham0161b492013-02-09 01:29:05 +00004319
Jim Ingham221d51c2013-05-08 00:35:16 +00004320 m_process_sp->SetPublicState (m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004321
4322 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4323 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00004324 {
4325 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00004326 uint32_t num_threads = curr_thread_list.GetSize();
4327 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00004328
Jim Ingham4b536182011-08-09 02:12:22 +00004329 // The actions might change one of the thread's stop_info's opinions about whether we should
4330 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00004331
4332 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4333 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4334 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4335 // 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
4336 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00004337 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00004338 for (idx = 0; idx < num_threads; ++idx)
4339 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4340
Jim Inghamc7078c22012-12-13 22:24:15 +00004341 // Use this to track whether we should continue from here. We will only continue the target running if
4342 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4343 // then it doesn't matter what the other threads say...
4344
4345 bool still_should_stop = false;
Jim Ingham4b536182011-08-09 02:12:22 +00004346
Jim Ingham0ad7e052013-04-25 02:04:59 +00004347 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4348 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4349 // thing to do is, and it's better to let the user decide than continue behind their backs.
4350
4351 bool does_anybody_have_an_opinion = false;
4352
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004353 for (idx = 0; idx < num_threads; ++idx)
4354 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00004355 curr_thread_list = m_process_sp->GetThreadList();
4356 if (curr_thread_list.GetSize() != num_threads)
4357 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004358 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004359 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004360 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 +00004361 break;
4362 }
4363
4364 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4365
4366 if (thread_sp->GetIndexID() != thread_index_array[idx])
4367 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004368 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00004369 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00004370 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00004371 idx,
4372 thread_index_array[idx],
4373 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00004374 break;
4375 }
4376
Jim Inghamb15bfc72010-10-20 00:39:53 +00004377 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham5d88a062012-10-16 00:09:33 +00004378 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004379 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004380 does_anybody_have_an_opinion = true;
Jim Ingham0161b492013-02-09 01:29:05 +00004381 bool this_thread_wants_to_stop;
4382 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham4b536182011-08-09 02:12:22 +00004383 {
Jim Ingham0161b492013-02-09 01:29:05 +00004384 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4385 }
4386 else
4387 {
4388 stop_info_sp->PerformAction(event_ptr);
4389 // The stop action might restart the target. If it does, then we want to mark that in the
4390 // event so that whoever is receiving it will know to wait for the running event and reflect
4391 // that state appropriately.
4392 // We also need to stop processing actions, since they aren't expecting the target to be running.
4393
4394 // FIXME: we might have run.
4395 if (stop_info_sp->HasTargetRunSinceMe())
4396 {
4397 SetRestarted (true);
4398 break;
4399 }
4400
4401 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00004402 }
Jim Inghamc7078c22012-12-13 22:24:15 +00004403
Jim Inghamc7078c22012-12-13 22:24:15 +00004404 if (still_should_stop == false)
4405 still_should_stop = this_thread_wants_to_stop;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004406 }
4407 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00004408
Ashok Thirumurthicf7c55e2013-04-18 14:38:20 +00004409
Jim Inghama8ca6e22013-05-03 23:04:37 +00004410 if (!GetRestarted())
Jim Ingham9575d842011-03-11 03:53:59 +00004411 {
Jim Ingham0ad7e052013-04-25 02:04:59 +00004412 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham4b536182011-08-09 02:12:22 +00004413 {
4414 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00004415 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00004416 // Use the public resume method here, since this is just
4417 // extending a public resume.
Jim Ingham0161b492013-02-09 01:29:05 +00004418 m_process_sp->PrivateResume();
Jim Ingham4b536182011-08-09 02:12:22 +00004419 }
4420 else
4421 {
4422 // If we didn't restart, run the Stop Hooks here:
4423 // They might also restart the target, so watch for that.
4424 m_process_sp->GetTarget().RunStopHooks();
4425 if (m_process_sp->GetPrivateState() == eStateRunning)
4426 SetRestarted(true);
4427 }
Jim Ingham9575d842011-03-11 03:53:59 +00004428 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004429 }
4430}
4431
4432void
4433Process::ProcessEventData::Dump (Stream *s) const
4434{
4435 if (m_process_sp)
Daniel Malead01b2952012-11-29 21:49:15 +00004436 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004437
Greg Clayton8b82f082011-04-12 05:54:46 +00004438 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004439}
4440
4441const Process::ProcessEventData *
4442Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4443{
4444 if (event_ptr)
4445 {
4446 const EventData *event_data = event_ptr->GetData();
4447 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4448 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4449 }
4450 return NULL;
4451}
4452
4453ProcessSP
4454Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4455{
4456 ProcessSP process_sp;
4457 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4458 if (data)
4459 process_sp = data->GetProcessSP();
4460 return process_sp;
4461}
4462
4463StateType
4464Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4465{
4466 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4467 if (data == NULL)
4468 return eStateInvalid;
4469 else
4470 return data->GetState();
4471}
4472
4473bool
4474Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4475{
4476 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4477 if (data == NULL)
4478 return false;
4479 else
4480 return data->GetRestarted();
4481}
4482
4483void
4484Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4485{
4486 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4487 if (data != NULL)
4488 data->SetRestarted(new_value);
4489}
4490
Jim Ingham0161b492013-02-09 01:29:05 +00004491size_t
4492Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4493{
4494 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4495 if (data != NULL)
4496 return data->GetNumRestartedReasons();
4497 else
4498 return 0;
4499}
4500
4501const char *
4502Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4503{
4504 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4505 if (data != NULL)
4506 return data->GetRestartedReasonAtIndex(idx);
4507 else
4508 return NULL;
4509}
4510
4511void
4512Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4513{
4514 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4515 if (data != NULL)
4516 data->AddRestartedReason(reason);
4517}
4518
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004519bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00004520Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4521{
4522 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4523 if (data == NULL)
4524 return false;
4525 else
4526 return data->GetInterrupted ();
4527}
4528
4529void
4530Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4531{
4532 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4533 if (data != NULL)
4534 data->SetInterrupted(new_value);
4535}
4536
4537bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004538Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4539{
4540 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4541 if (data)
4542 {
4543 data->SetUpdateStateOnRemoval();
4544 return true;
4545 }
4546 return false;
4547}
4548
Greg Claytond9e416c2012-02-18 05:35:26 +00004549lldb::TargetSP
4550Process::CalculateTarget ()
4551{
4552 return m_target.shared_from_this();
4553}
4554
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004555void
Greg Clayton0603aa92010-10-04 01:05:56 +00004556Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004557{
Greg Claytonc14ee322011-09-22 04:58:26 +00004558 exe_ctx.SetTargetPtr (&m_target);
4559 exe_ctx.SetProcessPtr (this);
4560 exe_ctx.SetThreadPtr(NULL);
4561 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00004562}
4563
Greg Claytone996fd32011-03-08 22:40:15 +00004564//uint32_t
4565//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4566//{
4567// return 0;
4568//}
4569//
4570//ArchSpec
4571//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4572//{
4573// return Host::GetArchSpecForExistingProcess (pid);
4574//}
4575//
4576//ArchSpec
4577//Process::GetArchSpecForExistingProcess (const char *process_name)
4578//{
4579// return Host::GetArchSpecForExistingProcess (process_name);
4580//}
4581//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004582void
4583Process::AppendSTDOUT (const char * s, size_t len)
4584{
Greg Clayton3af9ea52010-11-18 05:57:03 +00004585 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004586 m_stdout_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004587 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004588}
4589
4590void
Greg Clayton93e86192011-11-13 04:45:22 +00004591Process::AppendSTDERR (const char * s, size_t len)
4592{
4593 Mutex::Locker locker (m_stdio_communication_mutex);
4594 m_stderr_data.append (s, len);
Greg Clayton35a4cc52012-10-29 20:52:08 +00004595 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Clayton93e86192011-11-13 04:45:22 +00004596}
4597
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004598void
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004599Process::BroadcastAsyncProfileData(const std::string &one_profile_data)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004600{
4601 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004602 m_profile_data.push_back(one_profile_data);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004603 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4604}
4605
4606size_t
4607Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4608{
4609 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004610 if (m_profile_data.empty())
4611 return 0;
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004612
4613 std::string &one_profile_data = m_profile_data.front();
4614 size_t bytes_available = one_profile_data.size();
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004615 if (bytes_available > 0)
4616 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004617 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004618 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004619 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004620 if (bytes_available > buf_size)
4621 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004622 memcpy(buf, one_profile_data.c_str(), buf_size);
4623 one_profile_data.erase(0, buf_size);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004624 bytes_available = buf_size;
4625 }
4626 else
4627 {
Han Ming Ong91ed6b82013-06-24 18:15:05 +00004628 memcpy(buf, one_profile_data.c_str(), bytes_available);
Han Ming Ong929a94f2012-11-29 22:14:45 +00004629 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongab3b8b22012-11-17 00:21:04 +00004630 }
4631 }
4632 return bytes_available;
4633}
4634
4635
Greg Clayton93e86192011-11-13 04:45:22 +00004636//------------------------------------------------------------------
4637// Process STDIO
4638//------------------------------------------------------------------
4639
4640size_t
4641Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4642{
4643 Mutex::Locker locker(m_stdio_communication_mutex);
4644 size_t bytes_available = m_stdout_data.size();
4645 if (bytes_available > 0)
4646 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004647 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004648 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004649 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004650 if (bytes_available > buf_size)
4651 {
4652 memcpy(buf, m_stdout_data.c_str(), buf_size);
4653 m_stdout_data.erase(0, buf_size);
4654 bytes_available = buf_size;
4655 }
4656 else
4657 {
4658 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4659 m_stdout_data.clear();
4660 }
4661 }
4662 return bytes_available;
4663}
4664
4665
4666size_t
4667Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4668{
4669 Mutex::Locker locker(m_stdio_communication_mutex);
4670 size_t bytes_available = m_stderr_data.size();
4671 if (bytes_available > 0)
4672 {
Greg Clayton5160ce52013-03-27 23:08:40 +00004673 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton93e86192011-11-13 04:45:22 +00004674 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +00004675 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Clayton93e86192011-11-13 04:45:22 +00004676 if (bytes_available > buf_size)
4677 {
4678 memcpy(buf, m_stderr_data.c_str(), buf_size);
4679 m_stderr_data.erase(0, buf_size);
4680 bytes_available = buf_size;
4681 }
4682 else
4683 {
4684 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4685 m_stderr_data.clear();
4686 }
4687 }
4688 return bytes_available;
4689}
4690
4691void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004692Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4693{
4694 Process *process = (Process *) baton;
4695 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4696}
4697
4698size_t
4699Process::ProcessInputReaderCallback (void *baton,
4700 InputReader &reader,
4701 lldb::InputReaderAction notification,
4702 const char *bytes,
4703 size_t bytes_len)
4704{
4705 Process *process = (Process *) baton;
4706
4707 switch (notification)
4708 {
4709 case eInputReaderActivate:
4710 break;
4711
4712 case eInputReaderDeactivate:
4713 break;
4714
4715 case eInputReaderReactivate:
4716 break;
4717
Caroline Tice969ed3d2011-05-02 20:41:46 +00004718 case eInputReaderAsynchronousOutputWritten:
4719 break;
4720
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004721 case eInputReaderGotToken:
4722 {
4723 Error error;
4724 process->PutSTDIN (bytes, bytes_len, error);
4725 }
4726 break;
4727
Caroline Ticeefed6132010-11-19 20:47:54 +00004728 case eInputReaderInterrupt:
Jim Inghamfc65a502013-06-19 00:56:17 +00004729 process->SendAsyncInterrupt();
Caroline Ticeefed6132010-11-19 20:47:54 +00004730 break;
4731
4732 case eInputReaderEndOfFile:
4733 process->AppendSTDOUT ("^D", 2);
4734 break;
4735
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004736 case eInputReaderDone:
4737 break;
4738
4739 }
4740
4741 return bytes_len;
4742}
4743
4744void
4745Process::ResetProcessInputReader ()
4746{
4747 m_process_input_reader.reset();
4748}
4749
4750void
Greg Claytonee95ed52011-11-17 22:14:31 +00004751Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004752{
4753 // First set up the Read Thread for reading/handling process I/O
4754
Greg Clayton7b0992d2013-04-18 22:45:39 +00004755 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004756
4757 if (conn_ap.get())
4758 {
4759 m_stdio_communication.SetConnection (conn_ap.release());
4760 if (m_stdio_communication.IsConnected())
4761 {
4762 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4763 m_stdio_communication.StartReadThread();
4764
4765 // Now read thread is set up, set up input reader.
4766
4767 if (!m_process_input_reader.get())
4768 {
4769 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4770 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4771 this,
4772 eInputReaderGranularityByte,
4773 NULL,
4774 NULL,
4775 false));
4776
4777 if (err.Fail())
4778 m_process_input_reader.reset();
4779 }
4780 }
4781 }
4782}
4783
4784void
4785Process::PushProcessInputReader ()
4786{
4787 if (m_process_input_reader && !m_process_input_reader->IsActive())
4788 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4789}
4790
4791void
4792Process::PopProcessInputReader ()
4793{
4794 if (m_process_input_reader && m_process_input_reader->IsActive())
4795 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4796}
4797
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004798// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004799void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004800Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004801{
Greg Clayton67cc0632012-08-22 17:17:09 +00004802// static std::vector<OptionEnumValueElement> g_plugins;
4803//
4804// int i=0;
4805// const char *name;
4806// OptionEnumValueElement option_enum;
4807// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4808// {
4809// if (name)
4810// {
4811// option_enum.value = i;
4812// option_enum.string_value = name;
4813// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4814// g_plugins.push_back (option_enum);
4815// }
4816// ++i;
4817// }
4818// option_enum.value = 0;
4819// option_enum.string_value = NULL;
4820// option_enum.usage = NULL;
4821// g_plugins.push_back (option_enum);
4822//
4823// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4824// {
4825// if (::strcmp (name, "plugin") == 0)
4826// {
4827// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4828// break;
4829// }
4830// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004831//
Greg Clayton6920b522012-08-22 18:39:03 +00004832 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004833}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004834
Greg Clayton99d0faf2010-11-18 23:32:35 +00004835void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004836Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004837{
Greg Clayton6920b522012-08-22 18:39:03 +00004838 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004839}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004840
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004841ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004842Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004843 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004844 const EvaluateExpressionOptions &options,
Jim Inghamf48169b2010-11-30 02:22:11 +00004845 Stream &errors)
4846{
4847 ExecutionResults return_value = eExecutionSetupError;
4848
Jim Ingham77787032011-01-20 02:03:18 +00004849 if (thread_plan_sp.get() == NULL)
4850 {
4851 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004852 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004853 }
Jim Ingham7d7931d2013-03-28 00:05:34 +00004854
4855 if (!thread_plan_sp->ValidatePlan(NULL))
4856 {
4857 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4858 return eExecutionSetupError;
4859 }
4860
Greg Claytonc14ee322011-09-22 04:58:26 +00004861 if (exe_ctx.GetProcessPtr() != this)
4862 {
4863 errors.Printf("RunThreadPlan called on wrong process.");
4864 return eExecutionSetupError;
4865 }
4866
4867 Thread *thread = exe_ctx.GetThreadPtr();
4868 if (thread == NULL)
4869 {
4870 errors.Printf("RunThreadPlan called with invalid thread.");
4871 return eExecutionSetupError;
4872 }
Jim Ingham77787032011-01-20 02:03:18 +00004873
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004874 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4875 // For that to be true the plan can't be private - since private plans suppress themselves in the
4876 // GetCompletedPlan call.
4877
4878 bool orig_plan_private = thread_plan_sp->GetPrivate();
4879 thread_plan_sp->SetPrivate(false);
4880
Jim Ingham444586b2011-01-24 06:34:17 +00004881 if (m_private_state.GetValue() != eStateStopped)
4882 {
4883 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004884 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004885 }
4886
Jim Ingham66243842011-08-13 00:56:10 +00004887 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004888 const uint32_t thread_idx_id = thread->GetIndexID();
Jason Molendab57e4a12013-11-04 09:33:30 +00004889 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
Jim Ingham11b0e052013-02-19 23:22:45 +00004890 if (!selected_frame_sp)
4891 {
4892 thread->SetSelectedFrame(0);
4893 selected_frame_sp = thread->GetSelectedFrame();
4894 if (!selected_frame_sp)
4895 {
4896 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4897 return eExecutionSetupError;
4898 }
4899 }
4900
4901 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004902
4903 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4904 // so we should arrange to reset them as well.
4905
Greg Claytonc14ee322011-09-22 04:58:26 +00004906 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004907
Jim Ingham66243842011-08-13 00:56:10 +00004908 uint32_t selected_tid;
4909 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004910 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004911 {
4912 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004913 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004914 }
4915 else
4916 {
4917 selected_tid = LLDB_INVALID_THREAD_ID;
4918 }
4919
Jim Ingham372787f2012-04-07 00:00:41 +00004920 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004921 lldb::StateType old_state;
4922 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004923
Greg Clayton5160ce52013-03-27 23:08:40 +00004924 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004925 if (Host::GetCurrentThread() == m_private_state_thread)
4926 {
Jim Ingham076b3042012-04-10 01:21:57 +00004927 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4928 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004929 // 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 +00004930 // we are fielding public events here.
4931 if (log)
Jason Molendad251c9d2012-11-17 01:41:04 +00004932 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 +00004933
4934
Jim Ingham372787f2012-04-07 00:00:41 +00004935 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004936
4937 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4938 // returning control here.
4939 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4940 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4941 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4942 // do just what we want.
4943 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4944 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4945 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4946 old_state = m_public_state.GetValue();
4947 m_public_state.SetValueNoLock(eStateStopped);
4948
4949 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004950 StartPrivateStateThread(true);
4951 }
4952
4953 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004954
Jim Ingham6fbc48b2013-11-07 00:11:47 +00004955 if (options.GetDebug())
4956 {
4957 // In this case, we aren't actually going to run, we just want to stop right away.
4958 // Flush this thread so we will refetch the stacks and show the correct backtrace.
4959 // FIXME: To make this prettier we should invent some stop reason for this, but that
4960 // is only cosmetic, and this functionality is only of use to lldb developers who can
4961 // live with not pretty...
4962 thread->Flush();
4963 return eExecutionStoppedForDebug;
4964 }
4965
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004966 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004967
Sean Callanana46ec452012-07-11 21:31:24 +00004968 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004969
Jim Ingham77787032011-01-20 02:03:18 +00004970 {
Sean Callanana46ec452012-07-11 21:31:24 +00004971 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4972 // restored on exit to the function.
4973 //
4974 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4975 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004976
Sean Callanana46ec452012-07-11 21:31:24 +00004977 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004978
Jim Inghamf48169b2010-11-30 02:22:11 +00004979 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004980 {
4981 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004982 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malead01b2952012-11-29 21:49:15 +00004983 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanana46ec452012-07-11 21:31:24 +00004984 thread->GetIndexID(),
4985 thread->GetID(),
4986 s.GetData());
4987 }
4988
4989 bool got_event;
4990 lldb::EventSP event_sp;
4991 lldb::StateType stop_state = lldb::eStateInvalid;
4992
4993 TimeValue* timeout_ptr = NULL;
4994 TimeValue real_timeout;
4995
Jim Ingham0161b492013-02-09 01:29:05 +00004996 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 +00004997 bool do_resume = true;
Jim Ingham184e9812013-01-15 02:47:48 +00004998 bool handle_running_event = true;
Jim Ingham35e1bda2012-10-16 21:41:58 +00004999 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanana46ec452012-07-11 21:31:24 +00005000
Jim Ingham0161b492013-02-09 01:29:05 +00005001 // This is just for accounting:
5002 uint32_t num_resumes = 0;
5003
5004 TimeValue one_thread_timeout = TimeValue::Now();
5005 TimeValue final_timeout = one_thread_timeout;
5006
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005007 uint32_t timeout_usec = options.GetTimeoutUsec();
5008 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005009 {
5010 // If we are running all threads then we take half the time to run all threads, bounded by
5011 // .25 sec.
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005012 if (options.GetTimeoutUsec() == 0)
Jim Ingham0161b492013-02-09 01:29:05 +00005013 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
5014 else
5015 {
Greg Clayton03da4cc2013-04-19 21:31:16 +00005016 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham0161b492013-02-09 01:29:05 +00005017 if (computed_timeout > default_one_thread_timeout_usec)
5018 computed_timeout = default_one_thread_timeout_usec;
5019 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
5020 }
5021 final_timeout.OffsetWithMicroSeconds (timeout_usec);
5022 }
5023 else
5024 {
5025 if (timeout_usec != 0)
5026 final_timeout.OffsetWithMicroSeconds(timeout_usec);
5027 }
5028
Jim Ingham1460e4b2014-01-10 23:46:59 +00005029 // This isn't going to work if there are unfetched events on the queue.
5030 // Are there cases where we might want to run the remaining events here, and then try to
5031 // call the function? That's probably being too tricky for our own good.
5032
5033 Event *other_events = listener.PeekAtNextEvent();
5034 if (other_events != NULL)
5035 {
5036 errors.Printf("Calling RunThreadPlan with pending events on the queue.");
5037 return eExecutionSetupError;
5038 }
5039
5040 // We also need to make sure that the next event is delivered. We might be calling a function as part of
5041 // a thread plan, in which case the last delivered event could be the running event, and we don't want
5042 // event coalescing to cause us to lose OUR running event...
5043 ForceNextEventDelivery();
5044
Jim Ingham8559a352012-11-26 23:52:18 +00005045 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
5046 // So don't call return anywhere within it.
5047
Sean Callanana46ec452012-07-11 21:31:24 +00005048 while (1)
5049 {
5050 // We usually want to resume the process if we get to the top of the loop.
5051 // The only exception is if we get two running events with no intervening
5052 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham0161b492013-02-09 01:29:05 +00005053 if (log)
5054 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
5055 do_resume,
5056 handle_running_event,
5057 before_first_timeout);
Sean Callanana46ec452012-07-11 21:31:24 +00005058
Jim Ingham184e9812013-01-15 02:47:48 +00005059 if (do_resume || handle_running_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005060 {
5061 // Do the initial resume and wait for the running event before going further.
5062
Jim Ingham184e9812013-01-15 02:47:48 +00005063 if (do_resume)
Sean Callanana46ec452012-07-11 21:31:24 +00005064 {
Jim Ingham0161b492013-02-09 01:29:05 +00005065 num_resumes++;
Jim Ingham184e9812013-01-15 02:47:48 +00005066 Error resume_error = PrivateResume ();
5067 if (!resume_error.Success())
5068 {
Jim Ingham0161b492013-02-09 01:29:05 +00005069 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
5070 num_resumes,
5071 resume_error.AsCString());
Jim Ingham184e9812013-01-15 02:47:48 +00005072 return_value = eExecutionSetupError;
5073 break;
5074 }
Sean Callanana46ec452012-07-11 21:31:24 +00005075 }
Sean Callanana46ec452012-07-11 21:31:24 +00005076
Jim Ingham0161b492013-02-09 01:29:05 +00005077 TimeValue resume_timeout = TimeValue::Now();
5078 resume_timeout.OffsetWithMicroSeconds(500000);
5079
5080 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005081 if (!got_event)
5082 {
5083 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005084 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
5085 num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005086
Jim Ingham0161b492013-02-09 01:29:05 +00005087 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanana46ec452012-07-11 21:31:24 +00005088 return_value = eExecutionSetupError;
5089 break;
5090 }
5091
5092 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham0161b492013-02-09 01:29:05 +00005093
Sean Callanana46ec452012-07-11 21:31:24 +00005094 if (stop_state != eStateRunning)
5095 {
Jim Ingham0161b492013-02-09 01:29:05 +00005096 bool restarted = false;
5097
5098 if (stop_state == eStateStopped)
5099 {
5100 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
5101 if (log)
5102 log->Printf("Process::RunThreadPlan(): didn't get running event after "
5103 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
5104 num_resumes,
5105 StateAsCString(stop_state),
5106 restarted,
5107 do_resume,
5108 handle_running_event);
5109 }
5110
5111 if (restarted)
5112 {
5113 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
5114 // event here. But if I do, the best thing is to Halt and then get out of here.
5115 Halt();
5116 }
5117
Jim Ingham35e1bda2012-10-16 21:41:58 +00005118 errors.Printf("Didn't get running event after initial resume, got %s instead.",
5119 StateAsCString(stop_state));
Sean Callanana46ec452012-07-11 21:31:24 +00005120 return_value = eExecutionSetupError;
5121 break;
5122 }
5123
5124 if (log)
5125 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
5126 // We need to call the function synchronously, so spin waiting for it to return.
5127 // If we get interrupted while executing, we're going to lose our context, and
5128 // won't be able to gather the result at this point.
5129 // We set the timeout AFTER the resume, since the resume takes some time and we
5130 // don't want to charge that to the timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005131 }
Jim Ingham0f16e732011-02-08 05:20:59 +00005132 else
5133 {
Sean Callanana46ec452012-07-11 21:31:24 +00005134 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005135 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005136 }
Jim Ingham0161b492013-02-09 01:29:05 +00005137
5138 if (before_first_timeout)
5139 {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005140 if (options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005141 timeout_ptr = &one_thread_timeout;
5142 else
5143 {
5144 if (timeout_usec == 0)
5145 timeout_ptr = NULL;
5146 else
5147 timeout_ptr = &final_timeout;
5148 }
5149 }
5150 else
5151 {
5152 if (timeout_usec == 0)
5153 timeout_ptr = NULL;
5154 else
5155 timeout_ptr = &final_timeout;
5156 }
5157
5158 do_resume = true;
5159 handle_running_event = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00005160
Sean Callanana46ec452012-07-11 21:31:24 +00005161 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00005162 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00005163
Jim Ingham0f16e732011-02-08 05:20:59 +00005164 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00005165 {
Sean Callanana46ec452012-07-11 21:31:24 +00005166 if (timeout_ptr)
5167 {
Matt Kopec676a4872013-02-21 23:55:31 +00005168 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham0161b492013-02-09 01:29:05 +00005169 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
5170 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanana46ec452012-07-11 21:31:24 +00005171 }
Jim Ingham20829ac2011-08-09 22:24:33 +00005172 else
Sean Callanana46ec452012-07-11 21:31:24 +00005173 {
5174 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
5175 }
5176 }
5177
5178 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
5179
5180 if (got_event)
5181 {
5182 if (event_sp.get())
5183 {
5184 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005185 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005186 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005187 Halt();
Jim Inghamcfc09352012-07-27 23:57:19 +00005188 return_value = eExecutionInterrupted;
5189 errors.Printf ("Execution halted by user interrupt.");
5190 if (log)
5191 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham0161b492013-02-09 01:29:05 +00005192 break;
Jim Inghamcfc09352012-07-27 23:57:19 +00005193 }
5194 else
5195 {
5196 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5197 if (log)
5198 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
5199
5200 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00005201 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005202 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00005203 {
Jim Ingham0161b492013-02-09 01:29:05 +00005204 // We stopped, figure out what we are going to do now.
Jim Inghamcfc09352012-07-27 23:57:19 +00005205 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
5206 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005207 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005208 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00005209 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00005210 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
5211 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00005212 }
5213 else
5214 {
Jim Ingham0161b492013-02-09 01:29:05 +00005215 // If we were restarted, we just need to go back up to fetch another event.
5216 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Inghamcfc09352012-07-27 23:57:19 +00005217 {
5218 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005219 {
5220 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
5221 }
5222 keep_going = true;
5223 do_resume = false;
5224 handle_running_event = true;
5225
Jim Inghamcfc09352012-07-27 23:57:19 +00005226 }
5227 else
5228 {
Jim Ingham0161b492013-02-09 01:29:05 +00005229
5230 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
5231 StopReason stop_reason = eStopReasonInvalid;
5232 if (stop_info_sp)
5233 stop_reason = stop_info_sp->GetStopReason();
5234
5235
5236 // FIXME: We only check if the stop reason is plan complete, should we make sure that
5237 // it is OUR plan that is complete?
5238 if (stop_reason == eStopReasonPlanComplete)
Jim Ingham184e9812013-01-15 02:47:48 +00005239 {
5240 if (log)
Jim Ingham0161b492013-02-09 01:29:05 +00005241 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
5242 // Now mark this plan as private so it doesn't get reported as the stop reason
5243 // after this point.
5244 if (thread_plan_sp)
5245 thread_plan_sp->SetPrivate (orig_plan_private);
5246 return_value = eExecutionCompleted;
Jim Ingham184e9812013-01-15 02:47:48 +00005247 }
5248 else
5249 {
Jim Ingham0161b492013-02-09 01:29:05 +00005250 // Something restarted the target, so just wait for it to stop for real.
Jim Ingham184e9812013-01-15 02:47:48 +00005251 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham0161b492013-02-09 01:29:05 +00005252 {
5253 if (log)
5254 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Ingham184e9812013-01-15 02:47:48 +00005255 return_value = eExecutionHitBreakpoint;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005256 if (!options.DoesIgnoreBreakpoints())
Sean Callanan4b388c92013-07-30 19:54:09 +00005257 {
5258 event_to_broadcast_sp = event_sp;
5259 }
Jim Ingham0161b492013-02-09 01:29:05 +00005260 }
Jim Ingham184e9812013-01-15 02:47:48 +00005261 else
Jim Ingham0161b492013-02-09 01:29:05 +00005262 {
5263 if (log)
5264 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005265 if (!options.DoesUnwindOnError())
Sean Callanan4b388c92013-07-30 19:54:09 +00005266 event_to_broadcast_sp = event_sp;
Jim Ingham184e9812013-01-15 02:47:48 +00005267 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005268 }
Jim Ingham184e9812013-01-15 02:47:48 +00005269 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005270 }
Sean Callanana46ec452012-07-11 21:31:24 +00005271 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005272 }
5273 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005274
Jim Inghamcfc09352012-07-27 23:57:19 +00005275 case lldb::eStateRunning:
Jim Ingham0161b492013-02-09 01:29:05 +00005276 // This shouldn't really happen, but sometimes we do get two running events without an
5277 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Inghamcfc09352012-07-27 23:57:19 +00005278 do_resume = false;
5279 keep_going = true;
Jim Ingham184e9812013-01-15 02:47:48 +00005280 handle_running_event = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00005281 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005282
Jim Inghamcfc09352012-07-27 23:57:19 +00005283 default:
5284 if (log)
5285 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5286
5287 if (stop_state == eStateExited)
5288 event_to_broadcast_sp = event_sp;
5289
Sean Callananbf154da2012-08-08 17:35:10 +00005290 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00005291 return_value = eExecutionInterrupted;
5292 break;
5293 }
Sean Callanana46ec452012-07-11 21:31:24 +00005294 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005295
Sean Callanana46ec452012-07-11 21:31:24 +00005296 if (keep_going)
5297 continue;
5298 else
5299 break;
5300 }
5301 else
5302 {
5303 if (log)
5304 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5305 return_value = eExecutionInterrupted;
5306 break;
5307 }
5308 }
5309 else
5310 {
5311 // If we didn't get an event that means we've timed out...
5312 // We will interrupt the process here. Depending on what we were asked to do we will
5313 // either exit, or try with all threads running for the same timeout.
Sean Callanana46ec452012-07-11 21:31:24 +00005314
5315 if (log) {
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005316 if (options.GetTryAllThreads())
Sean Callanana46ec452012-07-11 21:31:24 +00005317 {
Jim Ingham0161b492013-02-09 01:29:05 +00005318 uint64_t remaining_time = final_timeout - TimeValue::Now();
5319 if (before_first_timeout)
5320 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005321 "running till for %" PRIu64 " usec with all threads enabled.",
Jim Ingham0161b492013-02-09 01:29:05 +00005322 remaining_time);
Sean Callanana46ec452012-07-11 21:31:24 +00005323 else
5324 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jason Molenda6a8658a2013-10-27 02:32:23 +00005325 "and timeout: %u timed out, abandoning execution.",
Jim Ingham35e1bda2012-10-16 21:41:58 +00005326 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005327 }
5328 else
Jason Molenda6a8658a2013-10-27 02:32:23 +00005329 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %u timed out, "
Jim Ingham35e1bda2012-10-16 21:41:58 +00005330 "abandoning execution.",
5331 timeout_usec);
Sean Callanana46ec452012-07-11 21:31:24 +00005332 }
5333
Jim Ingham0161b492013-02-09 01:29:05 +00005334 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5335 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5336 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5337 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5338 // stopped event. That's what this while loop does.
5339
5340 bool back_to_top = true;
5341 uint32_t try_halt_again = 0;
5342 bool do_halt = true;
5343 const uint32_t num_retries = 5;
5344 while (try_halt_again < num_retries)
Sean Callanana46ec452012-07-11 21:31:24 +00005345 {
Jim Ingham0161b492013-02-09 01:29:05 +00005346 Error halt_error;
5347 if (do_halt)
5348 {
5349 if (log)
5350 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5351 halt_error = Halt();
5352 }
5353 if (halt_error.Success())
5354 {
5355 if (log)
5356 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5357
5358 real_timeout = TimeValue::Now();
5359 real_timeout.OffsetWithMicroSeconds(500000);
5360
5361 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanana46ec452012-07-11 21:31:24 +00005362
Jim Ingham0161b492013-02-09 01:29:05 +00005363 if (got_event)
Sean Callanana46ec452012-07-11 21:31:24 +00005364 {
Jim Ingham0161b492013-02-09 01:29:05 +00005365 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5366 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005367 {
Jim Ingham0161b492013-02-09 01:29:05 +00005368 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5369 if (stop_state == lldb::eStateStopped
5370 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5371 log->PutCString (" Event was the Halt interruption event.");
Sean Callanana46ec452012-07-11 21:31:24 +00005372 }
5373
Jim Ingham0161b492013-02-09 01:29:05 +00005374 if (stop_state == lldb::eStateStopped)
Sean Callanana46ec452012-07-11 21:31:24 +00005375 {
Jim Ingham0161b492013-02-09 01:29:05 +00005376 // Between the time we initiated the Halt and the time we delivered it, the process could have
5377 // already finished its job. Check that here:
5378
5379 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5380 {
5381 if (log)
5382 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5383 "Exiting wait loop.");
5384 return_value = eExecutionCompleted;
5385 back_to_top = false;
5386 break;
5387 }
5388
5389 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5390 {
5391 if (log)
5392 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5393 "Exiting wait loop.");
5394 try_halt_again++;
5395 do_halt = false;
5396 continue;
5397 }
Sean Callanana46ec452012-07-11 21:31:24 +00005398
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005399 if (!options.GetTryAllThreads())
Jim Ingham0161b492013-02-09 01:29:05 +00005400 {
5401 if (log)
5402 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5403 return_value = eExecutionInterrupted;
5404 back_to_top = false;
5405 break;
5406 }
5407
5408 if (before_first_timeout)
5409 {
5410 // Set all the other threads to run, and return to the top of the loop, which will continue;
5411 before_first_timeout = false;
5412 thread_plan_sp->SetStopOthers (false);
5413 if (log)
5414 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanana46ec452012-07-11 21:31:24 +00005415
Jim Ingham0161b492013-02-09 01:29:05 +00005416 back_to_top = true;
5417 break;
5418 }
5419 else
5420 {
5421 // Running all threads failed, so return Interrupted.
5422 if (log)
5423 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5424 return_value = eExecutionInterrupted;
5425 back_to_top = false;
5426 break;
5427 }
Sean Callanana46ec452012-07-11 21:31:24 +00005428 }
5429 }
5430 else
Jim Ingham0161b492013-02-09 01:29:05 +00005431 { if (log)
5432 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5433 "I'm getting out of here passing Interrupted.");
Sean Callanana46ec452012-07-11 21:31:24 +00005434 return_value = eExecutionInterrupted;
Jim Ingham0161b492013-02-09 01:29:05 +00005435 back_to_top = false;
5436 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005437 }
5438 }
Jim Ingham0161b492013-02-09 01:29:05 +00005439 else
5440 {
5441 try_halt_again++;
5442 continue;
5443 }
Sean Callanana46ec452012-07-11 21:31:24 +00005444 }
Jim Ingham0161b492013-02-09 01:29:05 +00005445
5446 if (!back_to_top || try_halt_again > num_retries)
5447 break;
5448 else
5449 continue;
Sean Callanana46ec452012-07-11 21:31:24 +00005450 }
Sean Callanana46ec452012-07-11 21:31:24 +00005451 } // END WAIT LOOP
5452
5453 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5454 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5455 {
5456 StopPrivateStateThread();
5457 Error error;
5458 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00005459 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005460 {
5461 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5462 }
5463 m_public_state.SetValueNoLock(old_state);
5464
5465 }
5466
Jim Ingham184e9812013-01-15 02:47:48 +00005467 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5468 // could happen:
5469 // 1) The execution successfully completed
5470 // 2) We hit a breakpoint, and ignore_breakpoints was true
5471 // 3) We got some other error, and discard_on_error was true
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005472 bool should_unwind = (return_value == eExecutionInterrupted && options.DoesUnwindOnError())
5473 || (return_value == eExecutionHitBreakpoint && options.DoesIgnoreBreakpoints());
Jim Ingham8559a352012-11-26 23:52:18 +00005474
Jim Ingham184e9812013-01-15 02:47:48 +00005475 if (return_value == eExecutionCompleted
5476 || should_unwind)
Jim Ingham8559a352012-11-26 23:52:18 +00005477 {
5478 thread_plan_sp->RestoreThreadState();
5479 }
Sean Callanana46ec452012-07-11 21:31:24 +00005480
5481 // Now do some processing on the results of the run:
Jim Ingham184e9812013-01-15 02:47:48 +00005482 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanana46ec452012-07-11 21:31:24 +00005483 {
5484 if (log)
5485 {
5486 StreamString s;
5487 if (event_sp)
5488 event_sp->Dump (&s);
5489 else
5490 {
5491 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5492 }
5493
5494 StreamString ts;
5495
5496 const char *event_explanation = NULL;
5497
5498 do
5499 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005500 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005501 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005502 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00005503 break;
5504 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005505 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00005506 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005507 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00005508 break;
5509 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005510 else
Sean Callanana46ec452012-07-11 21:31:24 +00005511 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005512 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5513
5514 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00005515 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005516 event_explanation = "<no event data>";
5517 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005518 }
5519
Jim Inghamcfc09352012-07-27 23:57:19 +00005520 Process *process = event_data->GetProcessSP().get();
5521
5522 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00005523 {
Jim Inghamcfc09352012-07-27 23:57:19 +00005524 event_explanation = "<no process>";
5525 break;
Sean Callanana46ec452012-07-11 21:31:24 +00005526 }
Jim Inghamcfc09352012-07-27 23:57:19 +00005527
5528 ThreadList &thread_list = process->GetThreadList();
5529
5530 uint32_t num_threads = thread_list.GetSize();
5531 uint32_t thread_index;
5532
5533 ts.Printf("<%u threads> ", num_threads);
5534
5535 for (thread_index = 0;
5536 thread_index < num_threads;
5537 ++thread_index)
5538 {
5539 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5540
5541 if (!thread)
5542 {
5543 ts.Printf("<?> ");
5544 continue;
5545 }
5546
Daniel Malead01b2952012-11-29 21:49:15 +00005547 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Inghamcfc09352012-07-27 23:57:19 +00005548 RegisterContext *register_context = thread->GetRegisterContext().get();
5549
5550 if (register_context)
Daniel Malead01b2952012-11-29 21:49:15 +00005551 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Inghamcfc09352012-07-27 23:57:19 +00005552 else
5553 ts.Printf("[ip unknown] ");
5554
5555 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5556 if (stop_info_sp)
5557 {
5558 const char *stop_desc = stop_info_sp->GetDescription();
5559 if (stop_desc)
5560 ts.PutCString (stop_desc);
5561 }
5562 ts.Printf(">");
5563 }
5564
5565 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00005566 }
Sean Callanana46ec452012-07-11 21:31:24 +00005567 } while (0);
5568
Jim Inghamcfc09352012-07-27 23:57:19 +00005569 if (event_explanation)
5570 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00005571 else
Jim Inghamcfc09352012-07-27 23:57:19 +00005572 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5573 }
5574
Jim Inghame4483cf2013-09-27 01:13:01 +00005575 if (should_unwind)
Jim Inghamcfc09352012-07-27 23:57:19 +00005576 {
5577 if (log)
5578 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5579 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5580 thread_plan_sp->SetPrivate (orig_plan_private);
5581 }
5582 else
5583 {
5584 if (log)
5585 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00005586 }
5587 }
5588 else if (return_value == eExecutionSetupError)
5589 {
5590 if (log)
5591 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00005592
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005593 if (options.DoesUnwindOnError())
Jim Ingham0f16e732011-02-08 05:20:59 +00005594 {
Greg Claytonc14ee322011-09-22 04:58:26 +00005595 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00005596 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00005597 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005598 }
5599 else
5600 {
Sean Callanana46ec452012-07-11 21:31:24 +00005601 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00005602 {
Jim Ingham0f16e732011-02-08 05:20:59 +00005603 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00005604 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5605 return_value = eExecutionCompleted;
5606 }
5607 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5608 {
5609 if (log)
5610 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5611 return_value = eExecutionDiscarded;
5612 }
5613 else
5614 {
5615 if (log)
5616 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005617 if (options.DoesUnwindOnError() && thread_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00005618 {
5619 if (log)
Jim Ingham184e9812013-01-15 02:47:48 +00005620 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanana46ec452012-07-11 21:31:24 +00005621 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5622 thread_plan_sp->SetPrivate (orig_plan_private);
5623 }
5624 }
5625 }
5626
5627 // Thread we ran the function in may have gone away because we ran the target
5628 // Check that it's still there, and if it is put it back in the context. Also restore the
5629 // frame in the context if it is still present.
5630 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5631 if (thread)
5632 {
5633 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5634 }
5635
5636 // Also restore the current process'es selected frame & thread, since this function calling may
5637 // be done behind the user's back.
5638
5639 if (selected_tid != LLDB_INVALID_THREAD_ID)
5640 {
5641 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5642 {
5643 // We were able to restore the selected thread, now restore the frame:
Daniel Maleaa012d3a2013-07-31 20:21:20 +00005644 Mutex::Locker lock(GetThreadList().GetMutex());
Jason Molendab57e4a12013-11-04 09:33:30 +00005645 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Sean Callanana46ec452012-07-11 21:31:24 +00005646 if (old_frame_sp)
5647 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00005648 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005649 }
5650 }
Jim Inghamf48169b2010-11-30 02:22:11 +00005651
Sean Callanana46ec452012-07-11 21:31:24 +00005652 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00005653
Sean Callanana46ec452012-07-11 21:31:24 +00005654 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00005655 {
Sean Callanana46ec452012-07-11 21:31:24 +00005656 if (log)
5657 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5658 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00005659 }
5660
5661 return return_value;
5662}
5663
5664const char *
5665Process::ExecutionResultAsCString (ExecutionResults result)
5666{
5667 const char *result_name;
5668
5669 switch (result)
5670 {
Greg Claytone0d378b2011-03-24 21:19:54 +00005671 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005672 result_name = "eExecutionCompleted";
5673 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005674 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00005675 result_name = "eExecutionDiscarded";
5676 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005677 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00005678 result_name = "eExecutionInterrupted";
5679 break;
Jim Ingham184e9812013-01-15 02:47:48 +00005680 case eExecutionHitBreakpoint:
5681 result_name = "eExecutionHitBreakpoint";
5682 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005683 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00005684 result_name = "eExecutionSetupError";
5685 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00005686 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00005687 result_name = "eExecutionTimedOut";
5688 break;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00005689 case eExecutionStoppedForDebug:
5690 result_name = "eExecutionStoppedForDebug";
5691 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00005692 }
5693 return result_name;
5694}
5695
Greg Clayton7260f622011-04-18 08:33:37 +00005696void
5697Process::GetStatus (Stream &strm)
5698{
5699 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00005700 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00005701 {
5702 if (state == eStateExited)
5703 {
5704 int exit_status = GetExitStatus();
5705 const char *exit_description = GetExitDescription();
Daniel Malead01b2952012-11-29 21:49:15 +00005706 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00005707 GetID(),
5708 exit_status,
5709 exit_status,
5710 exit_description ? exit_description : "");
5711 }
5712 else
5713 {
5714 if (state == eStateConnected)
5715 strm.Printf ("Connected to remote target.\n");
5716 else
Daniel Malead01b2952012-11-29 21:49:15 +00005717 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00005718 }
5719 }
5720 else
5721 {
Daniel Malead01b2952012-11-29 21:49:15 +00005722 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00005723 }
5724}
5725
5726size_t
5727Process::GetThreadStatus (Stream &strm,
5728 bool only_threads_with_stop_reason,
5729 uint32_t start_frame,
5730 uint32_t num_frames,
5731 uint32_t num_frames_with_source)
5732{
5733 size_t num_thread_infos_dumped = 0;
5734
Jim Ingham41f2b942012-09-10 20:50:15 +00005735 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Clayton7260f622011-04-18 08:33:37 +00005736 const size_t num_threads = GetThreadList().GetSize();
5737 for (uint32_t i = 0; i < num_threads; i++)
5738 {
5739 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5740 if (thread)
5741 {
5742 if (only_threads_with_stop_reason)
5743 {
Jim Ingham5d88a062012-10-16 00:09:33 +00005744 StopInfoSP stop_info_sp = thread->GetStopInfo();
5745 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Clayton7260f622011-04-18 08:33:37 +00005746 continue;
5747 }
5748 thread->GetStatus (strm,
5749 start_frame,
5750 num_frames,
5751 num_frames_with_source);
5752 ++num_thread_infos_dumped;
5753 }
5754 }
5755 return num_thread_infos_dumped;
5756}
5757
Greg Claytona9f40ad2012-02-22 04:37:26 +00005758void
5759Process::AddInvalidMemoryRegion (const LoadRange &region)
5760{
5761 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5762}
5763
5764bool
5765Process::RemoveInvalidMemoryRange (const LoadRange &region)
5766{
5767 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5768}
5769
Jim Ingham372787f2012-04-07 00:00:41 +00005770void
5771Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5772{
5773 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5774}
5775
5776bool
5777Process::RunPreResumeActions ()
5778{
5779 bool result = true;
5780 while (!m_pre_resume_actions.empty())
5781 {
5782 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5783 m_pre_resume_actions.pop_back();
5784 bool this_result = action.callback (action.baton);
5785 if (result == true) result = this_result;
5786 }
5787 return result;
5788}
5789
5790void
5791Process::ClearPreResumeActions ()
5792{
5793 m_pre_resume_actions.clear();
5794}
Greg Claytona9f40ad2012-02-22 04:37:26 +00005795
Greg Claytonfa559e52012-05-18 02:38:05 +00005796void
5797Process::Flush ()
5798{
5799 m_thread_list.Flush();
Jason Molenda5e8dce42013-12-13 00:29:16 +00005800 m_extended_thread_list.Flush();
5801 m_extended_thread_stop_id = 0;
5802 m_queue_list.Clear();
5803 m_queue_list_stop_id = 0;
Greg Claytonfa559e52012-05-18 02:38:05 +00005804}
Greg Clayton90ba8112012-12-05 00:16:59 +00005805
5806void
5807Process::DidExec ()
5808{
5809 Target &target = GetTarget();
5810 target.CleanupProcess ();
Greg Claytonb35db632013-11-09 00:03:31 +00005811 target.ClearModules(false);
Greg Clayton90ba8112012-12-05 00:16:59 +00005812 m_dynamic_checkers_ap.reset();
5813 m_abi_sp.reset();
Jason Molendaeef51062013-11-05 03:57:19 +00005814 m_system_runtime_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005815 m_os_ap.reset();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005816 m_dyld_ap.reset();
Greg Clayton90ba8112012-12-05 00:16:59 +00005817 m_image_tokens.clear();
5818 m_allocated_memory_cache.Clear();
5819 m_language_runtimes.clear();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005820 m_thread_list.DiscardThreadPlans();
Greg Clayton15fc2be2013-05-21 01:00:52 +00005821 m_memory_cache.Clear(true);
Greg Clayton90ba8112012-12-05 00:16:59 +00005822 DoDidExec();
5823 CompleteAttach ();
Greg Clayton095eeaa2013-11-05 23:28:00 +00005824 // Flush the process (threads and all stack frames) after running CompleteAttach()
5825 // in case the dynamic loader loaded things in new locations.
5826 Flush();
Greg Claytonb35db632013-11-09 00:03:31 +00005827
5828 // After we figure out what was loaded/unloaded in CompleteAttach,
5829 // we need to let the target know so it can do any cleanup it needs to.
5830 target.DidExec();
Greg Clayton90ba8112012-12-05 00:16:59 +00005831}
Greg Clayton095eeaa2013-11-05 23:28:00 +00005832
Jim Ingham1460e4b2014-01-10 23:46:59 +00005833addr_t
5834Process::ResolveIndirectFunction(const Address *address, Error &error)
5835{
5836 if (address == nullptr)
5837 {
5838 Symbol *symbol = address->CalculateSymbolContextSymbol();
5839 error.SetErrorStringWithFormat("unable to determine direct function call for indirect function %s",
5840 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5841 return LLDB_INVALID_ADDRESS;
5842 }
5843
5844 addr_t function_addr = LLDB_INVALID_ADDRESS;
5845
5846 addr_t addr = address->GetLoadAddress(&GetTarget());
5847 std::map<addr_t,addr_t>::const_iterator iter = m_resolved_indirect_addresses.find(addr);
5848 if (iter != m_resolved_indirect_addresses.end())
5849 {
5850 function_addr = (*iter).second;
5851 }
5852 else
5853 {
5854 if (!InferiorCall(this, address, function_addr))
5855 {
5856 Symbol *symbol = address->CalculateSymbolContextSymbol();
5857 error.SetErrorStringWithFormat ("Unable to call resolver for indirect function %s",
5858 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5859 function_addr = LLDB_INVALID_ADDRESS;
5860 }
5861 else
5862 {
5863 m_resolved_indirect_addresses.insert(std::pair<addr_t, addr_t>(addr, function_addr));
5864 }
5865 }
5866 return function_addr;
5867}
5868