blob: a6a6b5435ba592e0545396ffc6e1953fe7a154a7 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malead891f9b2012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner24943d22010-06-08 16:52:24 +000012#include "lldb/Target/Process.h"
13
14#include "lldb/lldb-private-log.h"
15
16#include "lldb/Breakpoint/StoppointCallbackContext.h"
17#include "lldb/Breakpoint/BreakpointLocation.h"
18#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000021#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000022#include "lldb/Core/Log.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
25#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000026#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000027#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#include "lldb/Host/Host.h"
29#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000030#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000031#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000032#include "lldb/Target/LanguageRuntime.h"
33#include "lldb/Target/CPPLanguageRuntime.h"
34#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000035#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000037#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Target/Target.h"
39#include "lldb/Target/TargetList.h"
40#include "lldb/Target/Thread.h"
41#include "lldb/Target/ThreadPlan.h"
Jim Inghamd21d98b2012-04-10 01:21:57 +000042#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner24943d22010-06-08 16:52:24 +000043
44using namespace lldb;
45using namespace lldb_private;
46
Greg Clayton73844aa2012-08-22 17:17:09 +000047
48// Comment out line below to disable memory caching, overriding the process setting
49// target.process.disable-memory-cache
50#define ENABLE_MEMORY_CACHING
51
52#ifdef ENABLE_MEMORY_CACHING
53#define DISABLE_MEM_CACHE_DEFAULT false
54#else
55#define DISABLE_MEM_CACHE_DEFAULT true
56#endif
57
58class ProcessOptionValueProperties : public OptionValueProperties
59{
60public:
61 ProcessOptionValueProperties (const ConstString &name) :
62 OptionValueProperties (name)
63 {
64 }
65
66 // This constructor is used when creating ProcessOptionValueProperties when it
67 // is part of a new lldb_private::Process instance. It will copy all current
68 // global property values as needed
69 ProcessOptionValueProperties (ProcessProperties *global_properties) :
70 OptionValueProperties(*global_properties->GetValueProperties())
71 {
72 }
73
74 virtual const Property *
75 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
76 {
77 // When gettings the value for a key from the process options, we will always
78 // try and grab the setting from the current process if there is one. Else we just
79 // use the one from this instance.
80 if (exe_ctx)
81 {
82 Process *process = exe_ctx->GetProcessPtr();
83 if (process)
84 {
85 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
86 if (this != instance_properties)
87 return instance_properties->ProtectedGetPropertyAtIndex (idx);
88 }
89 }
90 return ProtectedGetPropertyAtIndex (idx);
91 }
92};
93
94static PropertyDefinition
95g_properties[] =
96{
97 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
Jim Inghamdacdc012012-11-29 00:41:12 +000098 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
99 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Ingham46be7f22013-01-31 19:48:57 +0000100 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
101 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
Greg Clayton507a6382012-11-29 18:48:47 +0000102 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
Jim Ingham090f8312013-01-26 02:19:28 +0000103 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
Greg Clayton73844aa2012-08-22 17:17:09 +0000104 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
105};
106
107enum {
108 ePropertyDisableMemCache,
Greg Clayton2e7f3132012-10-18 22:40:37 +0000109 ePropertyExtraStartCommand,
Jim Inghamb7940202013-01-15 02:47:48 +0000110 ePropertyIgnoreBreakpointsInExpressions,
111 ePropertyUnwindOnErrorInExpressions,
Jim Ingham090f8312013-01-26 02:19:28 +0000112 ePropertyPythonOSPluginPath,
113 ePropertyStopOnSharedLibraryEvents
Greg Clayton73844aa2012-08-22 17:17:09 +0000114};
115
116ProcessProperties::ProcessProperties (bool is_global) :
117 Properties ()
118{
119 if (is_global)
120 {
121 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
122 m_collection_sp->Initialize(g_properties);
123 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham090f8312013-01-26 02:19:28 +0000124 ConstString("Settings specific to threads."),
Greg Clayton73844aa2012-08-22 17:17:09 +0000125 true,
126 Thread::GetGlobalProperties()->GetValueProperties());
127 }
128 else
129 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
130}
131
132ProcessProperties::~ProcessProperties()
133{
134}
135
136bool
137ProcessProperties::GetDisableMemoryCache() const
138{
139 const uint32_t idx = ePropertyDisableMemCache;
140 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
141}
142
143Args
144ProcessProperties::GetExtraStartupCommands () const
145{
146 Args args;
147 const uint32_t idx = ePropertyExtraStartCommand;
148 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
149 return args;
150}
151
152void
153ProcessProperties::SetExtraStartupCommands (const Args &args)
154{
155 const uint32_t idx = ePropertyExtraStartCommand;
156 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
157}
158
Greg Clayton2e7f3132012-10-18 22:40:37 +0000159FileSpec
160ProcessProperties::GetPythonOSPluginPath () const
161{
162 const uint32_t idx = ePropertyPythonOSPluginPath;
163 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
164}
165
166void
167ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
168{
169 const uint32_t idx = ePropertyPythonOSPluginPath;
170 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
171}
172
Jim Inghamb7940202013-01-15 02:47:48 +0000173
174bool
175ProcessProperties::GetIgnoreBreakpointsInExpressions () const
176{
177 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
178 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
179}
180
181void
182ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
183{
184 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
185 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
186}
187
188bool
189ProcessProperties::GetUnwindOnErrorInExpressions () const
190{
191 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
192 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
193}
194
195void
196ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
197{
198 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
199 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
200}
201
Jim Ingham090f8312013-01-26 02:19:28 +0000202bool
203ProcessProperties::GetStopOnSharedLibraryEvents () const
204{
205 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
206 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
207}
208
209void
210ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
211{
212 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
213 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
214}
215
Greg Clayton24bc5d92011-03-30 18:16:51 +0000216void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000217ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000218{
219 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +0000220 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000221 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000222
223 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000224 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000225
226 if (m_executable)
227 {
228 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
229 s.PutCString (" file = ");
230 m_executable.Dump(&s);
231 s.EOL();
232 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000233 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000234 if (argc > 0)
235 {
236 for (uint32_t i=0; i<argc; i++)
237 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000238 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +0000239 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000240 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000241 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000242 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000243 }
244 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000245
246 const uint32_t envc = m_environment.GetArgumentCount();
247 if (envc > 0)
248 {
249 for (uint32_t i=0; i<envc; i++)
250 {
251 const char *env = m_environment.GetArgumentAtIndex(i);
252 if (i < 10)
253 s.Printf (" env[%u] = %s\n", i, env);
254 else
255 s.Printf ("env[%u] = %s\n", i, env);
256 }
257 }
258
Greg Claytonff39f742011-04-01 00:29:43 +0000259 if (m_arch.IsValid())
260 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
261
Greg Claytonb72d0f02011-04-12 05:54:46 +0000262 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000263 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000264 cstr = platform->GetUserName (m_uid);
265 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000266 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000267 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000268 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000269 cstr = platform->GetGroupName (m_gid);
270 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000271 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000272 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000273 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000274 cstr = platform->GetUserName (m_euid);
275 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000276 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000277 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000278 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000279 cstr = platform->GetGroupName (m_egid);
280 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000281 }
282}
283
284void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000285ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000286{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000287 const char *label;
288 if (show_args || verbose)
289 label = "ARGUMENTS";
290 else
291 label = "NAME";
292
Greg Claytonff39f742011-04-01 00:29:43 +0000293 if (verbose)
294 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000295 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000296 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
297 }
298 else
299 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000300 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000301 s.PutCString ("====== ====== ========== ======= ============================\n");
302 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000303}
304
305void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000306ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000307{
308 if (m_pid != LLDB_INVALID_PROCESS_ID)
309 {
310 const char *cstr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000311 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000312
Greg Clayton24bc5d92011-03-30 18:16:51 +0000313
Greg Claytonff39f742011-04-01 00:29:43 +0000314 if (verbose)
315 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000316 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000317 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
318 s.Printf ("%-10s ", cstr);
319 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000320 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000321
Greg Claytonb72d0f02011-04-12 05:54:46 +0000322 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000323 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
324 s.Printf ("%-10s ", cstr);
325 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000326 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000327
Greg Claytonb72d0f02011-04-12 05:54:46 +0000328 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000329 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
330 s.Printf ("%-10s ", cstr);
331 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000332 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000333
Greg Claytonb72d0f02011-04-12 05:54:46 +0000334 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000335 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
336 s.Printf ("%-10s ", cstr);
337 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000338 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000339 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
340 }
341 else
342 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000343 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000344 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000345 (int)m_arch.GetTriple().getArchName().size(),
346 m_arch.GetTriple().getArchName().data());
347 }
348
Greg Claytonb72d0f02011-04-12 05:54:46 +0000349 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000350 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000351 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000352 if (argc > 0)
353 {
354 for (uint32_t i=0; i<argc; i++)
355 {
356 if (i > 0)
357 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000358 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000359 }
360 }
361 }
362 else
363 {
364 s.PutCString (GetName());
365 }
366
367 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000368 }
369}
370
Greg Claytonb72d0f02011-04-12 05:54:46 +0000371
372void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000373ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000374{
375 m_arguments.SetArguments (argv);
376
377 // Is the first argument the executable?
378 if (first_arg_is_executable)
379 {
380 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
381 if (first_arg)
382 {
383 // Yes the first argument is an executable, set it as the executable
384 // in the launch options. Don't resolve the file path as the path
385 // could be a remote platform path
386 const bool resolve = false;
387 m_executable.SetFile(first_arg, resolve);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000388 }
389 }
390}
391void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000392ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000393{
394 // Copy all arguments
395 m_arguments = args;
396
397 // Is the first argument the executable?
398 if (first_arg_is_executable)
399 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000400 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000401 if (first_arg)
402 {
403 // Yes the first argument is an executable, set it as the executable
404 // in the launch options. Don't resolve the file path as the path
405 // could be a remote platform path
406 const bool resolve = false;
407 m_executable.SetFile(first_arg, resolve);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000408 }
409 }
410}
411
Greg Claytonabb33022011-11-08 02:43:13 +0000412void
Greg Clayton464c6162011-11-17 22:14:31 +0000413ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000414{
415 // If notthing was specified, then check the process for any default
416 // settings that were set with "settings set"
417 if (m_file_actions.empty())
418 {
Greg Claytonabb33022011-11-08 02:43:13 +0000419 if (m_flags.Test(eLaunchFlagDisableSTDIO))
420 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000421 AppendSuppressFileAction (STDIN_FILENO , true, false);
422 AppendSuppressFileAction (STDOUT_FILENO, false, true);
423 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000424 }
425 else
426 {
427 // Check for any values that might have gotten set with any of:
428 // (lldb) settings set target.input-path
429 // (lldb) settings set target.output-path
430 // (lldb) settings set target.error-path
Greg Clayton73844aa2012-08-22 17:17:09 +0000431 FileSpec in_path;
432 FileSpec out_path;
433 FileSpec err_path;
Greg Claytonabb33022011-11-08 02:43:13 +0000434 if (target)
435 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000436 in_path = target->GetStandardInputPath();
437 out_path = target->GetStandardOutputPath();
438 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000439 }
440
Greg Clayton73844aa2012-08-22 17:17:09 +0000441 if (in_path || out_path || err_path)
442 {
443 char path[PATH_MAX];
444 if (in_path && in_path.GetPath(path, sizeof(path)))
445 AppendOpenFileAction(STDIN_FILENO, path, true, false);
446
447 if (out_path && out_path.GetPath(path, sizeof(path)))
448 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
449
450 if (err_path && err_path.GetPath(path, sizeof(path)))
451 AppendOpenFileAction(STDERR_FILENO, path, false, true);
452 }
453 else if (default_to_use_pty)
Greg Clayton464c6162011-11-17 22:14:31 +0000454 {
455 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000456 {
Greg Clayton73844aa2012-08-22 17:17:09 +0000457 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
458 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
459 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
460 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000461 }
462 }
Greg Claytonabb33022011-11-08 02:43:13 +0000463 }
464 }
465}
466
Greg Clayton527154d2011-11-15 03:53:30 +0000467
468bool
Greg Clayton97471182012-04-14 01:42:46 +0000469ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
470 bool localhost,
471 bool will_debug,
472 bool first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000473{
474 error.Clear();
475
476 if (GetFlags().Test (eLaunchFlagLaunchInShell))
477 {
478 const char *shell_executable = GetShell();
479 if (shell_executable)
480 {
481 char shell_resolved_path[PATH_MAX];
482
483 if (localhost)
484 {
485 FileSpec shell_filespec (shell_executable, true);
486
487 if (!shell_filespec.Exists())
488 {
489 // Resolve the path in case we just got "bash", "sh" or "tcsh"
490 if (!shell_filespec.ResolveExecutableLocation ())
491 {
492 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
493 return false;
494 }
495 }
496 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
497 shell_executable = shell_resolved_path;
498 }
499
Greg Clayton0c8446c2012-10-17 22:57:12 +0000500 const char **argv = GetArguments().GetConstArgumentVector ();
501 if (argv == NULL || argv[0] == NULL)
502 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000503 Args shell_arguments;
504 std::string safe_arg;
505 shell_arguments.AppendArgument (shell_executable);
Greg Clayton527154d2011-11-15 03:53:30 +0000506 shell_arguments.AppendArgument ("-c");
Greg Clayton97471182012-04-14 01:42:46 +0000507 StreamString shell_command;
508 if (will_debug)
Greg Clayton527154d2011-11-15 03:53:30 +0000509 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000510 // Add a modified PATH environment variable in case argv[0]
511 // is a relative path
512 const char *argv0 = argv[0];
513 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
514 {
515 // We have a relative path to our executable which may not work if
516 // we just try to run "a.out" (without it being converted to "./a.out")
517 const char *working_dir = GetWorkingDirectory();
Greg Clayton68bd76f2013-02-14 03:54:39 +0000518 // Be sure to put quotes around PATH's value in case any paths have spaces...
519 std::string new_path("PATH=\"");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000520 const size_t empty_path_len = new_path.size();
521
522 if (working_dir && working_dir[0])
523 {
524 new_path += working_dir;
525 }
526 else
527 {
528 char current_working_dir[PATH_MAX];
529 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
530 if (cwd && cwd[0])
531 new_path += cwd;
532 }
533 const char *curr_path = getenv("PATH");
534 if (curr_path)
535 {
536 if (new_path.size() > empty_path_len)
537 new_path += ':';
538 new_path += curr_path;
539 }
Greg Clayton68bd76f2013-02-14 03:54:39 +0000540 new_path += "\" ";
Greg Clayton0c8446c2012-10-17 22:57:12 +0000541 shell_command.PutCString(new_path.c_str());
542 }
543
Greg Clayton97471182012-04-14 01:42:46 +0000544 shell_command.PutCString ("exec");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000545
546#if defined(__APPLE__)
547 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Clayton97471182012-04-14 01:42:46 +0000548 if (GetArchitecture().IsValid())
549 {
550 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton0c8446c2012-10-17 22:57:12 +0000551 // Set the resume count to 2:
Greg Clayton97471182012-04-14 01:42:46 +0000552 // 1 - stop in shell
553 // 2 - stop in /usr/bin/arch
554 // 3 - then we will stop in our program
555 SetResumeCount(2);
556 }
557 else
558 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000559 // Set the resume count to 1:
Greg Clayton97471182012-04-14 01:42:46 +0000560 // 1 - stop in shell
561 // 2 - then we will stop in our program
562 SetResumeCount(1);
563 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000564#else
565 // Set the resume count to 1:
566 // 1 - stop in shell
567 // 2 - then we will stop in our program
568 SetResumeCount(1);
569#endif
Greg Clayton527154d2011-11-15 03:53:30 +0000570 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000571
572 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000573 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000574 // There should only be one argument that is the shell command itself to be used as is
575 if (argv[0] && !argv[1])
576 shell_command.Printf("%s", argv[0]);
Greg Clayton97471182012-04-14 01:42:46 +0000577 else
Greg Clayton0c8446c2012-10-17 22:57:12 +0000578 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000579 }
Greg Clayton97471182012-04-14 01:42:46 +0000580 else
581 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000582 for (size_t i=0; argv[i] != NULL; ++i)
583 {
584 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
585 shell_command.Printf(" %s", arg);
586 }
Greg Clayton97471182012-04-14 01:42:46 +0000587 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000588 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000589 m_executable.SetFile(shell_executable, false);
590 m_arguments = shell_arguments;
591 return true;
592 }
593 else
594 {
595 error.SetErrorString ("invalid shell path");
596 }
597 }
598 else
599 {
600 error.SetErrorString ("not launching in shell");
601 }
602 return false;
603}
604
605
Greg Clayton24bc5d92011-03-30 18:16:51 +0000606bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000607ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
608{
609 if ((read || write) && fd >= 0 && path && path[0])
610 {
611 m_action = eFileActionOpen;
612 m_fd = fd;
613 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000614 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000615 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000616 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000617 else
Greg Clayton527154d2011-11-15 03:53:30 +0000618 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000619 m_path.assign (path);
620 return true;
621 }
622 else
623 {
624 Clear();
625 }
626 return false;
627}
628
629bool
630ProcessLaunchInfo::FileAction::Close (int fd)
631{
632 Clear();
633 if (fd >= 0)
634 {
635 m_action = eFileActionClose;
636 m_fd = fd;
637 }
638 return m_fd >= 0;
639}
640
641
642bool
643ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
644{
645 Clear();
646 if (fd >= 0 && dup_fd >= 0)
647 {
648 m_action = eFileActionDuplicate;
649 m_fd = fd;
650 m_arg = dup_fd;
651 }
652 return m_fd >= 0;
653}
654
655
656
657bool
658ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
659 const FileAction *info,
660 Log *log,
661 Error& error)
662{
663 if (info == NULL)
664 return false;
665
666 switch (info->m_action)
667 {
668 case eFileActionNone:
669 error.Clear();
670 break;
671
672 case eFileActionClose:
673 if (info->m_fd == -1)
674 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
675 else
676 {
677 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
678 eErrorTypePOSIX);
679 if (log && (error.Fail() || log))
680 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
681 file_actions, info->m_fd);
682 }
683 break;
684
685 case eFileActionDuplicate:
686 if (info->m_fd == -1)
687 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
688 else if (info->m_arg == -1)
689 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
690 else
691 {
692 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
693 eErrorTypePOSIX);
694 if (log && (error.Fail() || log))
695 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
696 file_actions, info->m_fd, info->m_arg);
697 }
698 break;
699
700 case eFileActionOpen:
701 if (info->m_fd == -1)
702 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
703 else
704 {
705 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000706
Greg Claytonb72d0f02011-04-12 05:54:46 +0000707 mode_t mode = 0;
708
Greg Clayton527154d2011-11-15 03:53:30 +0000709 if (oflag & O_CREAT)
710 mode = 0640;
711
Greg Claytonb72d0f02011-04-12 05:54:46 +0000712 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
713 info->m_fd,
714 info->m_path.c_str(),
715 oflag,
716 mode),
717 eErrorTypePOSIX);
718 if (error.Fail() || log)
719 error.PutToLog(log,
720 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
721 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
722 }
723 break;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000724 }
725 return error.Success();
726}
727
728Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000729ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000730{
731 Error error;
Greg Clayton6475c422012-12-04 00:32:51 +0000732 const int short_option = m_getopt_table[option_idx].val;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000733
734 switch (short_option)
735 {
736 case 's': // Stop at program entry point
737 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
738 break;
739
Greg Claytonb72d0f02011-04-12 05:54:46 +0000740 case 'i': // STDIN for read only
741 {
742 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000743 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000744 launch_info.AppendFileAction (action);
745 }
746 break;
747
748 case 'o': // Open STDOUT for write only
749 {
750 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000751 if (action.Open (STDOUT_FILENO, option_arg, false, true))
752 launch_info.AppendFileAction (action);
753 }
754 break;
755
756 case 'e': // STDERR for write only
757 {
758 ProcessLaunchInfo::FileAction action;
759 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000760 launch_info.AppendFileAction (action);
761 }
762 break;
763
Greg Clayton95ec1682012-03-06 04:01:04 +0000764
Greg Claytonb72d0f02011-04-12 05:54:46 +0000765 case 'p': // Process plug-in name
766 launch_info.SetProcessPluginName (option_arg);
767 break;
768
769 case 'n': // Disable STDIO
770 {
771 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000772 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000773 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000774 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000775 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000776 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000777 launch_info.AppendFileAction (action);
778 }
779 break;
780
781 case 'w':
782 launch_info.SetWorkingDirectory (option_arg);
783 break;
784
785 case 't': // Open process in new terminal window
786 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
787 break;
788
789 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000790 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
791 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000792 break;
793
794 case 'A':
795 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
796 break;
797
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000798 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000799 if (option_arg && option_arg[0])
800 launch_info.SetShell (option_arg);
801 else
802 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000803 break;
804
Greg Claytonb72d0f02011-04-12 05:54:46 +0000805 case 'v':
806 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
807 break;
808
809 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000810 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000811 break;
812
813 }
814 return error;
815}
816
817OptionDefinition
818ProcessLaunchCommandOptions::g_option_table[] =
819{
820{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
821{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
822{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
Sean Callanan9a91ef62012-10-24 01:12:14 +0000823{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000824{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
825{ LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Sean Callanan9a91ef62012-10-24 01:12:14 +0000826{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000827
Sean Callanan9a91ef62012-10-24 01:12:14 +0000828{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
829{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
830{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000831
832{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
833
834{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', no_argument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
835
836{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
837};
838
839
840
841bool
842ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000843{
844 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
845 return true;
846 const char *match_name = m_match_info.GetName();
847 if (!match_name)
848 return true;
849
850 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
851}
852
853bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000854ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000855{
856 if (!NameMatches (proc_info.GetName()))
857 return false;
858
859 if (m_match_info.ProcessIDIsValid() &&
860 m_match_info.GetProcessID() != proc_info.GetProcessID())
861 return false;
862
863 if (m_match_info.ParentProcessIDIsValid() &&
864 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
865 return false;
866
Greg Claytonb72d0f02011-04-12 05:54:46 +0000867 if (m_match_info.UserIDIsValid () &&
868 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000869 return false;
870
Greg Claytonb72d0f02011-04-12 05:54:46 +0000871 if (m_match_info.GroupIDIsValid () &&
872 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000873 return false;
874
875 if (m_match_info.EffectiveUserIDIsValid () &&
876 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
877 return false;
878
879 if (m_match_info.EffectiveGroupIDIsValid () &&
880 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
881 return false;
882
883 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callanan40e278c2012-12-13 22:07:14 +0000884 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton24bc5d92011-03-30 18:16:51 +0000885 return false;
886 return true;
887}
888
889bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000890ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000891{
892 if (m_name_match_type != eNameMatchIgnore)
893 return false;
894
895 if (m_match_info.ProcessIDIsValid())
896 return false;
897
898 if (m_match_info.ParentProcessIDIsValid())
899 return false;
900
Greg Claytonb72d0f02011-04-12 05:54:46 +0000901 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000902 return false;
903
Greg Claytonb72d0f02011-04-12 05:54:46 +0000904 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000905 return false;
906
907 if (m_match_info.EffectiveUserIDIsValid ())
908 return false;
909
910 if (m_match_info.EffectiveGroupIDIsValid ())
911 return false;
912
913 if (m_match_info.GetArchitecture().IsValid())
914 return false;
915
916 if (m_match_all_users)
917 return false;
918
919 return true;
920
921}
922
923void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000924ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000925{
926 m_match_info.Clear();
927 m_name_match_type = eNameMatchIgnore;
928 m_match_all_users = false;
929}
Greg Claytonfd119992011-01-07 06:08:19 +0000930
Greg Clayton46c9a352012-02-09 06:16:32 +0000931ProcessSP
932Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000933{
Greg Clayton64742742013-01-16 17:29:04 +0000934 static uint32_t g_process_unique_id = 0;
935
Greg Clayton46c9a352012-02-09 06:16:32 +0000936 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000937 ProcessCreateInstance create_callback = NULL;
938 if (plugin_name)
939 {
940 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
941 if (create_callback)
942 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000943 process_sp = create_callback(target, listener, crash_file_path);
944 if (process_sp)
945 {
Greg Clayton64742742013-01-16 17:29:04 +0000946 if (process_sp->CanDebug(target, true))
947 {
948 process_sp->m_process_unique_id = ++g_process_unique_id;
949 }
950 else
Greg Clayton46c9a352012-02-09 06:16:32 +0000951 process_sp.reset();
952 }
Chris Lattner24943d22010-06-08 16:52:24 +0000953 }
954 }
955 else
956 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000957 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000958 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000959 process_sp = create_callback(target, listener, crash_file_path);
960 if (process_sp)
961 {
Greg Clayton64742742013-01-16 17:29:04 +0000962 if (process_sp->CanDebug(target, false))
963 {
964 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Clayton46c9a352012-02-09 06:16:32 +0000965 break;
Greg Clayton64742742013-01-16 17:29:04 +0000966 }
967 else
968 process_sp.reset();
Greg Clayton46c9a352012-02-09 06:16:32 +0000969 }
Chris Lattner24943d22010-06-08 16:52:24 +0000970 }
971 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000972 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000973}
974
Jim Ingham5a15e692012-02-16 06:50:00 +0000975ConstString &
976Process::GetStaticBroadcasterClass ()
977{
978 static ConstString class_name ("lldb.process");
979 return class_name;
980}
Chris Lattner24943d22010-06-08 16:52:24 +0000981
982//----------------------------------------------------------------------
983// Process constructor
984//----------------------------------------------------------------------
985Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +0000986 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +0000987 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000988 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +0000989 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000990 m_public_state (eStateUnloaded),
991 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000992 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
993 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000994 m_private_state_listener ("lldb.process.internal_state_listener"),
995 m_private_state_control_wait(),
996 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000997 m_mod_id (),
Greg Clayton64742742013-01-16 17:29:04 +0000998 m_process_unique_id(0),
Chris Lattner24943d22010-06-08 16:52:24 +0000999 m_thread_index_id (0),
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001000 m_thread_id_to_index_id_map (),
Chris Lattner24943d22010-06-08 16:52:24 +00001001 m_exit_status (-1),
1002 m_exit_string (),
1003 m_thread_list (this),
1004 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001005 m_image_tokens (),
1006 m_listener (listener),
1007 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001008 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +00001009 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001010 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +00001011 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +00001012 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +00001013 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +00001014 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +00001015 m_stderr_data (),
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001016 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1017 m_profile_data (),
Greg Clayton613b8732011-05-17 03:37:42 +00001018 m_memory_cache (*this),
1019 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +00001020 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +00001021 m_next_event_action_ap(),
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00001022 m_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +00001023 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001024 m_finalize_called(false),
Jim Ingham89e248f2013-02-09 01:29:05 +00001025 m_last_broadcast_state (eStateInvalid),
Jason Molenda1d9c8022013-03-05 03:33:59 +00001026 m_destroy_in_process (false),
1027 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +00001028{
Jim Ingham5a15e692012-02-16 06:50:00 +00001029 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +00001030
Greg Clayton952e9dc2013-03-27 23:08:40 +00001031 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001032 if (log)
1033 log->Printf ("%p Process::Process()", this);
1034
Greg Clayton49ce6822010-10-31 03:01:06 +00001035 SetEventName (eBroadcastBitStateChanged, "state-changed");
1036 SetEventName (eBroadcastBitInterrupt, "interrupt");
1037 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1038 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001039 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Clayton49ce6822010-10-31 03:01:06 +00001040
Greg Clayton84332782012-10-29 20:52:08 +00001041 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1042 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1043 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1044
Chris Lattner24943d22010-06-08 16:52:24 +00001045 listener.StartListeningForEvents (this,
1046 eBroadcastBitStateChanged |
1047 eBroadcastBitInterrupt |
1048 eBroadcastBitSTDOUT |
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001049 eBroadcastBitSTDERR |
1050 eBroadcastBitProfileData);
Chris Lattner24943d22010-06-08 16:52:24 +00001051
1052 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001053 eBroadcastBitStateChanged |
1054 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +00001055
1056 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1057 eBroadcastInternalStateControlStop |
1058 eBroadcastInternalStateControlPause |
1059 eBroadcastInternalStateControlResume);
1060}
1061
1062//----------------------------------------------------------------------
1063// Destructor
1064//----------------------------------------------------------------------
1065Process::~Process()
1066{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001067 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001068 if (log)
1069 log->Printf ("%p Process::~Process()", this);
1070 StopPrivateStateThread();
1071}
1072
Greg Clayton73844aa2012-08-22 17:17:09 +00001073const ProcessPropertiesSP &
1074Process::GetGlobalProperties()
1075{
1076 static ProcessPropertiesSP g_settings_sp;
1077 if (!g_settings_sp)
1078 g_settings_sp.reset (new ProcessProperties (true));
1079 return g_settings_sp;
1080}
1081
Chris Lattner24943d22010-06-08 16:52:24 +00001082void
1083Process::Finalize()
1084{
Greg Claytonffa43a62011-11-17 04:46:02 +00001085 switch (GetPrivateState())
1086 {
1087 case eStateConnected:
1088 case eStateAttaching:
1089 case eStateLaunching:
1090 case eStateStopped:
1091 case eStateRunning:
1092 case eStateStepping:
1093 case eStateCrashed:
1094 case eStateSuspended:
1095 if (GetShouldDetach())
1096 Detach();
1097 else
1098 Destroy();
1099 break;
1100
1101 case eStateInvalid:
1102 case eStateUnloaded:
1103 case eStateDetached:
1104 case eStateExited:
1105 break;
1106 }
1107
Greg Clayton2f57db02011-10-01 00:45:15 +00001108 // Clear our broadcaster before we proceed with destroying
1109 Broadcaster::Clear();
1110
Chris Lattner24943d22010-06-08 16:52:24 +00001111 // Do any cleanup needed prior to being destructed... Subclasses
1112 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001113
1114 // We need to destroy the loader before the derived Process class gets destroyed
1115 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001116 m_dynamic_checkers_ap.reset();
1117 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001118 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001119 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001120 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001121 std::vector<Notifications> empty_notifications;
1122 m_notifications.swap(empty_notifications);
1123 m_image_tokens.clear();
1124 m_memory_cache.Clear();
1125 m_allocated_memory_cache.Clear();
1126 m_language_runtimes.clear();
1127 m_next_event_action_ap.reset();
Greg Clayton84332782012-10-29 20:52:08 +00001128//#ifdef LLDB_CONFIGURATION_DEBUG
1129// StreamFile s(stdout, false);
1130// EventSP event_sp;
1131// while (m_private_state_listener.GetNextEvent(event_sp))
1132// {
1133// event_sp->Dump (&s);
1134// s.EOL();
1135// }
1136//#endif
1137 // We have to be very careful here as the m_private_state_listener might
1138 // contain events that have ProcessSP values in them which can keep this
1139 // process around forever. These events need to be cleared out.
1140 m_private_state_listener.Clear();
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001141 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001142}
1143
1144void
1145Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1146{
1147 m_notifications.push_back(callbacks);
1148 if (callbacks.initialize != NULL)
1149 callbacks.initialize (callbacks.baton, this);
1150}
1151
1152bool
1153Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1154{
1155 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1156 for (pos = m_notifications.begin(); pos != end; ++pos)
1157 {
1158 if (pos->baton == callbacks.baton &&
1159 pos->initialize == callbacks.initialize &&
1160 pos->process_state_changed == callbacks.process_state_changed)
1161 {
1162 m_notifications.erase(pos);
1163 return true;
1164 }
1165 }
1166 return false;
1167}
1168
1169void
1170Process::SynchronouslyNotifyStateChanged (StateType state)
1171{
1172 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1173 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1174 {
1175 if (notification_pos->process_state_changed)
1176 notification_pos->process_state_changed (notification_pos->baton, this, state);
1177 }
1178}
1179
1180// FIXME: We need to do some work on events before the general Listener sees them.
1181// For instance if we are continuing from a breakpoint, we need to ensure that we do
1182// the little "insert real insn, step & stop" trick. But we can't do that when the
1183// event is delivered by the broadcaster - since that is done on the thread that is
1184// waiting for new events, so if we needed more than one event for our handling, we would
1185// stall. So instead we do it when we fetch the event off of the queue.
1186//
1187
1188StateType
1189Process::GetNextEvent (EventSP &event_sp)
1190{
1191 StateType state = eStateInvalid;
1192
1193 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1194 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1195
1196 return state;
1197}
1198
1199
1200StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001201Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001202{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001203 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1204 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1205 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001206 if (event_sp_ptr)
1207 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001208 StateType state = GetState();
1209 // If we are exited or detached, we won't ever get back to any
1210 // other valid state...
1211 if (state == eStateDetached || state == eStateExited)
1212 return state;
1213
1214 while (state != eStateInvalid)
1215 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001216 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001217 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001218 if (event_sp_ptr && event_sp)
1219 *event_sp_ptr = event_sp;
1220
Jim Ingham21f37ad2011-08-09 02:12:22 +00001221 switch (state)
1222 {
1223 case eStateCrashed:
1224 case eStateDetached:
1225 case eStateExited:
1226 case eStateUnloaded:
1227 return state;
1228 case eStateStopped:
1229 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1230 continue;
1231 else
1232 return state;
1233 default:
1234 continue;
1235 }
1236 }
1237 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001238}
1239
1240
1241StateType
1242Process::WaitForState
1243(
1244 const TimeValue *timeout,
1245 const StateType *match_states, const uint32_t num_match_states
1246)
1247{
1248 EventSP event_sp;
1249 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001250 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001251 while (state != eStateInvalid)
1252 {
Greg Claytond8c62532010-10-07 04:19:01 +00001253 // If we are exited or detached, we won't ever get back to any
1254 // other valid state...
1255 if (state == eStateDetached || state == eStateExited)
1256 return state;
1257
Chris Lattner24943d22010-06-08 16:52:24 +00001258 state = WaitForStateChangedEvents (timeout, event_sp);
1259
1260 for (i=0; i<num_match_states; ++i)
1261 {
1262 if (match_states[i] == state)
1263 return state;
1264 }
1265 }
1266 return state;
1267}
1268
Jim Ingham63e24d72010-10-11 23:53:14 +00001269bool
1270Process::HijackProcessEvents (Listener *listener)
1271{
1272 if (listener != NULL)
1273 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001274 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001275 }
1276 else
1277 return false;
1278}
1279
1280void
1281Process::RestoreProcessEvents ()
1282{
1283 RestoreBroadcaster();
1284}
1285
Jim Inghamf9f40c22011-02-08 05:20:59 +00001286bool
1287Process::HijackPrivateProcessEvents (Listener *listener)
1288{
1289 if (listener != NULL)
1290 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001291 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001292 }
1293 else
1294 return false;
1295}
1296
1297void
1298Process::RestorePrivateProcessEvents ()
1299{
1300 m_private_state_broadcaster.RestoreBroadcaster();
1301}
1302
Chris Lattner24943d22010-06-08 16:52:24 +00001303StateType
1304Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1305{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001306 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001307
1308 if (log)
1309 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1310
1311 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001312 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1313 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001314 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001315 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001316 {
1317 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1318 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1319 else if (log)
1320 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1321 }
Chris Lattner24943d22010-06-08 16:52:24 +00001322
1323 if (log)
1324 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1325 __FUNCTION__,
1326 timeout,
1327 StateAsCString(state));
1328 return state;
1329}
1330
1331Event *
1332Process::PeekAtStateChangedEvents ()
1333{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001334 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001335
1336 if (log)
1337 log->Printf ("Process::%s...", __FUNCTION__);
1338
1339 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001340 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1341 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001342 if (log)
1343 {
1344 if (event_ptr)
1345 {
1346 log->Printf ("Process::%s (event_ptr) => %s",
1347 __FUNCTION__,
1348 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1349 }
1350 else
1351 {
1352 log->Printf ("Process::%s no events found",
1353 __FUNCTION__);
1354 }
1355 }
1356 return event_ptr;
1357}
1358
1359StateType
1360Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1361{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001362 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001363
1364 if (log)
1365 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1366
1367 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001368 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1369 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001370 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001371 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001372 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1373 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001374
1375 // This is a bit of a hack, but when we wait here we could very well return
1376 // to the command-line, and that could disable the log, which would render the
1377 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001378 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001379 {
1380 if (state == eStateInvalid)
1381 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1382 else
1383 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1384 }
Chris Lattner24943d22010-06-08 16:52:24 +00001385 return state;
1386}
1387
1388bool
1389Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1390{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001391 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001392
1393 if (log)
1394 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1395
1396 if (control_only)
1397 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1398 else
1399 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1400}
1401
1402bool
1403Process::IsRunning () const
1404{
1405 return StateIsRunningState (m_public_state.GetValue());
1406}
1407
1408int
1409Process::GetExitStatus ()
1410{
1411 if (m_public_state.GetValue() == eStateExited)
1412 return m_exit_status;
1413 return -1;
1414}
1415
Greg Clayton638351a2010-12-04 00:10:17 +00001416
Chris Lattner24943d22010-06-08 16:52:24 +00001417const char *
1418Process::GetExitDescription ()
1419{
1420 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1421 return m_exit_string.c_str();
1422 return NULL;
1423}
1424
Greg Clayton72e1c782011-01-22 23:43:18 +00001425bool
Chris Lattner24943d22010-06-08 16:52:24 +00001426Process::SetExitStatus (int status, const char *cstr)
1427{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001428 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton68ca8232011-01-25 02:58:48 +00001429 if (log)
1430 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1431 status, status,
1432 cstr ? "\"" : "",
1433 cstr ? cstr : "NULL",
1434 cstr ? "\"" : "");
1435
Greg Clayton72e1c782011-01-22 23:43:18 +00001436 // We were already in the exited state
1437 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001438 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001439 if (log)
1440 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001441 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001442 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001443
1444 m_exit_status = status;
1445 if (cstr)
1446 m_exit_string = cstr;
1447 else
1448 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001449
Greg Clayton72e1c782011-01-22 23:43:18 +00001450 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001451
Greg Clayton72e1c782011-01-22 23:43:18 +00001452 SetPrivateState (eStateExited);
1453 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001454}
1455
1456// This static callback can be used to watch for local child processes on
1457// the current host. The the child process exits, the process will be
1458// found in the global target list (we want to be completely sure that the
1459// lldb_private::Process doesn't go away before we can deliver the signal.
1460bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001461Process::SetProcessExitStatus (void *callback_baton,
1462 lldb::pid_t pid,
1463 bool exited,
1464 int signo, // Zero for no signal
1465 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001466)
1467{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001468 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton1c4642c2011-11-16 05:37:56 +00001469 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001470 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001471 callback_baton,
1472 pid,
1473 exited,
1474 signo,
1475 exit_status);
1476
1477 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001478 {
Greg Clayton63094e02010-06-23 01:19:29 +00001479 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001480 if (target_sp)
1481 {
1482 ProcessSP process_sp (target_sp->GetProcessSP());
1483 if (process_sp)
1484 {
1485 const char *signal_cstr = NULL;
1486 if (signo)
1487 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1488
1489 process_sp->SetExitStatus (exit_status, signal_cstr);
1490 }
1491 }
1492 return true;
1493 }
1494 return false;
1495}
1496
1497
Greg Clayton37f962e2011-08-22 02:49:39 +00001498void
1499Process::UpdateThreadListIfNeeded ()
1500{
1501 const uint32_t stop_id = GetStopID();
1502 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1503 {
Greg Clayton20206082011-11-17 01:23:07 +00001504 const StateType state = GetPrivateState();
1505 if (StateIsStoppedState (state, true))
1506 {
1507 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001508 // m_thread_list does have its own mutex, but we need to
1509 // hold onto the mutex between the call to UpdateThreadList(...)
1510 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001511 ThreadList new_thread_list(this);
1512 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001513 // thread list, but only update if "true" is returned
1514 if (UpdateThreadList (m_thread_list, new_thread_list))
1515 {
Jim Inghameb175302013-03-01 20:04:25 +00001516 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1517 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1518 // shutting us down, causing a deadlock.
1519 if (!m_destroy_in_process)
1520 {
1521 OperatingSystem *os = GetOperatingSystem ();
1522 if (os)
Greg Clayton9acf3692013-04-12 20:07:46 +00001523 {
1524 // Clear any old backing threads where memory threads might have been
1525 // backed by actual threads from the lldb_private::Process subclass
1526 size_t num_old_threads = m_thread_list.GetSize(false);
1527 for (size_t i=0; i<num_old_threads; ++i)
1528 m_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1529
1530 // Now let the OperatingSystem plug-in update the thread list
Jim Inghameb175302013-03-01 20:04:25 +00001531 os->UpdateThreadList (m_thread_list, new_thread_list);
Greg Clayton9acf3692013-04-12 20:07:46 +00001532 }
Jim Inghameb175302013-03-01 20:04:25 +00001533 m_thread_list.Update (new_thread_list);
1534 m_thread_list.SetStopID (stop_id);
1535 }
Greg Claytonae932352012-04-10 00:18:59 +00001536 }
Greg Clayton20206082011-11-17 01:23:07 +00001537 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001538 }
1539}
1540
Greg Clayton52ebc0a2013-01-18 23:41:08 +00001541ThreadSP
1542Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1543{
1544 OperatingSystem *os = GetOperatingSystem ();
1545 if (os)
1546 return os->CreateThread(tid, context);
1547 return ThreadSP();
1548}
1549
1550
1551
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001552// This is obsoleted. Staged removal for Xcode.
Chris Lattner24943d22010-06-08 16:52:24 +00001553uint32_t
1554Process::GetNextThreadIndexID ()
1555{
1556 return ++m_thread_index_id;
1557}
1558
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001559uint32_t
1560Process::GetNextThreadIndexID (uint64_t thread_id)
1561{
1562 return AssignIndexIDToThread(thread_id);
1563}
1564
1565bool
1566Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1567{
1568 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1569 if (iterator == m_thread_id_to_index_id_map.end())
1570 {
1571 return false;
1572 }
1573 else
1574 {
1575 return true;
1576 }
1577}
1578
1579uint32_t
1580Process::AssignIndexIDToThread(uint64_t thread_id)
1581{
1582 uint32_t result = 0;
1583 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1584 if (iterator == m_thread_id_to_index_id_map.end())
1585 {
1586 result = ++m_thread_index_id;
1587 m_thread_id_to_index_id_map[thread_id] = result;
1588 }
1589 else
1590 {
1591 result = iterator->second;
1592 }
1593
1594 return result;
1595}
1596
Chris Lattner24943d22010-06-08 16:52:24 +00001597StateType
1598Process::GetState()
1599{
1600 // If any other threads access this we will need a mutex for it
1601 return m_public_state.GetValue ();
1602}
1603
1604void
1605Process::SetPublicState (StateType new_state)
1606{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001607 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001608 if (log)
1609 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001610 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001611 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001612
1613 // On the transition from Run to Stopped, we unlock the writer end of the
1614 // run lock. The lock gets locked in Resume, which is the public API
1615 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001616 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1617 {
Sean Callanana3772862012-06-02 01:16:20 +00001618 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001619 {
Sean Callanana3772862012-06-02 01:16:20 +00001620 if (log)
1621 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00001622 m_run_lock.WriteUnlock();
Sean Callanana3772862012-06-02 01:16:20 +00001623 }
1624 else
1625 {
1626 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1627 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1628 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001629 {
Sean Callanana3772862012-06-02 01:16:20 +00001630 if (new_state_is_stopped)
1631 {
1632 if (log)
1633 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00001634 m_run_lock.WriteUnlock();
Sean Callanana3772862012-06-02 01:16:20 +00001635 }
Greg Claytona894fe72012-04-05 16:12:35 +00001636 }
Greg Claytona894fe72012-04-05 16:12:35 +00001637 }
1638 }
Chris Lattner24943d22010-06-08 16:52:24 +00001639}
1640
Jim Ingham027aaa72012-04-19 01:40:33 +00001641Error
1642Process::Resume ()
1643{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001644 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham027aaa72012-04-19 01:40:33 +00001645 if (log)
1646 log->Printf("Process::Resume -- locking run lock");
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00001647 if (!m_run_lock.WriteTryLock())
Jim Ingham027aaa72012-04-19 01:40:33 +00001648 {
1649 Error error("Resume request failed - process still running.");
1650 if (log)
1651 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1652 return error;
1653 }
1654 return PrivateResume();
1655}
1656
Chris Lattner24943d22010-06-08 16:52:24 +00001657StateType
1658Process::GetPrivateState ()
1659{
1660 return m_private_state.GetValue();
1661}
1662
1663void
1664Process::SetPrivateState (StateType new_state)
1665{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001666 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001667 bool state_changed = false;
1668
1669 if (log)
1670 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1671
1672 Mutex::Locker locker(m_private_state.GetMutex());
1673
1674 const StateType old_state = m_private_state.GetValueNoLock ();
1675 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001676 // This code is left commented out in case we ever need to control
1677 // the private process state with another run lock. Right now it doesn't
1678 // seem like we need to do this, but if we ever do, we can uncomment and
1679 // use this code.
1680// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1681// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1682// if (old_state_is_stopped != new_state_is_stopped)
1683// {
1684// if (new_state_is_stopped)
1685// m_private_run_lock.WriteUnlock();
1686// else
1687// m_private_run_lock.WriteLock();
1688// }
1689
Chris Lattner24943d22010-06-08 16:52:24 +00001690 if (state_changed)
1691 {
1692 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001693 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001694 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001695 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001696 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001697 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001698 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001699 }
1700 // Use our target to get a shared pointer to ourselves...
Greg Clayton84332782012-10-29 20:52:08 +00001701 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1702 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1703 else
1704 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001705 }
1706 else
1707 {
1708 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001709 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001710 }
1711}
1712
Jim Ingham0296fe72011-11-08 03:00:11 +00001713void
1714Process::SetRunningUserExpression (bool on)
1715{
1716 m_mod_id.SetRunningUserExpression (on);
1717}
1718
Chris Lattner24943d22010-06-08 16:52:24 +00001719addr_t
1720Process::GetImageInfoAddress()
1721{
1722 return LLDB_INVALID_ADDRESS;
1723}
1724
Greg Clayton0baa3942010-11-04 01:54:29 +00001725//----------------------------------------------------------------------
1726// LoadImage
1727//
1728// This function provides a default implementation that works for most
1729// unix variants. Any Process subclasses that need to do shared library
1730// loading differently should override LoadImage and UnloadImage and
1731// do what is needed.
1732//----------------------------------------------------------------------
1733uint32_t
1734Process::LoadImage (const FileSpec &image_spec, Error &error)
1735{
Greg Clayton77d40712012-04-18 00:05:19 +00001736 char path[PATH_MAX];
1737 image_spec.GetPath(path, sizeof(path));
1738
Greg Clayton0baa3942010-11-04 01:54:29 +00001739 DynamicLoader *loader = GetDynamicLoader();
1740 if (loader)
1741 {
1742 error = loader->CanLoadImage();
1743 if (error.Fail())
1744 return LLDB_INVALID_IMAGE_TOKEN;
1745 }
1746
1747 if (error.Success())
1748 {
1749 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001750
1751 if (thread_sp)
1752 {
1753 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1754
1755 if (frame_sp)
1756 {
1757 ExecutionContext exe_ctx;
1758 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001759 const bool unwind_on_error = true;
1760 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001761 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001762 expr.Printf("dlopen (\"%s\", 2)", path);
1763 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001764 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001765 ClangUserExpression::Evaluate (exe_ctx,
1766 eExecutionPolicyAlways,
1767 lldb::eLanguageTypeUnknown,
1768 ClangUserExpression::eResultTypeAny,
1769 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001770 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001771 expr.GetData(),
1772 prefix,
1773 result_valobj_sp,
1774 true,
1775 ClangUserExpression::kDefaultTimeout);
Johnny Chenb14ec342011-09-09 00:01:43 +00001776 error = result_valobj_sp->GetError();
1777 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001778 {
1779 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001780 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001781 {
1782 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1783 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1784 {
1785 uint32_t image_token = m_image_tokens.size();
1786 m_image_tokens.push_back (image_ptr);
1787 return image_token;
1788 }
1789 }
1790 }
1791 }
1792 }
1793 }
Greg Clayton77d40712012-04-18 00:05:19 +00001794 if (!error.AsCString())
1795 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001796 return LLDB_INVALID_IMAGE_TOKEN;
1797}
1798
1799//----------------------------------------------------------------------
1800// UnloadImage
1801//
1802// This function provides a default implementation that works for most
1803// unix variants. Any Process subclasses that need to do shared library
1804// loading differently should override LoadImage and UnloadImage and
1805// do what is needed.
1806//----------------------------------------------------------------------
1807Error
1808Process::UnloadImage (uint32_t image_token)
1809{
1810 Error error;
1811 if (image_token < m_image_tokens.size())
1812 {
1813 const addr_t image_addr = m_image_tokens[image_token];
1814 if (image_addr == LLDB_INVALID_ADDRESS)
1815 {
1816 error.SetErrorString("image already unloaded");
1817 }
1818 else
1819 {
1820 DynamicLoader *loader = GetDynamicLoader();
1821 if (loader)
1822 error = loader->CanLoadImage();
1823
1824 if (error.Success())
1825 {
1826 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001827
1828 if (thread_sp)
1829 {
1830 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1831
1832 if (frame_sp)
1833 {
1834 ExecutionContext exe_ctx;
1835 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001836 const bool unwind_on_error = true;
1837 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001838 StreamString expr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001839 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton0baa3942010-11-04 01:54:29 +00001840 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001841 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001842 ClangUserExpression::Evaluate (exe_ctx,
1843 eExecutionPolicyAlways,
1844 lldb::eLanguageTypeUnknown,
1845 ClangUserExpression::eResultTypeAny,
1846 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001847 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001848 expr.GetData(),
1849 prefix,
1850 result_valobj_sp,
1851 true,
1852 ClangUserExpression::kDefaultTimeout);
Greg Clayton0baa3942010-11-04 01:54:29 +00001853 if (result_valobj_sp->GetError().Success())
1854 {
1855 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001856 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001857 {
1858 if (scalar.UInt(1))
1859 {
1860 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1861 }
1862 else
1863 {
1864 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1865 }
1866 }
1867 }
1868 else
1869 {
1870 error = result_valobj_sp->GetError();
1871 }
1872 }
1873 }
1874 }
1875 }
1876 }
1877 else
1878 {
1879 error.SetErrorString("invalid image token");
1880 }
1881 return error;
1882}
1883
Greg Clayton75906e42011-05-11 18:39:18 +00001884const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001885Process::GetABI()
1886{
Greg Clayton75906e42011-05-11 18:39:18 +00001887 if (!m_abi_sp)
1888 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1889 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001890}
1891
Jim Ingham642036f2010-09-23 02:01:19 +00001892LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001893Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001894{
1895 LanguageRuntimeCollection::iterator pos;
1896 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001897 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001898 {
Jim Inghame3117662012-03-10 00:22:19 +00001899 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001900
Jim Inghame3117662012-03-10 00:22:19 +00001901 m_language_runtimes[language] = runtime_sp;
1902 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001903 }
1904 else
1905 return (*pos).second.get();
1906}
1907
1908CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001909Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001910{
Jim Inghame3117662012-03-10 00:22:19 +00001911 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001912 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1913 return static_cast<CPPLanguageRuntime *> (runtime);
1914 return NULL;
1915}
1916
1917ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001918Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001919{
Jim Inghame3117662012-03-10 00:22:19 +00001920 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001921 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1922 return static_cast<ObjCLanguageRuntime *> (runtime);
1923 return NULL;
1924}
1925
Enrico Granata6b1763b2012-05-21 16:51:35 +00001926bool
1927Process::IsPossibleDynamicValue (ValueObject& in_value)
1928{
1929 if (in_value.IsDynamic())
1930 return false;
1931 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1932
1933 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1934 {
1935 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1936 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1937 }
1938
1939 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1940 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1941 return true;
1942
1943 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1944 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1945}
1946
Chris Lattner24943d22010-06-08 16:52:24 +00001947BreakpointSiteList &
1948Process::GetBreakpointSiteList()
1949{
1950 return m_breakpoint_site_list;
1951}
1952
1953const BreakpointSiteList &
1954Process::GetBreakpointSiteList() const
1955{
1956 return m_breakpoint_site_list;
1957}
1958
1959
1960void
1961Process::DisableAllBreakpointSites ()
1962{
1963 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001964 size_t num_sites = m_breakpoint_site_list.GetSize();
1965 for (size_t i = 0; i < num_sites; i++)
1966 {
Jim Inghamefb4aeb2013-02-15 02:06:30 +00001967 DisableBreakpointSite (m_breakpoint_site_list.GetByIndex(i).get());
Jim Ingham06b84492012-07-04 00:35:43 +00001968 }
Chris Lattner24943d22010-06-08 16:52:24 +00001969}
1970
1971Error
1972Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1973{
1974 Error error (DisableBreakpointSiteByID (break_id));
1975
1976 if (error.Success())
1977 m_breakpoint_site_list.Remove(break_id);
1978
1979 return error;
1980}
1981
1982Error
1983Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1984{
1985 Error error;
1986 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1987 if (bp_site_sp)
1988 {
1989 if (bp_site_sp->IsEnabled())
Jim Inghamefb4aeb2013-02-15 02:06:30 +00001990 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001991 }
1992 else
1993 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001994 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001995 }
1996
1997 return error;
1998}
1999
2000Error
2001Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2002{
2003 Error error;
2004 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2005 if (bp_site_sp)
2006 {
2007 if (!bp_site_sp->IsEnabled())
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002008 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002009 }
2010 else
2011 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002012 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00002013 }
2014 return error;
2015}
2016
Stephen Wilson3fd1f362010-07-17 00:56:13 +00002017lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00002018Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00002019{
Greg Clayton265ab332011-05-19 18:17:41 +00002020 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002021 if (load_addr != LLDB_INVALID_ADDRESS)
2022 {
2023 BreakpointSiteSP bp_site_sp;
2024
2025 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2026 // create a new breakpoint site and add it.
2027
2028 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2029
2030 if (bp_site_sp)
2031 {
2032 bp_site_sp->AddOwner (owner);
2033 owner->SetBreakpointSite (bp_site_sp);
2034 return bp_site_sp->GetID();
2035 }
2036 else
2037 {
Greg Clayton36da2aa2013-01-25 18:06:21 +00002038 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner24943d22010-06-08 16:52:24 +00002039 if (bp_site_sp)
2040 {
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002041 if (EnableBreakpointSite (bp_site_sp.get()).Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002042 {
2043 owner->SetBreakpointSite (bp_site_sp);
2044 return m_breakpoint_site_list.Add (bp_site_sp);
2045 }
2046 }
2047 }
2048 }
2049 // We failed to enable the breakpoint
2050 return LLDB_INVALID_BREAK_ID;
2051
2052}
2053
2054void
2055Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2056{
2057 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2058 if (num_owners == 0)
2059 {
Jim Ingham700ff7e2013-04-06 00:16:39 +00002060 // Don't try to disable the site if we don't have a live process anymore.
2061 if (IsAlive())
2062 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002063 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2064 }
2065}
2066
2067
2068size_t
2069Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2070{
2071 size_t bytes_removed = 0;
2072 addr_t intersect_addr;
2073 size_t intersect_size;
2074 size_t opcode_offset;
2075 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002076 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00002077 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00002078
Jim Ingham82820f92011-06-29 19:42:28 +00002079 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00002080 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002081 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00002082 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002083 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00002084 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002085 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00002086 {
2087 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2088 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00002089 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00002090 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002091 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00002092 }
Chris Lattner24943d22010-06-08 16:52:24 +00002093 }
2094 }
2095 }
2096 return bytes_removed;
2097}
2098
2099
Greg Claytonb1888f22011-03-19 01:12:21 +00002100
2101size_t
2102Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2103{
2104 PlatformSP platform_sp (m_target.GetPlatform());
2105 if (platform_sp)
2106 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2107 return 0;
2108}
2109
Chris Lattner24943d22010-06-08 16:52:24 +00002110Error
2111Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2112{
2113 Error error;
2114 assert (bp_site != NULL);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002115 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002116 const addr_t bp_addr = bp_site->GetLoadAddress();
2117 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002118 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002119 if (bp_site->IsEnabled())
2120 {
2121 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002122 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002123 return error;
2124 }
2125
2126 if (bp_addr == LLDB_INVALID_ADDRESS)
2127 {
2128 error.SetErrorString("BreakpointSite contains an invalid load address.");
2129 return error;
2130 }
2131 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2132 // trap for the breakpoint site
2133 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2134
2135 if (bp_opcode_size == 0)
2136 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002137 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002138 }
2139 else
2140 {
2141 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2142
2143 if (bp_opcode_bytes == NULL)
2144 {
2145 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2146 return error;
2147 }
2148
2149 // Save the original opcode by reading it
2150 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2151 {
2152 // Write a software breakpoint in place of the original opcode
2153 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2154 {
2155 uint8_t verify_bp_opcode_bytes[64];
2156 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2157 {
2158 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2159 {
2160 bp_site->SetEnabled(true);
2161 bp_site->SetType (BreakpointSite::eSoftware);
2162 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002163 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner24943d22010-06-08 16:52:24 +00002164 bp_site->GetID(),
2165 (uint64_t)bp_addr);
2166 }
2167 else
Greg Clayton9c236732011-10-26 00:56:27 +00002168 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00002169 }
2170 else
2171 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2172 }
2173 else
2174 error.SetErrorString("Unable to write breakpoint trap to memory.");
2175 }
2176 else
2177 error.SetErrorString("Unable to read memory at breakpoint address.");
2178 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002179 if (log && error.Fail())
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002180 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002181 bp_site->GetID(),
2182 (uint64_t)bp_addr,
2183 error.AsCString());
2184 return error;
2185}
2186
2187Error
2188Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2189{
2190 Error error;
2191 assert (bp_site != NULL);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002192 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002193 addr_t bp_addr = bp_site->GetLoadAddress();
2194 lldb::user_id_t breakID = bp_site->GetID();
2195 if (log)
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002196 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002197
2198 if (bp_site->IsHardware())
2199 {
2200 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2201 }
2202 else if (bp_site->IsEnabled())
2203 {
2204 const size_t break_op_size = bp_site->GetByteSize();
2205 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2206 if (break_op_size > 0)
2207 {
2208 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002209 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002210 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002211 bool break_op_found = false;
2212
2213 // Read the breakpoint opcode
2214 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2215 {
2216 bool verify = false;
2217 // Make sure we have the a breakpoint opcode exists at this address
2218 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2219 {
2220 break_op_found = true;
2221 // We found a valid breakpoint opcode at this address, now restore
2222 // the saved opcode.
2223 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2224 {
2225 verify = true;
2226 }
2227 else
2228 error.SetErrorString("Memory write failed when restoring original opcode.");
2229 }
2230 else
2231 {
2232 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2233 // Set verify to true and so we can check if the original opcode has already been restored
2234 verify = true;
2235 }
2236
2237 if (verify)
2238 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002239 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002240 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002241 // Verify that our original opcode made it back to the inferior
2242 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2243 {
2244 // compare the memory we just read with the original opcode
2245 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2246 {
2247 // SUCCESS
2248 bp_site->SetEnabled(false);
2249 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002250 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002251 return error;
2252 }
2253 else
2254 {
2255 if (break_op_found)
2256 error.SetErrorString("Failed to restore original opcode.");
2257 }
2258 }
2259 else
2260 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2261 }
2262 }
2263 else
2264 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2265 }
2266 }
2267 else
2268 {
2269 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002270 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002271 return error;
2272 }
2273
2274 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002275 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002276 bp_site->GetID(),
2277 (uint64_t)bp_addr,
2278 error.AsCString());
2279 return error;
2280
2281}
2282
Greg Claytonfd119992011-01-07 06:08:19 +00002283// Uncomment to verify memory caching works after making changes to caching code
2284//#define VERIFY_MEMORY_READS
2285
Sean Callananf90b5f32012-06-07 22:26:42 +00002286size_t
2287Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2288{
2289 if (!GetDisableMemoryCache())
2290 {
Greg Claytonfd119992011-01-07 06:08:19 +00002291#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002292 // Memory caching is enabled, with debug verification
2293
2294 if (buf && size)
2295 {
2296 // Uncomment the line below to make sure memory caching is working.
2297 // I ran this through the test suite and got no assertions, so I am
2298 // pretty confident this is working well. If any changes are made to
2299 // memory caching, uncomment the line below and test your changes!
2300
2301 // Verify all memory reads by using the cache first, then redundantly
2302 // reading the same memory from the inferior and comparing to make sure
2303 // everything is exactly the same.
2304 std::string verify_buf (size, '\0');
2305 assert (verify_buf.size() == size);
2306 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2307 Error verify_error;
2308 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2309 assert (cache_bytes_read == verify_bytes_read);
2310 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2311 assert (verify_error.Success() == error.Success());
2312 return cache_bytes_read;
2313 }
2314 return 0;
2315#else // !defined(VERIFY_MEMORY_READS)
2316 // Memory caching is enabled, without debug verification
2317
2318 return m_memory_cache.Read (addr, buf, size, error);
2319#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002320 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002321 else
2322 {
2323 // Memory caching is disabled
2324
2325 return ReadMemoryFromInferior (addr, buf, size, error);
2326 }
Greg Claytonfd119992011-01-07 06:08:19 +00002327}
Greg Claytonfd119992011-01-07 06:08:19 +00002328
Greg Claytondd29b972012-05-18 23:20:01 +00002329size_t
2330Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2331{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002332 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002333 out_str.clear();
2334 addr_t curr_addr = addr;
2335 while (1)
2336 {
2337 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2338 if (length == 0)
2339 break;
2340 out_str.append(buf, length);
2341 // If we got "length - 1" bytes, we didn't get the whole C string, we
2342 // need to read some more characters
2343 if (length == sizeof(buf) - 1)
2344 curr_addr += length;
2345 else
2346 break;
2347 }
2348 return out_str.size();
2349}
2350
Greg Claytonfd119992011-01-07 06:08:19 +00002351
2352size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002353Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002354{
2355 size_t total_cstr_len = 0;
2356 if (dst && dst_max_len)
2357 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002358 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002359 // NULL out everything just to be safe
2360 memset (dst, 0, dst_max_len);
2361 Error error;
2362 addr_t curr_addr = addr;
2363 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2364 size_t bytes_left = dst_max_len - 1;
2365 char *curr_dst = dst;
2366
2367 while (bytes_left > 0)
2368 {
2369 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2370 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2371 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2372
2373 if (bytes_read == 0)
2374 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002375 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002376 dst[total_cstr_len] = '\0';
2377 break;
2378 }
2379 const size_t len = strlen(curr_dst);
2380
2381 total_cstr_len += len;
2382
2383 if (len < bytes_to_read)
2384 break;
2385
2386 curr_dst += bytes_read;
2387 curr_addr += bytes_read;
2388 bytes_left -= bytes_read;
2389 }
2390 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002391 else
2392 {
2393 if (dst == NULL)
2394 result_error.SetErrorString("invalid arguments");
2395 else
2396 result_error.Clear();
2397 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002398 return total_cstr_len;
2399}
2400
2401size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002402Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2403{
Chris Lattner24943d22010-06-08 16:52:24 +00002404 if (buf == NULL || size == 0)
2405 return 0;
2406
2407 size_t bytes_read = 0;
2408 uint8_t *bytes = (uint8_t *)buf;
2409
2410 while (bytes_read < size)
2411 {
2412 const size_t curr_size = size - bytes_read;
2413 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2414 bytes + bytes_read,
2415 curr_size,
2416 error);
2417 bytes_read += curr_bytes_read;
2418 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2419 break;
2420 }
2421
2422 // Replace any software breakpoint opcodes that fall into this range back
2423 // into "buf" before we return
2424 if (bytes_read > 0)
2425 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2426 return bytes_read;
2427}
2428
Greg Claytonf72fdee2010-12-16 20:01:20 +00002429uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002430Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002431{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002432 Scalar scalar;
2433 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2434 return scalar.ULongLong(fail_value);
2435 return fail_value;
2436}
2437
2438addr_t
2439Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2440{
2441 Scalar scalar;
2442 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2443 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2444 return LLDB_INVALID_ADDRESS;
2445}
2446
2447
2448bool
2449Process::WritePointerToMemory (lldb::addr_t vm_addr,
2450 lldb::addr_t ptr_value,
2451 Error &error)
2452{
2453 Scalar scalar;
2454 const uint32_t addr_byte_size = GetAddressByteSize();
2455 if (addr_byte_size <= 4)
2456 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002457 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002458 scalar = ptr_value;
2459 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002460}
2461
Chris Lattner24943d22010-06-08 16:52:24 +00002462size_t
2463Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2464{
2465 size_t bytes_written = 0;
2466 const uint8_t *bytes = (const uint8_t *)buf;
2467
2468 while (bytes_written < size)
2469 {
2470 const size_t curr_size = size - bytes_written;
2471 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2472 bytes + bytes_written,
2473 curr_size,
2474 error);
2475 bytes_written += curr_bytes_written;
2476 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2477 break;
2478 }
2479 return bytes_written;
2480}
2481
2482size_t
2483Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2484{
Greg Claytonfd119992011-01-07 06:08:19 +00002485#if defined (ENABLE_MEMORY_CACHING)
2486 m_memory_cache.Flush (addr, size);
2487#endif
2488
Chris Lattner24943d22010-06-08 16:52:24 +00002489 if (buf == NULL || size == 0)
2490 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002491
Jim Ingham21f37ad2011-08-09 02:12:22 +00002492 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002493
Chris Lattner24943d22010-06-08 16:52:24 +00002494 // We need to write any data that would go where any current software traps
2495 // (enabled software breakpoints) any software traps (breakpoints) that we
2496 // may have placed in our tasks memory.
2497
2498 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2499 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2500
2501 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002502 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002503
2504 BreakpointSiteList::collection::const_iterator pos;
2505 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002506 addr_t intersect_addr = 0;
2507 size_t intersect_size = 0;
2508 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002509 const uint8_t *ubuf = (const uint8_t *)buf;
2510
2511 for (pos = iter; pos != end; ++pos)
2512 {
2513 BreakpointSiteSP bp;
2514 bp = pos->second;
2515
2516 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2517 assert(addr <= intersect_addr && intersect_addr < addr + size);
2518 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2519 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2520
2521 // Check for bytes before this breakpoint
2522 const addr_t curr_addr = addr + bytes_written;
2523 if (intersect_addr > curr_addr)
2524 {
2525 // There are some bytes before this breakpoint that we need to
2526 // just write to memory
2527 size_t curr_size = intersect_addr - curr_addr;
2528 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2529 ubuf + bytes_written,
2530 curr_size,
2531 error);
2532 bytes_written += curr_bytes_written;
2533 if (curr_bytes_written != curr_size)
2534 {
2535 // We weren't able to write all of the requested bytes, we
2536 // are done looping and will return the number of bytes that
2537 // we have written so far.
2538 break;
2539 }
2540 }
2541
2542 // Now write any bytes that would cover up any software breakpoints
2543 // directly into the breakpoint opcode buffer
2544 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2545 bytes_written += intersect_size;
2546 }
2547
2548 // Write any remaining bytes after the last breakpoint if we have any left
2549 if (bytes_written < size)
2550 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2551 ubuf + bytes_written,
2552 size - bytes_written,
2553 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002554
Chris Lattner24943d22010-06-08 16:52:24 +00002555 return bytes_written;
2556}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002557
2558size_t
Greg Clayton36da2aa2013-01-25 18:06:21 +00002559Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonc0fa5332011-05-22 22:46:53 +00002560{
2561 if (byte_size == UINT32_MAX)
2562 byte_size = scalar.GetByteSize();
2563 if (byte_size > 0)
2564 {
2565 uint8_t buf[32];
2566 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2567 if (mem_size > 0)
2568 return WriteMemory(addr, buf, mem_size, error);
2569 else
2570 error.SetErrorString ("failed to get scalar as memory data");
2571 }
2572 else
2573 {
2574 error.SetErrorString ("invalid scalar value");
2575 }
2576 return 0;
2577}
2578
2579size_t
2580Process::ReadScalarIntegerFromMemory (addr_t addr,
2581 uint32_t byte_size,
2582 bool is_signed,
2583 Scalar &scalar,
2584 Error &error)
2585{
2586 uint64_t uval;
2587
2588 if (byte_size <= sizeof(uval))
2589 {
2590 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2591 if (bytes_read == byte_size)
2592 {
2593 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Clayton36da2aa2013-01-25 18:06:21 +00002594 lldb::offset_t offset = 0;
Greg Claytonc0fa5332011-05-22 22:46:53 +00002595 if (byte_size <= 4)
2596 scalar = data.GetMaxU32 (&offset, byte_size);
2597 else
2598 scalar = data.GetMaxU64 (&offset, byte_size);
2599
2600 if (is_signed)
2601 scalar.SignExtend(byte_size * 8);
2602 return bytes_read;
2603 }
2604 }
2605 else
2606 {
2607 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2608 }
2609 return 0;
2610}
2611
Greg Clayton613b8732011-05-17 03:37:42 +00002612#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002613addr_t
2614Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2615{
Jim Inghame6bd1422011-06-20 17:32:44 +00002616 if (GetPrivateState() != eStateStopped)
2617 return LLDB_INVALID_ADDRESS;
2618
Greg Clayton613b8732011-05-17 03:37:42 +00002619#if defined (USE_ALLOCATE_MEMORY_CACHE)
2620 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2621#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002622 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002623 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2860ba92011-01-23 19:58:49 +00002624 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002625 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16" PRIx64 " (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002626 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002627 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002628 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002629 m_mod_id.GetStopID(),
2630 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002631 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002632#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002633}
2634
Sean Callanan6cf6c472011-09-20 23:01:51 +00002635bool
2636Process::CanJIT ()
2637{
Sean Callanan04200f62012-02-14 22:50:38 +00002638 if (m_can_jit == eCanJITDontKnow)
2639 {
2640 Error err;
2641
2642 uint64_t allocated_memory = AllocateMemory(8,
2643 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2644 err);
2645
2646 if (err.Success())
2647 m_can_jit = eCanJITYes;
2648 else
2649 m_can_jit = eCanJITNo;
2650
2651 DeallocateMemory (allocated_memory);
2652 }
2653
Sean Callanan6cf6c472011-09-20 23:01:51 +00002654 return m_can_jit == eCanJITYes;
2655}
2656
2657void
2658Process::SetCanJIT (bool can_jit)
2659{
2660 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2661}
2662
Chris Lattner24943d22010-06-08 16:52:24 +00002663Error
2664Process::DeallocateMemory (addr_t ptr)
2665{
Greg Clayton613b8732011-05-17 03:37:42 +00002666 Error error;
2667#if defined (USE_ALLOCATE_MEMORY_CACHE)
2668 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2669 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002670 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Clayton613b8732011-05-17 03:37:42 +00002671 }
2672#else
2673 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002674
Greg Clayton952e9dc2013-03-27 23:08:40 +00002675 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2860ba92011-01-23 19:58:49 +00002676 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002677 log->Printf("Process::DeallocateMemory(addr=0x%16.16" PRIx64 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002678 ptr,
2679 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002680 m_mod_id.GetStopID(),
2681 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002682#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002683 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002684}
2685
Han Ming Ong2529aa32012-11-17 00:33:14 +00002686
Greg Claytonb5a8f142012-02-05 02:38:54 +00002687ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002688Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton2ddb2b82013-02-01 21:38:35 +00002689 lldb::addr_t header_addr)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002690{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002691 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002692 if (module_sp)
2693 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002694 Error error;
2695 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2696 if (objfile)
Greg Clayton6c5438b2012-02-24 21:55:59 +00002697 return module_sp;
Greg Claytonb5a8f142012-02-05 02:38:54 +00002698 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002699 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002700}
Chris Lattner24943d22010-06-08 16:52:24 +00002701
2702Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002703Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002704{
2705 Error error;
2706 error.SetErrorString("watchpoints are not supported");
2707 return error;
2708}
2709
2710Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002711Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002712{
2713 Error error;
2714 error.SetErrorString("watchpoints are not supported");
2715 return error;
2716}
2717
2718StateType
2719Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2720{
2721 StateType state;
2722 // Now wait for the process to launch and return control to us, and then
2723 // call DidLaunch:
2724 while (1)
2725 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002726 event_sp.reset();
2727 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2728
Greg Clayton20206082011-11-17 01:23:07 +00002729 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002730 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002731
2732 // If state is invalid, then we timed out
2733 if (state == eStateInvalid)
2734 break;
2735
2736 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002737 HandlePrivateEvent (event_sp);
2738 }
2739 return state;
2740}
2741
2742Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002743Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002744{
2745 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002746 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002747 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002748 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002749 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002750
Greg Clayton5beb99d2011-08-11 02:48:45 +00002751 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002752 if (exe_module)
2753 {
Greg Clayton180546b2011-04-30 01:09:13 +00002754 char local_exec_file_path[PATH_MAX];
2755 char platform_exec_file_path[PATH_MAX];
2756 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2757 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002758 if (exe_module->GetFileSpec().Exists())
2759 {
Greg Claytona2f74232011-02-24 22:24:29 +00002760 if (PrivateStateThreadIsValid ())
2761 PausePrivateStateThread ();
2762
Chris Lattner24943d22010-06-08 16:52:24 +00002763 error = WillLaunch (exe_module);
2764 if (error.Success())
2765 {
Greg Claytond8c62532010-10-07 04:19:01 +00002766 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002767 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002768
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00002769 if (m_run_lock.WriteTryLock())
Greg Clayton777c6b72012-09-04 20:29:05 +00002770 {
2771 // Now launch using these arguments.
2772 error = DoLaunch (exe_module, launch_info);
2773 }
2774 else
2775 {
2776 // This shouldn't happen
2777 error.SetErrorString("failed to acquire process run lock");
2778 }
Chris Lattner24943d22010-06-08 16:52:24 +00002779
2780 if (error.Fail())
2781 {
2782 if (GetID() != LLDB_INVALID_PROCESS_ID)
2783 {
2784 SetID (LLDB_INVALID_PROCESS_ID);
2785 const char *error_string = error.AsCString();
2786 if (error_string == NULL)
2787 error_string = "launch failed";
2788 SetExitStatus (-1, error_string);
2789 }
2790 }
2791 else
2792 {
2793 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002794 TimeValue timeout_time;
2795 timeout_time = TimeValue::Now();
2796 timeout_time.OffsetWithSeconds(10);
2797 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002798
Greg Clayton49859592011-06-22 01:42:17 +00002799 if (state == eStateInvalid || event_sp.get() == NULL)
2800 {
2801 // We were able to launch the process, but we failed to
2802 // catch the initial stop.
2803 SetExitStatus (0, "failed to catch stop after launch");
2804 Destroy();
2805 }
2806 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002807 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002808
Chris Lattner24943d22010-06-08 16:52:24 +00002809 DidLaunch ();
2810
Greg Clayton9ce95382012-02-13 23:10:39 +00002811 DynamicLoader *dyld = GetDynamicLoader ();
2812 if (dyld)
2813 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002814
Greg Clayton37f962e2011-08-22 02:49:39 +00002815 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002816 // This delays passing the stopped event to listeners till DidLaunch gets
2817 // a chance to complete...
2818 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002819
2820 if (PrivateStateThreadIsValid ())
2821 ResumePrivateStateThread ();
2822 else
2823 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002824 }
2825 else if (state == eStateExited)
2826 {
2827 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2828 // not likely to work, and return an invalid pid.
2829 HandlePrivateEvent (event_sp);
2830 }
2831 }
2832 }
2833 }
2834 else
2835 {
Greg Clayton9c236732011-10-26 00:56:27 +00002836 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002837 }
2838 }
2839 return error;
2840}
2841
Greg Clayton46c9a352012-02-09 06:16:32 +00002842
2843Error
2844Process::LoadCore ()
2845{
2846 Error error = DoLoadCore();
2847 if (error.Success())
2848 {
2849 if (PrivateStateThreadIsValid ())
2850 ResumePrivateStateThread ();
2851 else
2852 StartPrivateStateThread ();
2853
Greg Clayton9ce95382012-02-13 23:10:39 +00002854 DynamicLoader *dyld = GetDynamicLoader ();
2855 if (dyld)
2856 dyld->DidAttach();
2857
2858 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002859 // We successfully loaded a core file, now pretend we stopped so we can
2860 // show all of the threads in the core file and explore the crashed
2861 // state.
2862 SetPrivateState (eStateStopped);
2863
2864 }
2865 return error;
2866}
2867
Greg Clayton9ce95382012-02-13 23:10:39 +00002868DynamicLoader *
2869Process::GetDynamicLoader ()
2870{
2871 if (m_dyld_ap.get() == NULL)
2872 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2873 return m_dyld_ap.get();
2874}
Greg Clayton46c9a352012-02-09 06:16:32 +00002875
2876
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002877Process::NextEventAction::EventActionResult
2878Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002879{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002880 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2881 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002882 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002883 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002884 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002885 return eEventActionRetry;
2886
2887 case eStateStopped:
2888 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002889 {
2890 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002891 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002892 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2893 if (m_exec_count > 0)
2894 {
2895 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002896 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002897 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002898 return eEventActionRetry;
2899 }
2900 else
2901 {
2902 m_process->CompleteAttach ();
2903 return eEventActionSuccess;
2904 }
2905 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002906 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002907
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002908 default:
2909 case eStateExited:
2910 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002911 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002912 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002913
2914 m_exit_string.assign ("No valid Process");
2915 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002916}
Chris Lattner24943d22010-06-08 16:52:24 +00002917
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002918Process::NextEventAction::EventActionResult
2919Process::AttachCompletionHandler::HandleBeingInterrupted()
2920{
2921 return eEventActionSuccess;
2922}
2923
2924const char *
2925Process::AttachCompletionHandler::GetExitString ()
2926{
2927 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002928}
2929
2930Error
Greg Clayton527154d2011-11-15 03:53:30 +00002931Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002932{
Chris Lattner24943d22010-06-08 16:52:24 +00002933 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002934 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002935 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002936 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002937
Greg Clayton527154d2011-11-15 03:53:30 +00002938 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002939 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002940 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002941 {
Greg Clayton527154d2011-11-15 03:53:30 +00002942 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002943
Greg Clayton527154d2011-11-15 03:53:30 +00002944 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002945 {
Greg Clayton527154d2011-11-15 03:53:30 +00002946 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2947
2948 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002949 {
Greg Clayton527154d2011-11-15 03:53:30 +00002950 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2951 if (error.Success())
2952 {
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00002953 if (m_run_lock.WriteTryLock())
Greg Claytond34a3b22012-10-12 16:10:12 +00002954 {
2955 m_should_detach = true;
2956 SetPublicState (eStateAttaching);
2957 // Now attach using these arguments.
2958 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2959 }
2960 else
2961 {
2962 // This shouldn't happen
2963 error.SetErrorString("failed to acquire process run lock");
2964 }
Greg Claytonffa43a62011-11-17 04:46:02 +00002965
Greg Clayton527154d2011-11-15 03:53:30 +00002966 if (error.Fail())
2967 {
2968 if (GetID() != LLDB_INVALID_PROCESS_ID)
2969 {
2970 SetID (LLDB_INVALID_PROCESS_ID);
2971 if (error.AsCString() == NULL)
2972 error.SetErrorString("attach failed");
2973
2974 SetExitStatus(-1, error.AsCString());
2975 }
2976 }
2977 else
2978 {
2979 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2980 StartPrivateStateThread();
2981 }
2982 return error;
2983 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002984 }
Greg Clayton527154d2011-11-15 03:53:30 +00002985 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002986 {
Greg Clayton527154d2011-11-15 03:53:30 +00002987 ProcessInstanceInfoList process_infos;
2988 PlatformSP platform_sp (m_target.GetPlatform ());
2989
2990 if (platform_sp)
2991 {
2992 ProcessInstanceInfoMatch match_info;
2993 match_info.GetProcessInfo() = attach_info;
2994 match_info.SetNameMatchType (eNameMatchEquals);
2995 platform_sp->FindProcesses (match_info, process_infos);
2996 const uint32_t num_matches = process_infos.GetSize();
2997 if (num_matches == 1)
2998 {
2999 attach_pid = process_infos.GetProcessIDAtIndex(0);
3000 // Fall through and attach using the above process ID
3001 }
3002 else
3003 {
3004 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3005 if (num_matches > 1)
3006 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3007 else
3008 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3009 }
3010 }
3011 else
3012 {
3013 error.SetErrorString ("invalid platform, can't find processes by name");
3014 return error;
3015 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003016 }
Chris Lattner24943d22010-06-08 16:52:24 +00003017 }
3018 else
Greg Clayton527154d2011-11-15 03:53:30 +00003019 {
3020 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003021 }
3022 }
Greg Clayton527154d2011-11-15 03:53:30 +00003023
3024 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003025 {
Greg Clayton527154d2011-11-15 03:53:30 +00003026 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003027 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00003028 {
Greg Clayton527154d2011-11-15 03:53:30 +00003029
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00003030 if (m_run_lock.WriteTryLock())
Greg Claytond34a3b22012-10-12 16:10:12 +00003031 {
3032 // Now attach using these arguments.
3033 m_should_detach = true;
3034 SetPublicState (eStateAttaching);
3035 error = DoAttachToProcessWithID (attach_pid, attach_info);
3036 }
3037 else
3038 {
3039 // This shouldn't happen
3040 error.SetErrorString("failed to acquire process run lock");
3041 }
3042
Greg Clayton527154d2011-11-15 03:53:30 +00003043 if (error.Success())
3044 {
3045
3046 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3047 StartPrivateStateThread();
3048 }
3049 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003050 {
3051 if (GetID() != LLDB_INVALID_PROCESS_ID)
3052 {
3053 SetID (LLDB_INVALID_PROCESS_ID);
3054 const char *error_string = error.AsCString();
3055 if (error_string == NULL)
3056 error_string = "attach failed";
3057
3058 SetExitStatus(-1, error_string);
3059 }
3060 }
Chris Lattner24943d22010-06-08 16:52:24 +00003061 }
3062 }
3063 return error;
3064}
3065
Greg Clayton75c703d2011-02-16 04:46:07 +00003066void
3067Process::CompleteAttach ()
3068{
3069 // Let the process subclass figure out at much as it can about the process
3070 // before we go looking for a dynamic loader plug-in.
3071 DidAttach();
3072
Jim Ingham0d7f7772011-09-15 01:10:17 +00003073 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3074 // the same as the one we've already set, switch architectures.
3075 PlatformSP platform_sp (m_target.GetPlatform ());
3076 assert (platform_sp.get());
3077 if (platform_sp)
3078 {
Greg Claytonb170aee2012-05-08 01:45:38 +00003079 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Claytonaad2b0f2013-01-11 20:49:54 +00003080 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Claytonb170aee2012-05-08 01:45:38 +00003081 {
3082 ArchSpec platform_arch;
3083 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3084 if (platform_sp)
3085 {
3086 m_target.SetPlatform (platform_sp);
3087 m_target.SetArchitecture(platform_arch);
3088 }
3089 }
3090 else
3091 {
3092 ProcessInstanceInfo process_info;
3093 platform_sp->GetProcessInfo (GetID(), process_info);
3094 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callanan40e278c2012-12-13 22:07:14 +00003095 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Claytonb170aee2012-05-08 01:45:38 +00003096 m_target.SetArchitecture (process_arch);
3097 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00003098 }
3099
3100 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00003101 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00003102 DynamicLoader *dyld = GetDynamicLoader ();
3103 if (dyld)
3104 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00003105
Greg Clayton37f962e2011-08-22 02:49:39 +00003106 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00003107 // Figure out which one is the executable, and set that in our target:
Enrico Granata146d9522012-11-08 02:22:02 +00003108 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham93367902012-05-30 02:19:25 +00003109 Mutex::Locker modules_locker(target_modules.GetMutex());
3110 size_t num_modules = target_modules.GetSize();
3111 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003112
Greg Clayton75c703d2011-02-16 04:46:07 +00003113 for (int i = 0; i < num_modules; i++)
3114 {
Jim Ingham93367902012-05-30 02:19:25 +00003115 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00003116 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00003117 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00003118 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00003119 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003120 break;
3121 }
3122 }
Jim Ingham93367902012-05-30 02:19:25 +00003123 if (new_executable_module_sp)
3124 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00003125}
3126
Chris Lattner24943d22010-06-08 16:52:24 +00003127Error
Jason Molendafac2e622012-09-29 04:02:01 +00003128Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00003129{
Greg Claytone71e2582011-02-04 01:58:07 +00003130 m_abi_sp.reset();
3131 m_process_input_reader.reset();
3132
3133 // Find the process and its architecture. Make sure it matches the architecture
3134 // of the current Target, and if not adjust it.
3135
Jason Molendafac2e622012-09-29 04:02:01 +00003136 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00003137 if (error.Success())
3138 {
Greg Claytona2f74232011-02-24 22:24:29 +00003139 if (GetID() != LLDB_INVALID_PROCESS_ID)
3140 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00003141 EventSP event_sp;
3142 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3143
3144 if (state == eStateStopped || state == eStateCrashed)
3145 {
3146 // If we attached and actually have a process on the other end, then
3147 // this ended up being the equivalent of an attach.
3148 CompleteAttach ();
3149
3150 // This delays passing the stopped event to listeners till
3151 // CompleteAttach gets a chance to complete...
3152 HandlePrivateEvent (event_sp);
3153
3154 }
Greg Claytona2f74232011-02-24 22:24:29 +00003155 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00003156
3157 if (PrivateStateThreadIsValid ())
3158 ResumePrivateStateThread ();
3159 else
3160 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00003161 }
3162 return error;
3163}
3164
3165
3166Error
Jim Ingham027aaa72012-04-19 01:40:33 +00003167Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00003168{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003169 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00003170 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003171 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00003172 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00003173 StateAsCString(m_public_state.GetValue()),
3174 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00003175
3176 Error error (WillResume());
3177 // Tell the process it is about to resume before the thread list
3178 if (error.Success())
3179 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003180 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003181 // can let all of our threads know that they are about to be
3182 // resumed. Threads will each be called with
3183 // Thread::WillResume(StateType) where StateType contains the state
3184 // that they are supposed to have when the process is resumed
3185 // (suspended/running/stepping). Threads should also check
3186 // their resume signal in lldb::Thread::GetResumeSignal()
3187 // to see if they are suppoed to start back up with a signal.
3188 if (m_thread_list.WillResume())
3189 {
Jim Ingham1831e782012-04-07 00:00:41 +00003190 // Last thing, do the PreResumeActions.
3191 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003192 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003193 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham1831e782012-04-07 00:00:41 +00003194 }
3195 else
3196 {
3197 m_mod_id.BumpResumeID();
3198 error = DoResume();
3199 if (error.Success())
3200 {
3201 DidResume();
3202 m_thread_list.DidResume();
3203 if (log)
3204 log->Printf ("Process thinks the process has resumed.");
3205 }
Chris Lattner24943d22010-06-08 16:52:24 +00003206 }
3207 }
3208 else
3209 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003210 // Somebody wanted to run without running. So generate a continue & a stopped event,
3211 // and let the world handle them.
3212 if (log)
3213 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3214
3215 SetPrivateState(eStateRunning);
3216 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003217 }
3218 }
Jim Inghamac959662011-01-24 06:34:17 +00003219 else if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003220 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003221 return error;
3222}
3223
3224Error
3225Process::Halt ()
3226{
Jim Ingham43892562012-06-06 00:29:30 +00003227 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3228 // we could just straightaway get another event. It just narrows the window...
3229 m_currently_handling_event.WaitForValueEqualTo(false);
3230
3231
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003232 // Pause our private state thread so we can ensure no one else eats
3233 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003234 Listener halt_listener ("lldb.process.halt_listener");
3235 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003236
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003237 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003238 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003239
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003240 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003241 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003242
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003243 bool caused_stop = false;
3244
3245 // Ask the process subclass to actually halt our process
3246 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003247 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003248 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003249 if (m_public_state.GetValue() == eStateAttaching)
3250 {
3251 SetExitStatus(SIGKILL, "Cancelled async attach.");
3252 Destroy ();
3253 }
3254 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003255 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003256 // If "caused_stop" is true, then DoHalt stopped the process. If
3257 // "caused_stop" is false, the process was already stopped.
3258 // If the DoHalt caused the process to stop, then we want to catch
3259 // this event and set the interrupted bool to true before we pass
3260 // this along so clients know that the process was interrupted by
3261 // a halt command.
3262 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003263 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003264 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003265 TimeValue timeout_time;
3266 timeout_time = TimeValue::Now();
3267 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003268 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3269 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003270
Jim Inghamf9f40c22011-02-08 05:20:59 +00003271 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003272 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003273 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003274 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003275 }
3276 else
3277 {
Greg Clayton20206082011-11-17 01:23:07 +00003278 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003279 {
3280 // We caused the process to interrupt itself, so mark this
3281 // as such in the stop event so clients can tell an interrupted
3282 // process from a natural stop
3283 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3284 }
3285 else
3286 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00003287 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003288 if (log)
3289 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3290 error.SetErrorString ("Did not get stopped event after halt.");
3291 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003292 }
3293 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003294 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003295 }
3296 }
Chris Lattner24943d22010-06-08 16:52:24 +00003297 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003298 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003299 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003300
3301 // Post any event we might have consumed. If all goes well, we will have
3302 // stopped the process, intercepted the event and set the interrupted
3303 // bool in the event. Post it to the private event queue and that will end up
3304 // correctly setting the state.
3305 if (event_sp)
3306 m_private_state_broadcaster.BroadcastEvent(event_sp);
3307
Chris Lattner24943d22010-06-08 16:52:24 +00003308 return error;
3309}
3310
3311Error
Jim Inghame33bb5b2013-03-29 01:18:12 +00003312Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3313{
3314 Error error;
3315 if (m_public_state.GetValue() == eStateRunning)
3316 {
3317 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3318 if (log)
3319 log->Printf("Process::Destroy() About to halt.");
3320 error = Halt();
3321 if (error.Success())
3322 {
3323 // Consume the halt event.
3324 TimeValue timeout (TimeValue::Now());
3325 timeout.OffsetWithSeconds(1);
3326 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3327
3328 // If the process exited while we were waiting for it to stop, put the exited event into
3329 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3330 // they don't have a process anymore...
3331
3332 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3333 {
3334 if (log)
3335 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3336 return error;
3337 }
3338 else
3339 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3340
3341 if (state != eStateStopped)
3342 {
3343 if (log)
3344 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3345 // If we really couldn't stop the process then we should just error out here, but if the
3346 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3347 StateType private_state = m_private_state.GetValue();
3348 if (private_state != eStateStopped)
3349 {
3350 return error;
3351 }
3352 }
3353 }
3354 else
3355 {
3356 if (log)
3357 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3358 }
3359 }
3360 return error;
3361}
3362
3363Error
Chris Lattner24943d22010-06-08 16:52:24 +00003364Process::Detach ()
3365{
Jim Inghame33bb5b2013-03-29 01:18:12 +00003366 EventSP exit_event_sp;
3367 Error error;
3368 m_destroy_in_process = true;
3369
3370 error = WillDetach();
Chris Lattner24943d22010-06-08 16:52:24 +00003371
3372 if (error.Success())
3373 {
Jim Inghame33bb5b2013-03-29 01:18:12 +00003374 if (DetachRequiresHalt())
3375 {
3376 error = HaltForDestroyOrDetach (exit_event_sp);
3377 if (!error.Success())
3378 {
3379 m_destroy_in_process = false;
3380 return error;
3381 }
3382 else if (exit_event_sp)
3383 {
3384 // We shouldn't need to do anything else here. There's no process left to detach from...
3385 StopPrivateStateThread();
3386 m_destroy_in_process = false;
3387 return error;
3388 }
3389 }
3390
Chris Lattner24943d22010-06-08 16:52:24 +00003391 error = DoDetach();
3392 if (error.Success())
3393 {
3394 DidDetach();
3395 StopPrivateStateThread();
3396 }
3397 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003398 m_destroy_in_process = false;
3399
3400 // If we exited when we were waiting for a process to stop, then
3401 // forward the event here so we don't lose the event
3402 if (exit_event_sp)
3403 {
3404 // Directly broadcast our exited event because we shut down our
3405 // private state thread above
3406 BroadcastEvent(exit_event_sp);
3407 }
3408
3409 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3410 // the last events through the event system, in which case we might strand the write lock. Unlock
3411 // it here so when we do to tear down the process we don't get an error destroying the lock.
3412
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00003413 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003414 return error;
3415}
3416
3417Error
3418Process::Destroy ()
3419{
Jim Inghameb175302013-03-01 20:04:25 +00003420
3421 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3422 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3423 // failed and the process stays around for some reason it won't be in a confused state.
3424
3425 m_destroy_in_process = true;
3426
Chris Lattner24943d22010-06-08 16:52:24 +00003427 Error error (WillDestroy());
3428 if (error.Success())
3429 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003430 EventSP exit_event_sp;
Jim Inghame33bb5b2013-03-29 01:18:12 +00003431 if (DestroyRequiresHalt())
Jim Inghamf4928de2012-05-23 15:46:31 +00003432 {
Jim Inghame33bb5b2013-03-29 01:18:12 +00003433 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Inghamf4928de2012-05-23 15:46:31 +00003434 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003435
Jim Ingham43892562012-06-06 00:29:30 +00003436 if (m_public_state.GetValue() != eStateRunning)
3437 {
3438 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3439 // kill it, we don't want it hitting a breakpoint...
3440 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3441 // we're not going to have much luck doing this now.
3442 m_thread_list.DiscardThreadPlans();
3443 DisableAllBreakpointSites();
3444 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003445
Chris Lattner24943d22010-06-08 16:52:24 +00003446 error = DoDestroy();
3447 if (error.Success())
3448 {
3449 DidDestroy();
3450 StopPrivateStateThread();
3451 }
Caroline Tice861efb32010-11-16 05:07:41 +00003452 m_stdio_communication.StopReadThread();
3453 m_stdio_communication.Disconnect();
3454 if (m_process_input_reader && m_process_input_reader->IsActive())
3455 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3456 if (m_process_input_reader)
3457 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003458
3459 // If we exited when we were waiting for a process to stop, then
3460 // forward the event here so we don't lose the event
3461 if (exit_event_sp)
3462 {
3463 // Directly broadcast our exited event because we shut down our
3464 // private state thread above
3465 BroadcastEvent(exit_event_sp);
3466 }
3467
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003468 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3469 // the last events through the event system, in which case we might strand the write lock. Unlock
3470 // it here so when we do to tear down the process we don't get an error destroying the lock.
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00003471 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003472 }
Jim Inghameb175302013-03-01 20:04:25 +00003473
3474 m_destroy_in_process = false;
3475
Chris Lattner24943d22010-06-08 16:52:24 +00003476 return error;
3477}
3478
3479Error
3480Process::Signal (int signal)
3481{
3482 Error error (WillSignal());
3483 if (error.Success())
3484 {
3485 error = DoSignal(signal);
3486 if (error.Success())
3487 DidSignal();
3488 }
3489 return error;
3490}
3491
Greg Clayton395fc332011-02-15 21:59:32 +00003492lldb::ByteOrder
3493Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003494{
Greg Clayton395fc332011-02-15 21:59:32 +00003495 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003496}
3497
3498uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003499Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003500{
Greg Clayton395fc332011-02-15 21:59:32 +00003501 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003502}
3503
Greg Clayton395fc332011-02-15 21:59:32 +00003504
Chris Lattner24943d22010-06-08 16:52:24 +00003505bool
3506Process::ShouldBroadcastEvent (Event *event_ptr)
3507{
3508 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3509 bool return_value = true;
Greg Clayton952e9dc2013-03-27 23:08:40 +00003510 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham89e248f2013-02-09 01:29:05 +00003511
Chris Lattner24943d22010-06-08 16:52:24 +00003512 switch (state)
3513 {
Greg Claytone71e2582011-02-04 01:58:07 +00003514 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003515 case eStateAttaching:
3516 case eStateLaunching:
3517 case eStateDetached:
3518 case eStateExited:
3519 case eStateUnloaded:
3520 // These events indicate changes in the state of the debugging session, always report them.
3521 return_value = true;
3522 break;
3523 case eStateInvalid:
3524 // We stopped for no apparent reason, don't report it.
3525 return_value = false;
3526 break;
3527 case eStateRunning:
3528 case eStateStepping:
3529 // If we've started the target running, we handle the cases where we
3530 // are already running and where there is a transition from stopped to
3531 // running differently.
3532 // running -> running: Automatically suppress extra running events
3533 // stopped -> running: Report except when there is one or more no votes
3534 // and no yes votes.
3535 SynchronouslyNotifyStateChanged (state);
Jim Ingham89e248f2013-02-09 01:29:05 +00003536 switch (m_last_broadcast_state)
Chris Lattner24943d22010-06-08 16:52:24 +00003537 {
3538 case eStateRunning:
3539 case eStateStepping:
3540 // We always suppress multiple runnings with no PUBLIC stop in between.
3541 return_value = false;
3542 break;
3543 default:
3544 // TODO: make this work correctly. For now always report
3545 // run if we aren't running so we don't miss any runnning
3546 // events. If I run the lldb/test/thread/a.out file and
3547 // break at main.cpp:58, run and hit the breakpoints on
3548 // multiple threads, then somehow during the stepping over
3549 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003550
3551 // This is a transition from stop to run.
3552 switch (m_thread_list.ShouldReportRun (event_ptr))
3553 {
3554 case eVoteYes:
3555 case eVoteNoOpinion:
3556 return_value = true;
3557 break;
3558 case eVoteNo:
3559 return_value = false;
3560 break;
3561 }
3562 break;
3563 }
3564 break;
3565 case eStateStopped:
3566 case eStateCrashed:
3567 case eStateSuspended:
3568 {
3569 // We've stopped. First see if we're going to restart the target.
3570 // If we are going to stop, then we always broadcast the event.
3571 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00003572 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003573
3574 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003575 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003576 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003577 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003578 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3579 event_ptr,
3580 StateAsCString(state));
3581 return_value = true;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003582 }
3583 else
3584 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003585 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3586 // Asking the thread list is also not likely to go well, since we are running again.
3587 // So in that case just report the event.
3588
3589 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3590 bool should_resume = false;
3591 if (!was_restarted)
3592 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
3593 if (was_restarted || should_resume)
Chris Lattner24943d22010-06-08 16:52:24 +00003594 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003595 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3596 if (log)
3597 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3598 should_resume,
3599 StateAsCString(state),
3600 was_restarted,
3601 stop_vote);
3602
3603 switch (stop_vote)
Chris Lattner24943d22010-06-08 16:52:24 +00003604 {
3605 case eVoteYes:
Jim Ingham89e248f2013-02-09 01:29:05 +00003606 return_value = true;
3607 break;
Chris Lattner24943d22010-06-08 16:52:24 +00003608 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003609 case eVoteNo:
3610 return_value = false;
3611 break;
3612 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003613
Jim Ingham8290bba2012-09-05 21:13:56 +00003614 if (!was_restarted)
Jim Ingham89e248f2013-02-09 01:29:05 +00003615 {
3616 if (log)
3617 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3618 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Ingham8290bba2012-09-05 21:13:56 +00003619 PrivateResume ();
Jim Ingham89e248f2013-02-09 01:29:05 +00003620 }
3621
Chris Lattner24943d22010-06-08 16:52:24 +00003622 }
3623 else
3624 {
3625 return_value = true;
3626 SynchronouslyNotifyStateChanged (state);
3627 }
3628 }
3629 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003630 break;
Chris Lattner24943d22010-06-08 16:52:24 +00003631 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003632
3633 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3634 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3635 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3636 // because the PublicState reflects the last event pulled off the queue, and there may be several
3637 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3638 // yet. m_last_broadcast_state gets updated here.
3639
3640 if (return_value)
3641 m_last_broadcast_state = state;
3642
Chris Lattner24943d22010-06-08 16:52:24 +00003643 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003644 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3645 event_ptr,
3646 StateAsCString(state),
3647 StateAsCString(m_last_broadcast_state),
3648 return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003649 return return_value;
3650}
3651
Chris Lattner24943d22010-06-08 16:52:24 +00003652
3653bool
Jim Ingham1831e782012-04-07 00:00:41 +00003654Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003655{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003656 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003657
Greg Claytonb72d0f02011-04-12 05:54:46 +00003658 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003659 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003660 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3661
Jim Ingham1831e782012-04-07 00:00:41 +00003662 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003663 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003664
3665 // Create a thread that watches our internal state and controls which
3666 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003667 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003668 if (already_running)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003669 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham1831e782012-04-07 00:00:41 +00003670 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003671 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003672
3673 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003674 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003675 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3676 if (success)
3677 {
3678 ResumePrivateStateThread();
3679 return true;
3680 }
3681 else
3682 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003683}
3684
3685void
3686Process::PausePrivateStateThread ()
3687{
3688 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3689}
3690
3691void
3692Process::ResumePrivateStateThread ()
3693{
3694 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3695}
3696
3697void
3698Process::StopPrivateStateThread ()
3699{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003700 if (PrivateStateThreadIsValid ())
3701 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003702 else
3703 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00003704 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003705 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003706 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003707 }
Chris Lattner24943d22010-06-08 16:52:24 +00003708}
3709
3710void
3711Process::ControlPrivateStateThread (uint32_t signal)
3712{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003713 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003714
3715 assert (signal == eBroadcastInternalStateControlStop ||
3716 signal == eBroadcastInternalStateControlPause ||
3717 signal == eBroadcastInternalStateControlResume);
3718
3719 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003720 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003721
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003722 // Signal the private state thread. First we should copy this is case the
3723 // thread starts exiting since the private state thread will NULL this out
3724 // when it exits
3725 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003726 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003727 {
3728 TimeValue timeout_time;
3729 bool timed_out;
3730
3731 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3732
3733 timeout_time = TimeValue::Now();
3734 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003735 if (log)
3736 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003737 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3738 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3739
3740 if (signal == eBroadcastInternalStateControlStop)
3741 {
3742 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003743 {
3744 Error error;
3745 Host::ThreadCancel (private_state_thread, &error);
3746 if (log)
3747 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3748 }
3749 else
3750 {
3751 if (log)
3752 log->Printf ("The control event killed the private state thread without having to cancel.");
3753 }
Chris Lattner24943d22010-06-08 16:52:24 +00003754
3755 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003756 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003757 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003758 }
3759 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003760 else
3761 {
3762 if (log)
3763 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3764 }
Chris Lattner24943d22010-06-08 16:52:24 +00003765}
3766
3767void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003768Process::SendAsyncInterrupt ()
3769{
3770 if (PrivateStateThreadIsValid())
3771 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3772 else
3773 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3774}
3775
3776void
Chris Lattner24943d22010-06-08 16:52:24 +00003777Process::HandlePrivateEvent (EventSP &event_sp)
3778{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003779 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003780 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003781
Greg Clayton68ca8232011-01-25 02:58:48 +00003782 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003783
3784 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003785 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003786 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003787 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham89e248f2013-02-09 01:29:05 +00003788 if (log)
3789 log->Printf ("Ran next event action, result was %d.", action_result);
3790
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003791 switch (action_result)
3792 {
3793 case NextEventAction::eEventActionSuccess:
3794 SetNextEventAction(NULL);
3795 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003796
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003797 case NextEventAction::eEventActionRetry:
3798 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003799
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003800 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003801 // Handle Exiting Here. If we already got an exited event,
3802 // we should just propagate it. Otherwise, swallow this event,
3803 // and set our state to exit so the next event will kill us.
3804 if (new_state != eStateExited)
3805 {
3806 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003807 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003808 SetNextEventAction(NULL);
3809 return;
3810 }
3811 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003812 break;
3813 }
3814 }
3815
Chris Lattner24943d22010-06-08 16:52:24 +00003816 // See if we should broadcast this state to external clients?
3817 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003818
3819 if (should_broadcast)
3820 {
3821 if (log)
3822 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003823 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003824 __FUNCTION__,
3825 GetID(),
3826 StateAsCString(new_state),
3827 StateAsCString (GetState ()),
3828 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003829 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003830 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003831 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003832 PushProcessInputReader ();
3833 else
3834 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003835
Chris Lattner24943d22010-06-08 16:52:24 +00003836 BroadcastEvent (event_sp);
3837 }
3838 else
3839 {
3840 if (log)
3841 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003842 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003843 __FUNCTION__,
3844 GetID(),
3845 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003846 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003847 }
3848 }
Jim Ingham43892562012-06-06 00:29:30 +00003849 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003850}
3851
3852void *
3853Process::PrivateStateThread (void *arg)
3854{
3855 Process *proc = static_cast<Process*> (arg);
3856 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003857 return result;
3858}
3859
3860void *
3861Process::RunPrivateStateThread ()
3862{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003863 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003864 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003865
Greg Clayton952e9dc2013-03-27 23:08:40 +00003866 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003867 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003868 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003869
3870 bool exit_now = false;
3871 while (!exit_now)
3872 {
3873 EventSP event_sp;
3874 WaitForEventsPrivate (NULL, event_sp, control_only);
3875 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3876 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003877 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003878 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003879
Chris Lattner24943d22010-06-08 16:52:24 +00003880 switch (event_sp->GetType())
3881 {
3882 case eBroadcastInternalStateControlStop:
3883 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003884 break; // doing any internal state managment below
3885
3886 case eBroadcastInternalStateControlPause:
3887 control_only = true;
3888 break;
3889
3890 case eBroadcastInternalStateControlResume:
3891 control_only = false;
3892 break;
3893 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003894
Chris Lattner24943d22010-06-08 16:52:24 +00003895 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003896 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003897 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003898 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3899 {
3900 if (m_public_state.GetValue() == eStateAttaching)
3901 {
3902 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003903 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00003904 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3905 }
3906 else
3907 {
3908 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003909 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00003910 Halt();
3911 }
3912 continue;
3913 }
Chris Lattner24943d22010-06-08 16:52:24 +00003914
3915 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3916
3917 if (internal_state != eStateInvalid)
3918 {
3919 HandlePrivateEvent (event_sp);
3920 }
3921
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003922 if (internal_state == eStateInvalid ||
3923 internal_state == eStateExited ||
3924 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003925 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003926 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003927 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003928
Chris Lattner24943d22010-06-08 16:52:24 +00003929 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003930 }
Chris Lattner24943d22010-06-08 16:52:24 +00003931 }
3932
Caroline Tice926060e2010-10-29 21:48:37 +00003933 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003934 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003935 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003936
Greg Claytona4881d02011-01-22 07:12:45 +00003937 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3938 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003939 return NULL;
3940}
3941
Chris Lattner24943d22010-06-08 16:52:24 +00003942//------------------------------------------------------------------
3943// Process Event Data
3944//------------------------------------------------------------------
3945
3946Process::ProcessEventData::ProcessEventData () :
3947 EventData (),
3948 m_process_sp (),
3949 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003950 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003951 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003952 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003953{
3954}
3955
3956Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3957 EventData (),
3958 m_process_sp (process_sp),
3959 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003960 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003961 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003962 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003963{
3964}
3965
3966Process::ProcessEventData::~ProcessEventData()
3967{
3968}
3969
3970const ConstString &
3971Process::ProcessEventData::GetFlavorString ()
3972{
3973 static ConstString g_flavor ("Process::ProcessEventData");
3974 return g_flavor;
3975}
3976
3977const ConstString &
3978Process::ProcessEventData::GetFlavor () const
3979{
3980 return ProcessEventData::GetFlavorString ();
3981}
3982
Chris Lattner24943d22010-06-08 16:52:24 +00003983void
3984Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3985{
3986 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003987 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3988 // the public event queue, then other times when we're pretending that this is where we stopped at the
3989 // end of expression evaluation. m_update_state is used to distinguish these
3990 // three cases; it is 0 when we're just pulling it off for private handling,
3991 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003992
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003993 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003994 return;
Jim Ingham89e248f2013-02-09 01:29:05 +00003995
Chris Lattner24943d22010-06-08 16:52:24 +00003996 m_process_sp->SetPublicState (m_state);
3997
3998 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3999 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00004000 {
4001 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00004002 uint32_t num_threads = curr_thread_list.GetSize();
4003 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00004004
Jim Ingham21f37ad2011-08-09 02:12:22 +00004005 // The actions might change one of the thread's stop_info's opinions about whether we should
4006 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00004007
4008 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4009 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4010 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4011 // 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
4012 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00004013 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00004014 for (idx = 0; idx < num_threads; ++idx)
4015 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4016
Jim Inghamb6059b22012-12-13 22:24:15 +00004017 // Use this to track whether we should continue from here. We will only continue the target running if
4018 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4019 // then it doesn't matter what the other threads say...
4020
4021 bool still_should_stop = false;
Jim Ingham21f37ad2011-08-09 02:12:22 +00004022
Chris Lattner24943d22010-06-08 16:52:24 +00004023 for (idx = 0; idx < num_threads; ++idx)
4024 {
Jim Ingham0296fe72011-11-08 03:00:11 +00004025 curr_thread_list = m_process_sp->GetThreadList();
4026 if (curr_thread_list.GetSize() != num_threads)
4027 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004028 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00004029 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00004030 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0296fe72011-11-08 03:00:11 +00004031 break;
4032 }
4033
4034 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4035
4036 if (thread_sp->GetIndexID() != thread_index_array[idx])
4037 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004038 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00004039 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00004040 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00004041 idx,
4042 thread_index_array[idx],
4043 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00004044 break;
4045 }
4046
Jim Ingham6297a3a2010-10-20 00:39:53 +00004047 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00004048 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00004049 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004050 bool this_thread_wants_to_stop;
4051 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham21f37ad2011-08-09 02:12:22 +00004052 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004053 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4054 }
4055 else
4056 {
4057 stop_info_sp->PerformAction(event_ptr);
4058 // The stop action might restart the target. If it does, then we want to mark that in the
4059 // event so that whoever is receiving it will know to wait for the running event and reflect
4060 // that state appropriately.
4061 // We also need to stop processing actions, since they aren't expecting the target to be running.
4062
4063 // FIXME: we might have run.
4064 if (stop_info_sp->HasTargetRunSinceMe())
4065 {
4066 SetRestarted (true);
4067 break;
4068 }
4069
4070 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004071 }
Jim Inghamb6059b22012-12-13 22:24:15 +00004072
Jim Inghamb6059b22012-12-13 22:24:15 +00004073 if (still_should_stop == false)
4074 still_should_stop = this_thread_wants_to_stop;
Chris Lattner24943d22010-06-08 16:52:24 +00004075 }
4076 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00004077
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00004078
4079 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00004080 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00004081 if (!still_should_stop)
4082 {
4083 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00004084 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00004085 // Use the public resume method here, since this is just
4086 // extending a public resume.
Jim Ingham89e248f2013-02-09 01:29:05 +00004087 m_process_sp->PrivateResume();
Jim Ingham21f37ad2011-08-09 02:12:22 +00004088 }
4089 else
4090 {
4091 // If we didn't restart, run the Stop Hooks here:
4092 // They might also restart the target, so watch for that.
4093 m_process_sp->GetTarget().RunStopHooks();
4094 if (m_process_sp->GetPrivateState() == eStateRunning)
4095 SetRestarted(true);
4096 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00004097 }
Chris Lattner24943d22010-06-08 16:52:24 +00004098 }
4099}
4100
4101void
4102Process::ProcessEventData::Dump (Stream *s) const
4103{
4104 if (m_process_sp)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004105 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00004106
Greg Claytonb72d0f02011-04-12 05:54:46 +00004107 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00004108}
4109
4110const Process::ProcessEventData *
4111Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4112{
4113 if (event_ptr)
4114 {
4115 const EventData *event_data = event_ptr->GetData();
4116 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4117 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4118 }
4119 return NULL;
4120}
4121
4122ProcessSP
4123Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4124{
4125 ProcessSP process_sp;
4126 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4127 if (data)
4128 process_sp = data->GetProcessSP();
4129 return process_sp;
4130}
4131
4132StateType
4133Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4134{
4135 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4136 if (data == NULL)
4137 return eStateInvalid;
4138 else
4139 return data->GetState();
4140}
4141
4142bool
4143Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4144{
4145 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4146 if (data == NULL)
4147 return false;
4148 else
4149 return data->GetRestarted();
4150}
4151
4152void
4153Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4154{
4155 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4156 if (data != NULL)
4157 data->SetRestarted(new_value);
4158}
4159
Jim Ingham89e248f2013-02-09 01:29:05 +00004160size_t
4161Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4162{
4163 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4164 if (data != NULL)
4165 return data->GetNumRestartedReasons();
4166 else
4167 return 0;
4168}
4169
4170const char *
4171Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4172{
4173 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4174 if (data != NULL)
4175 return data->GetRestartedReasonAtIndex(idx);
4176 else
4177 return NULL;
4178}
4179
4180void
4181Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4182{
4183 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4184 if (data != NULL)
4185 data->AddRestartedReason(reason);
4186}
4187
Chris Lattner24943d22010-06-08 16:52:24 +00004188bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00004189Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4190{
4191 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4192 if (data == NULL)
4193 return false;
4194 else
4195 return data->GetInterrupted ();
4196}
4197
4198void
4199Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4200{
4201 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4202 if (data != NULL)
4203 data->SetInterrupted(new_value);
4204}
4205
4206bool
Chris Lattner24943d22010-06-08 16:52:24 +00004207Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4208{
4209 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4210 if (data)
4211 {
4212 data->SetUpdateStateOnRemoval();
4213 return true;
4214 }
4215 return false;
4216}
4217
Greg Clayton289afcb2012-02-18 05:35:26 +00004218lldb::TargetSP
4219Process::CalculateTarget ()
4220{
4221 return m_target.shared_from_this();
4222}
4223
Chris Lattner24943d22010-06-08 16:52:24 +00004224void
Greg Claytona830adb2010-10-04 01:05:56 +00004225Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00004226{
Greg Clayton567e7f32011-09-22 04:58:26 +00004227 exe_ctx.SetTargetPtr (&m_target);
4228 exe_ctx.SetProcessPtr (this);
4229 exe_ctx.SetThreadPtr(NULL);
4230 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00004231}
4232
Greg Claytone4b9c1f2011-03-08 22:40:15 +00004233//uint32_t
4234//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4235//{
4236// return 0;
4237//}
4238//
4239//ArchSpec
4240//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4241//{
4242// return Host::GetArchSpecForExistingProcess (pid);
4243//}
4244//
4245//ArchSpec
4246//Process::GetArchSpecForExistingProcess (const char *process_name)
4247//{
4248// return Host::GetArchSpecForExistingProcess (process_name);
4249//}
4250//
Caroline Tice861efb32010-11-16 05:07:41 +00004251void
4252Process::AppendSTDOUT (const char * s, size_t len)
4253{
Greg Clayton20d338f2010-11-18 05:57:03 +00004254 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00004255 m_stdout_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004256 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00004257}
4258
4259void
Greg Claytonbd06ff42011-11-13 04:45:22 +00004260Process::AppendSTDERR (const char * s, size_t len)
4261{
4262 Mutex::Locker locker (m_stdio_communication_mutex);
4263 m_stderr_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004264 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004265}
4266
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004267void
4268Process::BroadcastAsyncProfileData(const char *s, size_t len)
4269{
4270 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004271 m_profile_data.push_back(s);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004272 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4273}
4274
4275size_t
4276Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4277{
4278 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004279 if (m_profile_data.empty())
4280 return 0;
4281
4282 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004283 if (bytes_available > 0)
4284 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004285 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004286 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004287 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004288 if (bytes_available > buf_size)
4289 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004290 memcpy(buf, m_profile_data.front().data(), buf_size);
4291 m_profile_data.front().erase(0, buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004292 bytes_available = buf_size;
4293 }
4294 else
4295 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004296 memcpy(buf, m_profile_data.front().data(), bytes_available);
4297 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004298 }
4299 }
4300 return bytes_available;
4301}
4302
4303
Greg Claytonbd06ff42011-11-13 04:45:22 +00004304//------------------------------------------------------------------
4305// Process STDIO
4306//------------------------------------------------------------------
4307
4308size_t
4309Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4310{
4311 Mutex::Locker locker(m_stdio_communication_mutex);
4312 size_t bytes_available = m_stdout_data.size();
4313 if (bytes_available > 0)
4314 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004315 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004316 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004317 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004318 if (bytes_available > buf_size)
4319 {
4320 memcpy(buf, m_stdout_data.c_str(), buf_size);
4321 m_stdout_data.erase(0, buf_size);
4322 bytes_available = buf_size;
4323 }
4324 else
4325 {
4326 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4327 m_stdout_data.clear();
4328 }
4329 }
4330 return bytes_available;
4331}
4332
4333
4334size_t
4335Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4336{
4337 Mutex::Locker locker(m_stdio_communication_mutex);
4338 size_t bytes_available = m_stderr_data.size();
4339 if (bytes_available > 0)
4340 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004341 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004342 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004343 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004344 if (bytes_available > buf_size)
4345 {
4346 memcpy(buf, m_stderr_data.c_str(), buf_size);
4347 m_stderr_data.erase(0, buf_size);
4348 bytes_available = buf_size;
4349 }
4350 else
4351 {
4352 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4353 m_stderr_data.clear();
4354 }
4355 }
4356 return bytes_available;
4357}
4358
4359void
Caroline Tice861efb32010-11-16 05:07:41 +00004360Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4361{
4362 Process *process = (Process *) baton;
4363 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4364}
4365
4366size_t
4367Process::ProcessInputReaderCallback (void *baton,
4368 InputReader &reader,
4369 lldb::InputReaderAction notification,
4370 const char *bytes,
4371 size_t bytes_len)
4372{
4373 Process *process = (Process *) baton;
4374
4375 switch (notification)
4376 {
4377 case eInputReaderActivate:
4378 break;
4379
4380 case eInputReaderDeactivate:
4381 break;
4382
4383 case eInputReaderReactivate:
4384 break;
4385
Caroline Tice4a348082011-05-02 20:41:46 +00004386 case eInputReaderAsynchronousOutputWritten:
4387 break;
4388
Caroline Tice861efb32010-11-16 05:07:41 +00004389 case eInputReaderGotToken:
4390 {
4391 Error error;
4392 process->PutSTDIN (bytes, bytes_len, error);
4393 }
4394 break;
4395
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004396 case eInputReaderInterrupt:
4397 process->Halt ();
4398 break;
4399
4400 case eInputReaderEndOfFile:
4401 process->AppendSTDOUT ("^D", 2);
4402 break;
4403
Caroline Tice861efb32010-11-16 05:07:41 +00004404 case eInputReaderDone:
4405 break;
4406
4407 }
4408
4409 return bytes_len;
4410}
4411
4412void
4413Process::ResetProcessInputReader ()
4414{
4415 m_process_input_reader.reset();
4416}
4417
4418void
Greg Clayton464c6162011-11-17 22:14:31 +00004419Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004420{
4421 // First set up the Read Thread for reading/handling process I/O
4422
4423 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4424
4425 if (conn_ap.get())
4426 {
4427 m_stdio_communication.SetConnection (conn_ap.release());
4428 if (m_stdio_communication.IsConnected())
4429 {
4430 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4431 m_stdio_communication.StartReadThread();
4432
4433 // Now read thread is set up, set up input reader.
4434
4435 if (!m_process_input_reader.get())
4436 {
4437 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4438 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4439 this,
4440 eInputReaderGranularityByte,
4441 NULL,
4442 NULL,
4443 false));
4444
4445 if (err.Fail())
4446 m_process_input_reader.reset();
4447 }
4448 }
4449 }
4450}
4451
4452void
4453Process::PushProcessInputReader ()
4454{
4455 if (m_process_input_reader && !m_process_input_reader->IsActive())
4456 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4457}
4458
4459void
4460Process::PopProcessInputReader ()
4461{
4462 if (m_process_input_reader && m_process_input_reader->IsActive())
4463 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4464}
4465
Greg Claytond284b662011-02-18 01:44:25 +00004466// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004467void
Caroline Tice2a456812011-03-10 22:14:10 +00004468Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004469{
Greg Clayton73844aa2012-08-22 17:17:09 +00004470// static std::vector<OptionEnumValueElement> g_plugins;
4471//
4472// int i=0;
4473// const char *name;
4474// OptionEnumValueElement option_enum;
4475// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4476// {
4477// if (name)
4478// {
4479// option_enum.value = i;
4480// option_enum.string_value = name;
4481// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4482// g_plugins.push_back (option_enum);
4483// }
4484// ++i;
4485// }
4486// option_enum.value = 0;
4487// option_enum.string_value = NULL;
4488// option_enum.usage = NULL;
4489// g_plugins.push_back (option_enum);
4490//
4491// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4492// {
4493// if (::strcmp (name, "plugin") == 0)
4494// {
4495// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4496// break;
4497// }
4498// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004499//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004500 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004501}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004502
Greg Clayton990de7b2010-11-18 23:32:35 +00004503void
Caroline Tice2a456812011-03-10 22:14:10 +00004504Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004505{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004506 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004507}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004508
Greg Clayton427f2902010-12-14 02:59:59 +00004509ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004510Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004511 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004512 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004513 bool run_others,
Jim Inghamb7940202013-01-15 02:47:48 +00004514 bool unwind_on_error,
4515 bool ignore_breakpoints,
Jim Ingham47beabb2012-10-16 21:41:58 +00004516 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004517 Stream &errors)
4518{
4519 ExecutionResults return_value = eExecutionSetupError;
4520
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004521 if (thread_plan_sp.get() == NULL)
4522 {
4523 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004524 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004525 }
Jim Ingham698194c2013-03-28 00:05:34 +00004526
4527 if (!thread_plan_sp->ValidatePlan(NULL))
4528 {
4529 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4530 return eExecutionSetupError;
4531 }
4532
Greg Clayton567e7f32011-09-22 04:58:26 +00004533 if (exe_ctx.GetProcessPtr() != this)
4534 {
4535 errors.Printf("RunThreadPlan called on wrong process.");
4536 return eExecutionSetupError;
4537 }
4538
4539 Thread *thread = exe_ctx.GetThreadPtr();
4540 if (thread == NULL)
4541 {
4542 errors.Printf("RunThreadPlan called with invalid thread.");
4543 return eExecutionSetupError;
4544 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004545
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004546 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4547 // For that to be true the plan can't be private - since private plans suppress themselves in the
4548 // GetCompletedPlan call.
4549
4550 bool orig_plan_private = thread_plan_sp->GetPrivate();
4551 thread_plan_sp->SetPrivate(false);
4552
Jim Inghamac959662011-01-24 06:34:17 +00004553 if (m_private_state.GetValue() != eStateStopped)
4554 {
4555 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004556 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004557 }
4558
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004559 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004560 const uint32_t thread_idx_id = thread->GetIndexID();
Jim Ingham9da225f2013-02-19 23:22:45 +00004561 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4562 if (!selected_frame_sp)
4563 {
4564 thread->SetSelectedFrame(0);
4565 selected_frame_sp = thread->GetSelectedFrame();
4566 if (!selected_frame_sp)
4567 {
4568 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4569 return eExecutionSetupError;
4570 }
4571 }
4572
4573 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004574
4575 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4576 // so we should arrange to reset them as well.
4577
Greg Clayton567e7f32011-09-22 04:58:26 +00004578 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004579
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004580 uint32_t selected_tid;
4581 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004582 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004583 {
4584 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004585 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004586 }
4587 else
4588 {
4589 selected_tid = LLDB_INVALID_THREAD_ID;
4590 }
4591
Jim Ingham1831e782012-04-07 00:00:41 +00004592 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004593 lldb::StateType old_state;
4594 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004595
Greg Clayton952e9dc2013-03-27 23:08:40 +00004596 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004597 if (Host::GetCurrentThread() == m_private_state_thread)
4598 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004599 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4600 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004601 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Inghamd21d98b2012-04-10 01:21:57 +00004602 // we are fielding public events here.
4603 if (log)
Jason Molenda559cf6e2012-11-17 01:41:04 +00004604 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
Jim Inghamd21d98b2012-04-10 01:21:57 +00004605
4606
Jim Ingham1831e782012-04-07 00:00:41 +00004607 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004608
4609 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4610 // returning control here.
4611 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4612 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4613 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4614 // do just what we want.
4615 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4616 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4617 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4618 old_state = m_public_state.GetValue();
4619 m_public_state.SetValueNoLock(eStateStopped);
4620
4621 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004622 StartPrivateStateThread(true);
4623 }
4624
4625 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004626
Jim Ingham6ae318c2011-01-23 21:14:08 +00004627 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004628
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004629 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004630
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004631 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004632 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4633 // restored on exit to the function.
4634 //
4635 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4636 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004637
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004638 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004639
Jim Ingham360f53f2010-11-30 02:22:11 +00004640 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004641 {
4642 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004643 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004644 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004645 thread->GetIndexID(),
4646 thread->GetID(),
4647 s.GetData());
4648 }
4649
4650 bool got_event;
4651 lldb::EventSP event_sp;
4652 lldb::StateType stop_state = lldb::eStateInvalid;
4653
4654 TimeValue* timeout_ptr = NULL;
4655 TimeValue real_timeout;
4656
Jim Ingham89e248f2013-02-09 01:29:05 +00004657 bool before_first_timeout = true; // This is set to false the first time that we have to halt the target.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004658 bool do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004659 bool handle_running_event = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004660 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004661
Jim Ingham89e248f2013-02-09 01:29:05 +00004662 // This is just for accounting:
4663 uint32_t num_resumes = 0;
4664
4665 TimeValue one_thread_timeout = TimeValue::Now();
4666 TimeValue final_timeout = one_thread_timeout;
4667
4668 if (run_others)
4669 {
4670 // If we are running all threads then we take half the time to run all threads, bounded by
4671 // .25 sec.
4672 if (timeout_usec == 0)
4673 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4674 else
4675 {
4676 uint64_t computed_timeout = computed_timeout = timeout_usec / 2;
4677 if (computed_timeout > default_one_thread_timeout_usec)
4678 computed_timeout = default_one_thread_timeout_usec;
4679 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4680 }
4681 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4682 }
4683 else
4684 {
4685 if (timeout_usec != 0)
4686 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4687 }
4688
Jim Ingham76b258d2012-11-26 23:52:18 +00004689 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4690 // So don't call return anywhere within it.
4691
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004692 while (1)
4693 {
4694 // We usually want to resume the process if we get to the top of the loop.
4695 // The only exception is if we get two running events with no intervening
4696 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham89e248f2013-02-09 01:29:05 +00004697 if (log)
4698 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4699 do_resume,
4700 handle_running_event,
4701 before_first_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004702
Jim Inghamb7940202013-01-15 02:47:48 +00004703 if (do_resume || handle_running_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004704 {
4705 // Do the initial resume and wait for the running event before going further.
4706
Jim Inghamb7940202013-01-15 02:47:48 +00004707 if (do_resume)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004708 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004709 num_resumes++;
Jim Inghamb7940202013-01-15 02:47:48 +00004710 Error resume_error = PrivateResume ();
4711 if (!resume_error.Success())
4712 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004713 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4714 num_resumes,
4715 resume_error.AsCString());
Jim Inghamb7940202013-01-15 02:47:48 +00004716 return_value = eExecutionSetupError;
4717 break;
4718 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004719 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004720
Jim Ingham89e248f2013-02-09 01:29:05 +00004721 TimeValue resume_timeout = TimeValue::Now();
4722 resume_timeout.OffsetWithMicroSeconds(500000);
4723
4724 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004725 if (!got_event)
4726 {
4727 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004728 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4729 num_resumes);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004730
Jim Ingham89e248f2013-02-09 01:29:05 +00004731 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004732 return_value = eExecutionSetupError;
4733 break;
4734 }
4735
4736 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham89e248f2013-02-09 01:29:05 +00004737
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004738 if (stop_state != eStateRunning)
4739 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004740 bool restarted = false;
4741
4742 if (stop_state == eStateStopped)
4743 {
4744 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4745 if (log)
4746 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4747 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4748 num_resumes,
4749 StateAsCString(stop_state),
4750 restarted,
4751 do_resume,
4752 handle_running_event);
4753 }
4754
4755 if (restarted)
4756 {
4757 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4758 // event here. But if I do, the best thing is to Halt and then get out of here.
4759 Halt();
4760 }
4761
Jim Ingham47beabb2012-10-16 21:41:58 +00004762 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4763 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004764 return_value = eExecutionSetupError;
4765 break;
4766 }
4767
4768 if (log)
4769 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4770 // We need to call the function synchronously, so spin waiting for it to return.
4771 // If we get interrupted while executing, we're going to lose our context, and
4772 // won't be able to gather the result at this point.
4773 // We set the timeout AFTER the resume, since the resume takes some time and we
4774 // don't want to charge that to the timeout.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004775 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004776 else
4777 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004778 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004779 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004780 }
Jim Ingham89e248f2013-02-09 01:29:05 +00004781
4782 if (before_first_timeout)
4783 {
4784 if (run_others)
4785 timeout_ptr = &one_thread_timeout;
4786 else
4787 {
4788 if (timeout_usec == 0)
4789 timeout_ptr = NULL;
4790 else
4791 timeout_ptr = &final_timeout;
4792 }
4793 }
4794 else
4795 {
4796 if (timeout_usec == 0)
4797 timeout_ptr = NULL;
4798 else
4799 timeout_ptr = &final_timeout;
4800 }
4801
4802 do_resume = true;
4803 handle_running_event = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004804
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004805 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004806 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004807
Jim Inghamf9f40c22011-02-08 05:20:59 +00004808 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004809 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004810 if (timeout_ptr)
4811 {
Matt Kopecfe21d4f2013-02-21 23:55:31 +00004812 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham89e248f2013-02-09 01:29:05 +00004813 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
4814 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004815 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004816 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004817 {
4818 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4819 }
4820 }
4821
4822 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4823
4824 if (got_event)
4825 {
4826 if (event_sp.get())
4827 {
4828 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004829 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004830 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004831 Halt();
Jim Ingham5d90ade2012-07-27 23:57:19 +00004832 return_value = eExecutionInterrupted;
4833 errors.Printf ("Execution halted by user interrupt.");
4834 if (log)
4835 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham89e248f2013-02-09 01:29:05 +00004836 break;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004837 }
4838 else
4839 {
4840 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4841 if (log)
4842 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4843
4844 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004845 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004846 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004847 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004848 // We stopped, figure out what we are going to do now.
Jim Ingham5d90ade2012-07-27 23:57:19 +00004849 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4850 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004851 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004852 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004853 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004854 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4855 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004856 }
4857 else
4858 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004859 // If we were restarted, we just need to go back up to fetch another event.
4860 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Ingham5d90ade2012-07-27 23:57:19 +00004861 {
4862 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004863 {
4864 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
4865 }
4866 keep_going = true;
4867 do_resume = false;
4868 handle_running_event = true;
4869
Jim Ingham5d90ade2012-07-27 23:57:19 +00004870 }
4871 else
4872 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004873
4874 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4875 StopReason stop_reason = eStopReasonInvalid;
4876 if (stop_info_sp)
4877 stop_reason = stop_info_sp->GetStopReason();
4878
4879
4880 // FIXME: We only check if the stop reason is plan complete, should we make sure that
4881 // it is OUR plan that is complete?
4882 if (stop_reason == eStopReasonPlanComplete)
Jim Inghamb7940202013-01-15 02:47:48 +00004883 {
4884 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004885 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4886 // Now mark this plan as private so it doesn't get reported as the stop reason
4887 // after this point.
4888 if (thread_plan_sp)
4889 thread_plan_sp->SetPrivate (orig_plan_private);
4890 return_value = eExecutionCompleted;
Jim Inghamb7940202013-01-15 02:47:48 +00004891 }
4892 else
4893 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004894 // Something restarted the target, so just wait for it to stop for real.
Jim Inghamb7940202013-01-15 02:47:48 +00004895 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham89e248f2013-02-09 01:29:05 +00004896 {
4897 if (log)
4898 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Inghamb7940202013-01-15 02:47:48 +00004899 return_value = eExecutionHitBreakpoint;
Jim Ingham89e248f2013-02-09 01:29:05 +00004900 }
Jim Inghamb7940202013-01-15 02:47:48 +00004901 else
Jim Ingham89e248f2013-02-09 01:29:05 +00004902 {
4903 if (log)
4904 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Inghamb7940202013-01-15 02:47:48 +00004905 return_value = eExecutionInterrupted;
Jim Ingham89e248f2013-02-09 01:29:05 +00004906 }
Jim Inghamb7940202013-01-15 02:47:48 +00004907 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004908 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004909 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004910 }
4911 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004912
Jim Ingham5d90ade2012-07-27 23:57:19 +00004913 case lldb::eStateRunning:
Jim Ingham89e248f2013-02-09 01:29:05 +00004914 // This shouldn't really happen, but sometimes we do get two running events without an
4915 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Ingham5d90ade2012-07-27 23:57:19 +00004916 do_resume = false;
4917 keep_going = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004918 handle_running_event = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004919 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004920
Jim Ingham5d90ade2012-07-27 23:57:19 +00004921 default:
4922 if (log)
4923 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4924
4925 if (stop_state == eStateExited)
4926 event_to_broadcast_sp = event_sp;
4927
Sean Callanan96abc622012-08-08 17:35:10 +00004928 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00004929 return_value = eExecutionInterrupted;
4930 break;
4931 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004932 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004933
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004934 if (keep_going)
4935 continue;
4936 else
4937 break;
4938 }
4939 else
4940 {
4941 if (log)
4942 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4943 return_value = eExecutionInterrupted;
4944 break;
4945 }
4946 }
4947 else
4948 {
4949 // If we didn't get an event that means we've timed out...
4950 // We will interrupt the process here. Depending on what we were asked to do we will
4951 // either exit, or try with all threads running for the same timeout.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004952
4953 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00004954 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004955 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004956 uint64_t remaining_time = final_timeout - TimeValue::Now();
4957 if (before_first_timeout)
4958 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
4959 "running till for %" PRId64 " usec with all threads enabled.",
4960 remaining_time);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004961 else
4962 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00004963 "and timeout: %d timed out, abandoning execution.",
4964 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004965 }
4966 else
4967 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004968 "abandoning execution.",
4969 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004970 }
4971
Jim Ingham89e248f2013-02-09 01:29:05 +00004972 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
4973 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
4974 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
4975 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
4976 // stopped event. That's what this while loop does.
4977
4978 bool back_to_top = true;
4979 uint32_t try_halt_again = 0;
4980 bool do_halt = true;
4981 const uint32_t num_retries = 5;
4982 while (try_halt_again < num_retries)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004983 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004984 Error halt_error;
4985 if (do_halt)
4986 {
4987 if (log)
4988 log->Printf ("Process::RunThreadPlan(): Running Halt.");
4989 halt_error = Halt();
4990 }
4991 if (halt_error.Success())
4992 {
4993 if (log)
4994 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4995
4996 real_timeout = TimeValue::Now();
4997 real_timeout.OffsetWithMicroSeconds(500000);
4998
4999 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005000
Jim Ingham89e248f2013-02-09 01:29:05 +00005001 if (got_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005002 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005003 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5004 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005005 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005006 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5007 if (stop_state == lldb::eStateStopped
5008 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5009 log->PutCString (" Event was the Halt interruption event.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005010 }
5011
Jim Ingham89e248f2013-02-09 01:29:05 +00005012 if (stop_state == lldb::eStateStopped)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005013 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005014 // Between the time we initiated the Halt and the time we delivered it, the process could have
5015 // already finished its job. Check that here:
5016
5017 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5018 {
5019 if (log)
5020 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5021 "Exiting wait loop.");
5022 return_value = eExecutionCompleted;
5023 back_to_top = false;
5024 break;
5025 }
5026
5027 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5028 {
5029 if (log)
5030 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5031 "Exiting wait loop.");
5032 try_halt_again++;
5033 do_halt = false;
5034 continue;
5035 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005036
Jim Ingham89e248f2013-02-09 01:29:05 +00005037 if (!run_others)
5038 {
5039 if (log)
5040 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5041 return_value = eExecutionInterrupted;
5042 back_to_top = false;
5043 break;
5044 }
5045
5046 if (before_first_timeout)
5047 {
5048 // Set all the other threads to run, and return to the top of the loop, which will continue;
5049 before_first_timeout = false;
5050 thread_plan_sp->SetStopOthers (false);
5051 if (log)
5052 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005053
Jim Ingham89e248f2013-02-09 01:29:05 +00005054 back_to_top = true;
5055 break;
5056 }
5057 else
5058 {
5059 // Running all threads failed, so return Interrupted.
5060 if (log)
5061 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5062 return_value = eExecutionInterrupted;
5063 back_to_top = false;
5064 break;
5065 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005066 }
5067 }
5068 else
Jim Ingham89e248f2013-02-09 01:29:05 +00005069 { if (log)
5070 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5071 "I'm getting out of here passing Interrupted.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005072 return_value = eExecutionInterrupted;
Jim Ingham89e248f2013-02-09 01:29:05 +00005073 back_to_top = false;
5074 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005075 }
5076 }
Jim Ingham89e248f2013-02-09 01:29:05 +00005077 else
5078 {
5079 try_halt_again++;
5080 continue;
5081 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005082 }
Jim Ingham89e248f2013-02-09 01:29:05 +00005083
5084 if (!back_to_top || try_halt_again > num_retries)
5085 break;
5086 else
5087 continue;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005088 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005089 } // END WAIT LOOP
5090
5091 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5092 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5093 {
5094 StopPrivateStateThread();
5095 Error error;
5096 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00005097 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005098 {
5099 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5100 }
5101 m_public_state.SetValueNoLock(old_state);
5102
5103 }
5104
Jim Inghamb7940202013-01-15 02:47:48 +00005105 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5106 // could happen:
5107 // 1) The execution successfully completed
5108 // 2) We hit a breakpoint, and ignore_breakpoints was true
5109 // 3) We got some other error, and discard_on_error was true
5110 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
5111 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham76b258d2012-11-26 23:52:18 +00005112
Jim Inghamb7940202013-01-15 02:47:48 +00005113 if (return_value == eExecutionCompleted
5114 || should_unwind)
Jim Ingham76b258d2012-11-26 23:52:18 +00005115 {
5116 thread_plan_sp->RestoreThreadState();
5117 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005118
5119 // Now do some processing on the results of the run:
Jim Inghamb7940202013-01-15 02:47:48 +00005120 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005121 {
5122 if (log)
5123 {
5124 StreamString s;
5125 if (event_sp)
5126 event_sp->Dump (&s);
5127 else
5128 {
5129 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5130 }
5131
5132 StreamString ts;
5133
5134 const char *event_explanation = NULL;
5135
5136 do
5137 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005138 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005139 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005140 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005141 break;
5142 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005143 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005144 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005145 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005146 break;
5147 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005148 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005149 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005150 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5151
5152 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005153 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005154 event_explanation = "<no event data>";
5155 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005156 }
5157
Jim Ingham5d90ade2012-07-27 23:57:19 +00005158 Process *process = event_data->GetProcessSP().get();
5159
5160 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005161 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005162 event_explanation = "<no process>";
5163 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005164 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005165
5166 ThreadList &thread_list = process->GetThreadList();
5167
5168 uint32_t num_threads = thread_list.GetSize();
5169 uint32_t thread_index;
5170
5171 ts.Printf("<%u threads> ", num_threads);
5172
5173 for (thread_index = 0;
5174 thread_index < num_threads;
5175 ++thread_index)
5176 {
5177 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5178
5179 if (!thread)
5180 {
5181 ts.Printf("<?> ");
5182 continue;
5183 }
5184
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005185 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00005186 RegisterContext *register_context = thread->GetRegisterContext().get();
5187
5188 if (register_context)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005189 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Ingham5d90ade2012-07-27 23:57:19 +00005190 else
5191 ts.Printf("[ip unknown] ");
5192
5193 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5194 if (stop_info_sp)
5195 {
5196 const char *stop_desc = stop_info_sp->GetDescription();
5197 if (stop_desc)
5198 ts.PutCString (stop_desc);
5199 }
5200 ts.Printf(">");
5201 }
5202
5203 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005204 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005205 } while (0);
5206
Jim Ingham5d90ade2012-07-27 23:57:19 +00005207 if (event_explanation)
5208 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005209 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00005210 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5211 }
5212
Jim Inghamb7940202013-01-15 02:47:48 +00005213 if (should_unwind && thread_plan_sp)
Jim Ingham5d90ade2012-07-27 23:57:19 +00005214 {
5215 if (log)
5216 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5217 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5218 thread_plan_sp->SetPrivate (orig_plan_private);
5219 }
5220 else
5221 {
5222 if (log)
5223 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005224 }
5225 }
5226 else if (return_value == eExecutionSetupError)
5227 {
5228 if (log)
5229 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00005230
Jim Inghamb7940202013-01-15 02:47:48 +00005231 if (unwind_on_error && thread_plan_sp)
Jim Inghamf9f40c22011-02-08 05:20:59 +00005232 {
Greg Clayton567e7f32011-09-22 04:58:26 +00005233 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00005234 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00005235 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005236 }
5237 else
5238 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005239 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00005240 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00005241 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005242 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5243 return_value = eExecutionCompleted;
5244 }
5245 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5246 {
5247 if (log)
5248 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5249 return_value = eExecutionDiscarded;
5250 }
5251 else
5252 {
5253 if (log)
5254 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamb7940202013-01-15 02:47:48 +00005255 if (unwind_on_error && thread_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005256 {
5257 if (log)
Jim Inghamb7940202013-01-15 02:47:48 +00005258 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005259 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5260 thread_plan_sp->SetPrivate (orig_plan_private);
5261 }
5262 }
5263 }
5264
5265 // Thread we ran the function in may have gone away because we ran the target
5266 // Check that it's still there, and if it is put it back in the context. Also restore the
5267 // frame in the context if it is still present.
5268 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5269 if (thread)
5270 {
5271 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5272 }
5273
5274 // Also restore the current process'es selected frame & thread, since this function calling may
5275 // be done behind the user's back.
5276
5277 if (selected_tid != LLDB_INVALID_THREAD_ID)
5278 {
5279 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5280 {
5281 // We were able to restore the selected thread, now restore the frame:
5282 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5283 if (old_frame_sp)
5284 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00005285 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005286 }
5287 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005288
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005289 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00005290
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005291 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00005292 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005293 if (log)
5294 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5295 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00005296 }
5297
5298 return return_value;
5299}
5300
5301const char *
5302Process::ExecutionResultAsCString (ExecutionResults result)
5303{
5304 const char *result_name;
5305
5306 switch (result)
5307 {
Greg Claytonb3448432011-03-24 21:19:54 +00005308 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005309 result_name = "eExecutionCompleted";
5310 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005311 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00005312 result_name = "eExecutionDiscarded";
5313 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005314 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005315 result_name = "eExecutionInterrupted";
5316 break;
Jim Inghamb7940202013-01-15 02:47:48 +00005317 case eExecutionHitBreakpoint:
5318 result_name = "eExecutionHitBreakpoint";
5319 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005320 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00005321 result_name = "eExecutionSetupError";
5322 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005323 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00005324 result_name = "eExecutionTimedOut";
5325 break;
5326 }
5327 return result_name;
5328}
5329
Greg Claytonabe0fed2011-04-18 08:33:37 +00005330void
5331Process::GetStatus (Stream &strm)
5332{
5333 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00005334 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00005335 {
5336 if (state == eStateExited)
5337 {
5338 int exit_status = GetExitStatus();
5339 const char *exit_description = GetExitDescription();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005340 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00005341 GetID(),
5342 exit_status,
5343 exit_status,
5344 exit_description ? exit_description : "");
5345 }
5346 else
5347 {
5348 if (state == eStateConnected)
5349 strm.Printf ("Connected to remote target.\n");
5350 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005351 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00005352 }
5353 }
5354 else
5355 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005356 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005357 }
5358}
5359
5360size_t
5361Process::GetThreadStatus (Stream &strm,
5362 bool only_threads_with_stop_reason,
5363 uint32_t start_frame,
5364 uint32_t num_frames,
5365 uint32_t num_frames_with_source)
5366{
5367 size_t num_thread_infos_dumped = 0;
5368
Jim Inghamb9950592012-09-10 20:50:15 +00005369 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005370 const size_t num_threads = GetThreadList().GetSize();
5371 for (uint32_t i = 0; i < num_threads; i++)
5372 {
5373 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5374 if (thread)
5375 {
5376 if (only_threads_with_stop_reason)
5377 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00005378 StopInfoSP stop_info_sp = thread->GetStopInfo();
5379 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00005380 continue;
5381 }
5382 thread->GetStatus (strm,
5383 start_frame,
5384 num_frames,
5385 num_frames_with_source);
5386 ++num_thread_infos_dumped;
5387 }
5388 }
5389 return num_thread_infos_dumped;
5390}
5391
Greg Clayton76113302012-02-22 04:37:26 +00005392void
5393Process::AddInvalidMemoryRegion (const LoadRange &region)
5394{
5395 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5396}
5397
5398bool
5399Process::RemoveInvalidMemoryRange (const LoadRange &region)
5400{
5401 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5402}
5403
Jim Ingham1831e782012-04-07 00:00:41 +00005404void
5405Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5406{
5407 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5408}
5409
5410bool
5411Process::RunPreResumeActions ()
5412{
5413 bool result = true;
5414 while (!m_pre_resume_actions.empty())
5415 {
5416 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5417 m_pre_resume_actions.pop_back();
5418 bool this_result = action.callback (action.baton);
5419 if (result == true) result = this_result;
5420 }
5421 return result;
5422}
5423
5424void
5425Process::ClearPreResumeActions ()
5426{
5427 m_pre_resume_actions.clear();
5428}
Greg Clayton76113302012-02-22 04:37:26 +00005429
Greg Claytoncf5927e2012-05-18 02:38:05 +00005430void
5431Process::Flush ()
5432{
5433 m_thread_list.Flush();
5434}
Greg Clayton0bce9a22012-12-05 00:16:59 +00005435
5436void
5437Process::DidExec ()
5438{
5439 Target &target = GetTarget();
5440 target.CleanupProcess ();
5441 ModuleList unloaded_modules (target.GetImages());
5442 target.ModulesDidUnload (unloaded_modules);
5443 target.GetSectionLoadList().Clear();
5444 m_dynamic_checkers_ap.reset();
5445 m_abi_sp.reset();
5446 m_os_ap.reset();
5447 m_dyld_ap.reset();
5448 m_image_tokens.clear();
5449 m_allocated_memory_cache.Clear();
5450 m_language_runtimes.clear();
5451 DoDidExec();
5452 CompleteAttach ();
5453}