blob: 99f473331d0ee9ae4f8a6c5f00218cfc6c0e18f0 [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();
518 std::string new_path("PATH=");
519 const size_t empty_path_len = new_path.size();
520
521 if (working_dir && working_dir[0])
522 {
523 new_path += working_dir;
524 }
525 else
526 {
527 char current_working_dir[PATH_MAX];
528 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
529 if (cwd && cwd[0])
530 new_path += cwd;
531 }
532 const char *curr_path = getenv("PATH");
533 if (curr_path)
534 {
535 if (new_path.size() > empty_path_len)
536 new_path += ':';
537 new_path += curr_path;
538 }
539 new_path += ' ';
540 shell_command.PutCString(new_path.c_str());
541 }
542
Greg Clayton97471182012-04-14 01:42:46 +0000543 shell_command.PutCString ("exec");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000544
545#if defined(__APPLE__)
546 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Clayton97471182012-04-14 01:42:46 +0000547 if (GetArchitecture().IsValid())
548 {
549 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton0c8446c2012-10-17 22:57:12 +0000550 // Set the resume count to 2:
Greg Clayton97471182012-04-14 01:42:46 +0000551 // 1 - stop in shell
552 // 2 - stop in /usr/bin/arch
553 // 3 - then we will stop in our program
554 SetResumeCount(2);
555 }
556 else
557 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000558 // Set the resume count to 1:
Greg Clayton97471182012-04-14 01:42:46 +0000559 // 1 - stop in shell
560 // 2 - then we will stop in our program
561 SetResumeCount(1);
562 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000563#else
564 // Set the resume count to 1:
565 // 1 - stop in shell
566 // 2 - then we will stop in our program
567 SetResumeCount(1);
568#endif
Greg Clayton527154d2011-11-15 03:53:30 +0000569 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000570
571 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000572 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000573 // There should only be one argument that is the shell command itself to be used as is
574 if (argv[0] && !argv[1])
575 shell_command.Printf("%s", argv[0]);
Greg Clayton97471182012-04-14 01:42:46 +0000576 else
Greg Clayton0c8446c2012-10-17 22:57:12 +0000577 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000578 }
Greg Clayton97471182012-04-14 01:42:46 +0000579 else
580 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000581 for (size_t i=0; argv[i] != NULL; ++i)
582 {
583 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
584 shell_command.Printf(" %s", arg);
585 }
Greg Clayton97471182012-04-14 01:42:46 +0000586 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000587 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000588 m_executable.SetFile(shell_executable, false);
589 m_arguments = shell_arguments;
590 return true;
591 }
592 else
593 {
594 error.SetErrorString ("invalid shell path");
595 }
596 }
597 else
598 {
599 error.SetErrorString ("not launching in shell");
600 }
601 return false;
602}
603
604
Greg Clayton24bc5d92011-03-30 18:16:51 +0000605bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000606ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
607{
608 if ((read || write) && fd >= 0 && path && path[0])
609 {
610 m_action = eFileActionOpen;
611 m_fd = fd;
612 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000613 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000614 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000615 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000616 else
Greg Clayton527154d2011-11-15 03:53:30 +0000617 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000618 m_path.assign (path);
619 return true;
620 }
621 else
622 {
623 Clear();
624 }
625 return false;
626}
627
628bool
629ProcessLaunchInfo::FileAction::Close (int fd)
630{
631 Clear();
632 if (fd >= 0)
633 {
634 m_action = eFileActionClose;
635 m_fd = fd;
636 }
637 return m_fd >= 0;
638}
639
640
641bool
642ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
643{
644 Clear();
645 if (fd >= 0 && dup_fd >= 0)
646 {
647 m_action = eFileActionDuplicate;
648 m_fd = fd;
649 m_arg = dup_fd;
650 }
651 return m_fd >= 0;
652}
653
654
655
656bool
657ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
658 const FileAction *info,
659 Log *log,
660 Error& error)
661{
662 if (info == NULL)
663 return false;
664
665 switch (info->m_action)
666 {
667 case eFileActionNone:
668 error.Clear();
669 break;
670
671 case eFileActionClose:
672 if (info->m_fd == -1)
673 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
674 else
675 {
676 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
677 eErrorTypePOSIX);
678 if (log && (error.Fail() || log))
679 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
680 file_actions, info->m_fd);
681 }
682 break;
683
684 case eFileActionDuplicate:
685 if (info->m_fd == -1)
686 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
687 else if (info->m_arg == -1)
688 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
689 else
690 {
691 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
692 eErrorTypePOSIX);
693 if (log && (error.Fail() || log))
694 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
695 file_actions, info->m_fd, info->m_arg);
696 }
697 break;
698
699 case eFileActionOpen:
700 if (info->m_fd == -1)
701 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
702 else
703 {
704 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000705
Greg Claytonb72d0f02011-04-12 05:54:46 +0000706 mode_t mode = 0;
707
Greg Clayton527154d2011-11-15 03:53:30 +0000708 if (oflag & O_CREAT)
709 mode = 0640;
710
Greg Claytonb72d0f02011-04-12 05:54:46 +0000711 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
712 info->m_fd,
713 info->m_path.c_str(),
714 oflag,
715 mode),
716 eErrorTypePOSIX);
717 if (error.Fail() || log)
718 error.PutToLog(log,
719 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
720 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
721 }
722 break;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000723 }
724 return error.Success();
725}
726
727Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000728ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000729{
730 Error error;
Greg Clayton6475c422012-12-04 00:32:51 +0000731 const int short_option = m_getopt_table[option_idx].val;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000732
733 switch (short_option)
734 {
735 case 's': // Stop at program entry point
736 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
737 break;
738
Greg Claytonb72d0f02011-04-12 05:54:46 +0000739 case 'i': // STDIN for read only
740 {
741 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000742 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000743 launch_info.AppendFileAction (action);
744 }
745 break;
746
747 case 'o': // Open STDOUT for write only
748 {
749 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000750 if (action.Open (STDOUT_FILENO, option_arg, false, true))
751 launch_info.AppendFileAction (action);
752 }
753 break;
754
755 case 'e': // STDERR for write only
756 {
757 ProcessLaunchInfo::FileAction action;
758 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000759 launch_info.AppendFileAction (action);
760 }
761 break;
762
Greg Clayton95ec1682012-03-06 04:01:04 +0000763
Greg Claytonb72d0f02011-04-12 05:54:46 +0000764 case 'p': // Process plug-in name
765 launch_info.SetProcessPluginName (option_arg);
766 break;
767
768 case 'n': // Disable STDIO
769 {
770 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000771 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000772 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000773 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000774 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000775 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000776 launch_info.AppendFileAction (action);
777 }
778 break;
779
780 case 'w':
781 launch_info.SetWorkingDirectory (option_arg);
782 break;
783
784 case 't': // Open process in new terminal window
785 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
786 break;
787
788 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000789 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
790 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000791 break;
792
793 case 'A':
794 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
795 break;
796
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000797 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000798 if (option_arg && option_arg[0])
799 launch_info.SetShell (option_arg);
800 else
801 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000802 break;
803
Greg Claytonb72d0f02011-04-12 05:54:46 +0000804 case 'v':
805 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
806 break;
807
808 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000809 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000810 break;
811
812 }
813 return error;
814}
815
816OptionDefinition
817ProcessLaunchCommandOptions::g_option_table[] =
818{
819{ 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."},
820{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
821{ 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 +0000822{ 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 +0000823{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
824{ 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 +0000825{ 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 +0000826
Sean Callanan9a91ef62012-10-24 01:12:14 +0000827{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
828{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
829{ 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 +0000830
831{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
832
833{ 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."},
834
835{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
836};
837
838
839
840bool
841ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000842{
843 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
844 return true;
845 const char *match_name = m_match_info.GetName();
846 if (!match_name)
847 return true;
848
849 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
850}
851
852bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000853ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000854{
855 if (!NameMatches (proc_info.GetName()))
856 return false;
857
858 if (m_match_info.ProcessIDIsValid() &&
859 m_match_info.GetProcessID() != proc_info.GetProcessID())
860 return false;
861
862 if (m_match_info.ParentProcessIDIsValid() &&
863 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
864 return false;
865
Greg Claytonb72d0f02011-04-12 05:54:46 +0000866 if (m_match_info.UserIDIsValid () &&
867 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000868 return false;
869
Greg Claytonb72d0f02011-04-12 05:54:46 +0000870 if (m_match_info.GroupIDIsValid () &&
871 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000872 return false;
873
874 if (m_match_info.EffectiveUserIDIsValid () &&
875 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
876 return false;
877
878 if (m_match_info.EffectiveGroupIDIsValid () &&
879 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
880 return false;
881
882 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callanan40e278c2012-12-13 22:07:14 +0000883 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton24bc5d92011-03-30 18:16:51 +0000884 return false;
885 return true;
886}
887
888bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000889ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000890{
891 if (m_name_match_type != eNameMatchIgnore)
892 return false;
893
894 if (m_match_info.ProcessIDIsValid())
895 return false;
896
897 if (m_match_info.ParentProcessIDIsValid())
898 return false;
899
Greg Claytonb72d0f02011-04-12 05:54:46 +0000900 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000901 return false;
902
Greg Claytonb72d0f02011-04-12 05:54:46 +0000903 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000904 return false;
905
906 if (m_match_info.EffectiveUserIDIsValid ())
907 return false;
908
909 if (m_match_info.EffectiveGroupIDIsValid ())
910 return false;
911
912 if (m_match_info.GetArchitecture().IsValid())
913 return false;
914
915 if (m_match_all_users)
916 return false;
917
918 return true;
919
920}
921
922void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000923ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000924{
925 m_match_info.Clear();
926 m_name_match_type = eNameMatchIgnore;
927 m_match_all_users = false;
928}
Greg Claytonfd119992011-01-07 06:08:19 +0000929
Greg Clayton46c9a352012-02-09 06:16:32 +0000930ProcessSP
931Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000932{
Greg Clayton64742742013-01-16 17:29:04 +0000933 static uint32_t g_process_unique_id = 0;
934
Greg Clayton46c9a352012-02-09 06:16:32 +0000935 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000936 ProcessCreateInstance create_callback = NULL;
937 if (plugin_name)
938 {
939 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
940 if (create_callback)
941 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000942 process_sp = create_callback(target, listener, crash_file_path);
943 if (process_sp)
944 {
Greg Clayton64742742013-01-16 17:29:04 +0000945 if (process_sp->CanDebug(target, true))
946 {
947 process_sp->m_process_unique_id = ++g_process_unique_id;
948 }
949 else
Greg Clayton46c9a352012-02-09 06:16:32 +0000950 process_sp.reset();
951 }
Chris Lattner24943d22010-06-08 16:52:24 +0000952 }
953 }
954 else
955 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000956 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000957 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000958 process_sp = create_callback(target, listener, crash_file_path);
959 if (process_sp)
960 {
Greg Clayton64742742013-01-16 17:29:04 +0000961 if (process_sp->CanDebug(target, false))
962 {
963 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Clayton46c9a352012-02-09 06:16:32 +0000964 break;
Greg Clayton64742742013-01-16 17:29:04 +0000965 }
966 else
967 process_sp.reset();
Greg Clayton46c9a352012-02-09 06:16:32 +0000968 }
Chris Lattner24943d22010-06-08 16:52:24 +0000969 }
970 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000971 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000972}
973
Jim Ingham5a15e692012-02-16 06:50:00 +0000974ConstString &
975Process::GetStaticBroadcasterClass ()
976{
977 static ConstString class_name ("lldb.process");
978 return class_name;
979}
Chris Lattner24943d22010-06-08 16:52:24 +0000980
981//----------------------------------------------------------------------
982// Process constructor
983//----------------------------------------------------------------------
984Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +0000985 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +0000986 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000987 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +0000988 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000989 m_public_state (eStateUnloaded),
990 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000991 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
992 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000993 m_private_state_listener ("lldb.process.internal_state_listener"),
994 m_private_state_control_wait(),
995 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000996 m_mod_id (),
Greg Clayton64742742013-01-16 17:29:04 +0000997 m_process_unique_id(0),
Chris Lattner24943d22010-06-08 16:52:24 +0000998 m_thread_index_id (0),
Han Ming Ongccd5c4e2013-01-08 22:10:01 +0000999 m_thread_id_to_index_id_map (),
Chris Lattner24943d22010-06-08 16:52:24 +00001000 m_exit_status (-1),
1001 m_exit_string (),
1002 m_thread_list (this),
1003 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001004 m_image_tokens (),
1005 m_listener (listener),
1006 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001007 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +00001008 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001009 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +00001010 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +00001011 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +00001012 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +00001013 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +00001014 m_stderr_data (),
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001015 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1016 m_profile_data (),
Greg Clayton613b8732011-05-17 03:37:42 +00001017 m_memory_cache (*this),
1018 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +00001019 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +00001020 m_next_event_action_ap(),
Bill Wendlingce96dad2012-04-06 00:10:21 +00001021 m_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +00001022 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001023 m_finalize_called(false),
Jim Ingham89e248f2013-02-09 01:29:05 +00001024 m_last_broadcast_state (eStateInvalid),
Bill Wendlingce96dad2012-04-06 00:10:21 +00001025 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +00001026{
Jim Ingham5a15e692012-02-16 06:50:00 +00001027 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +00001028
Greg Claytone005f2c2010-11-06 01:53:30 +00001029 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001030 if (log)
1031 log->Printf ("%p Process::Process()", this);
1032
Greg Clayton49ce6822010-10-31 03:01:06 +00001033 SetEventName (eBroadcastBitStateChanged, "state-changed");
1034 SetEventName (eBroadcastBitInterrupt, "interrupt");
1035 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1036 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001037 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Clayton49ce6822010-10-31 03:01:06 +00001038
Greg Clayton84332782012-10-29 20:52:08 +00001039 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1040 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1041 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1042
Chris Lattner24943d22010-06-08 16:52:24 +00001043 listener.StartListeningForEvents (this,
1044 eBroadcastBitStateChanged |
1045 eBroadcastBitInterrupt |
1046 eBroadcastBitSTDOUT |
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001047 eBroadcastBitSTDERR |
1048 eBroadcastBitProfileData);
Chris Lattner24943d22010-06-08 16:52:24 +00001049
1050 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001051 eBroadcastBitStateChanged |
1052 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +00001053
1054 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1055 eBroadcastInternalStateControlStop |
1056 eBroadcastInternalStateControlPause |
1057 eBroadcastInternalStateControlResume);
1058}
1059
1060//----------------------------------------------------------------------
1061// Destructor
1062//----------------------------------------------------------------------
1063Process::~Process()
1064{
Greg Claytone005f2c2010-11-06 01:53:30 +00001065 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001066 if (log)
1067 log->Printf ("%p Process::~Process()", this);
1068 StopPrivateStateThread();
1069}
1070
Greg Clayton73844aa2012-08-22 17:17:09 +00001071const ProcessPropertiesSP &
1072Process::GetGlobalProperties()
1073{
1074 static ProcessPropertiesSP g_settings_sp;
1075 if (!g_settings_sp)
1076 g_settings_sp.reset (new ProcessProperties (true));
1077 return g_settings_sp;
1078}
1079
Chris Lattner24943d22010-06-08 16:52:24 +00001080void
1081Process::Finalize()
1082{
Greg Claytonffa43a62011-11-17 04:46:02 +00001083 switch (GetPrivateState())
1084 {
1085 case eStateConnected:
1086 case eStateAttaching:
1087 case eStateLaunching:
1088 case eStateStopped:
1089 case eStateRunning:
1090 case eStateStepping:
1091 case eStateCrashed:
1092 case eStateSuspended:
1093 if (GetShouldDetach())
1094 Detach();
1095 else
1096 Destroy();
1097 break;
1098
1099 case eStateInvalid:
1100 case eStateUnloaded:
1101 case eStateDetached:
1102 case eStateExited:
1103 break;
1104 }
1105
Greg Clayton2f57db02011-10-01 00:45:15 +00001106 // Clear our broadcaster before we proceed with destroying
1107 Broadcaster::Clear();
1108
Chris Lattner24943d22010-06-08 16:52:24 +00001109 // Do any cleanup needed prior to being destructed... Subclasses
1110 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001111
1112 // We need to destroy the loader before the derived Process class gets destroyed
1113 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001114 m_dynamic_checkers_ap.reset();
1115 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001116 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001117 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001118 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001119 std::vector<Notifications> empty_notifications;
1120 m_notifications.swap(empty_notifications);
1121 m_image_tokens.clear();
1122 m_memory_cache.Clear();
1123 m_allocated_memory_cache.Clear();
1124 m_language_runtimes.clear();
1125 m_next_event_action_ap.reset();
Greg Clayton84332782012-10-29 20:52:08 +00001126//#ifdef LLDB_CONFIGURATION_DEBUG
1127// StreamFile s(stdout, false);
1128// EventSP event_sp;
1129// while (m_private_state_listener.GetNextEvent(event_sp))
1130// {
1131// event_sp->Dump (&s);
1132// s.EOL();
1133// }
1134//#endif
1135 // We have to be very careful here as the m_private_state_listener might
1136 // contain events that have ProcessSP values in them which can keep this
1137 // process around forever. These events need to be cleared out.
1138 m_private_state_listener.Clear();
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001139 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001140}
1141
1142void
1143Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1144{
1145 m_notifications.push_back(callbacks);
1146 if (callbacks.initialize != NULL)
1147 callbacks.initialize (callbacks.baton, this);
1148}
1149
1150bool
1151Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1152{
1153 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1154 for (pos = m_notifications.begin(); pos != end; ++pos)
1155 {
1156 if (pos->baton == callbacks.baton &&
1157 pos->initialize == callbacks.initialize &&
1158 pos->process_state_changed == callbacks.process_state_changed)
1159 {
1160 m_notifications.erase(pos);
1161 return true;
1162 }
1163 }
1164 return false;
1165}
1166
1167void
1168Process::SynchronouslyNotifyStateChanged (StateType state)
1169{
1170 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1171 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1172 {
1173 if (notification_pos->process_state_changed)
1174 notification_pos->process_state_changed (notification_pos->baton, this, state);
1175 }
1176}
1177
1178// FIXME: We need to do some work on events before the general Listener sees them.
1179// For instance if we are continuing from a breakpoint, we need to ensure that we do
1180// the little "insert real insn, step & stop" trick. But we can't do that when the
1181// event is delivered by the broadcaster - since that is done on the thread that is
1182// waiting for new events, so if we needed more than one event for our handling, we would
1183// stall. So instead we do it when we fetch the event off of the queue.
1184//
1185
1186StateType
1187Process::GetNextEvent (EventSP &event_sp)
1188{
1189 StateType state = eStateInvalid;
1190
1191 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1192 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1193
1194 return state;
1195}
1196
1197
1198StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001199Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001200{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001201 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1202 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1203 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001204 if (event_sp_ptr)
1205 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001206 StateType state = GetState();
1207 // If we are exited or detached, we won't ever get back to any
1208 // other valid state...
1209 if (state == eStateDetached || state == eStateExited)
1210 return state;
1211
1212 while (state != eStateInvalid)
1213 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001214 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001215 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001216 if (event_sp_ptr && event_sp)
1217 *event_sp_ptr = event_sp;
1218
Jim Ingham21f37ad2011-08-09 02:12:22 +00001219 switch (state)
1220 {
1221 case eStateCrashed:
1222 case eStateDetached:
1223 case eStateExited:
1224 case eStateUnloaded:
1225 return state;
1226 case eStateStopped:
1227 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1228 continue;
1229 else
1230 return state;
1231 default:
1232 continue;
1233 }
1234 }
1235 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001236}
1237
1238
1239StateType
1240Process::WaitForState
1241(
1242 const TimeValue *timeout,
1243 const StateType *match_states, const uint32_t num_match_states
1244)
1245{
1246 EventSP event_sp;
1247 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001248 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001249 while (state != eStateInvalid)
1250 {
Greg Claytond8c62532010-10-07 04:19:01 +00001251 // If we are exited or detached, we won't ever get back to any
1252 // other valid state...
1253 if (state == eStateDetached || state == eStateExited)
1254 return state;
1255
Chris Lattner24943d22010-06-08 16:52:24 +00001256 state = WaitForStateChangedEvents (timeout, event_sp);
1257
1258 for (i=0; i<num_match_states; ++i)
1259 {
1260 if (match_states[i] == state)
1261 return state;
1262 }
1263 }
1264 return state;
1265}
1266
Jim Ingham63e24d72010-10-11 23:53:14 +00001267bool
1268Process::HijackProcessEvents (Listener *listener)
1269{
1270 if (listener != NULL)
1271 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001272 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001273 }
1274 else
1275 return false;
1276}
1277
1278void
1279Process::RestoreProcessEvents ()
1280{
1281 RestoreBroadcaster();
1282}
1283
Jim Inghamf9f40c22011-02-08 05:20:59 +00001284bool
1285Process::HijackPrivateProcessEvents (Listener *listener)
1286{
1287 if (listener != NULL)
1288 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001289 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001290 }
1291 else
1292 return false;
1293}
1294
1295void
1296Process::RestorePrivateProcessEvents ()
1297{
1298 m_private_state_broadcaster.RestoreBroadcaster();
1299}
1300
Chris Lattner24943d22010-06-08 16:52:24 +00001301StateType
1302Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1303{
Greg Claytone005f2c2010-11-06 01:53:30 +00001304 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001305
1306 if (log)
1307 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1308
1309 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001310 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1311 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001312 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001313 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001314 {
1315 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1316 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1317 else if (log)
1318 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1319 }
Chris Lattner24943d22010-06-08 16:52:24 +00001320
1321 if (log)
1322 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1323 __FUNCTION__,
1324 timeout,
1325 StateAsCString(state));
1326 return state;
1327}
1328
1329Event *
1330Process::PeekAtStateChangedEvents ()
1331{
Greg Claytone005f2c2010-11-06 01:53:30 +00001332 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001333
1334 if (log)
1335 log->Printf ("Process::%s...", __FUNCTION__);
1336
1337 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001338 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1339 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001340 if (log)
1341 {
1342 if (event_ptr)
1343 {
1344 log->Printf ("Process::%s (event_ptr) => %s",
1345 __FUNCTION__,
1346 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1347 }
1348 else
1349 {
1350 log->Printf ("Process::%s no events found",
1351 __FUNCTION__);
1352 }
1353 }
1354 return event_ptr;
1355}
1356
1357StateType
1358Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1359{
Greg Claytone005f2c2010-11-06 01:53:30 +00001360 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001361
1362 if (log)
1363 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1364
1365 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001366 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1367 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001368 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001369 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001370 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1371 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001372
1373 // This is a bit of a hack, but when we wait here we could very well return
1374 // to the command-line, and that could disable the log, which would render the
1375 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001376 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001377 {
1378 if (state == eStateInvalid)
1379 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1380 else
1381 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1382 }
Chris Lattner24943d22010-06-08 16:52:24 +00001383 return state;
1384}
1385
1386bool
1387Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1388{
Greg Claytone005f2c2010-11-06 01:53:30 +00001389 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001390
1391 if (log)
1392 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1393
1394 if (control_only)
1395 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1396 else
1397 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1398}
1399
1400bool
1401Process::IsRunning () const
1402{
1403 return StateIsRunningState (m_public_state.GetValue());
1404}
1405
1406int
1407Process::GetExitStatus ()
1408{
1409 if (m_public_state.GetValue() == eStateExited)
1410 return m_exit_status;
1411 return -1;
1412}
1413
Greg Clayton638351a2010-12-04 00:10:17 +00001414
Chris Lattner24943d22010-06-08 16:52:24 +00001415const char *
1416Process::GetExitDescription ()
1417{
1418 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1419 return m_exit_string.c_str();
1420 return NULL;
1421}
1422
Greg Clayton72e1c782011-01-22 23:43:18 +00001423bool
Chris Lattner24943d22010-06-08 16:52:24 +00001424Process::SetExitStatus (int status, const char *cstr)
1425{
Greg Clayton68ca8232011-01-25 02:58:48 +00001426 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1427 if (log)
1428 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1429 status, status,
1430 cstr ? "\"" : "",
1431 cstr ? cstr : "NULL",
1432 cstr ? "\"" : "");
1433
Greg Clayton72e1c782011-01-22 23:43:18 +00001434 // We were already in the exited state
1435 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001436 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001437 if (log)
1438 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001439 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001440 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001441
1442 m_exit_status = status;
1443 if (cstr)
1444 m_exit_string = cstr;
1445 else
1446 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001447
Greg Clayton72e1c782011-01-22 23:43:18 +00001448 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001449
Greg Clayton72e1c782011-01-22 23:43:18 +00001450 SetPrivateState (eStateExited);
1451 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001452}
1453
1454// This static callback can be used to watch for local child processes on
1455// the current host. The the child process exits, the process will be
1456// found in the global target list (we want to be completely sure that the
1457// lldb_private::Process doesn't go away before we can deliver the signal.
1458bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001459Process::SetProcessExitStatus (void *callback_baton,
1460 lldb::pid_t pid,
1461 bool exited,
1462 int signo, // Zero for no signal
1463 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001464)
1465{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001466 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1467 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001468 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001469 callback_baton,
1470 pid,
1471 exited,
1472 signo,
1473 exit_status);
1474
1475 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001476 {
Greg Clayton63094e02010-06-23 01:19:29 +00001477 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001478 if (target_sp)
1479 {
1480 ProcessSP process_sp (target_sp->GetProcessSP());
1481 if (process_sp)
1482 {
1483 const char *signal_cstr = NULL;
1484 if (signo)
1485 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1486
1487 process_sp->SetExitStatus (exit_status, signal_cstr);
1488 }
1489 }
1490 return true;
1491 }
1492 return false;
1493}
1494
1495
Greg Clayton37f962e2011-08-22 02:49:39 +00001496void
1497Process::UpdateThreadListIfNeeded ()
1498{
1499 const uint32_t stop_id = GetStopID();
1500 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1501 {
Greg Clayton20206082011-11-17 01:23:07 +00001502 const StateType state = GetPrivateState();
1503 if (StateIsStoppedState (state, true))
1504 {
1505 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001506 // m_thread_list does have its own mutex, but we need to
1507 // hold onto the mutex between the call to UpdateThreadList(...)
1508 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001509 ThreadList new_thread_list(this);
1510 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001511 // thread list, but only update if "true" is returned
1512 if (UpdateThreadList (m_thread_list, new_thread_list))
1513 {
1514 OperatingSystem *os = GetOperatingSystem ();
1515 if (os)
1516 os->UpdateThreadList (m_thread_list, new_thread_list);
1517 m_thread_list.Update (new_thread_list);
1518 m_thread_list.SetStopID (stop_id);
1519 }
Greg Clayton20206082011-11-17 01:23:07 +00001520 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001521 }
1522}
1523
Greg Clayton52ebc0a2013-01-18 23:41:08 +00001524ThreadSP
1525Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1526{
1527 OperatingSystem *os = GetOperatingSystem ();
1528 if (os)
1529 return os->CreateThread(tid, context);
1530 return ThreadSP();
1531}
1532
1533
1534
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001535// This is obsoleted. Staged removal for Xcode.
Chris Lattner24943d22010-06-08 16:52:24 +00001536uint32_t
1537Process::GetNextThreadIndexID ()
1538{
1539 return ++m_thread_index_id;
1540}
1541
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001542uint32_t
1543Process::GetNextThreadIndexID (uint64_t thread_id)
1544{
1545 return AssignIndexIDToThread(thread_id);
1546}
1547
1548bool
1549Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1550{
1551 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1552 if (iterator == m_thread_id_to_index_id_map.end())
1553 {
1554 return false;
1555 }
1556 else
1557 {
1558 return true;
1559 }
1560}
1561
1562uint32_t
1563Process::AssignIndexIDToThread(uint64_t thread_id)
1564{
1565 uint32_t result = 0;
1566 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1567 if (iterator == m_thread_id_to_index_id_map.end())
1568 {
1569 result = ++m_thread_index_id;
1570 m_thread_id_to_index_id_map[thread_id] = result;
1571 }
1572 else
1573 {
1574 result = iterator->second;
1575 }
1576
1577 return result;
1578}
1579
Chris Lattner24943d22010-06-08 16:52:24 +00001580StateType
1581Process::GetState()
1582{
1583 // If any other threads access this we will need a mutex for it
1584 return m_public_state.GetValue ();
1585}
1586
1587void
1588Process::SetPublicState (StateType new_state)
1589{
Greg Clayton68ca8232011-01-25 02:58:48 +00001590 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001591 if (log)
1592 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001593 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001594 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001595
1596 // On the transition from Run to Stopped, we unlock the writer end of the
1597 // run lock. The lock gets locked in Resume, which is the public API
1598 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001599 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1600 {
Sean Callanana3772862012-06-02 01:16:20 +00001601 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001602 {
Sean Callanana3772862012-06-02 01:16:20 +00001603 if (log)
1604 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1605 m_run_lock.WriteUnlock();
1606 }
1607 else
1608 {
1609 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1610 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1611 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001612 {
Sean Callanana3772862012-06-02 01:16:20 +00001613 if (new_state_is_stopped)
1614 {
1615 if (log)
1616 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1617 m_run_lock.WriteUnlock();
1618 }
Greg Claytona894fe72012-04-05 16:12:35 +00001619 }
Greg Claytona894fe72012-04-05 16:12:35 +00001620 }
1621 }
Chris Lattner24943d22010-06-08 16:52:24 +00001622}
1623
Jim Ingham027aaa72012-04-19 01:40:33 +00001624Error
1625Process::Resume ()
1626{
1627 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1628 if (log)
1629 log->Printf("Process::Resume -- locking run lock");
1630 if (!m_run_lock.WriteTryLock())
1631 {
1632 Error error("Resume request failed - process still running.");
1633 if (log)
1634 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1635 return error;
1636 }
1637 return PrivateResume();
1638}
1639
Chris Lattner24943d22010-06-08 16:52:24 +00001640StateType
1641Process::GetPrivateState ()
1642{
1643 return m_private_state.GetValue();
1644}
1645
1646void
1647Process::SetPrivateState (StateType new_state)
1648{
Greg Clayton68ca8232011-01-25 02:58:48 +00001649 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001650 bool state_changed = false;
1651
1652 if (log)
1653 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1654
1655 Mutex::Locker locker(m_private_state.GetMutex());
1656
1657 const StateType old_state = m_private_state.GetValueNoLock ();
1658 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001659 // This code is left commented out in case we ever need to control
1660 // the private process state with another run lock. Right now it doesn't
1661 // seem like we need to do this, but if we ever do, we can uncomment and
1662 // use this code.
1663// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1664// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1665// if (old_state_is_stopped != new_state_is_stopped)
1666// {
1667// if (new_state_is_stopped)
1668// m_private_run_lock.WriteUnlock();
1669// else
1670// m_private_run_lock.WriteLock();
1671// }
1672
Chris Lattner24943d22010-06-08 16:52:24 +00001673 if (state_changed)
1674 {
1675 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001676 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001677 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001678 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001679 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001680 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001681 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001682 }
1683 // Use our target to get a shared pointer to ourselves...
Greg Clayton84332782012-10-29 20:52:08 +00001684 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1685 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1686 else
1687 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001688 }
1689 else
1690 {
1691 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001692 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001693 }
1694}
1695
Jim Ingham0296fe72011-11-08 03:00:11 +00001696void
1697Process::SetRunningUserExpression (bool on)
1698{
1699 m_mod_id.SetRunningUserExpression (on);
1700}
1701
Chris Lattner24943d22010-06-08 16:52:24 +00001702addr_t
1703Process::GetImageInfoAddress()
1704{
1705 return LLDB_INVALID_ADDRESS;
1706}
1707
Greg Clayton0baa3942010-11-04 01:54:29 +00001708//----------------------------------------------------------------------
1709// LoadImage
1710//
1711// This function provides a default implementation that works for most
1712// unix variants. Any Process subclasses that need to do shared library
1713// loading differently should override LoadImage and UnloadImage and
1714// do what is needed.
1715//----------------------------------------------------------------------
1716uint32_t
1717Process::LoadImage (const FileSpec &image_spec, Error &error)
1718{
Greg Clayton77d40712012-04-18 00:05:19 +00001719 char path[PATH_MAX];
1720 image_spec.GetPath(path, sizeof(path));
1721
Greg Clayton0baa3942010-11-04 01:54:29 +00001722 DynamicLoader *loader = GetDynamicLoader();
1723 if (loader)
1724 {
1725 error = loader->CanLoadImage();
1726 if (error.Fail())
1727 return LLDB_INVALID_IMAGE_TOKEN;
1728 }
1729
1730 if (error.Success())
1731 {
1732 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001733
1734 if (thread_sp)
1735 {
1736 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1737
1738 if (frame_sp)
1739 {
1740 ExecutionContext exe_ctx;
1741 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001742 const bool unwind_on_error = true;
1743 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001744 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001745 expr.Printf("dlopen (\"%s\", 2)", path);
1746 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001747 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001748 ClangUserExpression::Evaluate (exe_ctx,
1749 eExecutionPolicyAlways,
1750 lldb::eLanguageTypeUnknown,
1751 ClangUserExpression::eResultTypeAny,
1752 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001753 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001754 expr.GetData(),
1755 prefix,
1756 result_valobj_sp,
1757 true,
1758 ClangUserExpression::kDefaultTimeout);
Johnny Chenb14ec342011-09-09 00:01:43 +00001759 error = result_valobj_sp->GetError();
1760 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001761 {
1762 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001763 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001764 {
1765 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1766 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1767 {
1768 uint32_t image_token = m_image_tokens.size();
1769 m_image_tokens.push_back (image_ptr);
1770 return image_token;
1771 }
1772 }
1773 }
1774 }
1775 }
1776 }
Greg Clayton77d40712012-04-18 00:05:19 +00001777 if (!error.AsCString())
1778 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001779 return LLDB_INVALID_IMAGE_TOKEN;
1780}
1781
1782//----------------------------------------------------------------------
1783// UnloadImage
1784//
1785// This function provides a default implementation that works for most
1786// unix variants. Any Process subclasses that need to do shared library
1787// loading differently should override LoadImage and UnloadImage and
1788// do what is needed.
1789//----------------------------------------------------------------------
1790Error
1791Process::UnloadImage (uint32_t image_token)
1792{
1793 Error error;
1794 if (image_token < m_image_tokens.size())
1795 {
1796 const addr_t image_addr = m_image_tokens[image_token];
1797 if (image_addr == LLDB_INVALID_ADDRESS)
1798 {
1799 error.SetErrorString("image already unloaded");
1800 }
1801 else
1802 {
1803 DynamicLoader *loader = GetDynamicLoader();
1804 if (loader)
1805 error = loader->CanLoadImage();
1806
1807 if (error.Success())
1808 {
1809 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001810
1811 if (thread_sp)
1812 {
1813 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1814
1815 if (frame_sp)
1816 {
1817 ExecutionContext exe_ctx;
1818 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001819 const bool unwind_on_error = true;
1820 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001821 StreamString expr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001822 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton0baa3942010-11-04 01:54:29 +00001823 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001824 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001825 ClangUserExpression::Evaluate (exe_ctx,
1826 eExecutionPolicyAlways,
1827 lldb::eLanguageTypeUnknown,
1828 ClangUserExpression::eResultTypeAny,
1829 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001830 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001831 expr.GetData(),
1832 prefix,
1833 result_valobj_sp,
1834 true,
1835 ClangUserExpression::kDefaultTimeout);
Greg Clayton0baa3942010-11-04 01:54:29 +00001836 if (result_valobj_sp->GetError().Success())
1837 {
1838 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001839 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001840 {
1841 if (scalar.UInt(1))
1842 {
1843 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1844 }
1845 else
1846 {
1847 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1848 }
1849 }
1850 }
1851 else
1852 {
1853 error = result_valobj_sp->GetError();
1854 }
1855 }
1856 }
1857 }
1858 }
1859 }
1860 else
1861 {
1862 error.SetErrorString("invalid image token");
1863 }
1864 return error;
1865}
1866
Greg Clayton75906e42011-05-11 18:39:18 +00001867const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001868Process::GetABI()
1869{
Greg Clayton75906e42011-05-11 18:39:18 +00001870 if (!m_abi_sp)
1871 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1872 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001873}
1874
Jim Ingham642036f2010-09-23 02:01:19 +00001875LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001876Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001877{
1878 LanguageRuntimeCollection::iterator pos;
1879 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001880 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001881 {
Jim Inghame3117662012-03-10 00:22:19 +00001882 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001883
Jim Inghame3117662012-03-10 00:22:19 +00001884 m_language_runtimes[language] = runtime_sp;
1885 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001886 }
1887 else
1888 return (*pos).second.get();
1889}
1890
1891CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001892Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001893{
Jim Inghame3117662012-03-10 00:22:19 +00001894 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001895 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1896 return static_cast<CPPLanguageRuntime *> (runtime);
1897 return NULL;
1898}
1899
1900ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001901Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001902{
Jim Inghame3117662012-03-10 00:22:19 +00001903 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001904 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1905 return static_cast<ObjCLanguageRuntime *> (runtime);
1906 return NULL;
1907}
1908
Enrico Granata6b1763b2012-05-21 16:51:35 +00001909bool
1910Process::IsPossibleDynamicValue (ValueObject& in_value)
1911{
1912 if (in_value.IsDynamic())
1913 return false;
1914 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1915
1916 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1917 {
1918 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1919 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1920 }
1921
1922 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1923 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1924 return true;
1925
1926 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1927 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1928}
1929
Chris Lattner24943d22010-06-08 16:52:24 +00001930BreakpointSiteList &
1931Process::GetBreakpointSiteList()
1932{
1933 return m_breakpoint_site_list;
1934}
1935
1936const BreakpointSiteList &
1937Process::GetBreakpointSiteList() const
1938{
1939 return m_breakpoint_site_list;
1940}
1941
1942
1943void
1944Process::DisableAllBreakpointSites ()
1945{
1946 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001947 size_t num_sites = m_breakpoint_site_list.GetSize();
1948 for (size_t i = 0; i < num_sites; i++)
1949 {
1950 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1951 }
Chris Lattner24943d22010-06-08 16:52:24 +00001952}
1953
1954Error
1955Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1956{
1957 Error error (DisableBreakpointSiteByID (break_id));
1958
1959 if (error.Success())
1960 m_breakpoint_site_list.Remove(break_id);
1961
1962 return error;
1963}
1964
1965Error
1966Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1967{
1968 Error error;
1969 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1970 if (bp_site_sp)
1971 {
1972 if (bp_site_sp->IsEnabled())
1973 error = DisableBreakpoint (bp_site_sp.get());
1974 }
1975 else
1976 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001977 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001978 }
1979
1980 return error;
1981}
1982
1983Error
1984Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1985{
1986 Error error;
1987 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1988 if (bp_site_sp)
1989 {
1990 if (!bp_site_sp->IsEnabled())
1991 error = EnableBreakpoint (bp_site_sp.get());
1992 }
1993 else
1994 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001995 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001996 }
1997 return error;
1998}
1999
Stephen Wilson3fd1f362010-07-17 00:56:13 +00002000lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00002001Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00002002{
Greg Clayton265ab332011-05-19 18:17:41 +00002003 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002004 if (load_addr != LLDB_INVALID_ADDRESS)
2005 {
2006 BreakpointSiteSP bp_site_sp;
2007
2008 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2009 // create a new breakpoint site and add it.
2010
2011 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2012
2013 if (bp_site_sp)
2014 {
2015 bp_site_sp->AddOwner (owner);
2016 owner->SetBreakpointSite (bp_site_sp);
2017 return bp_site_sp->GetID();
2018 }
2019 else
2020 {
Greg Clayton36da2aa2013-01-25 18:06:21 +00002021 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner24943d22010-06-08 16:52:24 +00002022 if (bp_site_sp)
2023 {
2024 if (EnableBreakpoint (bp_site_sp.get()).Success())
2025 {
2026 owner->SetBreakpointSite (bp_site_sp);
2027 return m_breakpoint_site_list.Add (bp_site_sp);
2028 }
2029 }
2030 }
2031 }
2032 // We failed to enable the breakpoint
2033 return LLDB_INVALID_BREAK_ID;
2034
2035}
2036
2037void
2038Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2039{
2040 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2041 if (num_owners == 0)
2042 {
2043 DisableBreakpoint(bp_site_sp.get());
2044 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2045 }
2046}
2047
2048
2049size_t
2050Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2051{
2052 size_t bytes_removed = 0;
2053 addr_t intersect_addr;
2054 size_t intersect_size;
2055 size_t opcode_offset;
2056 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002057 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00002058 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00002059
Jim Ingham82820f92011-06-29 19:42:28 +00002060 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00002061 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002062 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00002063 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002064 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00002065 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002066 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00002067 {
2068 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2069 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00002070 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00002071 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002072 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00002073 }
Chris Lattner24943d22010-06-08 16:52:24 +00002074 }
2075 }
2076 }
2077 return bytes_removed;
2078}
2079
2080
Greg Claytonb1888f22011-03-19 01:12:21 +00002081
2082size_t
2083Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2084{
2085 PlatformSP platform_sp (m_target.GetPlatform());
2086 if (platform_sp)
2087 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2088 return 0;
2089}
2090
Chris Lattner24943d22010-06-08 16:52:24 +00002091Error
2092Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2093{
2094 Error error;
2095 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002096 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002097 const addr_t bp_addr = bp_site->GetLoadAddress();
2098 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002099 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002100 if (bp_site->IsEnabled())
2101 {
2102 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002103 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 +00002104 return error;
2105 }
2106
2107 if (bp_addr == LLDB_INVALID_ADDRESS)
2108 {
2109 error.SetErrorString("BreakpointSite contains an invalid load address.");
2110 return error;
2111 }
2112 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2113 // trap for the breakpoint site
2114 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2115
2116 if (bp_opcode_size == 0)
2117 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002118 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002119 }
2120 else
2121 {
2122 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2123
2124 if (bp_opcode_bytes == NULL)
2125 {
2126 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2127 return error;
2128 }
2129
2130 // Save the original opcode by reading it
2131 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2132 {
2133 // Write a software breakpoint in place of the original opcode
2134 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2135 {
2136 uint8_t verify_bp_opcode_bytes[64];
2137 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2138 {
2139 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2140 {
2141 bp_site->SetEnabled(true);
2142 bp_site->SetType (BreakpointSite::eSoftware);
2143 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002144 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner24943d22010-06-08 16:52:24 +00002145 bp_site->GetID(),
2146 (uint64_t)bp_addr);
2147 }
2148 else
Greg Clayton9c236732011-10-26 00:56:27 +00002149 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00002150 }
2151 else
2152 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2153 }
2154 else
2155 error.SetErrorString("Unable to write breakpoint trap to memory.");
2156 }
2157 else
2158 error.SetErrorString("Unable to read memory at breakpoint address.");
2159 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002160 if (log && error.Fail())
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002161 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002162 bp_site->GetID(),
2163 (uint64_t)bp_addr,
2164 error.AsCString());
2165 return error;
2166}
2167
2168Error
2169Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2170{
2171 Error error;
2172 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002173 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002174 addr_t bp_addr = bp_site->GetLoadAddress();
2175 lldb::user_id_t breakID = bp_site->GetID();
2176 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002177 log->Printf ("Process::DisableBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002178
2179 if (bp_site->IsHardware())
2180 {
2181 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2182 }
2183 else if (bp_site->IsEnabled())
2184 {
2185 const size_t break_op_size = bp_site->GetByteSize();
2186 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2187 if (break_op_size > 0)
2188 {
2189 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002190 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002191 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002192 bool break_op_found = false;
2193
2194 // Read the breakpoint opcode
2195 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2196 {
2197 bool verify = false;
2198 // Make sure we have the a breakpoint opcode exists at this address
2199 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2200 {
2201 break_op_found = true;
2202 // We found a valid breakpoint opcode at this address, now restore
2203 // the saved opcode.
2204 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2205 {
2206 verify = true;
2207 }
2208 else
2209 error.SetErrorString("Memory write failed when restoring original opcode.");
2210 }
2211 else
2212 {
2213 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2214 // Set verify to true and so we can check if the original opcode has already been restored
2215 verify = true;
2216 }
2217
2218 if (verify)
2219 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002220 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002221 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002222 // Verify that our original opcode made it back to the inferior
2223 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2224 {
2225 // compare the memory we just read with the original opcode
2226 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2227 {
2228 // SUCCESS
2229 bp_site->SetEnabled(false);
2230 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002231 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 +00002232 return error;
2233 }
2234 else
2235 {
2236 if (break_op_found)
2237 error.SetErrorString("Failed to restore original opcode.");
2238 }
2239 }
2240 else
2241 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2242 }
2243 }
2244 else
2245 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2246 }
2247 }
2248 else
2249 {
2250 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002251 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 +00002252 return error;
2253 }
2254
2255 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002256 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002257 bp_site->GetID(),
2258 (uint64_t)bp_addr,
2259 error.AsCString());
2260 return error;
2261
2262}
2263
Greg Claytonfd119992011-01-07 06:08:19 +00002264// Uncomment to verify memory caching works after making changes to caching code
2265//#define VERIFY_MEMORY_READS
2266
Sean Callananf90b5f32012-06-07 22:26:42 +00002267size_t
2268Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2269{
2270 if (!GetDisableMemoryCache())
2271 {
Greg Claytonfd119992011-01-07 06:08:19 +00002272#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002273 // Memory caching is enabled, with debug verification
2274
2275 if (buf && size)
2276 {
2277 // Uncomment the line below to make sure memory caching is working.
2278 // I ran this through the test suite and got no assertions, so I am
2279 // pretty confident this is working well. If any changes are made to
2280 // memory caching, uncomment the line below and test your changes!
2281
2282 // Verify all memory reads by using the cache first, then redundantly
2283 // reading the same memory from the inferior and comparing to make sure
2284 // everything is exactly the same.
2285 std::string verify_buf (size, '\0');
2286 assert (verify_buf.size() == size);
2287 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2288 Error verify_error;
2289 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2290 assert (cache_bytes_read == verify_bytes_read);
2291 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2292 assert (verify_error.Success() == error.Success());
2293 return cache_bytes_read;
2294 }
2295 return 0;
2296#else // !defined(VERIFY_MEMORY_READS)
2297 // Memory caching is enabled, without debug verification
2298
2299 return m_memory_cache.Read (addr, buf, size, error);
2300#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002301 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002302 else
2303 {
2304 // Memory caching is disabled
2305
2306 return ReadMemoryFromInferior (addr, buf, size, error);
2307 }
Greg Claytonfd119992011-01-07 06:08:19 +00002308}
Greg Claytonfd119992011-01-07 06:08:19 +00002309
Greg Claytondd29b972012-05-18 23:20:01 +00002310size_t
2311Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2312{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002313 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002314 out_str.clear();
2315 addr_t curr_addr = addr;
2316 while (1)
2317 {
2318 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2319 if (length == 0)
2320 break;
2321 out_str.append(buf, length);
2322 // If we got "length - 1" bytes, we didn't get the whole C string, we
2323 // need to read some more characters
2324 if (length == sizeof(buf) - 1)
2325 curr_addr += length;
2326 else
2327 break;
2328 }
2329 return out_str.size();
2330}
2331
Greg Claytonfd119992011-01-07 06:08:19 +00002332
2333size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002334Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002335{
2336 size_t total_cstr_len = 0;
2337 if (dst && dst_max_len)
2338 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002339 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002340 // NULL out everything just to be safe
2341 memset (dst, 0, dst_max_len);
2342 Error error;
2343 addr_t curr_addr = addr;
2344 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2345 size_t bytes_left = dst_max_len - 1;
2346 char *curr_dst = dst;
2347
2348 while (bytes_left > 0)
2349 {
2350 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2351 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2352 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2353
2354 if (bytes_read == 0)
2355 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002356 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002357 dst[total_cstr_len] = '\0';
2358 break;
2359 }
2360 const size_t len = strlen(curr_dst);
2361
2362 total_cstr_len += len;
2363
2364 if (len < bytes_to_read)
2365 break;
2366
2367 curr_dst += bytes_read;
2368 curr_addr += bytes_read;
2369 bytes_left -= bytes_read;
2370 }
2371 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002372 else
2373 {
2374 if (dst == NULL)
2375 result_error.SetErrorString("invalid arguments");
2376 else
2377 result_error.Clear();
2378 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002379 return total_cstr_len;
2380}
2381
2382size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002383Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2384{
Chris Lattner24943d22010-06-08 16:52:24 +00002385 if (buf == NULL || size == 0)
2386 return 0;
2387
2388 size_t bytes_read = 0;
2389 uint8_t *bytes = (uint8_t *)buf;
2390
2391 while (bytes_read < size)
2392 {
2393 const size_t curr_size = size - bytes_read;
2394 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2395 bytes + bytes_read,
2396 curr_size,
2397 error);
2398 bytes_read += curr_bytes_read;
2399 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2400 break;
2401 }
2402
2403 // Replace any software breakpoint opcodes that fall into this range back
2404 // into "buf" before we return
2405 if (bytes_read > 0)
2406 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2407 return bytes_read;
2408}
2409
Greg Claytonf72fdee2010-12-16 20:01:20 +00002410uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002411Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002412{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002413 Scalar scalar;
2414 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2415 return scalar.ULongLong(fail_value);
2416 return fail_value;
2417}
2418
2419addr_t
2420Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2421{
2422 Scalar scalar;
2423 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2424 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2425 return LLDB_INVALID_ADDRESS;
2426}
2427
2428
2429bool
2430Process::WritePointerToMemory (lldb::addr_t vm_addr,
2431 lldb::addr_t ptr_value,
2432 Error &error)
2433{
2434 Scalar scalar;
2435 const uint32_t addr_byte_size = GetAddressByteSize();
2436 if (addr_byte_size <= 4)
2437 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002438 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002439 scalar = ptr_value;
2440 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002441}
2442
Chris Lattner24943d22010-06-08 16:52:24 +00002443size_t
2444Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2445{
2446 size_t bytes_written = 0;
2447 const uint8_t *bytes = (const uint8_t *)buf;
2448
2449 while (bytes_written < size)
2450 {
2451 const size_t curr_size = size - bytes_written;
2452 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2453 bytes + bytes_written,
2454 curr_size,
2455 error);
2456 bytes_written += curr_bytes_written;
2457 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2458 break;
2459 }
2460 return bytes_written;
2461}
2462
2463size_t
2464Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2465{
Greg Claytonfd119992011-01-07 06:08:19 +00002466#if defined (ENABLE_MEMORY_CACHING)
2467 m_memory_cache.Flush (addr, size);
2468#endif
2469
Chris Lattner24943d22010-06-08 16:52:24 +00002470 if (buf == NULL || size == 0)
2471 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002472
Jim Ingham21f37ad2011-08-09 02:12:22 +00002473 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002474
Chris Lattner24943d22010-06-08 16:52:24 +00002475 // We need to write any data that would go where any current software traps
2476 // (enabled software breakpoints) any software traps (breakpoints) that we
2477 // may have placed in our tasks memory.
2478
2479 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2480 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2481
2482 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002483 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002484
2485 BreakpointSiteList::collection::const_iterator pos;
2486 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002487 addr_t intersect_addr = 0;
2488 size_t intersect_size = 0;
2489 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002490 const uint8_t *ubuf = (const uint8_t *)buf;
2491
2492 for (pos = iter; pos != end; ++pos)
2493 {
2494 BreakpointSiteSP bp;
2495 bp = pos->second;
2496
2497 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2498 assert(addr <= intersect_addr && intersect_addr < addr + size);
2499 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2500 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2501
2502 // Check for bytes before this breakpoint
2503 const addr_t curr_addr = addr + bytes_written;
2504 if (intersect_addr > curr_addr)
2505 {
2506 // There are some bytes before this breakpoint that we need to
2507 // just write to memory
2508 size_t curr_size = intersect_addr - curr_addr;
2509 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2510 ubuf + bytes_written,
2511 curr_size,
2512 error);
2513 bytes_written += curr_bytes_written;
2514 if (curr_bytes_written != curr_size)
2515 {
2516 // We weren't able to write all of the requested bytes, we
2517 // are done looping and will return the number of bytes that
2518 // we have written so far.
2519 break;
2520 }
2521 }
2522
2523 // Now write any bytes that would cover up any software breakpoints
2524 // directly into the breakpoint opcode buffer
2525 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2526 bytes_written += intersect_size;
2527 }
2528
2529 // Write any remaining bytes after the last breakpoint if we have any left
2530 if (bytes_written < size)
2531 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2532 ubuf + bytes_written,
2533 size - bytes_written,
2534 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002535
Chris Lattner24943d22010-06-08 16:52:24 +00002536 return bytes_written;
2537}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002538
2539size_t
Greg Clayton36da2aa2013-01-25 18:06:21 +00002540Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonc0fa5332011-05-22 22:46:53 +00002541{
2542 if (byte_size == UINT32_MAX)
2543 byte_size = scalar.GetByteSize();
2544 if (byte_size > 0)
2545 {
2546 uint8_t buf[32];
2547 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2548 if (mem_size > 0)
2549 return WriteMemory(addr, buf, mem_size, error);
2550 else
2551 error.SetErrorString ("failed to get scalar as memory data");
2552 }
2553 else
2554 {
2555 error.SetErrorString ("invalid scalar value");
2556 }
2557 return 0;
2558}
2559
2560size_t
2561Process::ReadScalarIntegerFromMemory (addr_t addr,
2562 uint32_t byte_size,
2563 bool is_signed,
2564 Scalar &scalar,
2565 Error &error)
2566{
2567 uint64_t uval;
2568
2569 if (byte_size <= sizeof(uval))
2570 {
2571 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2572 if (bytes_read == byte_size)
2573 {
2574 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Clayton36da2aa2013-01-25 18:06:21 +00002575 lldb::offset_t offset = 0;
Greg Claytonc0fa5332011-05-22 22:46:53 +00002576 if (byte_size <= 4)
2577 scalar = data.GetMaxU32 (&offset, byte_size);
2578 else
2579 scalar = data.GetMaxU64 (&offset, byte_size);
2580
2581 if (is_signed)
2582 scalar.SignExtend(byte_size * 8);
2583 return bytes_read;
2584 }
2585 }
2586 else
2587 {
2588 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2589 }
2590 return 0;
2591}
2592
Greg Clayton613b8732011-05-17 03:37:42 +00002593#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002594addr_t
2595Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2596{
Jim Inghame6bd1422011-06-20 17:32:44 +00002597 if (GetPrivateState() != eStateStopped)
2598 return LLDB_INVALID_ADDRESS;
2599
Greg Clayton613b8732011-05-17 03:37:42 +00002600#if defined (USE_ALLOCATE_MEMORY_CACHE)
2601 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2602#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002603 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2604 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2605 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002606 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 +00002607 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002608 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002609 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002610 m_mod_id.GetStopID(),
2611 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002612 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002613#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002614}
2615
Sean Callanan6cf6c472011-09-20 23:01:51 +00002616bool
2617Process::CanJIT ()
2618{
Sean Callanan04200f62012-02-14 22:50:38 +00002619 if (m_can_jit == eCanJITDontKnow)
2620 {
2621 Error err;
2622
2623 uint64_t allocated_memory = AllocateMemory(8,
2624 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2625 err);
2626
2627 if (err.Success())
2628 m_can_jit = eCanJITYes;
2629 else
2630 m_can_jit = eCanJITNo;
2631
2632 DeallocateMemory (allocated_memory);
2633 }
2634
Sean Callanan6cf6c472011-09-20 23:01:51 +00002635 return m_can_jit == eCanJITYes;
2636}
2637
2638void
2639Process::SetCanJIT (bool can_jit)
2640{
2641 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2642}
2643
Chris Lattner24943d22010-06-08 16:52:24 +00002644Error
2645Process::DeallocateMemory (addr_t ptr)
2646{
Greg Clayton613b8732011-05-17 03:37:42 +00002647 Error error;
2648#if defined (USE_ALLOCATE_MEMORY_CACHE)
2649 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2650 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002651 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Clayton613b8732011-05-17 03:37:42 +00002652 }
2653#else
2654 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002655
2656 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2657 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002658 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 +00002659 ptr,
2660 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002661 m_mod_id.GetStopID(),
2662 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002663#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002664 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002665}
2666
Han Ming Ong2529aa32012-11-17 00:33:14 +00002667
Greg Claytonb5a8f142012-02-05 02:38:54 +00002668ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002669Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton2ddb2b82013-02-01 21:38:35 +00002670 lldb::addr_t header_addr)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002671{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002672 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002673 if (module_sp)
2674 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002675 Error error;
2676 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2677 if (objfile)
Greg Clayton6c5438b2012-02-24 21:55:59 +00002678 return module_sp;
Greg Claytonb5a8f142012-02-05 02:38:54 +00002679 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002680 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002681}
Chris Lattner24943d22010-06-08 16:52:24 +00002682
2683Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002684Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002685{
2686 Error error;
2687 error.SetErrorString("watchpoints are not supported");
2688 return error;
2689}
2690
2691Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002692Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002693{
2694 Error error;
2695 error.SetErrorString("watchpoints are not supported");
2696 return error;
2697}
2698
2699StateType
2700Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2701{
2702 StateType state;
2703 // Now wait for the process to launch and return control to us, and then
2704 // call DidLaunch:
2705 while (1)
2706 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002707 event_sp.reset();
2708 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2709
Greg Clayton20206082011-11-17 01:23:07 +00002710 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002711 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002712
2713 // If state is invalid, then we timed out
2714 if (state == eStateInvalid)
2715 break;
2716
2717 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002718 HandlePrivateEvent (event_sp);
2719 }
2720 return state;
2721}
2722
2723Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002724Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002725{
2726 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002727 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002728 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002729 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002730 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002731
Greg Clayton5beb99d2011-08-11 02:48:45 +00002732 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002733 if (exe_module)
2734 {
Greg Clayton180546b2011-04-30 01:09:13 +00002735 char local_exec_file_path[PATH_MAX];
2736 char platform_exec_file_path[PATH_MAX];
2737 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2738 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002739 if (exe_module->GetFileSpec().Exists())
2740 {
Greg Claytona2f74232011-02-24 22:24:29 +00002741 if (PrivateStateThreadIsValid ())
2742 PausePrivateStateThread ();
2743
Chris Lattner24943d22010-06-08 16:52:24 +00002744 error = WillLaunch (exe_module);
2745 if (error.Success())
2746 {
Greg Claytond8c62532010-10-07 04:19:01 +00002747 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002748 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002749
Greg Clayton777c6b72012-09-04 20:29:05 +00002750 if (m_run_lock.WriteTryLock())
2751 {
2752 // Now launch using these arguments.
2753 error = DoLaunch (exe_module, launch_info);
2754 }
2755 else
2756 {
2757 // This shouldn't happen
2758 error.SetErrorString("failed to acquire process run lock");
2759 }
Chris Lattner24943d22010-06-08 16:52:24 +00002760
2761 if (error.Fail())
2762 {
2763 if (GetID() != LLDB_INVALID_PROCESS_ID)
2764 {
2765 SetID (LLDB_INVALID_PROCESS_ID);
2766 const char *error_string = error.AsCString();
2767 if (error_string == NULL)
2768 error_string = "launch failed";
2769 SetExitStatus (-1, error_string);
2770 }
2771 }
2772 else
2773 {
2774 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002775 TimeValue timeout_time;
2776 timeout_time = TimeValue::Now();
2777 timeout_time.OffsetWithSeconds(10);
2778 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002779
Greg Clayton49859592011-06-22 01:42:17 +00002780 if (state == eStateInvalid || event_sp.get() == NULL)
2781 {
2782 // We were able to launch the process, but we failed to
2783 // catch the initial stop.
2784 SetExitStatus (0, "failed to catch stop after launch");
2785 Destroy();
2786 }
2787 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002788 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002789
Chris Lattner24943d22010-06-08 16:52:24 +00002790 DidLaunch ();
2791
Greg Clayton9ce95382012-02-13 23:10:39 +00002792 DynamicLoader *dyld = GetDynamicLoader ();
2793 if (dyld)
2794 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002795
Greg Clayton37f962e2011-08-22 02:49:39 +00002796 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002797 // This delays passing the stopped event to listeners till DidLaunch gets
2798 // a chance to complete...
2799 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002800
2801 if (PrivateStateThreadIsValid ())
2802 ResumePrivateStateThread ();
2803 else
2804 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002805 }
2806 else if (state == eStateExited)
2807 {
2808 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2809 // not likely to work, and return an invalid pid.
2810 HandlePrivateEvent (event_sp);
2811 }
2812 }
2813 }
2814 }
2815 else
2816 {
Greg Clayton9c236732011-10-26 00:56:27 +00002817 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002818 }
2819 }
2820 return error;
2821}
2822
Greg Clayton46c9a352012-02-09 06:16:32 +00002823
2824Error
2825Process::LoadCore ()
2826{
2827 Error error = DoLoadCore();
2828 if (error.Success())
2829 {
2830 if (PrivateStateThreadIsValid ())
2831 ResumePrivateStateThread ();
2832 else
2833 StartPrivateStateThread ();
2834
Greg Clayton9ce95382012-02-13 23:10:39 +00002835 DynamicLoader *dyld = GetDynamicLoader ();
2836 if (dyld)
2837 dyld->DidAttach();
2838
2839 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002840 // We successfully loaded a core file, now pretend we stopped so we can
2841 // show all of the threads in the core file and explore the crashed
2842 // state.
2843 SetPrivateState (eStateStopped);
2844
2845 }
2846 return error;
2847}
2848
Greg Clayton9ce95382012-02-13 23:10:39 +00002849DynamicLoader *
2850Process::GetDynamicLoader ()
2851{
2852 if (m_dyld_ap.get() == NULL)
2853 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2854 return m_dyld_ap.get();
2855}
Greg Clayton46c9a352012-02-09 06:16:32 +00002856
2857
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002858Process::NextEventAction::EventActionResult
2859Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002860{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002861 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2862 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002863 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002864 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002865 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002866 return eEventActionRetry;
2867
2868 case eStateStopped:
2869 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002870 {
2871 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002872 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002873 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2874 if (m_exec_count > 0)
2875 {
2876 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002877 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002878 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002879 return eEventActionRetry;
2880 }
2881 else
2882 {
2883 m_process->CompleteAttach ();
2884 return eEventActionSuccess;
2885 }
2886 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002887 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002888
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002889 default:
2890 case eStateExited:
2891 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002892 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002893 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002894
2895 m_exit_string.assign ("No valid Process");
2896 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002897}
Chris Lattner24943d22010-06-08 16:52:24 +00002898
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002899Process::NextEventAction::EventActionResult
2900Process::AttachCompletionHandler::HandleBeingInterrupted()
2901{
2902 return eEventActionSuccess;
2903}
2904
2905const char *
2906Process::AttachCompletionHandler::GetExitString ()
2907{
2908 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002909}
2910
2911Error
Greg Clayton527154d2011-11-15 03:53:30 +00002912Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002913{
Chris Lattner24943d22010-06-08 16:52:24 +00002914 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002915 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002916 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002917 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002918
Greg Clayton527154d2011-11-15 03:53:30 +00002919 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002920 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002921 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002922 {
Greg Clayton527154d2011-11-15 03:53:30 +00002923 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002924
Greg Clayton527154d2011-11-15 03:53:30 +00002925 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002926 {
Greg Clayton527154d2011-11-15 03:53:30 +00002927 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2928
2929 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002930 {
Greg Clayton527154d2011-11-15 03:53:30 +00002931 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2932 if (error.Success())
2933 {
Greg Claytond34a3b22012-10-12 16:10:12 +00002934 if (m_run_lock.WriteTryLock())
2935 {
2936 m_should_detach = true;
2937 SetPublicState (eStateAttaching);
2938 // Now attach using these arguments.
2939 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2940 }
2941 else
2942 {
2943 // This shouldn't happen
2944 error.SetErrorString("failed to acquire process run lock");
2945 }
Greg Claytonffa43a62011-11-17 04:46:02 +00002946
Greg Clayton527154d2011-11-15 03:53:30 +00002947 if (error.Fail())
2948 {
2949 if (GetID() != LLDB_INVALID_PROCESS_ID)
2950 {
2951 SetID (LLDB_INVALID_PROCESS_ID);
2952 if (error.AsCString() == NULL)
2953 error.SetErrorString("attach failed");
2954
2955 SetExitStatus(-1, error.AsCString());
2956 }
2957 }
2958 else
2959 {
2960 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2961 StartPrivateStateThread();
2962 }
2963 return error;
2964 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002965 }
Greg Clayton527154d2011-11-15 03:53:30 +00002966 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002967 {
Greg Clayton527154d2011-11-15 03:53:30 +00002968 ProcessInstanceInfoList process_infos;
2969 PlatformSP platform_sp (m_target.GetPlatform ());
2970
2971 if (platform_sp)
2972 {
2973 ProcessInstanceInfoMatch match_info;
2974 match_info.GetProcessInfo() = attach_info;
2975 match_info.SetNameMatchType (eNameMatchEquals);
2976 platform_sp->FindProcesses (match_info, process_infos);
2977 const uint32_t num_matches = process_infos.GetSize();
2978 if (num_matches == 1)
2979 {
2980 attach_pid = process_infos.GetProcessIDAtIndex(0);
2981 // Fall through and attach using the above process ID
2982 }
2983 else
2984 {
2985 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2986 if (num_matches > 1)
2987 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2988 else
2989 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2990 }
2991 }
2992 else
2993 {
2994 error.SetErrorString ("invalid platform, can't find processes by name");
2995 return error;
2996 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002997 }
Chris Lattner24943d22010-06-08 16:52:24 +00002998 }
2999 else
Greg Clayton527154d2011-11-15 03:53:30 +00003000 {
3001 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003002 }
3003 }
Greg Clayton527154d2011-11-15 03:53:30 +00003004
3005 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003006 {
Greg Clayton527154d2011-11-15 03:53:30 +00003007 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003008 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00003009 {
Greg Clayton527154d2011-11-15 03:53:30 +00003010
Greg Claytond34a3b22012-10-12 16:10:12 +00003011 if (m_run_lock.WriteTryLock())
3012 {
3013 // Now attach using these arguments.
3014 m_should_detach = true;
3015 SetPublicState (eStateAttaching);
3016 error = DoAttachToProcessWithID (attach_pid, attach_info);
3017 }
3018 else
3019 {
3020 // This shouldn't happen
3021 error.SetErrorString("failed to acquire process run lock");
3022 }
3023
Greg Clayton527154d2011-11-15 03:53:30 +00003024 if (error.Success())
3025 {
3026
3027 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3028 StartPrivateStateThread();
3029 }
3030 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003031 {
3032 if (GetID() != LLDB_INVALID_PROCESS_ID)
3033 {
3034 SetID (LLDB_INVALID_PROCESS_ID);
3035 const char *error_string = error.AsCString();
3036 if (error_string == NULL)
3037 error_string = "attach failed";
3038
3039 SetExitStatus(-1, error_string);
3040 }
3041 }
Chris Lattner24943d22010-06-08 16:52:24 +00003042 }
3043 }
3044 return error;
3045}
3046
Greg Clayton75c703d2011-02-16 04:46:07 +00003047void
3048Process::CompleteAttach ()
3049{
3050 // Let the process subclass figure out at much as it can about the process
3051 // before we go looking for a dynamic loader plug-in.
3052 DidAttach();
3053
Jim Ingham0d7f7772011-09-15 01:10:17 +00003054 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3055 // the same as the one we've already set, switch architectures.
3056 PlatformSP platform_sp (m_target.GetPlatform ());
3057 assert (platform_sp.get());
3058 if (platform_sp)
3059 {
Greg Claytonb170aee2012-05-08 01:45:38 +00003060 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Claytonaad2b0f2013-01-11 20:49:54 +00003061 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Claytonb170aee2012-05-08 01:45:38 +00003062 {
3063 ArchSpec platform_arch;
3064 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3065 if (platform_sp)
3066 {
3067 m_target.SetPlatform (platform_sp);
3068 m_target.SetArchitecture(platform_arch);
3069 }
3070 }
3071 else
3072 {
3073 ProcessInstanceInfo process_info;
3074 platform_sp->GetProcessInfo (GetID(), process_info);
3075 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callanan40e278c2012-12-13 22:07:14 +00003076 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Claytonb170aee2012-05-08 01:45:38 +00003077 m_target.SetArchitecture (process_arch);
3078 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00003079 }
3080
3081 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00003082 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00003083 DynamicLoader *dyld = GetDynamicLoader ();
3084 if (dyld)
3085 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00003086
Greg Clayton37f962e2011-08-22 02:49:39 +00003087 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00003088 // Figure out which one is the executable, and set that in our target:
Enrico Granata146d9522012-11-08 02:22:02 +00003089 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham93367902012-05-30 02:19:25 +00003090 Mutex::Locker modules_locker(target_modules.GetMutex());
3091 size_t num_modules = target_modules.GetSize();
3092 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003093
Greg Clayton75c703d2011-02-16 04:46:07 +00003094 for (int i = 0; i < num_modules; i++)
3095 {
Jim Ingham93367902012-05-30 02:19:25 +00003096 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00003097 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00003098 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00003099 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00003100 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003101 break;
3102 }
3103 }
Jim Ingham93367902012-05-30 02:19:25 +00003104 if (new_executable_module_sp)
3105 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00003106}
3107
Chris Lattner24943d22010-06-08 16:52:24 +00003108Error
Jason Molendafac2e622012-09-29 04:02:01 +00003109Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00003110{
Greg Claytone71e2582011-02-04 01:58:07 +00003111 m_abi_sp.reset();
3112 m_process_input_reader.reset();
3113
3114 // Find the process and its architecture. Make sure it matches the architecture
3115 // of the current Target, and if not adjust it.
3116
Jason Molendafac2e622012-09-29 04:02:01 +00003117 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00003118 if (error.Success())
3119 {
Greg Claytona2f74232011-02-24 22:24:29 +00003120 if (GetID() != LLDB_INVALID_PROCESS_ID)
3121 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00003122 EventSP event_sp;
3123 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3124
3125 if (state == eStateStopped || state == eStateCrashed)
3126 {
3127 // If we attached and actually have a process on the other end, then
3128 // this ended up being the equivalent of an attach.
3129 CompleteAttach ();
3130
3131 // This delays passing the stopped event to listeners till
3132 // CompleteAttach gets a chance to complete...
3133 HandlePrivateEvent (event_sp);
3134
3135 }
Greg Claytona2f74232011-02-24 22:24:29 +00003136 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00003137
3138 if (PrivateStateThreadIsValid ())
3139 ResumePrivateStateThread ();
3140 else
3141 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00003142 }
3143 return error;
3144}
3145
3146
3147Error
Jim Ingham027aaa72012-04-19 01:40:33 +00003148Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00003149{
Jim Ingham89e248f2013-02-09 01:29:05 +00003150 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00003151 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003152 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00003153 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00003154 StateAsCString(m_public_state.GetValue()),
3155 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00003156
3157 Error error (WillResume());
3158 // Tell the process it is about to resume before the thread list
3159 if (error.Success())
3160 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003161 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003162 // can let all of our threads know that they are about to be
3163 // resumed. Threads will each be called with
3164 // Thread::WillResume(StateType) where StateType contains the state
3165 // that they are supposed to have when the process is resumed
3166 // (suspended/running/stepping). Threads should also check
3167 // their resume signal in lldb::Thread::GetResumeSignal()
3168 // to see if they are suppoed to start back up with a signal.
3169 if (m_thread_list.WillResume())
3170 {
Jim Ingham1831e782012-04-07 00:00:41 +00003171 // Last thing, do the PreResumeActions.
3172 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003173 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003174 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham1831e782012-04-07 00:00:41 +00003175 }
3176 else
3177 {
3178 m_mod_id.BumpResumeID();
3179 error = DoResume();
3180 if (error.Success())
3181 {
3182 DidResume();
3183 m_thread_list.DidResume();
3184 if (log)
3185 log->Printf ("Process thinks the process has resumed.");
3186 }
Chris Lattner24943d22010-06-08 16:52:24 +00003187 }
3188 }
3189 else
3190 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003191 // Somebody wanted to run without running. So generate a continue & a stopped event,
3192 // and let the world handle them.
3193 if (log)
3194 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3195
3196 SetPrivateState(eStateRunning);
3197 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003198 }
3199 }
Jim Inghamac959662011-01-24 06:34:17 +00003200 else if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003201 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003202 return error;
3203}
3204
3205Error
3206Process::Halt ()
3207{
Jim Ingham43892562012-06-06 00:29:30 +00003208 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3209 // we could just straightaway get another event. It just narrows the window...
3210 m_currently_handling_event.WaitForValueEqualTo(false);
3211
3212
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003213 // Pause our private state thread so we can ensure no one else eats
3214 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003215 Listener halt_listener ("lldb.process.halt_listener");
3216 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003217
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003218 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003219 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003220
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003221 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003222 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003223
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003224 bool caused_stop = false;
3225
3226 // Ask the process subclass to actually halt our process
3227 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003228 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003229 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003230 if (m_public_state.GetValue() == eStateAttaching)
3231 {
3232 SetExitStatus(SIGKILL, "Cancelled async attach.");
3233 Destroy ();
3234 }
3235 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003236 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003237 // If "caused_stop" is true, then DoHalt stopped the process. If
3238 // "caused_stop" is false, the process was already stopped.
3239 // If the DoHalt caused the process to stop, then we want to catch
3240 // this event and set the interrupted bool to true before we pass
3241 // this along so clients know that the process was interrupted by
3242 // a halt command.
3243 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003244 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003245 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003246 TimeValue timeout_time;
3247 timeout_time = TimeValue::Now();
3248 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003249 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3250 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003251
Jim Inghamf9f40c22011-02-08 05:20:59 +00003252 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003253 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003254 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003255 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003256 }
3257 else
3258 {
Greg Clayton20206082011-11-17 01:23:07 +00003259 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003260 {
3261 // We caused the process to interrupt itself, so mark this
3262 // as such in the stop event so clients can tell an interrupted
3263 // process from a natural stop
3264 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3265 }
3266 else
3267 {
3268 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3269 if (log)
3270 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3271 error.SetErrorString ("Did not get stopped event after halt.");
3272 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003273 }
3274 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003275 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003276 }
3277 }
Chris Lattner24943d22010-06-08 16:52:24 +00003278 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003279 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003280 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003281
3282 // Post any event we might have consumed. If all goes well, we will have
3283 // stopped the process, intercepted the event and set the interrupted
3284 // bool in the event. Post it to the private event queue and that will end up
3285 // correctly setting the state.
3286 if (event_sp)
3287 m_private_state_broadcaster.BroadcastEvent(event_sp);
3288
Chris Lattner24943d22010-06-08 16:52:24 +00003289 return error;
3290}
3291
3292Error
3293Process::Detach ()
3294{
3295 Error error (WillDetach());
3296
3297 if (error.Success())
3298 {
3299 DisableAllBreakpointSites();
3300 error = DoDetach();
3301 if (error.Success())
3302 {
3303 DidDetach();
3304 StopPrivateStateThread();
3305 }
3306 }
3307 return error;
3308}
3309
3310Error
3311Process::Destroy ()
3312{
3313 Error error (WillDestroy());
3314 if (error.Success())
3315 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003316 EventSP exit_event_sp;
Jim Inghamf4928de2012-05-23 15:46:31 +00003317 if (m_public_state.GetValue() == eStateRunning)
3318 {
Greg Clayton38ae5b92012-09-05 00:37:58 +00003319 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003320 if (log)
3321 log->Printf("Process::Destroy() About to halt.");
Jim Inghamf4928de2012-05-23 15:46:31 +00003322 error = Halt();
3323 if (error.Success())
3324 {
3325 // Consume the halt event.
Jim Inghamf4928de2012-05-23 15:46:31 +00003326 TimeValue timeout (TimeValue::Now());
Jim Ingham43892562012-06-06 00:29:30 +00003327 timeout.OffsetWithSeconds(1);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003328 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3329 if (state != eStateExited)
3330 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3331
Jim Inghamf4928de2012-05-23 15:46:31 +00003332 if (state != eStateStopped)
3333 {
Jim Inghamf4928de2012-05-23 15:46:31 +00003334 if (log)
3335 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Ingham43892562012-06-06 00:29:30 +00003336 // If we really couldn't stop the process then we should just error out here, but if the
3337 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3338 StateType private_state = m_private_state.GetValue();
3339 if (private_state != eStateStopped && private_state != eStateExited)
3340 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003341 // If we exited when we were waiting for a process to stop, then
3342 // forward the event here so we don't lose the event
Jim Ingham43892562012-06-06 00:29:30 +00003343 return error;
3344 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003345 }
3346 }
3347 else
3348 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003349 if (log)
3350 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3351 return error;
Jim Inghamf4928de2012-05-23 15:46:31 +00003352 }
3353 }
Jim Ingham43892562012-06-06 00:29:30 +00003354
3355 if (m_public_state.GetValue() != eStateRunning)
3356 {
3357 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3358 // kill it, we don't want it hitting a breakpoint...
3359 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3360 // we're not going to have much luck doing this now.
3361 m_thread_list.DiscardThreadPlans();
3362 DisableAllBreakpointSites();
3363 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003364
Chris Lattner24943d22010-06-08 16:52:24 +00003365 error = DoDestroy();
3366 if (error.Success())
3367 {
3368 DidDestroy();
3369 StopPrivateStateThread();
3370 }
Caroline Tice861efb32010-11-16 05:07:41 +00003371 m_stdio_communication.StopReadThread();
3372 m_stdio_communication.Disconnect();
3373 if (m_process_input_reader && m_process_input_reader->IsActive())
3374 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3375 if (m_process_input_reader)
3376 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003377
3378 // If we exited when we were waiting for a process to stop, then
3379 // forward the event here so we don't lose the event
3380 if (exit_event_sp)
3381 {
3382 // Directly broadcast our exited event because we shut down our
3383 // private state thread above
3384 BroadcastEvent(exit_event_sp);
3385 }
3386
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003387 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3388 // the last events through the event system, in which case we might strand the write lock. Unlock
3389 // it here so when we do to tear down the process we don't get an error destroying the lock.
3390 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003391 }
3392 return error;
3393}
3394
3395Error
3396Process::Signal (int signal)
3397{
3398 Error error (WillSignal());
3399 if (error.Success())
3400 {
3401 error = DoSignal(signal);
3402 if (error.Success())
3403 DidSignal();
3404 }
3405 return error;
3406}
3407
Greg Clayton395fc332011-02-15 21:59:32 +00003408lldb::ByteOrder
3409Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003410{
Greg Clayton395fc332011-02-15 21:59:32 +00003411 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003412}
3413
3414uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003415Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003416{
Greg Clayton395fc332011-02-15 21:59:32 +00003417 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003418}
3419
Greg Clayton395fc332011-02-15 21:59:32 +00003420
Chris Lattner24943d22010-06-08 16:52:24 +00003421bool
3422Process::ShouldBroadcastEvent (Event *event_ptr)
3423{
3424 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3425 bool return_value = true;
Jim Ingham89e248f2013-02-09 01:29:05 +00003426 LogSP log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
3427
Chris Lattner24943d22010-06-08 16:52:24 +00003428 switch (state)
3429 {
Greg Claytone71e2582011-02-04 01:58:07 +00003430 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003431 case eStateAttaching:
3432 case eStateLaunching:
3433 case eStateDetached:
3434 case eStateExited:
3435 case eStateUnloaded:
3436 // These events indicate changes in the state of the debugging session, always report them.
3437 return_value = true;
3438 break;
3439 case eStateInvalid:
3440 // We stopped for no apparent reason, don't report it.
3441 return_value = false;
3442 break;
3443 case eStateRunning:
3444 case eStateStepping:
3445 // If we've started the target running, we handle the cases where we
3446 // are already running and where there is a transition from stopped to
3447 // running differently.
3448 // running -> running: Automatically suppress extra running events
3449 // stopped -> running: Report except when there is one or more no votes
3450 // and no yes votes.
3451 SynchronouslyNotifyStateChanged (state);
Jim Ingham89e248f2013-02-09 01:29:05 +00003452 switch (m_last_broadcast_state)
Chris Lattner24943d22010-06-08 16:52:24 +00003453 {
3454 case eStateRunning:
3455 case eStateStepping:
3456 // We always suppress multiple runnings with no PUBLIC stop in between.
3457 return_value = false;
3458 break;
3459 default:
3460 // TODO: make this work correctly. For now always report
3461 // run if we aren't running so we don't miss any runnning
3462 // events. If I run the lldb/test/thread/a.out file and
3463 // break at main.cpp:58, run and hit the breakpoints on
3464 // multiple threads, then somehow during the stepping over
3465 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003466
3467 // This is a transition from stop to run.
3468 switch (m_thread_list.ShouldReportRun (event_ptr))
3469 {
3470 case eVoteYes:
3471 case eVoteNoOpinion:
3472 return_value = true;
3473 break;
3474 case eVoteNo:
3475 return_value = false;
3476 break;
3477 }
3478 break;
3479 }
3480 break;
3481 case eStateStopped:
3482 case eStateCrashed:
3483 case eStateSuspended:
3484 {
3485 // We've stopped. First see if we're going to restart the target.
3486 // If we are going to stop, then we always broadcast the event.
3487 // 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 +00003488 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003489
3490 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003491 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003492 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003493 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003494 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3495 event_ptr,
3496 StateAsCString(state));
3497 return_value = true;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003498 }
3499 else
3500 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003501 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3502 // Asking the thread list is also not likely to go well, since we are running again.
3503 // So in that case just report the event.
3504
3505 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3506 bool should_resume = false;
3507 if (!was_restarted)
3508 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
3509 if (was_restarted || should_resume)
Chris Lattner24943d22010-06-08 16:52:24 +00003510 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003511 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3512 if (log)
3513 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3514 should_resume,
3515 StateAsCString(state),
3516 was_restarted,
3517 stop_vote);
3518
3519 switch (stop_vote)
Chris Lattner24943d22010-06-08 16:52:24 +00003520 {
3521 case eVoteYes:
Jim Ingham89e248f2013-02-09 01:29:05 +00003522 return_value = true;
3523 break;
Chris Lattner24943d22010-06-08 16:52:24 +00003524 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003525 case eVoteNo:
3526 return_value = false;
3527 break;
3528 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003529
Jim Ingham8290bba2012-09-05 21:13:56 +00003530 if (!was_restarted)
Jim Ingham89e248f2013-02-09 01:29:05 +00003531 {
3532 if (log)
3533 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3534 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Ingham8290bba2012-09-05 21:13:56 +00003535 PrivateResume ();
Jim Ingham89e248f2013-02-09 01:29:05 +00003536 }
3537
Chris Lattner24943d22010-06-08 16:52:24 +00003538 }
3539 else
3540 {
3541 return_value = true;
3542 SynchronouslyNotifyStateChanged (state);
3543 }
3544 }
3545 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003546 break;
Chris Lattner24943d22010-06-08 16:52:24 +00003547 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003548
3549 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3550 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3551 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3552 // because the PublicState reflects the last event pulled off the queue, and there may be several
3553 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3554 // yet. m_last_broadcast_state gets updated here.
3555
3556 if (return_value)
3557 m_last_broadcast_state = state;
3558
Chris Lattner24943d22010-06-08 16:52:24 +00003559 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003560 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3561 event_ptr,
3562 StateAsCString(state),
3563 StateAsCString(m_last_broadcast_state),
3564 return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003565 return return_value;
3566}
3567
Chris Lattner24943d22010-06-08 16:52:24 +00003568
3569bool
Jim Ingham1831e782012-04-07 00:00:41 +00003570Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003571{
Greg Claytone005f2c2010-11-06 01:53:30 +00003572 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003573
Greg Claytonb72d0f02011-04-12 05:54:46 +00003574 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003575 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003576 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3577
Jim Ingham1831e782012-04-07 00:00:41 +00003578 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003579 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003580
3581 // Create a thread that watches our internal state and controls which
3582 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003583 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003584 if (already_running)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003585 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham1831e782012-04-07 00:00:41 +00003586 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003587 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003588
3589 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003590 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003591 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3592 if (success)
3593 {
3594 ResumePrivateStateThread();
3595 return true;
3596 }
3597 else
3598 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003599}
3600
3601void
3602Process::PausePrivateStateThread ()
3603{
3604 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3605}
3606
3607void
3608Process::ResumePrivateStateThread ()
3609{
3610 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3611}
3612
3613void
3614Process::StopPrivateStateThread ()
3615{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003616 if (PrivateStateThreadIsValid ())
3617 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003618 else
3619 {
3620 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3621 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003622 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003623 }
Chris Lattner24943d22010-06-08 16:52:24 +00003624}
3625
3626void
3627Process::ControlPrivateStateThread (uint32_t signal)
3628{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003629 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003630
3631 assert (signal == eBroadcastInternalStateControlStop ||
3632 signal == eBroadcastInternalStateControlPause ||
3633 signal == eBroadcastInternalStateControlResume);
3634
3635 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003636 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003637
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003638 // Signal the private state thread. First we should copy this is case the
3639 // thread starts exiting since the private state thread will NULL this out
3640 // when it exits
3641 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003642 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003643 {
3644 TimeValue timeout_time;
3645 bool timed_out;
3646
3647 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3648
3649 timeout_time = TimeValue::Now();
3650 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003651 if (log)
3652 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003653 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3654 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3655
3656 if (signal == eBroadcastInternalStateControlStop)
3657 {
3658 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003659 {
3660 Error error;
3661 Host::ThreadCancel (private_state_thread, &error);
3662 if (log)
3663 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3664 }
3665 else
3666 {
3667 if (log)
3668 log->Printf ("The control event killed the private state thread without having to cancel.");
3669 }
Chris Lattner24943d22010-06-08 16:52:24 +00003670
3671 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003672 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003673 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003674 }
3675 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003676 else
3677 {
3678 if (log)
3679 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3680 }
Chris Lattner24943d22010-06-08 16:52:24 +00003681}
3682
3683void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003684Process::SendAsyncInterrupt ()
3685{
3686 if (PrivateStateThreadIsValid())
3687 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3688 else
3689 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3690}
3691
3692void
Chris Lattner24943d22010-06-08 16:52:24 +00003693Process::HandlePrivateEvent (EventSP &event_sp)
3694{
Greg Claytone005f2c2010-11-06 01:53:30 +00003695 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003696 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003697
Greg Clayton68ca8232011-01-25 02:58:48 +00003698 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003699
3700 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003701 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003702 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003703 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham89e248f2013-02-09 01:29:05 +00003704 if (log)
3705 log->Printf ("Ran next event action, result was %d.", action_result);
3706
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003707 switch (action_result)
3708 {
3709 case NextEventAction::eEventActionSuccess:
3710 SetNextEventAction(NULL);
3711 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003712
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003713 case NextEventAction::eEventActionRetry:
3714 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003715
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003716 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003717 // Handle Exiting Here. If we already got an exited event,
3718 // we should just propagate it. Otherwise, swallow this event,
3719 // and set our state to exit so the next event will kill us.
3720 if (new_state != eStateExited)
3721 {
3722 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003723 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003724 SetNextEventAction(NULL);
3725 return;
3726 }
3727 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003728 break;
3729 }
3730 }
3731
Chris Lattner24943d22010-06-08 16:52:24 +00003732 // See if we should broadcast this state to external clients?
3733 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003734
3735 if (should_broadcast)
3736 {
3737 if (log)
3738 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003739 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003740 __FUNCTION__,
3741 GetID(),
3742 StateAsCString(new_state),
3743 StateAsCString (GetState ()),
3744 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003745 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003746 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003747 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003748 PushProcessInputReader ();
3749 else
3750 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003751
Chris Lattner24943d22010-06-08 16:52:24 +00003752 BroadcastEvent (event_sp);
3753 }
3754 else
3755 {
3756 if (log)
3757 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003758 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003759 __FUNCTION__,
3760 GetID(),
3761 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003762 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003763 }
3764 }
Jim Ingham43892562012-06-06 00:29:30 +00003765 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003766}
3767
3768void *
3769Process::PrivateStateThread (void *arg)
3770{
3771 Process *proc = static_cast<Process*> (arg);
3772 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003773 return result;
3774}
3775
3776void *
3777Process::RunPrivateStateThread ()
3778{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003779 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003780 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003781
Greg Claytone005f2c2010-11-06 01:53:30 +00003782 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003783 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003784 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003785
3786 bool exit_now = false;
3787 while (!exit_now)
3788 {
3789 EventSP event_sp;
3790 WaitForEventsPrivate (NULL, event_sp, control_only);
3791 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3792 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003793 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003794 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 +00003795
Chris Lattner24943d22010-06-08 16:52:24 +00003796 switch (event_sp->GetType())
3797 {
3798 case eBroadcastInternalStateControlStop:
3799 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003800 break; // doing any internal state managment below
3801
3802 case eBroadcastInternalStateControlPause:
3803 control_only = true;
3804 break;
3805
3806 case eBroadcastInternalStateControlResume:
3807 control_only = false;
3808 break;
3809 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003810
Chris Lattner24943d22010-06-08 16:52:24 +00003811 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003812 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003813 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003814 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3815 {
3816 if (m_public_state.GetValue() == eStateAttaching)
3817 {
3818 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003819 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 +00003820 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3821 }
3822 else
3823 {
3824 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003825 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00003826 Halt();
3827 }
3828 continue;
3829 }
Chris Lattner24943d22010-06-08 16:52:24 +00003830
3831 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3832
3833 if (internal_state != eStateInvalid)
3834 {
3835 HandlePrivateEvent (event_sp);
3836 }
3837
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003838 if (internal_state == eStateInvalid ||
3839 internal_state == eStateExited ||
3840 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003841 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003842 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003843 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 +00003844
Chris Lattner24943d22010-06-08 16:52:24 +00003845 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003846 }
Chris Lattner24943d22010-06-08 16:52:24 +00003847 }
3848
Caroline Tice926060e2010-10-29 21:48:37 +00003849 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003850 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003851 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003852
Greg Claytona4881d02011-01-22 07:12:45 +00003853 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3854 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003855 return NULL;
3856}
3857
Chris Lattner24943d22010-06-08 16:52:24 +00003858//------------------------------------------------------------------
3859// Process Event Data
3860//------------------------------------------------------------------
3861
3862Process::ProcessEventData::ProcessEventData () :
3863 EventData (),
3864 m_process_sp (),
3865 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003866 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003867 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003868 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003869{
3870}
3871
3872Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3873 EventData (),
3874 m_process_sp (process_sp),
3875 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003876 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003877 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003878 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003879{
3880}
3881
3882Process::ProcessEventData::~ProcessEventData()
3883{
3884}
3885
3886const ConstString &
3887Process::ProcessEventData::GetFlavorString ()
3888{
3889 static ConstString g_flavor ("Process::ProcessEventData");
3890 return g_flavor;
3891}
3892
3893const ConstString &
3894Process::ProcessEventData::GetFlavor () const
3895{
3896 return ProcessEventData::GetFlavorString ();
3897}
3898
Chris Lattner24943d22010-06-08 16:52:24 +00003899void
3900Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3901{
3902 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003903 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3904 // the public event queue, then other times when we're pretending that this is where we stopped at the
3905 // end of expression evaluation. m_update_state is used to distinguish these
3906 // three cases; it is 0 when we're just pulling it off for private handling,
3907 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003908
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003909 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003910 return;
Jim Ingham89e248f2013-02-09 01:29:05 +00003911
Chris Lattner24943d22010-06-08 16:52:24 +00003912 m_process_sp->SetPublicState (m_state);
3913
3914 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3915 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003916 {
3917 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003918 uint32_t num_threads = curr_thread_list.GetSize();
3919 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003920
Jim Ingham21f37ad2011-08-09 02:12:22 +00003921 // The actions might change one of the thread's stop_info's opinions about whether we should
3922 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003923
3924 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3925 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3926 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3927 // 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
3928 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003929 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003930 for (idx = 0; idx < num_threads; ++idx)
3931 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3932
Jim Inghamb6059b22012-12-13 22:24:15 +00003933 // Use this to track whether we should continue from here. We will only continue the target running if
3934 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
3935 // then it doesn't matter what the other threads say...
3936
3937 bool still_should_stop = false;
Jim Ingham21f37ad2011-08-09 02:12:22 +00003938
Chris Lattner24943d22010-06-08 16:52:24 +00003939 for (idx = 0; idx < num_threads; ++idx)
3940 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003941 curr_thread_list = m_process_sp->GetThreadList();
3942 if (curr_thread_list.GetSize() != num_threads)
3943 {
3944 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003945 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003946 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 +00003947 break;
3948 }
3949
3950 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3951
3952 if (thread_sp->GetIndexID() != thread_index_array[idx])
3953 {
3954 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003955 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003956 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003957 idx,
3958 thread_index_array[idx],
3959 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003960 break;
3961 }
3962
Jim Ingham6297a3a2010-10-20 00:39:53 +00003963 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00003964 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00003965 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003966 bool this_thread_wants_to_stop;
3967 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003968 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003969 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
3970 }
3971 else
3972 {
3973 stop_info_sp->PerformAction(event_ptr);
3974 // The stop action might restart the target. If it does, then we want to mark that in the
3975 // event so that whoever is receiving it will know to wait for the running event and reflect
3976 // that state appropriately.
3977 // We also need to stop processing actions, since they aren't expecting the target to be running.
3978
3979 // FIXME: we might have run.
3980 if (stop_info_sp->HasTargetRunSinceMe())
3981 {
3982 SetRestarted (true);
3983 break;
3984 }
3985
3986 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003987 }
Jim Inghamb6059b22012-12-13 22:24:15 +00003988
Jim Inghamb6059b22012-12-13 22:24:15 +00003989 if (still_should_stop == false)
3990 still_should_stop = this_thread_wants_to_stop;
Chris Lattner24943d22010-06-08 16:52:24 +00003991 }
3992 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003993
Jim Ingham21f37ad2011-08-09 02:12:22 +00003994
3995 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003996 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003997 if (!still_should_stop)
3998 {
3999 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00004000 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00004001 // Use the public resume method here, since this is just
4002 // extending a public resume.
Jim Ingham89e248f2013-02-09 01:29:05 +00004003 m_process_sp->PrivateResume();
Jim Ingham21f37ad2011-08-09 02:12:22 +00004004 }
4005 else
4006 {
4007 // If we didn't restart, run the Stop Hooks here:
4008 // They might also restart the target, so watch for that.
4009 m_process_sp->GetTarget().RunStopHooks();
4010 if (m_process_sp->GetPrivateState() == eStateRunning)
4011 SetRestarted(true);
4012 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00004013 }
Chris Lattner24943d22010-06-08 16:52:24 +00004014 }
4015}
4016
4017void
4018Process::ProcessEventData::Dump (Stream *s) const
4019{
4020 if (m_process_sp)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004021 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00004022
Greg Claytonb72d0f02011-04-12 05:54:46 +00004023 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00004024}
4025
4026const Process::ProcessEventData *
4027Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4028{
4029 if (event_ptr)
4030 {
4031 const EventData *event_data = event_ptr->GetData();
4032 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4033 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4034 }
4035 return NULL;
4036}
4037
4038ProcessSP
4039Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4040{
4041 ProcessSP process_sp;
4042 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4043 if (data)
4044 process_sp = data->GetProcessSP();
4045 return process_sp;
4046}
4047
4048StateType
4049Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4050{
4051 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4052 if (data == NULL)
4053 return eStateInvalid;
4054 else
4055 return data->GetState();
4056}
4057
4058bool
4059Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4060{
4061 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4062 if (data == NULL)
4063 return false;
4064 else
4065 return data->GetRestarted();
4066}
4067
4068void
4069Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4070{
4071 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4072 if (data != NULL)
4073 data->SetRestarted(new_value);
4074}
4075
Jim Ingham89e248f2013-02-09 01:29:05 +00004076size_t
4077Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4078{
4079 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4080 if (data != NULL)
4081 return data->GetNumRestartedReasons();
4082 else
4083 return 0;
4084}
4085
4086const char *
4087Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4088{
4089 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4090 if (data != NULL)
4091 return data->GetRestartedReasonAtIndex(idx);
4092 else
4093 return NULL;
4094}
4095
4096void
4097Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4098{
4099 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4100 if (data != NULL)
4101 data->AddRestartedReason(reason);
4102}
4103
Chris Lattner24943d22010-06-08 16:52:24 +00004104bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00004105Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4106{
4107 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4108 if (data == NULL)
4109 return false;
4110 else
4111 return data->GetInterrupted ();
4112}
4113
4114void
4115Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4116{
4117 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4118 if (data != NULL)
4119 data->SetInterrupted(new_value);
4120}
4121
4122bool
Chris Lattner24943d22010-06-08 16:52:24 +00004123Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4124{
4125 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4126 if (data)
4127 {
4128 data->SetUpdateStateOnRemoval();
4129 return true;
4130 }
4131 return false;
4132}
4133
Greg Clayton289afcb2012-02-18 05:35:26 +00004134lldb::TargetSP
4135Process::CalculateTarget ()
4136{
4137 return m_target.shared_from_this();
4138}
4139
Chris Lattner24943d22010-06-08 16:52:24 +00004140void
Greg Claytona830adb2010-10-04 01:05:56 +00004141Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00004142{
Greg Clayton567e7f32011-09-22 04:58:26 +00004143 exe_ctx.SetTargetPtr (&m_target);
4144 exe_ctx.SetProcessPtr (this);
4145 exe_ctx.SetThreadPtr(NULL);
4146 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00004147}
4148
Greg Claytone4b9c1f2011-03-08 22:40:15 +00004149//uint32_t
4150//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4151//{
4152// return 0;
4153//}
4154//
4155//ArchSpec
4156//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4157//{
4158// return Host::GetArchSpecForExistingProcess (pid);
4159//}
4160//
4161//ArchSpec
4162//Process::GetArchSpecForExistingProcess (const char *process_name)
4163//{
4164// return Host::GetArchSpecForExistingProcess (process_name);
4165//}
4166//
Caroline Tice861efb32010-11-16 05:07:41 +00004167void
4168Process::AppendSTDOUT (const char * s, size_t len)
4169{
Greg Clayton20d338f2010-11-18 05:57:03 +00004170 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00004171 m_stdout_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004172 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00004173}
4174
4175void
Greg Claytonbd06ff42011-11-13 04:45:22 +00004176Process::AppendSTDERR (const char * s, size_t len)
4177{
4178 Mutex::Locker locker (m_stdio_communication_mutex);
4179 m_stderr_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004180 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004181}
4182
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004183void
4184Process::BroadcastAsyncProfileData(const char *s, size_t len)
4185{
4186 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004187 m_profile_data.push_back(s);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004188 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4189}
4190
4191size_t
4192Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4193{
4194 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004195 if (m_profile_data.empty())
4196 return 0;
4197
4198 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004199 if (bytes_available > 0)
4200 {
4201 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4202 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004203 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004204 if (bytes_available > buf_size)
4205 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004206 memcpy(buf, m_profile_data.front().data(), buf_size);
4207 m_profile_data.front().erase(0, buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004208 bytes_available = buf_size;
4209 }
4210 else
4211 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004212 memcpy(buf, m_profile_data.front().data(), bytes_available);
4213 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004214 }
4215 }
4216 return bytes_available;
4217}
4218
4219
Greg Claytonbd06ff42011-11-13 04:45:22 +00004220//------------------------------------------------------------------
4221// Process STDIO
4222//------------------------------------------------------------------
4223
4224size_t
4225Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4226{
4227 Mutex::Locker locker(m_stdio_communication_mutex);
4228 size_t bytes_available = m_stdout_data.size();
4229 if (bytes_available > 0)
4230 {
4231 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4232 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004233 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004234 if (bytes_available > buf_size)
4235 {
4236 memcpy(buf, m_stdout_data.c_str(), buf_size);
4237 m_stdout_data.erase(0, buf_size);
4238 bytes_available = buf_size;
4239 }
4240 else
4241 {
4242 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4243 m_stdout_data.clear();
4244 }
4245 }
4246 return bytes_available;
4247}
4248
4249
4250size_t
4251Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4252{
4253 Mutex::Locker locker(m_stdio_communication_mutex);
4254 size_t bytes_available = m_stderr_data.size();
4255 if (bytes_available > 0)
4256 {
4257 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4258 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004259 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004260 if (bytes_available > buf_size)
4261 {
4262 memcpy(buf, m_stderr_data.c_str(), buf_size);
4263 m_stderr_data.erase(0, buf_size);
4264 bytes_available = buf_size;
4265 }
4266 else
4267 {
4268 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4269 m_stderr_data.clear();
4270 }
4271 }
4272 return bytes_available;
4273}
4274
4275void
Caroline Tice861efb32010-11-16 05:07:41 +00004276Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4277{
4278 Process *process = (Process *) baton;
4279 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4280}
4281
4282size_t
4283Process::ProcessInputReaderCallback (void *baton,
4284 InputReader &reader,
4285 lldb::InputReaderAction notification,
4286 const char *bytes,
4287 size_t bytes_len)
4288{
4289 Process *process = (Process *) baton;
4290
4291 switch (notification)
4292 {
4293 case eInputReaderActivate:
4294 break;
4295
4296 case eInputReaderDeactivate:
4297 break;
4298
4299 case eInputReaderReactivate:
4300 break;
4301
Caroline Tice4a348082011-05-02 20:41:46 +00004302 case eInputReaderAsynchronousOutputWritten:
4303 break;
4304
Caroline Tice861efb32010-11-16 05:07:41 +00004305 case eInputReaderGotToken:
4306 {
4307 Error error;
4308 process->PutSTDIN (bytes, bytes_len, error);
4309 }
4310 break;
4311
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004312 case eInputReaderInterrupt:
4313 process->Halt ();
4314 break;
4315
4316 case eInputReaderEndOfFile:
4317 process->AppendSTDOUT ("^D", 2);
4318 break;
4319
Caroline Tice861efb32010-11-16 05:07:41 +00004320 case eInputReaderDone:
4321 break;
4322
4323 }
4324
4325 return bytes_len;
4326}
4327
4328void
4329Process::ResetProcessInputReader ()
4330{
4331 m_process_input_reader.reset();
4332}
4333
4334void
Greg Clayton464c6162011-11-17 22:14:31 +00004335Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004336{
4337 // First set up the Read Thread for reading/handling process I/O
4338
4339 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4340
4341 if (conn_ap.get())
4342 {
4343 m_stdio_communication.SetConnection (conn_ap.release());
4344 if (m_stdio_communication.IsConnected())
4345 {
4346 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4347 m_stdio_communication.StartReadThread();
4348
4349 // Now read thread is set up, set up input reader.
4350
4351 if (!m_process_input_reader.get())
4352 {
4353 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4354 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4355 this,
4356 eInputReaderGranularityByte,
4357 NULL,
4358 NULL,
4359 false));
4360
4361 if (err.Fail())
4362 m_process_input_reader.reset();
4363 }
4364 }
4365 }
4366}
4367
4368void
4369Process::PushProcessInputReader ()
4370{
4371 if (m_process_input_reader && !m_process_input_reader->IsActive())
4372 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4373}
4374
4375void
4376Process::PopProcessInputReader ()
4377{
4378 if (m_process_input_reader && m_process_input_reader->IsActive())
4379 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4380}
4381
Greg Claytond284b662011-02-18 01:44:25 +00004382// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004383void
Caroline Tice2a456812011-03-10 22:14:10 +00004384Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004385{
Greg Clayton73844aa2012-08-22 17:17:09 +00004386// static std::vector<OptionEnumValueElement> g_plugins;
4387//
4388// int i=0;
4389// const char *name;
4390// OptionEnumValueElement option_enum;
4391// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4392// {
4393// if (name)
4394// {
4395// option_enum.value = i;
4396// option_enum.string_value = name;
4397// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4398// g_plugins.push_back (option_enum);
4399// }
4400// ++i;
4401// }
4402// option_enum.value = 0;
4403// option_enum.string_value = NULL;
4404// option_enum.usage = NULL;
4405// g_plugins.push_back (option_enum);
4406//
4407// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4408// {
4409// if (::strcmp (name, "plugin") == 0)
4410// {
4411// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4412// break;
4413// }
4414// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004415//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004416 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004417}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004418
Greg Clayton990de7b2010-11-18 23:32:35 +00004419void
Caroline Tice2a456812011-03-10 22:14:10 +00004420Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004421{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004422 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004423}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004424
Greg Clayton427f2902010-12-14 02:59:59 +00004425ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004426Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004427 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004428 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004429 bool run_others,
Jim Inghamb7940202013-01-15 02:47:48 +00004430 bool unwind_on_error,
4431 bool ignore_breakpoints,
Jim Ingham47beabb2012-10-16 21:41:58 +00004432 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004433 Stream &errors)
4434{
4435 ExecutionResults return_value = eExecutionSetupError;
4436
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004437 if (thread_plan_sp.get() == NULL)
4438 {
4439 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004440 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004441 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004442
4443 if (exe_ctx.GetProcessPtr() != this)
4444 {
4445 errors.Printf("RunThreadPlan called on wrong process.");
4446 return eExecutionSetupError;
4447 }
4448
4449 Thread *thread = exe_ctx.GetThreadPtr();
4450 if (thread == NULL)
4451 {
4452 errors.Printf("RunThreadPlan called with invalid thread.");
4453 return eExecutionSetupError;
4454 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004455
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004456 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4457 // For that to be true the plan can't be private - since private plans suppress themselves in the
4458 // GetCompletedPlan call.
4459
4460 bool orig_plan_private = thread_plan_sp->GetPrivate();
4461 thread_plan_sp->SetPrivate(false);
4462
Jim Inghamac959662011-01-24 06:34:17 +00004463 if (m_private_state.GetValue() != eStateStopped)
4464 {
4465 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004466 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004467 }
4468
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004469 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004470 const uint32_t thread_idx_id = thread->GetIndexID();
4471 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004472
4473 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4474 // so we should arrange to reset them as well.
4475
Greg Clayton567e7f32011-09-22 04:58:26 +00004476 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004477
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004478 uint32_t selected_tid;
4479 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004480 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004481 {
4482 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004483 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004484 }
4485 else
4486 {
4487 selected_tid = LLDB_INVALID_THREAD_ID;
4488 }
4489
Jim Ingham1831e782012-04-07 00:00:41 +00004490 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004491 lldb::StateType old_state;
4492 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004493
Jim Inghamd21d98b2012-04-10 01:21:57 +00004494 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004495 if (Host::GetCurrentThread() == m_private_state_thread)
4496 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004497 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4498 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004499 // 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 +00004500 // we are fielding public events here.
4501 if (log)
Jason Molenda559cf6e2012-11-17 01:41:04 +00004502 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 +00004503
4504
Jim Ingham1831e782012-04-07 00:00:41 +00004505 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004506
4507 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4508 // returning control here.
4509 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4510 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4511 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4512 // do just what we want.
4513 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4514 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4515 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4516 old_state = m_public_state.GetValue();
4517 m_public_state.SetValueNoLock(eStateStopped);
4518
4519 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004520 StartPrivateStateThread(true);
4521 }
4522
4523 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004524
Jim Ingham6ae318c2011-01-23 21:14:08 +00004525 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004526
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004527 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004528
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004529 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004530 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4531 // restored on exit to the function.
4532 //
4533 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4534 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004535
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004536 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004537
Jim Ingham360f53f2010-11-30 02:22:11 +00004538 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004539 {
4540 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004541 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004542 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004543 thread->GetIndexID(),
4544 thread->GetID(),
4545 s.GetData());
4546 }
4547
4548 bool got_event;
4549 lldb::EventSP event_sp;
4550 lldb::StateType stop_state = lldb::eStateInvalid;
4551
4552 TimeValue* timeout_ptr = NULL;
4553 TimeValue real_timeout;
4554
Jim Ingham89e248f2013-02-09 01:29:05 +00004555 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 +00004556 bool do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004557 bool handle_running_event = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004558 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004559
Jim Ingham89e248f2013-02-09 01:29:05 +00004560 // This is just for accounting:
4561 uint32_t num_resumes = 0;
4562
4563 TimeValue one_thread_timeout = TimeValue::Now();
4564 TimeValue final_timeout = one_thread_timeout;
4565
4566 if (run_others)
4567 {
4568 // If we are running all threads then we take half the time to run all threads, bounded by
4569 // .25 sec.
4570 if (timeout_usec == 0)
4571 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4572 else
4573 {
4574 uint64_t computed_timeout = computed_timeout = timeout_usec / 2;
4575 if (computed_timeout > default_one_thread_timeout_usec)
4576 computed_timeout = default_one_thread_timeout_usec;
4577 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4578 }
4579 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4580 }
4581 else
4582 {
4583 if (timeout_usec != 0)
4584 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4585 }
4586
Jim Ingham76b258d2012-11-26 23:52:18 +00004587 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4588 // So don't call return anywhere within it.
4589
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004590 while (1)
4591 {
4592 // We usually want to resume the process if we get to the top of the loop.
4593 // The only exception is if we get two running events with no intervening
4594 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham89e248f2013-02-09 01:29:05 +00004595 if (log)
4596 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4597 do_resume,
4598 handle_running_event,
4599 before_first_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004600
Jim Inghamb7940202013-01-15 02:47:48 +00004601 if (do_resume || handle_running_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004602 {
4603 // Do the initial resume and wait for the running event before going further.
4604
Jim Inghamb7940202013-01-15 02:47:48 +00004605 if (do_resume)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004606 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004607 num_resumes++;
Jim Inghamb7940202013-01-15 02:47:48 +00004608 Error resume_error = PrivateResume ();
4609 if (!resume_error.Success())
4610 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004611 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4612 num_resumes,
4613 resume_error.AsCString());
Jim Inghamb7940202013-01-15 02:47:48 +00004614 return_value = eExecutionSetupError;
4615 break;
4616 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004617 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004618
Jim Ingham89e248f2013-02-09 01:29:05 +00004619 TimeValue resume_timeout = TimeValue::Now();
4620 resume_timeout.OffsetWithMicroSeconds(500000);
4621
4622 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004623 if (!got_event)
4624 {
4625 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004626 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4627 num_resumes);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004628
Jim Ingham89e248f2013-02-09 01:29:05 +00004629 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004630 return_value = eExecutionSetupError;
4631 break;
4632 }
4633
4634 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham89e248f2013-02-09 01:29:05 +00004635
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004636 if (stop_state != eStateRunning)
4637 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004638 bool restarted = false;
4639
4640 if (stop_state == eStateStopped)
4641 {
4642 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4643 if (log)
4644 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4645 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4646 num_resumes,
4647 StateAsCString(stop_state),
4648 restarted,
4649 do_resume,
4650 handle_running_event);
4651 }
4652
4653 if (restarted)
4654 {
4655 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4656 // event here. But if I do, the best thing is to Halt and then get out of here.
4657 Halt();
4658 }
4659
Jim Ingham47beabb2012-10-16 21:41:58 +00004660 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4661 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004662 return_value = eExecutionSetupError;
4663 break;
4664 }
4665
4666 if (log)
4667 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4668 // We need to call the function synchronously, so spin waiting for it to return.
4669 // If we get interrupted while executing, we're going to lose our context, and
4670 // won't be able to gather the result at this point.
4671 // We set the timeout AFTER the resume, since the resume takes some time and we
4672 // don't want to charge that to the timeout.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004673 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004674 else
4675 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004676 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004677 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004678 }
Jim Ingham89e248f2013-02-09 01:29:05 +00004679
4680 if (before_first_timeout)
4681 {
4682 if (run_others)
4683 timeout_ptr = &one_thread_timeout;
4684 else
4685 {
4686 if (timeout_usec == 0)
4687 timeout_ptr = NULL;
4688 else
4689 timeout_ptr = &final_timeout;
4690 }
4691 }
4692 else
4693 {
4694 if (timeout_usec == 0)
4695 timeout_ptr = NULL;
4696 else
4697 timeout_ptr = &final_timeout;
4698 }
4699
4700 do_resume = true;
4701 handle_running_event = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004702
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004703 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004704 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004705
Jim Inghamf9f40c22011-02-08 05:20:59 +00004706 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004707 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004708 if (timeout_ptr)
4709 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004710 log->Printf ("Process::RunThreadPlan(): about to wait - now is %llu - endpoint is %llu",
4711 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
4712 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004713 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004714 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004715 {
4716 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4717 }
4718 }
4719
4720 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4721
4722 if (got_event)
4723 {
4724 if (event_sp.get())
4725 {
4726 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004727 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004728 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004729 Halt();
Jim Ingham5d90ade2012-07-27 23:57:19 +00004730 return_value = eExecutionInterrupted;
4731 errors.Printf ("Execution halted by user interrupt.");
4732 if (log)
4733 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham89e248f2013-02-09 01:29:05 +00004734 break;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004735 }
4736 else
4737 {
4738 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4739 if (log)
4740 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4741
4742 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004743 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004744 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004745 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004746 // We stopped, figure out what we are going to do now.
Jim Ingham5d90ade2012-07-27 23:57:19 +00004747 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4748 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004749 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004750 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004751 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004752 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4753 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004754 }
4755 else
4756 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004757 // If we were restarted, we just need to go back up to fetch another event.
4758 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Ingham5d90ade2012-07-27 23:57:19 +00004759 {
4760 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004761 {
4762 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
4763 }
4764 keep_going = true;
4765 do_resume = false;
4766 handle_running_event = true;
4767
Jim Ingham5d90ade2012-07-27 23:57:19 +00004768 }
4769 else
4770 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004771
4772 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4773 StopReason stop_reason = eStopReasonInvalid;
4774 if (stop_info_sp)
4775 stop_reason = stop_info_sp->GetStopReason();
4776
4777
4778 // FIXME: We only check if the stop reason is plan complete, should we make sure that
4779 // it is OUR plan that is complete?
4780 if (stop_reason == eStopReasonPlanComplete)
Jim Inghamb7940202013-01-15 02:47:48 +00004781 {
4782 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004783 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4784 // Now mark this plan as private so it doesn't get reported as the stop reason
4785 // after this point.
4786 if (thread_plan_sp)
4787 thread_plan_sp->SetPrivate (orig_plan_private);
4788 return_value = eExecutionCompleted;
Jim Inghamb7940202013-01-15 02:47:48 +00004789 }
4790 else
4791 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004792 // Something restarted the target, so just wait for it to stop for real.
Jim Inghamb7940202013-01-15 02:47:48 +00004793 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham89e248f2013-02-09 01:29:05 +00004794 {
4795 if (log)
4796 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Inghamb7940202013-01-15 02:47:48 +00004797 return_value = eExecutionHitBreakpoint;
Jim Ingham89e248f2013-02-09 01:29:05 +00004798 }
Jim Inghamb7940202013-01-15 02:47:48 +00004799 else
Jim Ingham89e248f2013-02-09 01:29:05 +00004800 {
4801 if (log)
4802 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Inghamb7940202013-01-15 02:47:48 +00004803 return_value = eExecutionInterrupted;
Jim Ingham89e248f2013-02-09 01:29:05 +00004804 }
Jim Inghamb7940202013-01-15 02:47:48 +00004805 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004806 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004807 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004808 }
4809 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004810
Jim Ingham5d90ade2012-07-27 23:57:19 +00004811 case lldb::eStateRunning:
Jim Ingham89e248f2013-02-09 01:29:05 +00004812 // This shouldn't really happen, but sometimes we do get two running events without an
4813 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Ingham5d90ade2012-07-27 23:57:19 +00004814 do_resume = false;
4815 keep_going = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004816 handle_running_event = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004817 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004818
Jim Ingham5d90ade2012-07-27 23:57:19 +00004819 default:
4820 if (log)
4821 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4822
4823 if (stop_state == eStateExited)
4824 event_to_broadcast_sp = event_sp;
4825
Sean Callanan96abc622012-08-08 17:35:10 +00004826 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00004827 return_value = eExecutionInterrupted;
4828 break;
4829 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004830 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004831
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004832 if (keep_going)
4833 continue;
4834 else
4835 break;
4836 }
4837 else
4838 {
4839 if (log)
4840 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4841 return_value = eExecutionInterrupted;
4842 break;
4843 }
4844 }
4845 else
4846 {
4847 // If we didn't get an event that means we've timed out...
4848 // We will interrupt the process here. Depending on what we were asked to do we will
4849 // either exit, or try with all threads running for the same timeout.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004850
4851 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00004852 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004853 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004854 uint64_t remaining_time = final_timeout - TimeValue::Now();
4855 if (before_first_timeout)
4856 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
4857 "running till for %" PRId64 " usec with all threads enabled.",
4858 remaining_time);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004859 else
4860 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00004861 "and timeout: %d timed out, abandoning execution.",
4862 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004863 }
4864 else
4865 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004866 "abandoning execution.",
4867 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004868 }
4869
Jim Ingham89e248f2013-02-09 01:29:05 +00004870 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
4871 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
4872 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
4873 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
4874 // stopped event. That's what this while loop does.
4875
4876 bool back_to_top = true;
4877 uint32_t try_halt_again = 0;
4878 bool do_halt = true;
4879 const uint32_t num_retries = 5;
4880 while (try_halt_again < num_retries)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004881 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004882 Error halt_error;
4883 if (do_halt)
4884 {
4885 if (log)
4886 log->Printf ("Process::RunThreadPlan(): Running Halt.");
4887 halt_error = Halt();
4888 }
4889 if (halt_error.Success())
4890 {
4891 if (log)
4892 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4893
4894 real_timeout = TimeValue::Now();
4895 real_timeout.OffsetWithMicroSeconds(500000);
4896
4897 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004898
Jim Ingham89e248f2013-02-09 01:29:05 +00004899 if (got_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004900 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004901 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4902 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004903 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004904 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4905 if (stop_state == lldb::eStateStopped
4906 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4907 log->PutCString (" Event was the Halt interruption event.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004908 }
4909
Jim Ingham89e248f2013-02-09 01:29:05 +00004910 if (stop_state == lldb::eStateStopped)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004911 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004912 // Between the time we initiated the Halt and the time we delivered it, the process could have
4913 // already finished its job. Check that here:
4914
4915 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4916 {
4917 if (log)
4918 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4919 "Exiting wait loop.");
4920 return_value = eExecutionCompleted;
4921 back_to_top = false;
4922 break;
4923 }
4924
4925 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
4926 {
4927 if (log)
4928 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
4929 "Exiting wait loop.");
4930 try_halt_again++;
4931 do_halt = false;
4932 continue;
4933 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004934
Jim Ingham89e248f2013-02-09 01:29:05 +00004935 if (!run_others)
4936 {
4937 if (log)
4938 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4939 return_value = eExecutionInterrupted;
4940 back_to_top = false;
4941 break;
4942 }
4943
4944 if (before_first_timeout)
4945 {
4946 // Set all the other threads to run, and return to the top of the loop, which will continue;
4947 before_first_timeout = false;
4948 thread_plan_sp->SetStopOthers (false);
4949 if (log)
4950 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004951
Jim Ingham89e248f2013-02-09 01:29:05 +00004952 back_to_top = true;
4953 break;
4954 }
4955 else
4956 {
4957 // Running all threads failed, so return Interrupted.
4958 if (log)
4959 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4960 return_value = eExecutionInterrupted;
4961 back_to_top = false;
4962 break;
4963 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004964 }
4965 }
4966 else
Jim Ingham89e248f2013-02-09 01:29:05 +00004967 { if (log)
4968 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4969 "I'm getting out of here passing Interrupted.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004970 return_value = eExecutionInterrupted;
Jim Ingham89e248f2013-02-09 01:29:05 +00004971 back_to_top = false;
4972 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004973 }
4974 }
Jim Ingham89e248f2013-02-09 01:29:05 +00004975 else
4976 {
4977 try_halt_again++;
4978 continue;
4979 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004980 }
Jim Ingham89e248f2013-02-09 01:29:05 +00004981
4982 if (!back_to_top || try_halt_again > num_retries)
4983 break;
4984 else
4985 continue;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004986 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004987 } // END WAIT LOOP
4988
4989 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4990 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4991 {
4992 StopPrivateStateThread();
4993 Error error;
4994 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00004995 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004996 {
4997 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4998 }
4999 m_public_state.SetValueNoLock(old_state);
5000
5001 }
5002
Jim Inghamb7940202013-01-15 02:47:48 +00005003 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5004 // could happen:
5005 // 1) The execution successfully completed
5006 // 2) We hit a breakpoint, and ignore_breakpoints was true
5007 // 3) We got some other error, and discard_on_error was true
5008 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
5009 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham76b258d2012-11-26 23:52:18 +00005010
Jim Inghamb7940202013-01-15 02:47:48 +00005011 if (return_value == eExecutionCompleted
5012 || should_unwind)
Jim Ingham76b258d2012-11-26 23:52:18 +00005013 {
5014 thread_plan_sp->RestoreThreadState();
5015 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005016
5017 // Now do some processing on the results of the run:
Jim Inghamb7940202013-01-15 02:47:48 +00005018 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005019 {
5020 if (log)
5021 {
5022 StreamString s;
5023 if (event_sp)
5024 event_sp->Dump (&s);
5025 else
5026 {
5027 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5028 }
5029
5030 StreamString ts;
5031
5032 const char *event_explanation = NULL;
5033
5034 do
5035 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005036 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005037 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005038 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005039 break;
5040 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005041 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005042 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005043 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005044 break;
5045 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005046 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005047 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005048 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5049
5050 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005051 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005052 event_explanation = "<no event data>";
5053 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005054 }
5055
Jim Ingham5d90ade2012-07-27 23:57:19 +00005056 Process *process = event_data->GetProcessSP().get();
5057
5058 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005059 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005060 event_explanation = "<no process>";
5061 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005062 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005063
5064 ThreadList &thread_list = process->GetThreadList();
5065
5066 uint32_t num_threads = thread_list.GetSize();
5067 uint32_t thread_index;
5068
5069 ts.Printf("<%u threads> ", num_threads);
5070
5071 for (thread_index = 0;
5072 thread_index < num_threads;
5073 ++thread_index)
5074 {
5075 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5076
5077 if (!thread)
5078 {
5079 ts.Printf("<?> ");
5080 continue;
5081 }
5082
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005083 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00005084 RegisterContext *register_context = thread->GetRegisterContext().get();
5085
5086 if (register_context)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005087 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Ingham5d90ade2012-07-27 23:57:19 +00005088 else
5089 ts.Printf("[ip unknown] ");
5090
5091 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5092 if (stop_info_sp)
5093 {
5094 const char *stop_desc = stop_info_sp->GetDescription();
5095 if (stop_desc)
5096 ts.PutCString (stop_desc);
5097 }
5098 ts.Printf(">");
5099 }
5100
5101 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005102 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005103 } while (0);
5104
Jim Ingham5d90ade2012-07-27 23:57:19 +00005105 if (event_explanation)
5106 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005107 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00005108 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5109 }
5110
Jim Inghamb7940202013-01-15 02:47:48 +00005111 if (should_unwind && thread_plan_sp)
Jim Ingham5d90ade2012-07-27 23:57:19 +00005112 {
5113 if (log)
5114 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5115 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5116 thread_plan_sp->SetPrivate (orig_plan_private);
5117 }
5118 else
5119 {
5120 if (log)
5121 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005122 }
5123 }
5124 else if (return_value == eExecutionSetupError)
5125 {
5126 if (log)
5127 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00005128
Jim Inghamb7940202013-01-15 02:47:48 +00005129 if (unwind_on_error && thread_plan_sp)
Jim Inghamf9f40c22011-02-08 05:20:59 +00005130 {
Greg Clayton567e7f32011-09-22 04:58:26 +00005131 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00005132 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00005133 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005134 }
5135 else
5136 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005137 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00005138 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00005139 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005140 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5141 return_value = eExecutionCompleted;
5142 }
5143 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5144 {
5145 if (log)
5146 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5147 return_value = eExecutionDiscarded;
5148 }
5149 else
5150 {
5151 if (log)
5152 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamb7940202013-01-15 02:47:48 +00005153 if (unwind_on_error && thread_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005154 {
5155 if (log)
Jim Inghamb7940202013-01-15 02:47:48 +00005156 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005157 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5158 thread_plan_sp->SetPrivate (orig_plan_private);
5159 }
5160 }
5161 }
5162
5163 // Thread we ran the function in may have gone away because we ran the target
5164 // Check that it's still there, and if it is put it back in the context. Also restore the
5165 // frame in the context if it is still present.
5166 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5167 if (thread)
5168 {
5169 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5170 }
5171
5172 // Also restore the current process'es selected frame & thread, since this function calling may
5173 // be done behind the user's back.
5174
5175 if (selected_tid != LLDB_INVALID_THREAD_ID)
5176 {
5177 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5178 {
5179 // We were able to restore the selected thread, now restore the frame:
5180 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5181 if (old_frame_sp)
5182 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00005183 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005184 }
5185 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005186
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005187 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00005188
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005189 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00005190 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005191 if (log)
5192 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5193 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00005194 }
5195
5196 return return_value;
5197}
5198
5199const char *
5200Process::ExecutionResultAsCString (ExecutionResults result)
5201{
5202 const char *result_name;
5203
5204 switch (result)
5205 {
Greg Claytonb3448432011-03-24 21:19:54 +00005206 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005207 result_name = "eExecutionCompleted";
5208 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005209 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00005210 result_name = "eExecutionDiscarded";
5211 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005212 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005213 result_name = "eExecutionInterrupted";
5214 break;
Jim Inghamb7940202013-01-15 02:47:48 +00005215 case eExecutionHitBreakpoint:
5216 result_name = "eExecutionHitBreakpoint";
5217 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005218 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00005219 result_name = "eExecutionSetupError";
5220 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005221 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00005222 result_name = "eExecutionTimedOut";
5223 break;
5224 }
5225 return result_name;
5226}
5227
Greg Claytonabe0fed2011-04-18 08:33:37 +00005228void
5229Process::GetStatus (Stream &strm)
5230{
5231 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00005232 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00005233 {
5234 if (state == eStateExited)
5235 {
5236 int exit_status = GetExitStatus();
5237 const char *exit_description = GetExitDescription();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005238 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00005239 GetID(),
5240 exit_status,
5241 exit_status,
5242 exit_description ? exit_description : "");
5243 }
5244 else
5245 {
5246 if (state == eStateConnected)
5247 strm.Printf ("Connected to remote target.\n");
5248 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005249 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00005250 }
5251 }
5252 else
5253 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005254 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005255 }
5256}
5257
5258size_t
5259Process::GetThreadStatus (Stream &strm,
5260 bool only_threads_with_stop_reason,
5261 uint32_t start_frame,
5262 uint32_t num_frames,
5263 uint32_t num_frames_with_source)
5264{
5265 size_t num_thread_infos_dumped = 0;
5266
Jim Inghamb9950592012-09-10 20:50:15 +00005267 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005268 const size_t num_threads = GetThreadList().GetSize();
5269 for (uint32_t i = 0; i < num_threads; i++)
5270 {
5271 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5272 if (thread)
5273 {
5274 if (only_threads_with_stop_reason)
5275 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00005276 StopInfoSP stop_info_sp = thread->GetStopInfo();
5277 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00005278 continue;
5279 }
5280 thread->GetStatus (strm,
5281 start_frame,
5282 num_frames,
5283 num_frames_with_source);
5284 ++num_thread_infos_dumped;
5285 }
5286 }
5287 return num_thread_infos_dumped;
5288}
5289
Greg Clayton76113302012-02-22 04:37:26 +00005290void
5291Process::AddInvalidMemoryRegion (const LoadRange &region)
5292{
5293 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5294}
5295
5296bool
5297Process::RemoveInvalidMemoryRange (const LoadRange &region)
5298{
5299 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5300}
5301
Jim Ingham1831e782012-04-07 00:00:41 +00005302void
5303Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5304{
5305 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5306}
5307
5308bool
5309Process::RunPreResumeActions ()
5310{
5311 bool result = true;
5312 while (!m_pre_resume_actions.empty())
5313 {
5314 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5315 m_pre_resume_actions.pop_back();
5316 bool this_result = action.callback (action.baton);
5317 if (result == true) result = this_result;
5318 }
5319 return result;
5320}
5321
5322void
5323Process::ClearPreResumeActions ()
5324{
5325 m_pre_resume_actions.clear();
5326}
Greg Clayton76113302012-02-22 04:37:26 +00005327
Greg Claytoncf5927e2012-05-18 02:38:05 +00005328void
5329Process::Flush ()
5330{
5331 m_thread_list.Flush();
5332}
Greg Clayton0bce9a22012-12-05 00:16:59 +00005333
5334void
5335Process::DidExec ()
5336{
5337 Target &target = GetTarget();
5338 target.CleanupProcess ();
5339 ModuleList unloaded_modules (target.GetImages());
5340 target.ModulesDidUnload (unloaded_modules);
5341 target.GetSectionLoadList().Clear();
5342 m_dynamic_checkers_ap.reset();
5343 m_abi_sp.reset();
5344 m_os_ap.reset();
5345 m_dyld_ap.reset();
5346 m_image_tokens.clear();
5347 m_allocated_memory_cache.Clear();
5348 m_language_runtimes.clear();
5349 DoDidExec();
5350 CompleteAttach ();
5351}