blob: c973a50ad0ba84b0bbbf5398915c55f4172a8868 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malead891f9b2012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner24943d22010-06-08 16:52:24 +000012#include "lldb/Target/Process.h"
13
14#include "lldb/lldb-private-log.h"
15
16#include "lldb/Breakpoint/StoppointCallbackContext.h"
17#include "lldb/Breakpoint/BreakpointLocation.h"
18#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000021#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000022#include "lldb/Core/Log.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000023#include "lldb/Core/Module.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/PluginManager.h"
25#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000026#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000027#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000028#include "lldb/Host/Host.h"
29#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000030#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000031#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000032#include "lldb/Target/LanguageRuntime.h"
33#include "lldb/Target/CPPLanguageRuntime.h"
34#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000035#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000037#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000038#include "lldb/Target/Target.h"
39#include "lldb/Target/TargetList.h"
40#include "lldb/Target/Thread.h"
41#include "lldb/Target/ThreadPlan.h"
Jim Inghamd21d98b2012-04-10 01:21:57 +000042#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner24943d22010-06-08 16:52:24 +000043
44using namespace lldb;
45using namespace lldb_private;
46
Greg Clayton73844aa2012-08-22 17:17:09 +000047
48// Comment out line below to disable memory caching, overriding the process setting
49// target.process.disable-memory-cache
50#define ENABLE_MEMORY_CACHING
51
52#ifdef ENABLE_MEMORY_CACHING
53#define DISABLE_MEM_CACHE_DEFAULT false
54#else
55#define DISABLE_MEM_CACHE_DEFAULT true
56#endif
57
58class ProcessOptionValueProperties : public OptionValueProperties
59{
60public:
61 ProcessOptionValueProperties (const ConstString &name) :
62 OptionValueProperties (name)
63 {
64 }
65
66 // This constructor is used when creating ProcessOptionValueProperties when it
67 // is part of a new lldb_private::Process instance. It will copy all current
68 // global property values as needed
69 ProcessOptionValueProperties (ProcessProperties *global_properties) :
70 OptionValueProperties(*global_properties->GetValueProperties())
71 {
72 }
73
74 virtual const Property *
75 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
76 {
77 // When gettings the value for a key from the process options, we will always
78 // try and grab the setting from the current process if there is one. Else we just
79 // use the one from this instance.
80 if (exe_ctx)
81 {
82 Process *process = exe_ctx->GetProcessPtr();
83 if (process)
84 {
85 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
86 if (this != instance_properties)
87 return instance_properties->ProtectedGetPropertyAtIndex (idx);
88 }
89 }
90 return ProtectedGetPropertyAtIndex (idx);
91 }
92};
93
94static PropertyDefinition
95g_properties[] =
96{
97 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
Jim Inghamdacdc012012-11-29 00:41:12 +000098 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used. "
99 "For instance, to turn on debugserver logging set this to \"QSetLogging:bitmask=LOG_DEFAULT;\"" },
Jim Ingham46be7f22013-01-31 19:48:57 +0000100 { "ignore-breakpoints-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, breakpoints will be ignored during expression evaluation." },
101 { "unwind-on-error-in-expressions", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, errors in expression evaluation will unwind the stack back to the state before the call." },
Greg Clayton507a6382012-11-29 18:48:47 +0000102 { "python-os-plugin-path", OptionValue::eTypeFileSpec, false, true, NULL, NULL, "A path to a python OS plug-in module file that contains a OperatingSystemPlugIn class." },
Jim Ingham090f8312013-01-26 02:19:28 +0000103 { "stop-on-sharedlibrary-events" , OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, stop when a shared library is loaded or unloaded." },
Greg Clayton73844aa2012-08-22 17:17:09 +0000104 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
105};
106
107enum {
108 ePropertyDisableMemCache,
Greg Clayton2e7f3132012-10-18 22:40:37 +0000109 ePropertyExtraStartCommand,
Jim Inghamb7940202013-01-15 02:47:48 +0000110 ePropertyIgnoreBreakpointsInExpressions,
111 ePropertyUnwindOnErrorInExpressions,
Jim Ingham090f8312013-01-26 02:19:28 +0000112 ePropertyPythonOSPluginPath,
113 ePropertyStopOnSharedLibraryEvents
Greg Clayton73844aa2012-08-22 17:17:09 +0000114};
115
116ProcessProperties::ProcessProperties (bool is_global) :
117 Properties ()
118{
119 if (is_global)
120 {
121 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
122 m_collection_sp->Initialize(g_properties);
123 m_collection_sp->AppendProperty(ConstString("thread"),
Jim Ingham090f8312013-01-26 02:19:28 +0000124 ConstString("Settings specific to threads."),
Greg Clayton73844aa2012-08-22 17:17:09 +0000125 true,
126 Thread::GetGlobalProperties()->GetValueProperties());
127 }
128 else
129 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
130}
131
132ProcessProperties::~ProcessProperties()
133{
134}
135
136bool
137ProcessProperties::GetDisableMemoryCache() const
138{
139 const uint32_t idx = ePropertyDisableMemCache;
140 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
141}
142
143Args
144ProcessProperties::GetExtraStartupCommands () const
145{
146 Args args;
147 const uint32_t idx = ePropertyExtraStartCommand;
148 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
149 return args;
150}
151
152void
153ProcessProperties::SetExtraStartupCommands (const Args &args)
154{
155 const uint32_t idx = ePropertyExtraStartCommand;
156 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
157}
158
Greg Clayton2e7f3132012-10-18 22:40:37 +0000159FileSpec
160ProcessProperties::GetPythonOSPluginPath () const
161{
162 const uint32_t idx = ePropertyPythonOSPluginPath;
163 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
164}
165
166void
167ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
168{
169 const uint32_t idx = ePropertyPythonOSPluginPath;
170 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
171}
172
Jim Inghamb7940202013-01-15 02:47:48 +0000173
174bool
175ProcessProperties::GetIgnoreBreakpointsInExpressions () const
176{
177 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
178 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
179}
180
181void
182ProcessProperties::SetIgnoreBreakpointsInExpressions (bool ignore)
183{
184 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
185 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
186}
187
188bool
189ProcessProperties::GetUnwindOnErrorInExpressions () const
190{
191 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
192 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
193}
194
195void
196ProcessProperties::SetUnwindOnErrorInExpressions (bool ignore)
197{
198 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
199 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, ignore);
200}
201
Jim Ingham090f8312013-01-26 02:19:28 +0000202bool
203ProcessProperties::GetStopOnSharedLibraryEvents () const
204{
205 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
206 return m_collection_sp->GetPropertyAtIndexAsBoolean(NULL, idx, g_properties[idx].default_uint_value != 0);
207}
208
209void
210ProcessProperties::SetStopOnSharedLibraryEvents (bool stop)
211{
212 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
213 m_collection_sp->SetPropertyAtIndexAsBoolean(NULL, idx, stop);
214}
215
Greg Clayton24bc5d92011-03-30 18:16:51 +0000216void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000217ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000218{
219 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +0000220 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000221 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000222
223 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000224 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000225
226 if (m_executable)
227 {
228 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
229 s.PutCString (" file = ");
230 m_executable.Dump(&s);
231 s.EOL();
232 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000233 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000234 if (argc > 0)
235 {
236 for (uint32_t i=0; i<argc; i++)
237 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000238 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +0000239 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000240 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000241 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000242 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000243 }
244 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000245
246 const uint32_t envc = m_environment.GetArgumentCount();
247 if (envc > 0)
248 {
249 for (uint32_t i=0; i<envc; i++)
250 {
251 const char *env = m_environment.GetArgumentAtIndex(i);
252 if (i < 10)
253 s.Printf (" env[%u] = %s\n", i, env);
254 else
255 s.Printf ("env[%u] = %s\n", i, env);
256 }
257 }
258
Greg Claytonff39f742011-04-01 00:29:43 +0000259 if (m_arch.IsValid())
260 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
261
Greg Claytonb72d0f02011-04-12 05:54:46 +0000262 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000263 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000264 cstr = platform->GetUserName (m_uid);
265 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000266 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000267 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000268 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000269 cstr = platform->GetGroupName (m_gid);
270 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000271 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000272 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000273 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000274 cstr = platform->GetUserName (m_euid);
275 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000276 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000277 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000278 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000279 cstr = platform->GetGroupName (m_egid);
280 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000281 }
282}
283
284void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000285ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000286{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000287 const char *label;
288 if (show_args || verbose)
289 label = "ARGUMENTS";
290 else
291 label = "NAME";
292
Greg Claytonff39f742011-04-01 00:29:43 +0000293 if (verbose)
294 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000295 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000296 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
297 }
298 else
299 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000300 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000301 s.PutCString ("====== ====== ========== ======= ============================\n");
302 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000303}
304
305void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000306ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000307{
308 if (m_pid != LLDB_INVALID_PROCESS_ID)
309 {
310 const char *cstr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000311 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000312
Greg Clayton24bc5d92011-03-30 18:16:51 +0000313
Greg Claytonff39f742011-04-01 00:29:43 +0000314 if (verbose)
315 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000316 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000317 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
318 s.Printf ("%-10s ", cstr);
319 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000320 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000321
Greg Claytonb72d0f02011-04-12 05:54:46 +0000322 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000323 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
324 s.Printf ("%-10s ", cstr);
325 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000326 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000327
Greg Claytonb72d0f02011-04-12 05:54:46 +0000328 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000329 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
330 s.Printf ("%-10s ", cstr);
331 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000332 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000333
Greg Claytonb72d0f02011-04-12 05:54:46 +0000334 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000335 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
336 s.Printf ("%-10s ", cstr);
337 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000338 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000339 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
340 }
341 else
342 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000343 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000344 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000345 (int)m_arch.GetTriple().getArchName().size(),
346 m_arch.GetTriple().getArchName().data());
347 }
348
Greg Claytonb72d0f02011-04-12 05:54:46 +0000349 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000350 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000351 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000352 if (argc > 0)
353 {
354 for (uint32_t i=0; i<argc; i++)
355 {
356 if (i > 0)
357 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000358 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000359 }
360 }
361 }
362 else
363 {
364 s.PutCString (GetName());
365 }
366
367 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000368 }
369}
370
Greg Claytonb72d0f02011-04-12 05:54:46 +0000371
372void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000373ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000374{
375 m_arguments.SetArguments (argv);
376
377 // Is the first argument the executable?
378 if (first_arg_is_executable)
379 {
380 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
381 if (first_arg)
382 {
383 // Yes the first argument is an executable, set it as the executable
384 // in the launch options. Don't resolve the file path as the path
385 // could be a remote platform path
386 const bool resolve = false;
387 m_executable.SetFile(first_arg, resolve);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000388 }
389 }
390}
391void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000392ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000393{
394 // Copy all arguments
395 m_arguments = args;
396
397 // Is the first argument the executable?
398 if (first_arg_is_executable)
399 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000400 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000401 if (first_arg)
402 {
403 // Yes the first argument is an executable, set it as the executable
404 // in the launch options. Don't resolve the file path as the path
405 // could be a remote platform path
406 const bool resolve = false;
407 m_executable.SetFile(first_arg, resolve);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000408 }
409 }
410}
411
Greg Claytonabb33022011-11-08 02:43:13 +0000412void
Greg Clayton464c6162011-11-17 22:14:31 +0000413ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000414{
415 // If notthing was specified, then check the process for any default
416 // settings that were set with "settings set"
417 if (m_file_actions.empty())
418 {
Greg Claytonabb33022011-11-08 02:43:13 +0000419 if (m_flags.Test(eLaunchFlagDisableSTDIO))
420 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000421 AppendSuppressFileAction (STDIN_FILENO , true, false);
422 AppendSuppressFileAction (STDOUT_FILENO, false, true);
423 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000424 }
425 else
426 {
427 // Check for any values that might have gotten set with any of:
428 // (lldb) settings set target.input-path
429 // (lldb) settings set target.output-path
430 // (lldb) settings set target.error-path
Greg Clayton73844aa2012-08-22 17:17:09 +0000431 FileSpec in_path;
432 FileSpec out_path;
433 FileSpec err_path;
Greg Claytonabb33022011-11-08 02:43:13 +0000434 if (target)
435 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000436 in_path = target->GetStandardInputPath();
437 out_path = target->GetStandardOutputPath();
438 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000439 }
440
Greg Clayton73844aa2012-08-22 17:17:09 +0000441 if (in_path || out_path || err_path)
442 {
443 char path[PATH_MAX];
444 if (in_path && in_path.GetPath(path, sizeof(path)))
445 AppendOpenFileAction(STDIN_FILENO, path, true, false);
446
447 if (out_path && out_path.GetPath(path, sizeof(path)))
448 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
449
450 if (err_path && err_path.GetPath(path, sizeof(path)))
451 AppendOpenFileAction(STDERR_FILENO, path, false, true);
452 }
453 else if (default_to_use_pty)
Greg Clayton464c6162011-11-17 22:14:31 +0000454 {
455 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000456 {
Greg Clayton73844aa2012-08-22 17:17:09 +0000457 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
458 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
459 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
460 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000461 }
462 }
Greg Claytonabb33022011-11-08 02:43:13 +0000463 }
464 }
465}
466
Greg Clayton527154d2011-11-15 03:53:30 +0000467
468bool
Greg Clayton97471182012-04-14 01:42:46 +0000469ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
470 bool localhost,
471 bool will_debug,
472 bool first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000473{
474 error.Clear();
475
476 if (GetFlags().Test (eLaunchFlagLaunchInShell))
477 {
478 const char *shell_executable = GetShell();
479 if (shell_executable)
480 {
481 char shell_resolved_path[PATH_MAX];
482
483 if (localhost)
484 {
485 FileSpec shell_filespec (shell_executable, true);
486
487 if (!shell_filespec.Exists())
488 {
489 // Resolve the path in case we just got "bash", "sh" or "tcsh"
490 if (!shell_filespec.ResolveExecutableLocation ())
491 {
492 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
493 return false;
494 }
495 }
496 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
497 shell_executable = shell_resolved_path;
498 }
499
Greg Clayton0c8446c2012-10-17 22:57:12 +0000500 const char **argv = GetArguments().GetConstArgumentVector ();
501 if (argv == NULL || argv[0] == NULL)
502 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000503 Args shell_arguments;
504 std::string safe_arg;
505 shell_arguments.AppendArgument (shell_executable);
Greg Clayton527154d2011-11-15 03:53:30 +0000506 shell_arguments.AppendArgument ("-c");
Greg Clayton97471182012-04-14 01:42:46 +0000507 StreamString shell_command;
508 if (will_debug)
Greg Clayton527154d2011-11-15 03:53:30 +0000509 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000510 // Add a modified PATH environment variable in case argv[0]
511 // is a relative path
512 const char *argv0 = argv[0];
513 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
514 {
515 // We have a relative path to our executable which may not work if
516 // we just try to run "a.out" (without it being converted to "./a.out")
517 const char *working_dir = GetWorkingDirectory();
Greg Clayton68bd76f2013-02-14 03:54:39 +0000518 // Be sure to put quotes around PATH's value in case any paths have spaces...
519 std::string new_path("PATH=\"");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000520 const size_t empty_path_len = new_path.size();
521
522 if (working_dir && working_dir[0])
523 {
524 new_path += working_dir;
525 }
526 else
527 {
528 char current_working_dir[PATH_MAX];
529 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
530 if (cwd && cwd[0])
531 new_path += cwd;
532 }
533 const char *curr_path = getenv("PATH");
534 if (curr_path)
535 {
536 if (new_path.size() > empty_path_len)
537 new_path += ':';
538 new_path += curr_path;
539 }
Greg Clayton68bd76f2013-02-14 03:54:39 +0000540 new_path += "\" ";
Greg Clayton0c8446c2012-10-17 22:57:12 +0000541 shell_command.PutCString(new_path.c_str());
542 }
543
Greg Clayton97471182012-04-14 01:42:46 +0000544 shell_command.PutCString ("exec");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000545
546#if defined(__APPLE__)
547 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Clayton97471182012-04-14 01:42:46 +0000548 if (GetArchitecture().IsValid())
549 {
550 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton0c8446c2012-10-17 22:57:12 +0000551 // Set the resume count to 2:
Greg Clayton97471182012-04-14 01:42:46 +0000552 // 1 - stop in shell
553 // 2 - stop in /usr/bin/arch
554 // 3 - then we will stop in our program
555 SetResumeCount(2);
556 }
557 else
558 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000559 // Set the resume count to 1:
Greg Clayton97471182012-04-14 01:42:46 +0000560 // 1 - stop in shell
561 // 2 - then we will stop in our program
562 SetResumeCount(1);
563 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000564#else
565 // Set the resume count to 1:
566 // 1 - stop in shell
567 // 2 - then we will stop in our program
568 SetResumeCount(1);
569#endif
Greg Clayton527154d2011-11-15 03:53:30 +0000570 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000571
572 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000573 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000574 // There should only be one argument that is the shell command itself to be used as is
575 if (argv[0] && !argv[1])
576 shell_command.Printf("%s", argv[0]);
Greg Clayton97471182012-04-14 01:42:46 +0000577 else
Greg Clayton0c8446c2012-10-17 22:57:12 +0000578 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000579 }
Greg Clayton97471182012-04-14 01:42:46 +0000580 else
581 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000582 for (size_t i=0; argv[i] != NULL; ++i)
583 {
584 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
585 shell_command.Printf(" %s", arg);
586 }
Greg Clayton97471182012-04-14 01:42:46 +0000587 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000588 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000589 m_executable.SetFile(shell_executable, false);
590 m_arguments = shell_arguments;
591 return true;
592 }
593 else
594 {
595 error.SetErrorString ("invalid shell path");
596 }
597 }
598 else
599 {
600 error.SetErrorString ("not launching in shell");
601 }
602 return false;
603}
604
605
Greg Clayton24bc5d92011-03-30 18:16:51 +0000606bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000607ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
608{
609 if ((read || write) && fd >= 0 && path && path[0])
610 {
611 m_action = eFileActionOpen;
612 m_fd = fd;
613 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000614 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000615 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000616 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000617 else
Greg Clayton527154d2011-11-15 03:53:30 +0000618 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000619 m_path.assign (path);
620 return true;
621 }
622 else
623 {
624 Clear();
625 }
626 return false;
627}
628
629bool
630ProcessLaunchInfo::FileAction::Close (int fd)
631{
632 Clear();
633 if (fd >= 0)
634 {
635 m_action = eFileActionClose;
636 m_fd = fd;
637 }
638 return m_fd >= 0;
639}
640
641
642bool
643ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
644{
645 Clear();
646 if (fd >= 0 && dup_fd >= 0)
647 {
648 m_action = eFileActionDuplicate;
649 m_fd = fd;
650 m_arg = dup_fd;
651 }
652 return m_fd >= 0;
653}
654
655
656
657bool
658ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
659 const FileAction *info,
660 Log *log,
661 Error& error)
662{
663 if (info == NULL)
664 return false;
665
666 switch (info->m_action)
667 {
668 case eFileActionNone:
669 error.Clear();
670 break;
671
672 case eFileActionClose:
673 if (info->m_fd == -1)
674 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
675 else
676 {
677 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
678 eErrorTypePOSIX);
679 if (log && (error.Fail() || log))
680 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
681 file_actions, info->m_fd);
682 }
683 break;
684
685 case eFileActionDuplicate:
686 if (info->m_fd == -1)
687 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
688 else if (info->m_arg == -1)
689 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
690 else
691 {
692 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
693 eErrorTypePOSIX);
694 if (log && (error.Fail() || log))
695 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
696 file_actions, info->m_fd, info->m_arg);
697 }
698 break;
699
700 case eFileActionOpen:
701 if (info->m_fd == -1)
702 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
703 else
704 {
705 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000706
Greg Claytonb72d0f02011-04-12 05:54:46 +0000707 mode_t mode = 0;
708
Greg Clayton527154d2011-11-15 03:53:30 +0000709 if (oflag & O_CREAT)
710 mode = 0640;
711
Greg Claytonb72d0f02011-04-12 05:54:46 +0000712 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
713 info->m_fd,
714 info->m_path.c_str(),
715 oflag,
716 mode),
717 eErrorTypePOSIX);
718 if (error.Fail() || log)
719 error.PutToLog(log,
720 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
721 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
722 }
723 break;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000724 }
725 return error.Success();
726}
727
728Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000729ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000730{
731 Error error;
Greg Clayton6475c422012-12-04 00:32:51 +0000732 const int short_option = m_getopt_table[option_idx].val;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000733
734 switch (short_option)
735 {
736 case 's': // Stop at program entry point
737 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
738 break;
739
Greg Claytonb72d0f02011-04-12 05:54:46 +0000740 case 'i': // STDIN for read only
741 {
742 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000743 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000744 launch_info.AppendFileAction (action);
745 }
746 break;
747
748 case 'o': // Open STDOUT for write only
749 {
750 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000751 if (action.Open (STDOUT_FILENO, option_arg, false, true))
752 launch_info.AppendFileAction (action);
753 }
754 break;
755
756 case 'e': // STDERR for write only
757 {
758 ProcessLaunchInfo::FileAction action;
759 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000760 launch_info.AppendFileAction (action);
761 }
762 break;
763
Greg Clayton95ec1682012-03-06 04:01:04 +0000764
Greg Claytonb72d0f02011-04-12 05:54:46 +0000765 case 'p': // Process plug-in name
766 launch_info.SetProcessPluginName (option_arg);
767 break;
768
769 case 'n': // Disable STDIO
770 {
771 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000772 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000773 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000774 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000775 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000776 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000777 launch_info.AppendFileAction (action);
778 }
779 break;
780
781 case 'w':
782 launch_info.SetWorkingDirectory (option_arg);
783 break;
784
785 case 't': // Open process in new terminal window
786 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
787 break;
788
789 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000790 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
791 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000792 break;
793
794 case 'A':
795 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
796 break;
797
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000798 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000799 if (option_arg && option_arg[0])
800 launch_info.SetShell (option_arg);
801 else
802 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000803 break;
804
Greg Claytonb72d0f02011-04-12 05:54:46 +0000805 case 'v':
806 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
807 break;
808
809 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000810 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000811 break;
812
813 }
814 return error;
815}
816
817OptionDefinition
818ProcessLaunchCommandOptions::g_option_table[] =
819{
820{ LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', no_argument, NULL, 0, eArgTypeNone, "Stop at the entry point of the program when launching a process."},
821{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
822{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
Sean Callanan9a91ef62012-10-24 01:12:14 +0000823{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypeDirectoryName, "Set the current working directory to <path> when running the inferior."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000824{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
825{ LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Sean Callanan9a91ef62012-10-24 01:12:14 +0000826{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypeFilename, "Run the process in a shell (not supported on all platforms)."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000827
Sean Callanan9a91ef62012-10-24 01:12:14 +0000828{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
829{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
830{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypeFilename, "Redirect stderr for the process to <filename>."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000831
832{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
833
834{ LLDB_OPT_SET_3 , false, "no-stdio", 'n', no_argument, NULL, 0, eArgTypeNone, "Do not set up for terminal I/O to go to running process."},
835
836{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
837};
838
839
840
841bool
842ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000843{
844 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
845 return true;
846 const char *match_name = m_match_info.GetName();
847 if (!match_name)
848 return true;
849
850 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
851}
852
853bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000854ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000855{
856 if (!NameMatches (proc_info.GetName()))
857 return false;
858
859 if (m_match_info.ProcessIDIsValid() &&
860 m_match_info.GetProcessID() != proc_info.GetProcessID())
861 return false;
862
863 if (m_match_info.ParentProcessIDIsValid() &&
864 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
865 return false;
866
Greg Claytonb72d0f02011-04-12 05:54:46 +0000867 if (m_match_info.UserIDIsValid () &&
868 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000869 return false;
870
Greg Claytonb72d0f02011-04-12 05:54:46 +0000871 if (m_match_info.GroupIDIsValid () &&
872 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000873 return false;
874
875 if (m_match_info.EffectiveUserIDIsValid () &&
876 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
877 return false;
878
879 if (m_match_info.EffectiveGroupIDIsValid () &&
880 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
881 return false;
882
883 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callanan40e278c2012-12-13 22:07:14 +0000884 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton24bc5d92011-03-30 18:16:51 +0000885 return false;
886 return true;
887}
888
889bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000890ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000891{
892 if (m_name_match_type != eNameMatchIgnore)
893 return false;
894
895 if (m_match_info.ProcessIDIsValid())
896 return false;
897
898 if (m_match_info.ParentProcessIDIsValid())
899 return false;
900
Greg Claytonb72d0f02011-04-12 05:54:46 +0000901 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000902 return false;
903
Greg Claytonb72d0f02011-04-12 05:54:46 +0000904 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000905 return false;
906
907 if (m_match_info.EffectiveUserIDIsValid ())
908 return false;
909
910 if (m_match_info.EffectiveGroupIDIsValid ())
911 return false;
912
913 if (m_match_info.GetArchitecture().IsValid())
914 return false;
915
916 if (m_match_all_users)
917 return false;
918
919 return true;
920
921}
922
923void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000924ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000925{
926 m_match_info.Clear();
927 m_name_match_type = eNameMatchIgnore;
928 m_match_all_users = false;
929}
Greg Claytonfd119992011-01-07 06:08:19 +0000930
Greg Clayton46c9a352012-02-09 06:16:32 +0000931ProcessSP
932Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000933{
Greg Clayton64742742013-01-16 17:29:04 +0000934 static uint32_t g_process_unique_id = 0;
935
Greg Clayton46c9a352012-02-09 06:16:32 +0000936 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000937 ProcessCreateInstance create_callback = NULL;
938 if (plugin_name)
939 {
940 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
941 if (create_callback)
942 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000943 process_sp = create_callback(target, listener, crash_file_path);
944 if (process_sp)
945 {
Greg Clayton64742742013-01-16 17:29:04 +0000946 if (process_sp->CanDebug(target, true))
947 {
948 process_sp->m_process_unique_id = ++g_process_unique_id;
949 }
950 else
Greg Clayton46c9a352012-02-09 06:16:32 +0000951 process_sp.reset();
952 }
Chris Lattner24943d22010-06-08 16:52:24 +0000953 }
954 }
955 else
956 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000957 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000958 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000959 process_sp = create_callback(target, listener, crash_file_path);
960 if (process_sp)
961 {
Greg Clayton64742742013-01-16 17:29:04 +0000962 if (process_sp->CanDebug(target, false))
963 {
964 process_sp->m_process_unique_id = ++g_process_unique_id;
Greg Clayton46c9a352012-02-09 06:16:32 +0000965 break;
Greg Clayton64742742013-01-16 17:29:04 +0000966 }
967 else
968 process_sp.reset();
Greg Clayton46c9a352012-02-09 06:16:32 +0000969 }
Chris Lattner24943d22010-06-08 16:52:24 +0000970 }
971 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000972 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000973}
974
Jim Ingham5a15e692012-02-16 06:50:00 +0000975ConstString &
976Process::GetStaticBroadcasterClass ()
977{
978 static ConstString class_name ("lldb.process");
979 return class_name;
980}
Chris Lattner24943d22010-06-08 16:52:24 +0000981
982//----------------------------------------------------------------------
983// Process constructor
984//----------------------------------------------------------------------
985Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +0000986 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +0000987 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000988 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +0000989 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000990 m_public_state (eStateUnloaded),
991 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000992 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
993 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000994 m_private_state_listener ("lldb.process.internal_state_listener"),
995 m_private_state_control_wait(),
996 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000997 m_mod_id (),
Greg Clayton64742742013-01-16 17:29:04 +0000998 m_process_unique_id(0),
Chris Lattner24943d22010-06-08 16:52:24 +0000999 m_thread_index_id (0),
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001000 m_thread_id_to_index_id_map (),
Chris Lattner24943d22010-06-08 16:52:24 +00001001 m_exit_status (-1),
1002 m_exit_string (),
1003 m_thread_list (this),
1004 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001005 m_image_tokens (),
1006 m_listener (listener),
1007 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001008 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +00001009 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +00001010 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +00001011 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +00001012 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +00001013 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +00001014 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +00001015 m_stderr_data (),
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001016 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
1017 m_profile_data (),
Greg Clayton613b8732011-05-17 03:37:42 +00001018 m_memory_cache (*this),
1019 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +00001020 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +00001021 m_next_event_action_ap(),
Greg Clayton0e7cff42013-04-11 22:26:47 +00001022 m_public_run_lock (),
1023 m_private_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +00001024 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001025 m_finalize_called(false),
Jim Ingham89e248f2013-02-09 01:29:05 +00001026 m_last_broadcast_state (eStateInvalid),
Jason Molenda1d9c8022013-03-05 03:33:59 +00001027 m_destroy_in_process (false),
1028 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +00001029{
Jim Ingham5a15e692012-02-16 06:50:00 +00001030 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +00001031
Greg Clayton952e9dc2013-03-27 23:08:40 +00001032 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001033 if (log)
1034 log->Printf ("%p Process::Process()", this);
1035
Greg Clayton49ce6822010-10-31 03:01:06 +00001036 SetEventName (eBroadcastBitStateChanged, "state-changed");
1037 SetEventName (eBroadcastBitInterrupt, "interrupt");
1038 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1039 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001040 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Clayton49ce6822010-10-31 03:01:06 +00001041
Greg Clayton84332782012-10-29 20:52:08 +00001042 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1043 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1044 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1045
Chris Lattner24943d22010-06-08 16:52:24 +00001046 listener.StartListeningForEvents (this,
1047 eBroadcastBitStateChanged |
1048 eBroadcastBitInterrupt |
1049 eBroadcastBitSTDOUT |
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001050 eBroadcastBitSTDERR |
1051 eBroadcastBitProfileData);
Chris Lattner24943d22010-06-08 16:52:24 +00001052
1053 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001054 eBroadcastBitStateChanged |
1055 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +00001056
1057 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1058 eBroadcastInternalStateControlStop |
1059 eBroadcastInternalStateControlPause |
1060 eBroadcastInternalStateControlResume);
1061}
1062
1063//----------------------------------------------------------------------
1064// Destructor
1065//----------------------------------------------------------------------
1066Process::~Process()
1067{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001068 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001069 if (log)
1070 log->Printf ("%p Process::~Process()", this);
1071 StopPrivateStateThread();
1072}
1073
Greg Clayton73844aa2012-08-22 17:17:09 +00001074const ProcessPropertiesSP &
1075Process::GetGlobalProperties()
1076{
1077 static ProcessPropertiesSP g_settings_sp;
1078 if (!g_settings_sp)
1079 g_settings_sp.reset (new ProcessProperties (true));
1080 return g_settings_sp;
1081}
1082
Chris Lattner24943d22010-06-08 16:52:24 +00001083void
1084Process::Finalize()
1085{
Greg Claytonffa43a62011-11-17 04:46:02 +00001086 switch (GetPrivateState())
1087 {
1088 case eStateConnected:
1089 case eStateAttaching:
1090 case eStateLaunching:
1091 case eStateStopped:
1092 case eStateRunning:
1093 case eStateStepping:
1094 case eStateCrashed:
1095 case eStateSuspended:
1096 if (GetShouldDetach())
1097 Detach();
1098 else
1099 Destroy();
1100 break;
1101
1102 case eStateInvalid:
1103 case eStateUnloaded:
1104 case eStateDetached:
1105 case eStateExited:
1106 break;
1107 }
1108
Greg Clayton2f57db02011-10-01 00:45:15 +00001109 // Clear our broadcaster before we proceed with destroying
1110 Broadcaster::Clear();
1111
Chris Lattner24943d22010-06-08 16:52:24 +00001112 // Do any cleanup needed prior to being destructed... Subclasses
1113 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001114
1115 // We need to destroy the loader before the derived Process class gets destroyed
1116 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001117 m_dynamic_checkers_ap.reset();
1118 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001119 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001120 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001121 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001122 std::vector<Notifications> empty_notifications;
1123 m_notifications.swap(empty_notifications);
1124 m_image_tokens.clear();
1125 m_memory_cache.Clear();
1126 m_allocated_memory_cache.Clear();
1127 m_language_runtimes.clear();
1128 m_next_event_action_ap.reset();
Greg Clayton84332782012-10-29 20:52:08 +00001129//#ifdef LLDB_CONFIGURATION_DEBUG
1130// StreamFile s(stdout, false);
1131// EventSP event_sp;
1132// while (m_private_state_listener.GetNextEvent(event_sp))
1133// {
1134// event_sp->Dump (&s);
1135// s.EOL();
1136// }
1137//#endif
1138 // We have to be very careful here as the m_private_state_listener might
1139 // contain events that have ProcessSP values in them which can keep this
1140 // process around forever. These events need to be cleared out.
1141 m_private_state_listener.Clear();
Greg Clayton0e7cff42013-04-11 22:26:47 +00001142 m_public_run_lock.WriteUnlock();
1143 m_private_run_lock.WriteUnlock();
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001144 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001145}
1146
1147void
1148Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1149{
1150 m_notifications.push_back(callbacks);
1151 if (callbacks.initialize != NULL)
1152 callbacks.initialize (callbacks.baton, this);
1153}
1154
1155bool
1156Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1157{
1158 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1159 for (pos = m_notifications.begin(); pos != end; ++pos)
1160 {
1161 if (pos->baton == callbacks.baton &&
1162 pos->initialize == callbacks.initialize &&
1163 pos->process_state_changed == callbacks.process_state_changed)
1164 {
1165 m_notifications.erase(pos);
1166 return true;
1167 }
1168 }
1169 return false;
1170}
1171
1172void
1173Process::SynchronouslyNotifyStateChanged (StateType state)
1174{
1175 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1176 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1177 {
1178 if (notification_pos->process_state_changed)
1179 notification_pos->process_state_changed (notification_pos->baton, this, state);
1180 }
1181}
1182
1183// FIXME: We need to do some work on events before the general Listener sees them.
1184// For instance if we are continuing from a breakpoint, we need to ensure that we do
1185// the little "insert real insn, step & stop" trick. But we can't do that when the
1186// event is delivered by the broadcaster - since that is done on the thread that is
1187// waiting for new events, so if we needed more than one event for our handling, we would
1188// stall. So instead we do it when we fetch the event off of the queue.
1189//
1190
1191StateType
1192Process::GetNextEvent (EventSP &event_sp)
1193{
1194 StateType state = eStateInvalid;
1195
1196 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1197 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1198
1199 return state;
1200}
1201
1202
1203StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001204Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001205{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001206 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1207 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1208 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001209 if (event_sp_ptr)
1210 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001211 StateType state = GetState();
1212 // If we are exited or detached, we won't ever get back to any
1213 // other valid state...
1214 if (state == eStateDetached || state == eStateExited)
1215 return state;
1216
1217 while (state != eStateInvalid)
1218 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001219 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001220 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001221 if (event_sp_ptr && event_sp)
1222 *event_sp_ptr = event_sp;
1223
Jim Ingham21f37ad2011-08-09 02:12:22 +00001224 switch (state)
1225 {
1226 case eStateCrashed:
1227 case eStateDetached:
1228 case eStateExited:
1229 case eStateUnloaded:
1230 return state;
1231 case eStateStopped:
1232 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1233 continue;
1234 else
1235 return state;
1236 default:
1237 continue;
1238 }
1239 }
1240 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001241}
1242
1243
1244StateType
1245Process::WaitForState
1246(
1247 const TimeValue *timeout,
1248 const StateType *match_states, const uint32_t num_match_states
1249)
1250{
1251 EventSP event_sp;
1252 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001253 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001254 while (state != eStateInvalid)
1255 {
Greg Claytond8c62532010-10-07 04:19:01 +00001256 // If we are exited or detached, we won't ever get back to any
1257 // other valid state...
1258 if (state == eStateDetached || state == eStateExited)
1259 return state;
1260
Chris Lattner24943d22010-06-08 16:52:24 +00001261 state = WaitForStateChangedEvents (timeout, event_sp);
1262
1263 for (i=0; i<num_match_states; ++i)
1264 {
1265 if (match_states[i] == state)
1266 return state;
1267 }
1268 }
1269 return state;
1270}
1271
Jim Ingham63e24d72010-10-11 23:53:14 +00001272bool
1273Process::HijackProcessEvents (Listener *listener)
1274{
1275 if (listener != NULL)
1276 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001277 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001278 }
1279 else
1280 return false;
1281}
1282
1283void
1284Process::RestoreProcessEvents ()
1285{
1286 RestoreBroadcaster();
1287}
1288
Jim Inghamf9f40c22011-02-08 05:20:59 +00001289bool
1290Process::HijackPrivateProcessEvents (Listener *listener)
1291{
1292 if (listener != NULL)
1293 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001294 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001295 }
1296 else
1297 return false;
1298}
1299
1300void
1301Process::RestorePrivateProcessEvents ()
1302{
1303 m_private_state_broadcaster.RestoreBroadcaster();
1304}
1305
Chris Lattner24943d22010-06-08 16:52:24 +00001306StateType
1307Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1308{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001309 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001310
1311 if (log)
1312 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1313
1314 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001315 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1316 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001317 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001318 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001319 {
1320 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1321 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1322 else if (log)
1323 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1324 }
Chris Lattner24943d22010-06-08 16:52:24 +00001325
1326 if (log)
1327 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1328 __FUNCTION__,
1329 timeout,
1330 StateAsCString(state));
1331 return state;
1332}
1333
1334Event *
1335Process::PeekAtStateChangedEvents ()
1336{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001337 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001338
1339 if (log)
1340 log->Printf ("Process::%s...", __FUNCTION__);
1341
1342 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001343 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1344 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001345 if (log)
1346 {
1347 if (event_ptr)
1348 {
1349 log->Printf ("Process::%s (event_ptr) => %s",
1350 __FUNCTION__,
1351 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1352 }
1353 else
1354 {
1355 log->Printf ("Process::%s no events found",
1356 __FUNCTION__);
1357 }
1358 }
1359 return event_ptr;
1360}
1361
1362StateType
1363Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1364{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001365 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001366
1367 if (log)
1368 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1369
1370 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001371 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1372 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001373 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001374 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001375 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1376 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001377
1378 // This is a bit of a hack, but when we wait here we could very well return
1379 // to the command-line, and that could disable the log, which would render the
1380 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001381 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001382 {
1383 if (state == eStateInvalid)
1384 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1385 else
1386 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1387 }
Chris Lattner24943d22010-06-08 16:52:24 +00001388 return state;
1389}
1390
1391bool
1392Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1393{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001394 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001395
1396 if (log)
1397 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1398
1399 if (control_only)
1400 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1401 else
1402 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1403}
1404
1405bool
1406Process::IsRunning () const
1407{
1408 return StateIsRunningState (m_public_state.GetValue());
1409}
1410
1411int
1412Process::GetExitStatus ()
1413{
1414 if (m_public_state.GetValue() == eStateExited)
1415 return m_exit_status;
1416 return -1;
1417}
1418
Greg Clayton638351a2010-12-04 00:10:17 +00001419
Chris Lattner24943d22010-06-08 16:52:24 +00001420const char *
1421Process::GetExitDescription ()
1422{
1423 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1424 return m_exit_string.c_str();
1425 return NULL;
1426}
1427
Greg Clayton72e1c782011-01-22 23:43:18 +00001428bool
Chris Lattner24943d22010-06-08 16:52:24 +00001429Process::SetExitStatus (int status, const char *cstr)
1430{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001431 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton68ca8232011-01-25 02:58:48 +00001432 if (log)
1433 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1434 status, status,
1435 cstr ? "\"" : "",
1436 cstr ? cstr : "NULL",
1437 cstr ? "\"" : "");
1438
Greg Clayton72e1c782011-01-22 23:43:18 +00001439 // We were already in the exited state
1440 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001441 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001442 if (log)
1443 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001444 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001445 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001446
1447 m_exit_status = status;
1448 if (cstr)
1449 m_exit_string = cstr;
1450 else
1451 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001452
Greg Clayton72e1c782011-01-22 23:43:18 +00001453 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001454
Greg Clayton72e1c782011-01-22 23:43:18 +00001455 SetPrivateState (eStateExited);
1456 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001457}
1458
1459// This static callback can be used to watch for local child processes on
1460// the current host. The the child process exits, the process will be
1461// found in the global target list (we want to be completely sure that the
1462// lldb_private::Process doesn't go away before we can deliver the signal.
1463bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001464Process::SetProcessExitStatus (void *callback_baton,
1465 lldb::pid_t pid,
1466 bool exited,
1467 int signo, // Zero for no signal
1468 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001469)
1470{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001471 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton1c4642c2011-11-16 05:37:56 +00001472 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001473 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001474 callback_baton,
1475 pid,
1476 exited,
1477 signo,
1478 exit_status);
1479
1480 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001481 {
Greg Clayton63094e02010-06-23 01:19:29 +00001482 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001483 if (target_sp)
1484 {
1485 ProcessSP process_sp (target_sp->GetProcessSP());
1486 if (process_sp)
1487 {
1488 const char *signal_cstr = NULL;
1489 if (signo)
1490 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1491
1492 process_sp->SetExitStatus (exit_status, signal_cstr);
1493 }
1494 }
1495 return true;
1496 }
1497 return false;
1498}
1499
1500
Greg Clayton37f962e2011-08-22 02:49:39 +00001501void
1502Process::UpdateThreadListIfNeeded ()
1503{
1504 const uint32_t stop_id = GetStopID();
1505 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1506 {
Greg Clayton20206082011-11-17 01:23:07 +00001507 const StateType state = GetPrivateState();
1508 if (StateIsStoppedState (state, true))
1509 {
1510 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001511 // m_thread_list does have its own mutex, but we need to
1512 // hold onto the mutex between the call to UpdateThreadList(...)
1513 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001514 ThreadList new_thread_list(this);
1515 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001516 // thread list, but only update if "true" is returned
1517 if (UpdateThreadList (m_thread_list, new_thread_list))
1518 {
Jim Inghameb175302013-03-01 20:04:25 +00001519 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1520 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1521 // shutting us down, causing a deadlock.
1522 if (!m_destroy_in_process)
1523 {
1524 OperatingSystem *os = GetOperatingSystem ();
1525 if (os)
Greg Clayton9acf3692013-04-12 20:07:46 +00001526 {
1527 // Clear any old backing threads where memory threads might have been
1528 // backed by actual threads from the lldb_private::Process subclass
1529 size_t num_old_threads = m_thread_list.GetSize(false);
1530 for (size_t i=0; i<num_old_threads; ++i)
1531 m_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1532
1533 // Now let the OperatingSystem plug-in update the thread list
Jim Inghameb175302013-03-01 20:04:25 +00001534 os->UpdateThreadList (m_thread_list, new_thread_list);
Greg Clayton9acf3692013-04-12 20:07:46 +00001535 }
Jim Inghameb175302013-03-01 20:04:25 +00001536 m_thread_list.Update (new_thread_list);
1537 m_thread_list.SetStopID (stop_id);
1538 }
Greg Claytonae932352012-04-10 00:18:59 +00001539 }
Greg Clayton20206082011-11-17 01:23:07 +00001540 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001541 }
1542}
1543
Greg Clayton52ebc0a2013-01-18 23:41:08 +00001544ThreadSP
1545Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1546{
1547 OperatingSystem *os = GetOperatingSystem ();
1548 if (os)
1549 return os->CreateThread(tid, context);
1550 return ThreadSP();
1551}
1552
1553
1554
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001555// This is obsoleted. Staged removal for Xcode.
Chris Lattner24943d22010-06-08 16:52:24 +00001556uint32_t
1557Process::GetNextThreadIndexID ()
1558{
1559 return ++m_thread_index_id;
1560}
1561
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001562uint32_t
1563Process::GetNextThreadIndexID (uint64_t thread_id)
1564{
1565 return AssignIndexIDToThread(thread_id);
1566}
1567
1568bool
1569Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1570{
1571 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1572 if (iterator == m_thread_id_to_index_id_map.end())
1573 {
1574 return false;
1575 }
1576 else
1577 {
1578 return true;
1579 }
1580}
1581
1582uint32_t
1583Process::AssignIndexIDToThread(uint64_t thread_id)
1584{
1585 uint32_t result = 0;
1586 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1587 if (iterator == m_thread_id_to_index_id_map.end())
1588 {
1589 result = ++m_thread_index_id;
1590 m_thread_id_to_index_id_map[thread_id] = result;
1591 }
1592 else
1593 {
1594 result = iterator->second;
1595 }
1596
1597 return result;
1598}
1599
Chris Lattner24943d22010-06-08 16:52:24 +00001600StateType
1601Process::GetState()
1602{
1603 // If any other threads access this we will need a mutex for it
1604 return m_public_state.GetValue ();
1605}
1606
1607void
1608Process::SetPublicState (StateType new_state)
1609{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001610 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001611 if (log)
1612 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001613 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001614 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001615
1616 // On the transition from Run to Stopped, we unlock the writer end of the
1617 // run lock. The lock gets locked in Resume, which is the public API
1618 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001619 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1620 {
Sean Callanana3772862012-06-02 01:16:20 +00001621 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001622 {
Sean Callanana3772862012-06-02 01:16:20 +00001623 if (log)
1624 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Greg Clayton0e7cff42013-04-11 22:26:47 +00001625 m_public_run_lock.WriteUnlock();
Sean Callanana3772862012-06-02 01:16:20 +00001626 }
1627 else
1628 {
1629 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1630 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1631 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001632 {
Sean Callanana3772862012-06-02 01:16:20 +00001633 if (new_state_is_stopped)
1634 {
1635 if (log)
1636 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Greg Clayton0e7cff42013-04-11 22:26:47 +00001637 m_public_run_lock.WriteUnlock();
Sean Callanana3772862012-06-02 01:16:20 +00001638 }
Greg Claytona894fe72012-04-05 16:12:35 +00001639 }
Greg Claytona894fe72012-04-05 16:12:35 +00001640 }
1641 }
Chris Lattner24943d22010-06-08 16:52:24 +00001642}
1643
Jim Ingham027aaa72012-04-19 01:40:33 +00001644Error
1645Process::Resume ()
1646{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001647 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham027aaa72012-04-19 01:40:33 +00001648 if (log)
1649 log->Printf("Process::Resume -- locking run lock");
Greg Clayton0e7cff42013-04-11 22:26:47 +00001650 if (!m_public_run_lock.WriteTryLock())
Jim Ingham027aaa72012-04-19 01:40:33 +00001651 {
1652 Error error("Resume request failed - process still running.");
1653 if (log)
1654 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1655 return error;
1656 }
1657 return PrivateResume();
1658}
1659
Chris Lattner24943d22010-06-08 16:52:24 +00001660StateType
1661Process::GetPrivateState ()
1662{
1663 return m_private_state.GetValue();
1664}
1665
1666void
1667Process::SetPrivateState (StateType new_state)
1668{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001669 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001670 bool state_changed = false;
1671
1672 if (log)
1673 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1674
1675 Mutex::Locker locker(m_private_state.GetMutex());
1676
1677 const StateType old_state = m_private_state.GetValueNoLock ();
1678 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001679 // This code is left commented out in case we ever need to control
1680 // the private process state with another run lock. Right now it doesn't
1681 // seem like we need to do this, but if we ever do, we can uncomment and
1682 // use this code.
1683// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1684// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1685// if (old_state_is_stopped != new_state_is_stopped)
1686// {
1687// if (new_state_is_stopped)
1688// m_private_run_lock.WriteUnlock();
1689// else
1690// m_private_run_lock.WriteLock();
1691// }
1692
Chris Lattner24943d22010-06-08 16:52:24 +00001693 if (state_changed)
1694 {
1695 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001696 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001697 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001698 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001699 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001700 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001701 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001702 }
1703 // Use our target to get a shared pointer to ourselves...
Greg Clayton84332782012-10-29 20:52:08 +00001704 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1705 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1706 else
1707 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001708 }
1709 else
1710 {
1711 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001712 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001713 }
1714}
1715
Jim Ingham0296fe72011-11-08 03:00:11 +00001716void
1717Process::SetRunningUserExpression (bool on)
1718{
1719 m_mod_id.SetRunningUserExpression (on);
1720}
1721
Chris Lattner24943d22010-06-08 16:52:24 +00001722addr_t
1723Process::GetImageInfoAddress()
1724{
1725 return LLDB_INVALID_ADDRESS;
1726}
1727
Greg Clayton0baa3942010-11-04 01:54:29 +00001728//----------------------------------------------------------------------
1729// LoadImage
1730//
1731// This function provides a default implementation that works for most
1732// unix variants. Any Process subclasses that need to do shared library
1733// loading differently should override LoadImage and UnloadImage and
1734// do what is needed.
1735//----------------------------------------------------------------------
1736uint32_t
1737Process::LoadImage (const FileSpec &image_spec, Error &error)
1738{
Greg Clayton77d40712012-04-18 00:05:19 +00001739 char path[PATH_MAX];
1740 image_spec.GetPath(path, sizeof(path));
1741
Greg Clayton0baa3942010-11-04 01:54:29 +00001742 DynamicLoader *loader = GetDynamicLoader();
1743 if (loader)
1744 {
1745 error = loader->CanLoadImage();
1746 if (error.Fail())
1747 return LLDB_INVALID_IMAGE_TOKEN;
1748 }
1749
1750 if (error.Success())
1751 {
1752 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001753
1754 if (thread_sp)
1755 {
1756 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1757
1758 if (frame_sp)
1759 {
1760 ExecutionContext exe_ctx;
1761 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001762 const bool unwind_on_error = true;
1763 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001764 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001765 expr.Printf("dlopen (\"%s\", 2)", path);
1766 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001767 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001768 ClangUserExpression::Evaluate (exe_ctx,
1769 eExecutionPolicyAlways,
1770 lldb::eLanguageTypeUnknown,
1771 ClangUserExpression::eResultTypeAny,
1772 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001773 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001774 expr.GetData(),
1775 prefix,
1776 result_valobj_sp,
1777 true,
1778 ClangUserExpression::kDefaultTimeout);
Johnny Chenb14ec342011-09-09 00:01:43 +00001779 error = result_valobj_sp->GetError();
1780 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001781 {
1782 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001783 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001784 {
1785 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1786 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1787 {
1788 uint32_t image_token = m_image_tokens.size();
1789 m_image_tokens.push_back (image_ptr);
1790 return image_token;
1791 }
1792 }
1793 }
1794 }
1795 }
1796 }
Greg Clayton77d40712012-04-18 00:05:19 +00001797 if (!error.AsCString())
1798 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001799 return LLDB_INVALID_IMAGE_TOKEN;
1800}
1801
1802//----------------------------------------------------------------------
1803// UnloadImage
1804//
1805// This function provides a default implementation that works for most
1806// unix variants. Any Process subclasses that need to do shared library
1807// loading differently should override LoadImage and UnloadImage and
1808// do what is needed.
1809//----------------------------------------------------------------------
1810Error
1811Process::UnloadImage (uint32_t image_token)
1812{
1813 Error error;
1814 if (image_token < m_image_tokens.size())
1815 {
1816 const addr_t image_addr = m_image_tokens[image_token];
1817 if (image_addr == LLDB_INVALID_ADDRESS)
1818 {
1819 error.SetErrorString("image already unloaded");
1820 }
1821 else
1822 {
1823 DynamicLoader *loader = GetDynamicLoader();
1824 if (loader)
1825 error = loader->CanLoadImage();
1826
1827 if (error.Success())
1828 {
1829 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001830
1831 if (thread_sp)
1832 {
1833 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1834
1835 if (frame_sp)
1836 {
1837 ExecutionContext exe_ctx;
1838 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001839 const bool unwind_on_error = true;
1840 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001841 StreamString expr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001842 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton0baa3942010-11-04 01:54:29 +00001843 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001844 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001845 ClangUserExpression::Evaluate (exe_ctx,
1846 eExecutionPolicyAlways,
1847 lldb::eLanguageTypeUnknown,
1848 ClangUserExpression::eResultTypeAny,
1849 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001850 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001851 expr.GetData(),
1852 prefix,
1853 result_valobj_sp,
1854 true,
1855 ClangUserExpression::kDefaultTimeout);
Greg Clayton0baa3942010-11-04 01:54:29 +00001856 if (result_valobj_sp->GetError().Success())
1857 {
1858 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001859 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001860 {
1861 if (scalar.UInt(1))
1862 {
1863 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1864 }
1865 else
1866 {
1867 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1868 }
1869 }
1870 }
1871 else
1872 {
1873 error = result_valobj_sp->GetError();
1874 }
1875 }
1876 }
1877 }
1878 }
1879 }
1880 else
1881 {
1882 error.SetErrorString("invalid image token");
1883 }
1884 return error;
1885}
1886
Greg Clayton75906e42011-05-11 18:39:18 +00001887const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001888Process::GetABI()
1889{
Greg Clayton75906e42011-05-11 18:39:18 +00001890 if (!m_abi_sp)
1891 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1892 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001893}
1894
Jim Ingham642036f2010-09-23 02:01:19 +00001895LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001896Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001897{
1898 LanguageRuntimeCollection::iterator pos;
1899 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001900 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001901 {
Jim Inghame3117662012-03-10 00:22:19 +00001902 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001903
Jim Inghame3117662012-03-10 00:22:19 +00001904 m_language_runtimes[language] = runtime_sp;
1905 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001906 }
1907 else
1908 return (*pos).second.get();
1909}
1910
1911CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001912Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001913{
Jim Inghame3117662012-03-10 00:22:19 +00001914 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001915 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1916 return static_cast<CPPLanguageRuntime *> (runtime);
1917 return NULL;
1918}
1919
1920ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001921Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001922{
Jim Inghame3117662012-03-10 00:22:19 +00001923 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001924 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1925 return static_cast<ObjCLanguageRuntime *> (runtime);
1926 return NULL;
1927}
1928
Enrico Granata6b1763b2012-05-21 16:51:35 +00001929bool
1930Process::IsPossibleDynamicValue (ValueObject& in_value)
1931{
1932 if (in_value.IsDynamic())
1933 return false;
1934 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1935
1936 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1937 {
1938 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1939 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1940 }
1941
1942 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1943 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1944 return true;
1945
1946 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1947 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1948}
1949
Chris Lattner24943d22010-06-08 16:52:24 +00001950BreakpointSiteList &
1951Process::GetBreakpointSiteList()
1952{
1953 return m_breakpoint_site_list;
1954}
1955
1956const BreakpointSiteList &
1957Process::GetBreakpointSiteList() const
1958{
1959 return m_breakpoint_site_list;
1960}
1961
1962
1963void
1964Process::DisableAllBreakpointSites ()
1965{
1966 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001967 size_t num_sites = m_breakpoint_site_list.GetSize();
1968 for (size_t i = 0; i < num_sites; i++)
1969 {
Jim Inghamefb4aeb2013-02-15 02:06:30 +00001970 DisableBreakpointSite (m_breakpoint_site_list.GetByIndex(i).get());
Jim Ingham06b84492012-07-04 00:35:43 +00001971 }
Chris Lattner24943d22010-06-08 16:52:24 +00001972}
1973
1974Error
1975Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1976{
1977 Error error (DisableBreakpointSiteByID (break_id));
1978
1979 if (error.Success())
1980 m_breakpoint_site_list.Remove(break_id);
1981
1982 return error;
1983}
1984
1985Error
1986Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1987{
1988 Error error;
1989 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1990 if (bp_site_sp)
1991 {
1992 if (bp_site_sp->IsEnabled())
Jim Inghamefb4aeb2013-02-15 02:06:30 +00001993 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001994 }
1995 else
1996 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001997 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001998 }
1999
2000 return error;
2001}
2002
2003Error
2004Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2005{
2006 Error error;
2007 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2008 if (bp_site_sp)
2009 {
2010 if (!bp_site_sp->IsEnabled())
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002011 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002012 }
2013 else
2014 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002015 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00002016 }
2017 return error;
2018}
2019
Stephen Wilson3fd1f362010-07-17 00:56:13 +00002020lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00002021Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00002022{
Greg Clayton265ab332011-05-19 18:17:41 +00002023 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002024 if (load_addr != LLDB_INVALID_ADDRESS)
2025 {
2026 BreakpointSiteSP bp_site_sp;
2027
2028 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2029 // create a new breakpoint site and add it.
2030
2031 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2032
2033 if (bp_site_sp)
2034 {
2035 bp_site_sp->AddOwner (owner);
2036 owner->SetBreakpointSite (bp_site_sp);
2037 return bp_site_sp->GetID();
2038 }
2039 else
2040 {
Greg Clayton36da2aa2013-01-25 18:06:21 +00002041 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner24943d22010-06-08 16:52:24 +00002042 if (bp_site_sp)
2043 {
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002044 if (EnableBreakpointSite (bp_site_sp.get()).Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002045 {
2046 owner->SetBreakpointSite (bp_site_sp);
2047 return m_breakpoint_site_list.Add (bp_site_sp);
2048 }
2049 }
2050 }
2051 }
2052 // We failed to enable the breakpoint
2053 return LLDB_INVALID_BREAK_ID;
2054
2055}
2056
2057void
2058Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2059{
2060 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2061 if (num_owners == 0)
2062 {
Jim Ingham700ff7e2013-04-06 00:16:39 +00002063 // Don't try to disable the site if we don't have a live process anymore.
2064 if (IsAlive())
2065 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002066 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2067 }
2068}
2069
2070
2071size_t
2072Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2073{
2074 size_t bytes_removed = 0;
2075 addr_t intersect_addr;
2076 size_t intersect_size;
2077 size_t opcode_offset;
2078 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002079 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00002080 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00002081
Jim Ingham82820f92011-06-29 19:42:28 +00002082 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00002083 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002084 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00002085 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002086 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00002087 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002088 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00002089 {
2090 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2091 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00002092 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00002093 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002094 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00002095 }
Chris Lattner24943d22010-06-08 16:52:24 +00002096 }
2097 }
2098 }
2099 return bytes_removed;
2100}
2101
2102
Greg Claytonb1888f22011-03-19 01:12:21 +00002103
2104size_t
2105Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2106{
2107 PlatformSP platform_sp (m_target.GetPlatform());
2108 if (platform_sp)
2109 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2110 return 0;
2111}
2112
Chris Lattner24943d22010-06-08 16:52:24 +00002113Error
2114Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2115{
2116 Error error;
2117 assert (bp_site != NULL);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002118 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002119 const addr_t bp_addr = bp_site->GetLoadAddress();
2120 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002121 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002122 if (bp_site->IsEnabled())
2123 {
2124 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002125 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 +00002126 return error;
2127 }
2128
2129 if (bp_addr == LLDB_INVALID_ADDRESS)
2130 {
2131 error.SetErrorString("BreakpointSite contains an invalid load address.");
2132 return error;
2133 }
2134 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2135 // trap for the breakpoint site
2136 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2137
2138 if (bp_opcode_size == 0)
2139 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002140 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002141 }
2142 else
2143 {
2144 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2145
2146 if (bp_opcode_bytes == NULL)
2147 {
2148 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2149 return error;
2150 }
2151
2152 // Save the original opcode by reading it
2153 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2154 {
2155 // Write a software breakpoint in place of the original opcode
2156 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2157 {
2158 uint8_t verify_bp_opcode_bytes[64];
2159 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2160 {
2161 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2162 {
2163 bp_site->SetEnabled(true);
2164 bp_site->SetType (BreakpointSite::eSoftware);
2165 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002166 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner24943d22010-06-08 16:52:24 +00002167 bp_site->GetID(),
2168 (uint64_t)bp_addr);
2169 }
2170 else
Greg Clayton9c236732011-10-26 00:56:27 +00002171 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00002172 }
2173 else
2174 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2175 }
2176 else
2177 error.SetErrorString("Unable to write breakpoint trap to memory.");
2178 }
2179 else
2180 error.SetErrorString("Unable to read memory at breakpoint address.");
2181 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002182 if (log && error.Fail())
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002183 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002184 bp_site->GetID(),
2185 (uint64_t)bp_addr,
2186 error.AsCString());
2187 return error;
2188}
2189
2190Error
2191Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2192{
2193 Error error;
2194 assert (bp_site != NULL);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002195 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002196 addr_t bp_addr = bp_site->GetLoadAddress();
2197 lldb::user_id_t breakID = bp_site->GetID();
2198 if (log)
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002199 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002200
2201 if (bp_site->IsHardware())
2202 {
2203 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2204 }
2205 else if (bp_site->IsEnabled())
2206 {
2207 const size_t break_op_size = bp_site->GetByteSize();
2208 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2209 if (break_op_size > 0)
2210 {
2211 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002212 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002213 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002214 bool break_op_found = false;
2215
2216 // Read the breakpoint opcode
2217 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2218 {
2219 bool verify = false;
2220 // Make sure we have the a breakpoint opcode exists at this address
2221 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2222 {
2223 break_op_found = true;
2224 // We found a valid breakpoint opcode at this address, now restore
2225 // the saved opcode.
2226 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2227 {
2228 verify = true;
2229 }
2230 else
2231 error.SetErrorString("Memory write failed when restoring original opcode.");
2232 }
2233 else
2234 {
2235 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2236 // Set verify to true and so we can check if the original opcode has already been restored
2237 verify = true;
2238 }
2239
2240 if (verify)
2241 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002242 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002243 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002244 // Verify that our original opcode made it back to the inferior
2245 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2246 {
2247 // compare the memory we just read with the original opcode
2248 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2249 {
2250 // SUCCESS
2251 bp_site->SetEnabled(false);
2252 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002253 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 +00002254 return error;
2255 }
2256 else
2257 {
2258 if (break_op_found)
2259 error.SetErrorString("Failed to restore original opcode.");
2260 }
2261 }
2262 else
2263 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2264 }
2265 }
2266 else
2267 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2268 }
2269 }
2270 else
2271 {
2272 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002273 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 +00002274 return error;
2275 }
2276
2277 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002278 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002279 bp_site->GetID(),
2280 (uint64_t)bp_addr,
2281 error.AsCString());
2282 return error;
2283
2284}
2285
Greg Claytonfd119992011-01-07 06:08:19 +00002286// Uncomment to verify memory caching works after making changes to caching code
2287//#define VERIFY_MEMORY_READS
2288
Sean Callananf90b5f32012-06-07 22:26:42 +00002289size_t
2290Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2291{
2292 if (!GetDisableMemoryCache())
2293 {
Greg Claytonfd119992011-01-07 06:08:19 +00002294#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002295 // Memory caching is enabled, with debug verification
2296
2297 if (buf && size)
2298 {
2299 // Uncomment the line below to make sure memory caching is working.
2300 // I ran this through the test suite and got no assertions, so I am
2301 // pretty confident this is working well. If any changes are made to
2302 // memory caching, uncomment the line below and test your changes!
2303
2304 // Verify all memory reads by using the cache first, then redundantly
2305 // reading the same memory from the inferior and comparing to make sure
2306 // everything is exactly the same.
2307 std::string verify_buf (size, '\0');
2308 assert (verify_buf.size() == size);
2309 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2310 Error verify_error;
2311 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2312 assert (cache_bytes_read == verify_bytes_read);
2313 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2314 assert (verify_error.Success() == error.Success());
2315 return cache_bytes_read;
2316 }
2317 return 0;
2318#else // !defined(VERIFY_MEMORY_READS)
2319 // Memory caching is enabled, without debug verification
2320
2321 return m_memory_cache.Read (addr, buf, size, error);
2322#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002323 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002324 else
2325 {
2326 // Memory caching is disabled
2327
2328 return ReadMemoryFromInferior (addr, buf, size, error);
2329 }
Greg Claytonfd119992011-01-07 06:08:19 +00002330}
Greg Claytonfd119992011-01-07 06:08:19 +00002331
Greg Claytondd29b972012-05-18 23:20:01 +00002332size_t
2333Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2334{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002335 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002336 out_str.clear();
2337 addr_t curr_addr = addr;
2338 while (1)
2339 {
2340 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2341 if (length == 0)
2342 break;
2343 out_str.append(buf, length);
2344 // If we got "length - 1" bytes, we didn't get the whole C string, we
2345 // need to read some more characters
2346 if (length == sizeof(buf) - 1)
2347 curr_addr += length;
2348 else
2349 break;
2350 }
2351 return out_str.size();
2352}
2353
Greg Claytonfd119992011-01-07 06:08:19 +00002354
2355size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002356Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002357{
2358 size_t total_cstr_len = 0;
2359 if (dst && dst_max_len)
2360 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002361 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002362 // NULL out everything just to be safe
2363 memset (dst, 0, dst_max_len);
2364 Error error;
2365 addr_t curr_addr = addr;
2366 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2367 size_t bytes_left = dst_max_len - 1;
2368 char *curr_dst = dst;
2369
2370 while (bytes_left > 0)
2371 {
2372 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2373 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2374 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2375
2376 if (bytes_read == 0)
2377 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002378 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002379 dst[total_cstr_len] = '\0';
2380 break;
2381 }
2382 const size_t len = strlen(curr_dst);
2383
2384 total_cstr_len += len;
2385
2386 if (len < bytes_to_read)
2387 break;
2388
2389 curr_dst += bytes_read;
2390 curr_addr += bytes_read;
2391 bytes_left -= bytes_read;
2392 }
2393 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002394 else
2395 {
2396 if (dst == NULL)
2397 result_error.SetErrorString("invalid arguments");
2398 else
2399 result_error.Clear();
2400 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002401 return total_cstr_len;
2402}
2403
2404size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002405Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2406{
Chris Lattner24943d22010-06-08 16:52:24 +00002407 if (buf == NULL || size == 0)
2408 return 0;
2409
2410 size_t bytes_read = 0;
2411 uint8_t *bytes = (uint8_t *)buf;
2412
2413 while (bytes_read < size)
2414 {
2415 const size_t curr_size = size - bytes_read;
2416 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2417 bytes + bytes_read,
2418 curr_size,
2419 error);
2420 bytes_read += curr_bytes_read;
2421 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2422 break;
2423 }
2424
2425 // Replace any software breakpoint opcodes that fall into this range back
2426 // into "buf" before we return
2427 if (bytes_read > 0)
2428 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2429 return bytes_read;
2430}
2431
Greg Claytonf72fdee2010-12-16 20:01:20 +00002432uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002433Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002434{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002435 Scalar scalar;
2436 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2437 return scalar.ULongLong(fail_value);
2438 return fail_value;
2439}
2440
2441addr_t
2442Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2443{
2444 Scalar scalar;
2445 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2446 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2447 return LLDB_INVALID_ADDRESS;
2448}
2449
2450
2451bool
2452Process::WritePointerToMemory (lldb::addr_t vm_addr,
2453 lldb::addr_t ptr_value,
2454 Error &error)
2455{
2456 Scalar scalar;
2457 const uint32_t addr_byte_size = GetAddressByteSize();
2458 if (addr_byte_size <= 4)
2459 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002460 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002461 scalar = ptr_value;
2462 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002463}
2464
Chris Lattner24943d22010-06-08 16:52:24 +00002465size_t
2466Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2467{
2468 size_t bytes_written = 0;
2469 const uint8_t *bytes = (const uint8_t *)buf;
2470
2471 while (bytes_written < size)
2472 {
2473 const size_t curr_size = size - bytes_written;
2474 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2475 bytes + bytes_written,
2476 curr_size,
2477 error);
2478 bytes_written += curr_bytes_written;
2479 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2480 break;
2481 }
2482 return bytes_written;
2483}
2484
2485size_t
2486Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2487{
Greg Claytonfd119992011-01-07 06:08:19 +00002488#if defined (ENABLE_MEMORY_CACHING)
2489 m_memory_cache.Flush (addr, size);
2490#endif
2491
Chris Lattner24943d22010-06-08 16:52:24 +00002492 if (buf == NULL || size == 0)
2493 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002494
Jim Ingham21f37ad2011-08-09 02:12:22 +00002495 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002496
Chris Lattner24943d22010-06-08 16:52:24 +00002497 // We need to write any data that would go where any current software traps
2498 // (enabled software breakpoints) any software traps (breakpoints) that we
2499 // may have placed in our tasks memory.
2500
2501 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2502 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2503
2504 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002505 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002506
2507 BreakpointSiteList::collection::const_iterator pos;
2508 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002509 addr_t intersect_addr = 0;
2510 size_t intersect_size = 0;
2511 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002512 const uint8_t *ubuf = (const uint8_t *)buf;
2513
2514 for (pos = iter; pos != end; ++pos)
2515 {
2516 BreakpointSiteSP bp;
2517 bp = pos->second;
2518
2519 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2520 assert(addr <= intersect_addr && intersect_addr < addr + size);
2521 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2522 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2523
2524 // Check for bytes before this breakpoint
2525 const addr_t curr_addr = addr + bytes_written;
2526 if (intersect_addr > curr_addr)
2527 {
2528 // There are some bytes before this breakpoint that we need to
2529 // just write to memory
2530 size_t curr_size = intersect_addr - curr_addr;
2531 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2532 ubuf + bytes_written,
2533 curr_size,
2534 error);
2535 bytes_written += curr_bytes_written;
2536 if (curr_bytes_written != curr_size)
2537 {
2538 // We weren't able to write all of the requested bytes, we
2539 // are done looping and will return the number of bytes that
2540 // we have written so far.
2541 break;
2542 }
2543 }
2544
2545 // Now write any bytes that would cover up any software breakpoints
2546 // directly into the breakpoint opcode buffer
2547 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2548 bytes_written += intersect_size;
2549 }
2550
2551 // Write any remaining bytes after the last breakpoint if we have any left
2552 if (bytes_written < size)
2553 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2554 ubuf + bytes_written,
2555 size - bytes_written,
2556 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002557
Chris Lattner24943d22010-06-08 16:52:24 +00002558 return bytes_written;
2559}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002560
2561size_t
Greg Clayton36da2aa2013-01-25 18:06:21 +00002562Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonc0fa5332011-05-22 22:46:53 +00002563{
2564 if (byte_size == UINT32_MAX)
2565 byte_size = scalar.GetByteSize();
2566 if (byte_size > 0)
2567 {
2568 uint8_t buf[32];
2569 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2570 if (mem_size > 0)
2571 return WriteMemory(addr, buf, mem_size, error);
2572 else
2573 error.SetErrorString ("failed to get scalar as memory data");
2574 }
2575 else
2576 {
2577 error.SetErrorString ("invalid scalar value");
2578 }
2579 return 0;
2580}
2581
2582size_t
2583Process::ReadScalarIntegerFromMemory (addr_t addr,
2584 uint32_t byte_size,
2585 bool is_signed,
2586 Scalar &scalar,
2587 Error &error)
2588{
2589 uint64_t uval;
2590
2591 if (byte_size <= sizeof(uval))
2592 {
2593 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2594 if (bytes_read == byte_size)
2595 {
2596 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Clayton36da2aa2013-01-25 18:06:21 +00002597 lldb::offset_t offset = 0;
Greg Claytonc0fa5332011-05-22 22:46:53 +00002598 if (byte_size <= 4)
2599 scalar = data.GetMaxU32 (&offset, byte_size);
2600 else
2601 scalar = data.GetMaxU64 (&offset, byte_size);
2602
2603 if (is_signed)
2604 scalar.SignExtend(byte_size * 8);
2605 return bytes_read;
2606 }
2607 }
2608 else
2609 {
2610 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2611 }
2612 return 0;
2613}
2614
Greg Clayton613b8732011-05-17 03:37:42 +00002615#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002616addr_t
2617Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2618{
Jim Inghame6bd1422011-06-20 17:32:44 +00002619 if (GetPrivateState() != eStateStopped)
2620 return LLDB_INVALID_ADDRESS;
2621
Greg Clayton613b8732011-05-17 03:37:42 +00002622#if defined (USE_ALLOCATE_MEMORY_CACHE)
2623 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2624#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002625 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002626 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2860ba92011-01-23 19:58:49 +00002627 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002628 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 +00002629 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002630 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002631 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002632 m_mod_id.GetStopID(),
2633 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002634 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002635#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002636}
2637
Sean Callanan6cf6c472011-09-20 23:01:51 +00002638bool
2639Process::CanJIT ()
2640{
Sean Callanan04200f62012-02-14 22:50:38 +00002641 if (m_can_jit == eCanJITDontKnow)
2642 {
2643 Error err;
2644
2645 uint64_t allocated_memory = AllocateMemory(8,
2646 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2647 err);
2648
2649 if (err.Success())
2650 m_can_jit = eCanJITYes;
2651 else
2652 m_can_jit = eCanJITNo;
2653
2654 DeallocateMemory (allocated_memory);
2655 }
2656
Sean Callanan6cf6c472011-09-20 23:01:51 +00002657 return m_can_jit == eCanJITYes;
2658}
2659
2660void
2661Process::SetCanJIT (bool can_jit)
2662{
2663 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2664}
2665
Chris Lattner24943d22010-06-08 16:52:24 +00002666Error
2667Process::DeallocateMemory (addr_t ptr)
2668{
Greg Clayton613b8732011-05-17 03:37:42 +00002669 Error error;
2670#if defined (USE_ALLOCATE_MEMORY_CACHE)
2671 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2672 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002673 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Clayton613b8732011-05-17 03:37:42 +00002674 }
2675#else
2676 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002677
Greg Clayton952e9dc2013-03-27 23:08:40 +00002678 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2860ba92011-01-23 19:58:49 +00002679 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002680 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 +00002681 ptr,
2682 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002683 m_mod_id.GetStopID(),
2684 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002685#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002686 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002687}
2688
Han Ming Ong2529aa32012-11-17 00:33:14 +00002689
Greg Claytonb5a8f142012-02-05 02:38:54 +00002690ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002691Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton2ddb2b82013-02-01 21:38:35 +00002692 lldb::addr_t header_addr)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002693{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002694 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002695 if (module_sp)
2696 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002697 Error error;
2698 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2699 if (objfile)
Greg Clayton6c5438b2012-02-24 21:55:59 +00002700 return module_sp;
Greg Claytonb5a8f142012-02-05 02:38:54 +00002701 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002702 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002703}
Chris Lattner24943d22010-06-08 16:52:24 +00002704
2705Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002706Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002707{
2708 Error error;
2709 error.SetErrorString("watchpoints are not supported");
2710 return error;
2711}
2712
2713Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002714Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002715{
2716 Error error;
2717 error.SetErrorString("watchpoints are not supported");
2718 return error;
2719}
2720
2721StateType
2722Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2723{
2724 StateType state;
2725 // Now wait for the process to launch and return control to us, and then
2726 // call DidLaunch:
2727 while (1)
2728 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002729 event_sp.reset();
2730 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2731
Greg Clayton20206082011-11-17 01:23:07 +00002732 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002733 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002734
2735 // If state is invalid, then we timed out
2736 if (state == eStateInvalid)
2737 break;
2738
2739 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002740 HandlePrivateEvent (event_sp);
2741 }
2742 return state;
2743}
2744
2745Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002746Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002747{
2748 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002749 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002750 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002751 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002752 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002753
Greg Clayton5beb99d2011-08-11 02:48:45 +00002754 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002755 if (exe_module)
2756 {
Greg Clayton180546b2011-04-30 01:09:13 +00002757 char local_exec_file_path[PATH_MAX];
2758 char platform_exec_file_path[PATH_MAX];
2759 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2760 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002761 if (exe_module->GetFileSpec().Exists())
2762 {
Greg Claytona2f74232011-02-24 22:24:29 +00002763 if (PrivateStateThreadIsValid ())
2764 PausePrivateStateThread ();
2765
Chris Lattner24943d22010-06-08 16:52:24 +00002766 error = WillLaunch (exe_module);
2767 if (error.Success())
2768 {
Greg Claytond8c62532010-10-07 04:19:01 +00002769 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002770 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002771
Greg Clayton0e7cff42013-04-11 22:26:47 +00002772 if (m_public_run_lock.WriteTryLock())
Greg Clayton777c6b72012-09-04 20:29:05 +00002773 {
2774 // Now launch using these arguments.
2775 error = DoLaunch (exe_module, launch_info);
2776 }
2777 else
2778 {
2779 // This shouldn't happen
2780 error.SetErrorString("failed to acquire process run lock");
2781 }
Chris Lattner24943d22010-06-08 16:52:24 +00002782
2783 if (error.Fail())
2784 {
2785 if (GetID() != LLDB_INVALID_PROCESS_ID)
2786 {
2787 SetID (LLDB_INVALID_PROCESS_ID);
2788 const char *error_string = error.AsCString();
2789 if (error_string == NULL)
2790 error_string = "launch failed";
2791 SetExitStatus (-1, error_string);
2792 }
2793 }
2794 else
2795 {
2796 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002797 TimeValue timeout_time;
2798 timeout_time = TimeValue::Now();
2799 timeout_time.OffsetWithSeconds(10);
2800 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002801
Greg Clayton49859592011-06-22 01:42:17 +00002802 if (state == eStateInvalid || event_sp.get() == NULL)
2803 {
2804 // We were able to launch the process, but we failed to
2805 // catch the initial stop.
2806 SetExitStatus (0, "failed to catch stop after launch");
2807 Destroy();
2808 }
2809 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002810 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002811
Chris Lattner24943d22010-06-08 16:52:24 +00002812 DidLaunch ();
2813
Greg Clayton9ce95382012-02-13 23:10:39 +00002814 DynamicLoader *dyld = GetDynamicLoader ();
2815 if (dyld)
2816 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002817
Greg Clayton37f962e2011-08-22 02:49:39 +00002818 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002819 // This delays passing the stopped event to listeners till DidLaunch gets
2820 // a chance to complete...
2821 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002822
2823 if (PrivateStateThreadIsValid ())
2824 ResumePrivateStateThread ();
2825 else
2826 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002827 }
2828 else if (state == eStateExited)
2829 {
2830 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2831 // not likely to work, and return an invalid pid.
2832 HandlePrivateEvent (event_sp);
2833 }
2834 }
2835 }
2836 }
2837 else
2838 {
Greg Clayton9c236732011-10-26 00:56:27 +00002839 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002840 }
2841 }
2842 return error;
2843}
2844
Greg Clayton46c9a352012-02-09 06:16:32 +00002845
2846Error
2847Process::LoadCore ()
2848{
2849 Error error = DoLoadCore();
2850 if (error.Success())
2851 {
2852 if (PrivateStateThreadIsValid ())
2853 ResumePrivateStateThread ();
2854 else
2855 StartPrivateStateThread ();
2856
Greg Clayton9ce95382012-02-13 23:10:39 +00002857 DynamicLoader *dyld = GetDynamicLoader ();
2858 if (dyld)
2859 dyld->DidAttach();
2860
2861 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002862 // We successfully loaded a core file, now pretend we stopped so we can
2863 // show all of the threads in the core file and explore the crashed
2864 // state.
2865 SetPrivateState (eStateStopped);
2866
2867 }
2868 return error;
2869}
2870
Greg Clayton9ce95382012-02-13 23:10:39 +00002871DynamicLoader *
2872Process::GetDynamicLoader ()
2873{
2874 if (m_dyld_ap.get() == NULL)
2875 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2876 return m_dyld_ap.get();
2877}
Greg Clayton46c9a352012-02-09 06:16:32 +00002878
2879
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002880Process::NextEventAction::EventActionResult
2881Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002882{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002883 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2884 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002885 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002886 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002887 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002888 return eEventActionRetry;
2889
2890 case eStateStopped:
2891 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002892 {
2893 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002894 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002895 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2896 if (m_exec_count > 0)
2897 {
2898 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002899 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002900 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002901 return eEventActionRetry;
2902 }
2903 else
2904 {
2905 m_process->CompleteAttach ();
2906 return eEventActionSuccess;
2907 }
2908 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002909 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002910
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002911 default:
2912 case eStateExited:
2913 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002914 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002915 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002916
2917 m_exit_string.assign ("No valid Process");
2918 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002919}
Chris Lattner24943d22010-06-08 16:52:24 +00002920
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002921Process::NextEventAction::EventActionResult
2922Process::AttachCompletionHandler::HandleBeingInterrupted()
2923{
2924 return eEventActionSuccess;
2925}
2926
2927const char *
2928Process::AttachCompletionHandler::GetExitString ()
2929{
2930 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002931}
2932
2933Error
Greg Clayton527154d2011-11-15 03:53:30 +00002934Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002935{
Chris Lattner24943d22010-06-08 16:52:24 +00002936 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002937 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002938 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002939 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002940
Greg Clayton527154d2011-11-15 03:53:30 +00002941 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002942 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002943 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002944 {
Greg Clayton527154d2011-11-15 03:53:30 +00002945 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002946
Greg Clayton527154d2011-11-15 03:53:30 +00002947 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002948 {
Greg Clayton527154d2011-11-15 03:53:30 +00002949 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2950
2951 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002952 {
Greg Clayton527154d2011-11-15 03:53:30 +00002953 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2954 if (error.Success())
2955 {
Greg Clayton0e7cff42013-04-11 22:26:47 +00002956 if (m_public_run_lock.WriteTryLock())
Greg Claytond34a3b22012-10-12 16:10:12 +00002957 {
Greg Claytonb3381b72013-04-18 00:42:25 +00002958 m_private_run_lock.WriteLock();
Greg Claytond34a3b22012-10-12 16:10:12 +00002959 m_should_detach = true;
2960 SetPublicState (eStateAttaching);
2961 // Now attach using these arguments.
2962 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2963 }
2964 else
2965 {
2966 // This shouldn't happen
2967 error.SetErrorString("failed to acquire process run lock");
2968 }
Greg Claytonffa43a62011-11-17 04:46:02 +00002969
Greg Clayton527154d2011-11-15 03:53:30 +00002970 if (error.Fail())
2971 {
2972 if (GetID() != LLDB_INVALID_PROCESS_ID)
2973 {
2974 SetID (LLDB_INVALID_PROCESS_ID);
2975 if (error.AsCString() == NULL)
2976 error.SetErrorString("attach failed");
2977
2978 SetExitStatus(-1, error.AsCString());
2979 }
2980 }
2981 else
2982 {
2983 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2984 StartPrivateStateThread();
2985 }
2986 return error;
2987 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002988 }
Greg Clayton527154d2011-11-15 03:53:30 +00002989 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002990 {
Greg Clayton527154d2011-11-15 03:53:30 +00002991 ProcessInstanceInfoList process_infos;
2992 PlatformSP platform_sp (m_target.GetPlatform ());
2993
2994 if (platform_sp)
2995 {
2996 ProcessInstanceInfoMatch match_info;
2997 match_info.GetProcessInfo() = attach_info;
2998 match_info.SetNameMatchType (eNameMatchEquals);
2999 platform_sp->FindProcesses (match_info, process_infos);
3000 const uint32_t num_matches = process_infos.GetSize();
3001 if (num_matches == 1)
3002 {
3003 attach_pid = process_infos.GetProcessIDAtIndex(0);
3004 // Fall through and attach using the above process ID
3005 }
3006 else
3007 {
3008 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3009 if (num_matches > 1)
3010 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3011 else
3012 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3013 }
3014 }
3015 else
3016 {
3017 error.SetErrorString ("invalid platform, can't find processes by name");
3018 return error;
3019 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003020 }
Chris Lattner24943d22010-06-08 16:52:24 +00003021 }
3022 else
Greg Clayton527154d2011-11-15 03:53:30 +00003023 {
3024 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003025 }
3026 }
Greg Clayton527154d2011-11-15 03:53:30 +00003027
3028 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003029 {
Greg Clayton527154d2011-11-15 03:53:30 +00003030 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003031 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00003032 {
Greg Clayton527154d2011-11-15 03:53:30 +00003033
Greg Clayton0e7cff42013-04-11 22:26:47 +00003034 if (m_public_run_lock.WriteTryLock())
Greg Claytond34a3b22012-10-12 16:10:12 +00003035 {
Greg Claytonb3381b72013-04-18 00:42:25 +00003036 m_private_run_lock.WriteLock();
Greg Claytond34a3b22012-10-12 16:10:12 +00003037 // Now attach using these arguments.
3038 m_should_detach = true;
3039 SetPublicState (eStateAttaching);
3040 error = DoAttachToProcessWithID (attach_pid, attach_info);
3041 }
3042 else
3043 {
3044 // This shouldn't happen
3045 error.SetErrorString("failed to acquire process run lock");
3046 }
3047
Greg Clayton527154d2011-11-15 03:53:30 +00003048 if (error.Success())
3049 {
3050
3051 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3052 StartPrivateStateThread();
3053 }
3054 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003055 {
3056 if (GetID() != LLDB_INVALID_PROCESS_ID)
3057 {
3058 SetID (LLDB_INVALID_PROCESS_ID);
3059 const char *error_string = error.AsCString();
3060 if (error_string == NULL)
3061 error_string = "attach failed";
3062
3063 SetExitStatus(-1, error_string);
3064 }
3065 }
Chris Lattner24943d22010-06-08 16:52:24 +00003066 }
3067 }
3068 return error;
3069}
3070
Greg Clayton75c703d2011-02-16 04:46:07 +00003071void
3072Process::CompleteAttach ()
3073{
3074 // Let the process subclass figure out at much as it can about the process
3075 // before we go looking for a dynamic loader plug-in.
3076 DidAttach();
3077
Jim Ingham0d7f7772011-09-15 01:10:17 +00003078 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3079 // the same as the one we've already set, switch architectures.
3080 PlatformSP platform_sp (m_target.GetPlatform ());
3081 assert (platform_sp.get());
3082 if (platform_sp)
3083 {
Greg Claytonb170aee2012-05-08 01:45:38 +00003084 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Claytonaad2b0f2013-01-11 20:49:54 +00003085 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Claytonb170aee2012-05-08 01:45:38 +00003086 {
3087 ArchSpec platform_arch;
3088 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3089 if (platform_sp)
3090 {
3091 m_target.SetPlatform (platform_sp);
3092 m_target.SetArchitecture(platform_arch);
3093 }
3094 }
3095 else
3096 {
3097 ProcessInstanceInfo process_info;
3098 platform_sp->GetProcessInfo (GetID(), process_info);
3099 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callanan40e278c2012-12-13 22:07:14 +00003100 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Claytonb170aee2012-05-08 01:45:38 +00003101 m_target.SetArchitecture (process_arch);
3102 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00003103 }
3104
3105 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00003106 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00003107 DynamicLoader *dyld = GetDynamicLoader ();
3108 if (dyld)
3109 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00003110
Greg Clayton37f962e2011-08-22 02:49:39 +00003111 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00003112 // Figure out which one is the executable, and set that in our target:
Enrico Granata146d9522012-11-08 02:22:02 +00003113 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham93367902012-05-30 02:19:25 +00003114 Mutex::Locker modules_locker(target_modules.GetMutex());
3115 size_t num_modules = target_modules.GetSize();
3116 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003117
Greg Clayton75c703d2011-02-16 04:46:07 +00003118 for (int i = 0; i < num_modules; i++)
3119 {
Jim Ingham93367902012-05-30 02:19:25 +00003120 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00003121 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00003122 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00003123 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00003124 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003125 break;
3126 }
3127 }
Jim Ingham93367902012-05-30 02:19:25 +00003128 if (new_executable_module_sp)
3129 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00003130}
3131
Chris Lattner24943d22010-06-08 16:52:24 +00003132Error
Jason Molendafac2e622012-09-29 04:02:01 +00003133Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00003134{
Greg Claytone71e2582011-02-04 01:58:07 +00003135 m_abi_sp.reset();
3136 m_process_input_reader.reset();
3137
3138 // Find the process and its architecture. Make sure it matches the architecture
3139 // of the current Target, and if not adjust it.
3140
Jason Molendafac2e622012-09-29 04:02:01 +00003141 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00003142 if (error.Success())
3143 {
Greg Claytona2f74232011-02-24 22:24:29 +00003144 if (GetID() != LLDB_INVALID_PROCESS_ID)
3145 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00003146 EventSP event_sp;
3147 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3148
3149 if (state == eStateStopped || state == eStateCrashed)
3150 {
3151 // If we attached and actually have a process on the other end, then
3152 // this ended up being the equivalent of an attach.
3153 CompleteAttach ();
3154
3155 // This delays passing the stopped event to listeners till
3156 // CompleteAttach gets a chance to complete...
3157 HandlePrivateEvent (event_sp);
3158
3159 }
Greg Claytona2f74232011-02-24 22:24:29 +00003160 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00003161
3162 if (PrivateStateThreadIsValid ())
3163 ResumePrivateStateThread ();
3164 else
3165 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00003166 }
3167 return error;
3168}
3169
3170
3171Error
Jim Ingham027aaa72012-04-19 01:40:33 +00003172Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00003173{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003174 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00003175 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003176 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00003177 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00003178 StateAsCString(m_public_state.GetValue()),
3179 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00003180
3181 Error error (WillResume());
3182 // Tell the process it is about to resume before the thread list
3183 if (error.Success())
3184 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003185 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003186 // can let all of our threads know that they are about to be
3187 // resumed. Threads will each be called with
3188 // Thread::WillResume(StateType) where StateType contains the state
3189 // that they are supposed to have when the process is resumed
3190 // (suspended/running/stepping). Threads should also check
3191 // their resume signal in lldb::Thread::GetResumeSignal()
3192 // to see if they are suppoed to start back up with a signal.
3193 if (m_thread_list.WillResume())
3194 {
Jim Ingham1831e782012-04-07 00:00:41 +00003195 // Last thing, do the PreResumeActions.
3196 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003197 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003198 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham1831e782012-04-07 00:00:41 +00003199 }
3200 else
3201 {
3202 m_mod_id.BumpResumeID();
Greg Clayton0e7cff42013-04-11 22:26:47 +00003203 m_private_run_lock.WriteLock();
Jim Ingham1831e782012-04-07 00:00:41 +00003204 error = DoResume();
3205 if (error.Success())
3206 {
3207 DidResume();
3208 m_thread_list.DidResume();
3209 if (log)
3210 log->Printf ("Process thinks the process has resumed.");
3211 }
Greg Clayton0e7cff42013-04-11 22:26:47 +00003212 else
3213 {
3214 m_private_run_lock.WriteUnlock();
3215 }
Chris Lattner24943d22010-06-08 16:52:24 +00003216 }
3217 }
3218 else
3219 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003220 // Somebody wanted to run without running. So generate a continue & a stopped event,
3221 // and let the world handle them.
3222 if (log)
3223 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3224
3225 SetPrivateState(eStateRunning);
3226 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003227 }
3228 }
Jim Inghamac959662011-01-24 06:34:17 +00003229 else if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003230 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003231 return error;
3232}
3233
3234Error
3235Process::Halt ()
3236{
Jim Ingham43892562012-06-06 00:29:30 +00003237 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3238 // we could just straightaway get another event. It just narrows the window...
3239 m_currently_handling_event.WaitForValueEqualTo(false);
3240
3241
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003242 // Pause our private state thread so we can ensure no one else eats
3243 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003244 Listener halt_listener ("lldb.process.halt_listener");
3245 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003246
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003247 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003248 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003249
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003250 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003251 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003252
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003253 bool caused_stop = false;
3254
3255 // Ask the process subclass to actually halt our process
3256 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003257 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003258 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003259 if (m_public_state.GetValue() == eStateAttaching)
3260 {
3261 SetExitStatus(SIGKILL, "Cancelled async attach.");
3262 Destroy ();
3263 }
3264 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003265 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003266 // If "caused_stop" is true, then DoHalt stopped the process. If
3267 // "caused_stop" is false, the process was already stopped.
3268 // If the DoHalt caused the process to stop, then we want to catch
3269 // this event and set the interrupted bool to true before we pass
3270 // this along so clients know that the process was interrupted by
3271 // a halt command.
3272 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003273 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003274 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003275 TimeValue timeout_time;
3276 timeout_time = TimeValue::Now();
3277 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003278 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3279 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003280
Jim Inghamf9f40c22011-02-08 05:20:59 +00003281 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003282 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003283 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003284 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003285 }
3286 else
3287 {
Greg Clayton20206082011-11-17 01:23:07 +00003288 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003289 {
3290 // We caused the process to interrupt itself, so mark this
3291 // as such in the stop event so clients can tell an interrupted
3292 // process from a natural stop
3293 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3294 }
3295 else
3296 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00003297 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003298 if (log)
3299 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3300 error.SetErrorString ("Did not get stopped event after halt.");
3301 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003302 }
3303 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003304 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003305 }
3306 }
Chris Lattner24943d22010-06-08 16:52:24 +00003307 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003308 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003309 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003310
3311 // Post any event we might have consumed. If all goes well, we will have
3312 // stopped the process, intercepted the event and set the interrupted
3313 // bool in the event. Post it to the private event queue and that will end up
3314 // correctly setting the state.
3315 if (event_sp)
3316 m_private_state_broadcaster.BroadcastEvent(event_sp);
3317
Chris Lattner24943d22010-06-08 16:52:24 +00003318 return error;
3319}
3320
3321Error
Jim Inghame33bb5b2013-03-29 01:18:12 +00003322Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3323{
3324 Error error;
3325 if (m_public_state.GetValue() == eStateRunning)
3326 {
3327 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3328 if (log)
3329 log->Printf("Process::Destroy() About to halt.");
3330 error = Halt();
3331 if (error.Success())
3332 {
3333 // Consume the halt event.
3334 TimeValue timeout (TimeValue::Now());
3335 timeout.OffsetWithSeconds(1);
3336 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3337
3338 // If the process exited while we were waiting for it to stop, put the exited event into
3339 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3340 // they don't have a process anymore...
3341
3342 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3343 {
3344 if (log)
3345 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3346 return error;
3347 }
3348 else
3349 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3350
3351 if (state != eStateStopped)
3352 {
3353 if (log)
3354 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3355 // If we really couldn't stop the process then we should just error out here, but if the
3356 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3357 StateType private_state = m_private_state.GetValue();
3358 if (private_state != eStateStopped)
3359 {
3360 return error;
3361 }
3362 }
3363 }
3364 else
3365 {
3366 if (log)
3367 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3368 }
3369 }
3370 return error;
3371}
3372
3373Error
Chris Lattner24943d22010-06-08 16:52:24 +00003374Process::Detach ()
3375{
Jim Inghame33bb5b2013-03-29 01:18:12 +00003376 EventSP exit_event_sp;
3377 Error error;
3378 m_destroy_in_process = true;
3379
3380 error = WillDetach();
Chris Lattner24943d22010-06-08 16:52:24 +00003381
3382 if (error.Success())
3383 {
Jim Inghame33bb5b2013-03-29 01:18:12 +00003384 if (DetachRequiresHalt())
3385 {
3386 error = HaltForDestroyOrDetach (exit_event_sp);
3387 if (!error.Success())
3388 {
3389 m_destroy_in_process = false;
3390 return error;
3391 }
3392 else if (exit_event_sp)
3393 {
3394 // We shouldn't need to do anything else here. There's no process left to detach from...
3395 StopPrivateStateThread();
3396 m_destroy_in_process = false;
3397 return error;
3398 }
3399 }
3400
Chris Lattner24943d22010-06-08 16:52:24 +00003401 error = DoDetach();
3402 if (error.Success())
3403 {
3404 DidDetach();
3405 StopPrivateStateThread();
3406 }
3407 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003408 m_destroy_in_process = false;
3409
3410 // If we exited when we were waiting for a process to stop, then
3411 // forward the event here so we don't lose the event
3412 if (exit_event_sp)
3413 {
3414 // Directly broadcast our exited event because we shut down our
3415 // private state thread above
3416 BroadcastEvent(exit_event_sp);
3417 }
3418
3419 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3420 // the last events through the event system, in which case we might strand the write lock. Unlock
3421 // it here so when we do to tear down the process we don't get an error destroying the lock.
3422
Greg Clayton0e7cff42013-04-11 22:26:47 +00003423 m_public_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003424 return error;
3425}
3426
3427Error
3428Process::Destroy ()
3429{
Jim Inghameb175302013-03-01 20:04:25 +00003430
3431 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3432 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3433 // failed and the process stays around for some reason it won't be in a confused state.
3434
3435 m_destroy_in_process = true;
3436
Chris Lattner24943d22010-06-08 16:52:24 +00003437 Error error (WillDestroy());
3438 if (error.Success())
3439 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003440 EventSP exit_event_sp;
Jim Inghame33bb5b2013-03-29 01:18:12 +00003441 if (DestroyRequiresHalt())
Jim Inghamf4928de2012-05-23 15:46:31 +00003442 {
Jim Inghame33bb5b2013-03-29 01:18:12 +00003443 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Inghamf4928de2012-05-23 15:46:31 +00003444 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003445
Jim Ingham43892562012-06-06 00:29:30 +00003446 if (m_public_state.GetValue() != eStateRunning)
3447 {
3448 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3449 // kill it, we don't want it hitting a breakpoint...
3450 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3451 // we're not going to have much luck doing this now.
3452 m_thread_list.DiscardThreadPlans();
3453 DisableAllBreakpointSites();
3454 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003455
Chris Lattner24943d22010-06-08 16:52:24 +00003456 error = DoDestroy();
3457 if (error.Success())
3458 {
3459 DidDestroy();
3460 StopPrivateStateThread();
3461 }
Caroline Tice861efb32010-11-16 05:07:41 +00003462 m_stdio_communication.StopReadThread();
3463 m_stdio_communication.Disconnect();
3464 if (m_process_input_reader && m_process_input_reader->IsActive())
3465 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3466 if (m_process_input_reader)
3467 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003468
3469 // If we exited when we were waiting for a process to stop, then
3470 // forward the event here so we don't lose the event
3471 if (exit_event_sp)
3472 {
3473 // Directly broadcast our exited event because we shut down our
3474 // private state thread above
3475 BroadcastEvent(exit_event_sp);
3476 }
3477
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003478 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3479 // the last events through the event system, in which case we might strand the write lock. Unlock
3480 // it here so when we do to tear down the process we don't get an error destroying the lock.
Greg Clayton0e7cff42013-04-11 22:26:47 +00003481 m_public_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003482 }
Jim Inghameb175302013-03-01 20:04:25 +00003483
3484 m_destroy_in_process = false;
3485
Chris Lattner24943d22010-06-08 16:52:24 +00003486 return error;
3487}
3488
3489Error
3490Process::Signal (int signal)
3491{
3492 Error error (WillSignal());
3493 if (error.Success())
3494 {
3495 error = DoSignal(signal);
3496 if (error.Success())
3497 DidSignal();
3498 }
3499 return error;
3500}
3501
Greg Clayton395fc332011-02-15 21:59:32 +00003502lldb::ByteOrder
3503Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003504{
Greg Clayton395fc332011-02-15 21:59:32 +00003505 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003506}
3507
3508uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003509Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003510{
Greg Clayton395fc332011-02-15 21:59:32 +00003511 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003512}
3513
Greg Clayton395fc332011-02-15 21:59:32 +00003514
Chris Lattner24943d22010-06-08 16:52:24 +00003515bool
3516Process::ShouldBroadcastEvent (Event *event_ptr)
3517{
3518 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3519 bool return_value = true;
Greg Clayton952e9dc2013-03-27 23:08:40 +00003520 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham89e248f2013-02-09 01:29:05 +00003521
Chris Lattner24943d22010-06-08 16:52:24 +00003522 switch (state)
3523 {
Greg Claytone71e2582011-02-04 01:58:07 +00003524 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003525 case eStateAttaching:
3526 case eStateLaunching:
3527 case eStateDetached:
3528 case eStateExited:
3529 case eStateUnloaded:
3530 // These events indicate changes in the state of the debugging session, always report them.
3531 return_value = true;
3532 break;
3533 case eStateInvalid:
3534 // We stopped for no apparent reason, don't report it.
3535 return_value = false;
3536 break;
3537 case eStateRunning:
3538 case eStateStepping:
3539 // If we've started the target running, we handle the cases where we
3540 // are already running and where there is a transition from stopped to
3541 // running differently.
3542 // running -> running: Automatically suppress extra running events
3543 // stopped -> running: Report except when there is one or more no votes
3544 // and no yes votes.
3545 SynchronouslyNotifyStateChanged (state);
Jim Ingham89e248f2013-02-09 01:29:05 +00003546 switch (m_last_broadcast_state)
Chris Lattner24943d22010-06-08 16:52:24 +00003547 {
3548 case eStateRunning:
3549 case eStateStepping:
3550 // We always suppress multiple runnings with no PUBLIC stop in between.
3551 return_value = false;
3552 break;
3553 default:
3554 // TODO: make this work correctly. For now always report
3555 // run if we aren't running so we don't miss any runnning
3556 // events. If I run the lldb/test/thread/a.out file and
3557 // break at main.cpp:58, run and hit the breakpoints on
3558 // multiple threads, then somehow during the stepping over
3559 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003560
3561 // This is a transition from stop to run.
3562 switch (m_thread_list.ShouldReportRun (event_ptr))
3563 {
3564 case eVoteYes:
3565 case eVoteNoOpinion:
3566 return_value = true;
3567 break;
3568 case eVoteNo:
3569 return_value = false;
3570 break;
3571 }
3572 break;
3573 }
3574 break;
3575 case eStateStopped:
3576 case eStateCrashed:
3577 case eStateSuspended:
3578 {
3579 // We've stopped. First see if we're going to restart the target.
3580 // If we are going to stop, then we always broadcast the event.
3581 // 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 +00003582 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003583
Greg Clayton0e7cff42013-04-11 22:26:47 +00003584 m_private_run_lock.WriteUnlock();
3585
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003586 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003587 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003588 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003589 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003590 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3591 event_ptr,
3592 StateAsCString(state));
3593 return_value = true;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003594 }
3595 else
3596 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003597 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3598 // Asking the thread list is also not likely to go well, since we are running again.
3599 // So in that case just report the event.
3600
3601 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3602 bool should_resume = false;
3603 if (!was_restarted)
3604 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
3605 if (was_restarted || should_resume)
Chris Lattner24943d22010-06-08 16:52:24 +00003606 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003607 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3608 if (log)
3609 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3610 should_resume,
3611 StateAsCString(state),
3612 was_restarted,
3613 stop_vote);
3614
3615 switch (stop_vote)
Chris Lattner24943d22010-06-08 16:52:24 +00003616 {
3617 case eVoteYes:
Jim Ingham89e248f2013-02-09 01:29:05 +00003618 return_value = true;
3619 break;
Chris Lattner24943d22010-06-08 16:52:24 +00003620 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003621 case eVoteNo:
3622 return_value = false;
3623 break;
3624 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003625
Jim Ingham8290bba2012-09-05 21:13:56 +00003626 if (!was_restarted)
Jim Ingham89e248f2013-02-09 01:29:05 +00003627 {
3628 if (log)
3629 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3630 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Ingham8290bba2012-09-05 21:13:56 +00003631 PrivateResume ();
Jim Ingham89e248f2013-02-09 01:29:05 +00003632 }
3633
Chris Lattner24943d22010-06-08 16:52:24 +00003634 }
3635 else
3636 {
3637 return_value = true;
3638 SynchronouslyNotifyStateChanged (state);
3639 }
3640 }
3641 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003642 break;
Chris Lattner24943d22010-06-08 16:52:24 +00003643 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003644
3645 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3646 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3647 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3648 // because the PublicState reflects the last event pulled off the queue, and there may be several
3649 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3650 // yet. m_last_broadcast_state gets updated here.
3651
3652 if (return_value)
3653 m_last_broadcast_state = state;
3654
Chris Lattner24943d22010-06-08 16:52:24 +00003655 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003656 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3657 event_ptr,
3658 StateAsCString(state),
3659 StateAsCString(m_last_broadcast_state),
3660 return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003661 return return_value;
3662}
3663
Chris Lattner24943d22010-06-08 16:52:24 +00003664
3665bool
Jim Ingham1831e782012-04-07 00:00:41 +00003666Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003667{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003668 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003669
Greg Claytonb72d0f02011-04-12 05:54:46 +00003670 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003671 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003672 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3673
Jim Ingham1831e782012-04-07 00:00:41 +00003674 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003675 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003676
3677 // Create a thread that watches our internal state and controls which
3678 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003679 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003680 if (already_running)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003681 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham1831e782012-04-07 00:00:41 +00003682 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003683 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003684
3685 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003686 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003687 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3688 if (success)
3689 {
3690 ResumePrivateStateThread();
3691 return true;
3692 }
3693 else
3694 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003695}
3696
3697void
3698Process::PausePrivateStateThread ()
3699{
3700 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3701}
3702
3703void
3704Process::ResumePrivateStateThread ()
3705{
3706 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3707}
3708
3709void
3710Process::StopPrivateStateThread ()
3711{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003712 if (PrivateStateThreadIsValid ())
3713 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003714 else
3715 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00003716 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003717 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003718 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003719 }
Chris Lattner24943d22010-06-08 16:52:24 +00003720}
3721
3722void
3723Process::ControlPrivateStateThread (uint32_t signal)
3724{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003725 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003726
3727 assert (signal == eBroadcastInternalStateControlStop ||
3728 signal == eBroadcastInternalStateControlPause ||
3729 signal == eBroadcastInternalStateControlResume);
3730
3731 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003732 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003733
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003734 // Signal the private state thread. First we should copy this is case the
3735 // thread starts exiting since the private state thread will NULL this out
3736 // when it exits
3737 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003738 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003739 {
3740 TimeValue timeout_time;
3741 bool timed_out;
3742
3743 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3744
3745 timeout_time = TimeValue::Now();
3746 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003747 if (log)
3748 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003749 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3750 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3751
3752 if (signal == eBroadcastInternalStateControlStop)
3753 {
3754 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003755 {
3756 Error error;
3757 Host::ThreadCancel (private_state_thread, &error);
3758 if (log)
3759 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3760 }
3761 else
3762 {
3763 if (log)
3764 log->Printf ("The control event killed the private state thread without having to cancel.");
3765 }
Chris Lattner24943d22010-06-08 16:52:24 +00003766
3767 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003768 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003769 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003770 }
3771 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003772 else
3773 {
3774 if (log)
3775 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3776 }
Chris Lattner24943d22010-06-08 16:52:24 +00003777}
3778
3779void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003780Process::SendAsyncInterrupt ()
3781{
3782 if (PrivateStateThreadIsValid())
3783 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3784 else
3785 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3786}
3787
3788void
Chris Lattner24943d22010-06-08 16:52:24 +00003789Process::HandlePrivateEvent (EventSP &event_sp)
3790{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003791 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003792 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003793
Greg Clayton68ca8232011-01-25 02:58:48 +00003794 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003795
3796 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003797 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003798 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003799 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham89e248f2013-02-09 01:29:05 +00003800 if (log)
3801 log->Printf ("Ran next event action, result was %d.", action_result);
3802
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003803 switch (action_result)
3804 {
3805 case NextEventAction::eEventActionSuccess:
3806 SetNextEventAction(NULL);
3807 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003808
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003809 case NextEventAction::eEventActionRetry:
3810 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003811
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003812 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003813 // Handle Exiting Here. If we already got an exited event,
3814 // we should just propagate it. Otherwise, swallow this event,
3815 // and set our state to exit so the next event will kill us.
3816 if (new_state != eStateExited)
3817 {
3818 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003819 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003820 SetNextEventAction(NULL);
3821 return;
3822 }
3823 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003824 break;
3825 }
3826 }
3827
Chris Lattner24943d22010-06-08 16:52:24 +00003828 // See if we should broadcast this state to external clients?
3829 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003830
3831 if (should_broadcast)
3832 {
3833 if (log)
3834 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003835 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003836 __FUNCTION__,
3837 GetID(),
3838 StateAsCString(new_state),
3839 StateAsCString (GetState ()),
3840 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003841 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003842 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003843 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003844 PushProcessInputReader ();
3845 else
3846 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003847
Chris Lattner24943d22010-06-08 16:52:24 +00003848 BroadcastEvent (event_sp);
3849 }
3850 else
3851 {
3852 if (log)
3853 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003854 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003855 __FUNCTION__,
3856 GetID(),
3857 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003858 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003859 }
3860 }
Jim Ingham43892562012-06-06 00:29:30 +00003861 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003862}
3863
3864void *
3865Process::PrivateStateThread (void *arg)
3866{
3867 Process *proc = static_cast<Process*> (arg);
3868 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003869 return result;
3870}
3871
3872void *
3873Process::RunPrivateStateThread ()
3874{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003875 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003876 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003877
Greg Clayton952e9dc2013-03-27 23:08:40 +00003878 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003879 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003880 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003881
3882 bool exit_now = false;
3883 while (!exit_now)
3884 {
3885 EventSP event_sp;
3886 WaitForEventsPrivate (NULL, event_sp, control_only);
3887 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3888 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003889 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003890 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 +00003891
Chris Lattner24943d22010-06-08 16:52:24 +00003892 switch (event_sp->GetType())
3893 {
3894 case eBroadcastInternalStateControlStop:
3895 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003896 break; // doing any internal state managment below
3897
3898 case eBroadcastInternalStateControlPause:
3899 control_only = true;
3900 break;
3901
3902 case eBroadcastInternalStateControlResume:
3903 control_only = false;
3904 break;
3905 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003906
Chris Lattner24943d22010-06-08 16:52:24 +00003907 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003908 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003909 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003910 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3911 {
3912 if (m_public_state.GetValue() == eStateAttaching)
3913 {
3914 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003915 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 +00003916 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3917 }
3918 else
3919 {
3920 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003921 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00003922 Halt();
3923 }
3924 continue;
3925 }
Chris Lattner24943d22010-06-08 16:52:24 +00003926
3927 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3928
3929 if (internal_state != eStateInvalid)
3930 {
3931 HandlePrivateEvent (event_sp);
3932 }
3933
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003934 if (internal_state == eStateInvalid ||
3935 internal_state == eStateExited ||
3936 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003937 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003938 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003939 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 +00003940
Chris Lattner24943d22010-06-08 16:52:24 +00003941 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003942 }
Chris Lattner24943d22010-06-08 16:52:24 +00003943 }
3944
Caroline Tice926060e2010-10-29 21:48:37 +00003945 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003946 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003947 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003948
Greg Clayton0e7cff42013-04-11 22:26:47 +00003949 m_public_run_lock.WriteUnlock();
Greg Claytona4881d02011-01-22 07:12:45 +00003950 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3951 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003952 return NULL;
3953}
3954
Chris Lattner24943d22010-06-08 16:52:24 +00003955//------------------------------------------------------------------
3956// Process Event Data
3957//------------------------------------------------------------------
3958
3959Process::ProcessEventData::ProcessEventData () :
3960 EventData (),
3961 m_process_sp (),
3962 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003963 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003964 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003965 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003966{
3967}
3968
3969Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3970 EventData (),
3971 m_process_sp (process_sp),
3972 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003973 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003974 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003975 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003976{
3977}
3978
3979Process::ProcessEventData::~ProcessEventData()
3980{
3981}
3982
3983const ConstString &
3984Process::ProcessEventData::GetFlavorString ()
3985{
3986 static ConstString g_flavor ("Process::ProcessEventData");
3987 return g_flavor;
3988}
3989
3990const ConstString &
3991Process::ProcessEventData::GetFlavor () const
3992{
3993 return ProcessEventData::GetFlavorString ();
3994}
3995
Chris Lattner24943d22010-06-08 16:52:24 +00003996void
3997Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3998{
3999 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00004000 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4001 // the public event queue, then other times when we're pretending that this is where we stopped at the
4002 // end of expression evaluation. m_update_state is used to distinguish these
4003 // three cases; it is 0 when we're just pulling it off for private handling,
4004 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00004005
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00004006 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00004007 return;
Jim Ingham89e248f2013-02-09 01:29:05 +00004008
Chris Lattner24943d22010-06-08 16:52:24 +00004009 m_process_sp->SetPublicState (m_state);
4010
4011 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4012 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00004013 {
4014 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00004015 uint32_t num_threads = curr_thread_list.GetSize();
4016 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00004017
Jim Ingham21f37ad2011-08-09 02:12:22 +00004018 // The actions might change one of the thread's stop_info's opinions about whether we should
4019 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00004020
4021 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4022 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4023 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4024 // 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
4025 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00004026 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00004027 for (idx = 0; idx < num_threads; ++idx)
4028 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4029
Jim Inghamb6059b22012-12-13 22:24:15 +00004030 // Use this to track whether we should continue from here. We will only continue the target running if
4031 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4032 // then it doesn't matter what the other threads say...
4033
4034 bool still_should_stop = false;
Jim Ingham21f37ad2011-08-09 02:12:22 +00004035
Chris Lattner24943d22010-06-08 16:52:24 +00004036 for (idx = 0; idx < num_threads; ++idx)
4037 {
Jim Ingham0296fe72011-11-08 03:00:11 +00004038 curr_thread_list = m_process_sp->GetThreadList();
4039 if (curr_thread_list.GetSize() != num_threads)
4040 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004041 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00004042 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00004043 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 +00004044 break;
4045 }
4046
4047 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4048
4049 if (thread_sp->GetIndexID() != thread_index_array[idx])
4050 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004051 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00004052 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00004053 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00004054 idx,
4055 thread_index_array[idx],
4056 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00004057 break;
4058 }
4059
Jim Ingham6297a3a2010-10-20 00:39:53 +00004060 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00004061 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00004062 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004063 bool this_thread_wants_to_stop;
4064 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham21f37ad2011-08-09 02:12:22 +00004065 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004066 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4067 }
4068 else
4069 {
4070 stop_info_sp->PerformAction(event_ptr);
4071 // The stop action might restart the target. If it does, then we want to mark that in the
4072 // event so that whoever is receiving it will know to wait for the running event and reflect
4073 // that state appropriately.
4074 // We also need to stop processing actions, since they aren't expecting the target to be running.
4075
4076 // FIXME: we might have run.
4077 if (stop_info_sp->HasTargetRunSinceMe())
4078 {
4079 SetRestarted (true);
4080 break;
4081 }
4082
4083 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004084 }
Jim Inghamb6059b22012-12-13 22:24:15 +00004085
Jim Inghamb6059b22012-12-13 22:24:15 +00004086 if (still_should_stop == false)
4087 still_should_stop = this_thread_wants_to_stop;
Chris Lattner24943d22010-06-08 16:52:24 +00004088 }
4089 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00004090
Greg Claytonb3381b72013-04-18 00:42:25 +00004091 const lldb::StateType state = m_process_sp->GetPrivateState();
4092 if (state != eStateRunning &&
4093 state != eStateCrashed &&
4094 state != eStateDetached &&
4095 state != eStateExited)
Jim Inghamd60d94a2011-03-11 03:53:59 +00004096 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00004097 if (!still_should_stop)
4098 {
4099 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00004100 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00004101 // Use the public resume method here, since this is just
4102 // extending a public resume.
Jim Ingham89e248f2013-02-09 01:29:05 +00004103 m_process_sp->PrivateResume();
Jim Ingham21f37ad2011-08-09 02:12:22 +00004104 }
4105 else
4106 {
4107 // If we didn't restart, run the Stop Hooks here:
4108 // They might also restart the target, so watch for that.
4109 m_process_sp->GetTarget().RunStopHooks();
4110 if (m_process_sp->GetPrivateState() == eStateRunning)
4111 SetRestarted(true);
4112 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00004113 }
Chris Lattner24943d22010-06-08 16:52:24 +00004114 }
4115}
4116
4117void
4118Process::ProcessEventData::Dump (Stream *s) const
4119{
4120 if (m_process_sp)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004121 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00004122
Greg Claytonb72d0f02011-04-12 05:54:46 +00004123 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00004124}
4125
4126const Process::ProcessEventData *
4127Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4128{
4129 if (event_ptr)
4130 {
4131 const EventData *event_data = event_ptr->GetData();
4132 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4133 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4134 }
4135 return NULL;
4136}
4137
4138ProcessSP
4139Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4140{
4141 ProcessSP process_sp;
4142 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4143 if (data)
4144 process_sp = data->GetProcessSP();
4145 return process_sp;
4146}
4147
4148StateType
4149Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4150{
4151 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4152 if (data == NULL)
4153 return eStateInvalid;
4154 else
4155 return data->GetState();
4156}
4157
4158bool
4159Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4160{
4161 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4162 if (data == NULL)
4163 return false;
4164 else
4165 return data->GetRestarted();
4166}
4167
4168void
4169Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4170{
4171 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4172 if (data != NULL)
4173 data->SetRestarted(new_value);
4174}
4175
Jim Ingham89e248f2013-02-09 01:29:05 +00004176size_t
4177Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4178{
4179 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4180 if (data != NULL)
4181 return data->GetNumRestartedReasons();
4182 else
4183 return 0;
4184}
4185
4186const char *
4187Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4188{
4189 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4190 if (data != NULL)
4191 return data->GetRestartedReasonAtIndex(idx);
4192 else
4193 return NULL;
4194}
4195
4196void
4197Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4198{
4199 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4200 if (data != NULL)
4201 data->AddRestartedReason(reason);
4202}
4203
Chris Lattner24943d22010-06-08 16:52:24 +00004204bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00004205Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4206{
4207 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4208 if (data == NULL)
4209 return false;
4210 else
4211 return data->GetInterrupted ();
4212}
4213
4214void
4215Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4216{
4217 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4218 if (data != NULL)
4219 data->SetInterrupted(new_value);
4220}
4221
4222bool
Chris Lattner24943d22010-06-08 16:52:24 +00004223Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4224{
4225 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4226 if (data)
4227 {
4228 data->SetUpdateStateOnRemoval();
4229 return true;
4230 }
4231 return false;
4232}
4233
Greg Clayton289afcb2012-02-18 05:35:26 +00004234lldb::TargetSP
4235Process::CalculateTarget ()
4236{
4237 return m_target.shared_from_this();
4238}
4239
Chris Lattner24943d22010-06-08 16:52:24 +00004240void
Greg Claytona830adb2010-10-04 01:05:56 +00004241Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00004242{
Greg Clayton567e7f32011-09-22 04:58:26 +00004243 exe_ctx.SetTargetPtr (&m_target);
4244 exe_ctx.SetProcessPtr (this);
4245 exe_ctx.SetThreadPtr(NULL);
4246 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00004247}
4248
Greg Claytone4b9c1f2011-03-08 22:40:15 +00004249//uint32_t
4250//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4251//{
4252// return 0;
4253//}
4254//
4255//ArchSpec
4256//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4257//{
4258// return Host::GetArchSpecForExistingProcess (pid);
4259//}
4260//
4261//ArchSpec
4262//Process::GetArchSpecForExistingProcess (const char *process_name)
4263//{
4264// return Host::GetArchSpecForExistingProcess (process_name);
4265//}
4266//
Caroline Tice861efb32010-11-16 05:07:41 +00004267void
4268Process::AppendSTDOUT (const char * s, size_t len)
4269{
Greg Clayton20d338f2010-11-18 05:57:03 +00004270 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00004271 m_stdout_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004272 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00004273}
4274
4275void
Greg Claytonbd06ff42011-11-13 04:45:22 +00004276Process::AppendSTDERR (const char * s, size_t len)
4277{
4278 Mutex::Locker locker (m_stdio_communication_mutex);
4279 m_stderr_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004280 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004281}
4282
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004283void
4284Process::BroadcastAsyncProfileData(const char *s, size_t len)
4285{
4286 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004287 m_profile_data.push_back(s);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004288 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4289}
4290
4291size_t
4292Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4293{
4294 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004295 if (m_profile_data.empty())
4296 return 0;
4297
4298 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004299 if (bytes_available > 0)
4300 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004301 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004302 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004303 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004304 if (bytes_available > buf_size)
4305 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004306 memcpy(buf, m_profile_data.front().data(), buf_size);
4307 m_profile_data.front().erase(0, buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004308 bytes_available = buf_size;
4309 }
4310 else
4311 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004312 memcpy(buf, m_profile_data.front().data(), bytes_available);
4313 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004314 }
4315 }
4316 return bytes_available;
4317}
4318
4319
Greg Claytonbd06ff42011-11-13 04:45:22 +00004320//------------------------------------------------------------------
4321// Process STDIO
4322//------------------------------------------------------------------
4323
4324size_t
4325Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4326{
4327 Mutex::Locker locker(m_stdio_communication_mutex);
4328 size_t bytes_available = m_stdout_data.size();
4329 if (bytes_available > 0)
4330 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004331 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004332 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004333 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004334 if (bytes_available > buf_size)
4335 {
4336 memcpy(buf, m_stdout_data.c_str(), buf_size);
4337 m_stdout_data.erase(0, buf_size);
4338 bytes_available = buf_size;
4339 }
4340 else
4341 {
4342 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4343 m_stdout_data.clear();
4344 }
4345 }
4346 return bytes_available;
4347}
4348
4349
4350size_t
4351Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4352{
4353 Mutex::Locker locker(m_stdio_communication_mutex);
4354 size_t bytes_available = m_stderr_data.size();
4355 if (bytes_available > 0)
4356 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004357 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004358 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004359 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004360 if (bytes_available > buf_size)
4361 {
4362 memcpy(buf, m_stderr_data.c_str(), buf_size);
4363 m_stderr_data.erase(0, buf_size);
4364 bytes_available = buf_size;
4365 }
4366 else
4367 {
4368 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4369 m_stderr_data.clear();
4370 }
4371 }
4372 return bytes_available;
4373}
4374
4375void
Caroline Tice861efb32010-11-16 05:07:41 +00004376Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4377{
4378 Process *process = (Process *) baton;
4379 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4380}
4381
4382size_t
4383Process::ProcessInputReaderCallback (void *baton,
4384 InputReader &reader,
4385 lldb::InputReaderAction notification,
4386 const char *bytes,
4387 size_t bytes_len)
4388{
4389 Process *process = (Process *) baton;
4390
4391 switch (notification)
4392 {
4393 case eInputReaderActivate:
4394 break;
4395
4396 case eInputReaderDeactivate:
4397 break;
4398
4399 case eInputReaderReactivate:
4400 break;
4401
Caroline Tice4a348082011-05-02 20:41:46 +00004402 case eInputReaderAsynchronousOutputWritten:
4403 break;
4404
Caroline Tice861efb32010-11-16 05:07:41 +00004405 case eInputReaderGotToken:
4406 {
4407 Error error;
4408 process->PutSTDIN (bytes, bytes_len, error);
4409 }
4410 break;
4411
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004412 case eInputReaderInterrupt:
4413 process->Halt ();
4414 break;
4415
4416 case eInputReaderEndOfFile:
4417 process->AppendSTDOUT ("^D", 2);
4418 break;
4419
Caroline Tice861efb32010-11-16 05:07:41 +00004420 case eInputReaderDone:
4421 break;
4422
4423 }
4424
4425 return bytes_len;
4426}
4427
4428void
4429Process::ResetProcessInputReader ()
4430{
4431 m_process_input_reader.reset();
4432}
4433
4434void
Greg Clayton464c6162011-11-17 22:14:31 +00004435Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004436{
4437 // First set up the Read Thread for reading/handling process I/O
4438
4439 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4440
4441 if (conn_ap.get())
4442 {
4443 m_stdio_communication.SetConnection (conn_ap.release());
4444 if (m_stdio_communication.IsConnected())
4445 {
4446 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4447 m_stdio_communication.StartReadThread();
4448
4449 // Now read thread is set up, set up input reader.
4450
4451 if (!m_process_input_reader.get())
4452 {
4453 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4454 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4455 this,
4456 eInputReaderGranularityByte,
4457 NULL,
4458 NULL,
4459 false));
4460
4461 if (err.Fail())
4462 m_process_input_reader.reset();
4463 }
4464 }
4465 }
4466}
4467
4468void
4469Process::PushProcessInputReader ()
4470{
4471 if (m_process_input_reader && !m_process_input_reader->IsActive())
4472 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4473}
4474
4475void
4476Process::PopProcessInputReader ()
4477{
4478 if (m_process_input_reader && m_process_input_reader->IsActive())
4479 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4480}
4481
Greg Claytond284b662011-02-18 01:44:25 +00004482// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004483void
Caroline Tice2a456812011-03-10 22:14:10 +00004484Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004485{
Greg Clayton73844aa2012-08-22 17:17:09 +00004486// static std::vector<OptionEnumValueElement> g_plugins;
4487//
4488// int i=0;
4489// const char *name;
4490// OptionEnumValueElement option_enum;
4491// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4492// {
4493// if (name)
4494// {
4495// option_enum.value = i;
4496// option_enum.string_value = name;
4497// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4498// g_plugins.push_back (option_enum);
4499// }
4500// ++i;
4501// }
4502// option_enum.value = 0;
4503// option_enum.string_value = NULL;
4504// option_enum.usage = NULL;
4505// g_plugins.push_back (option_enum);
4506//
4507// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4508// {
4509// if (::strcmp (name, "plugin") == 0)
4510// {
4511// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4512// break;
4513// }
4514// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004515//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004516 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004517}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004518
Greg Clayton990de7b2010-11-18 23:32:35 +00004519void
Caroline Tice2a456812011-03-10 22:14:10 +00004520Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004521{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004522 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004523}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004524
Greg Clayton427f2902010-12-14 02:59:59 +00004525ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004526Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004527 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004528 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004529 bool run_others,
Jim Inghamb7940202013-01-15 02:47:48 +00004530 bool unwind_on_error,
4531 bool ignore_breakpoints,
Jim Ingham47beabb2012-10-16 21:41:58 +00004532 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004533 Stream &errors)
4534{
4535 ExecutionResults return_value = eExecutionSetupError;
4536
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004537 if (thread_plan_sp.get() == NULL)
4538 {
4539 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004540 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004541 }
Jim Ingham698194c2013-03-28 00:05:34 +00004542
4543 if (!thread_plan_sp->ValidatePlan(NULL))
4544 {
4545 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4546 return eExecutionSetupError;
4547 }
4548
Greg Clayton567e7f32011-09-22 04:58:26 +00004549 if (exe_ctx.GetProcessPtr() != this)
4550 {
4551 errors.Printf("RunThreadPlan called on wrong process.");
4552 return eExecutionSetupError;
4553 }
4554
4555 Thread *thread = exe_ctx.GetThreadPtr();
4556 if (thread == NULL)
4557 {
4558 errors.Printf("RunThreadPlan called with invalid thread.");
4559 return eExecutionSetupError;
4560 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004561
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004562 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4563 // For that to be true the plan can't be private - since private plans suppress themselves in the
4564 // GetCompletedPlan call.
4565
4566 bool orig_plan_private = thread_plan_sp->GetPrivate();
4567 thread_plan_sp->SetPrivate(false);
4568
Jim Inghamac959662011-01-24 06:34:17 +00004569 if (m_private_state.GetValue() != eStateStopped)
4570 {
4571 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004572 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004573 }
4574
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004575 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004576 const uint32_t thread_idx_id = thread->GetIndexID();
Jim Ingham9da225f2013-02-19 23:22:45 +00004577 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4578 if (!selected_frame_sp)
4579 {
4580 thread->SetSelectedFrame(0);
4581 selected_frame_sp = thread->GetSelectedFrame();
4582 if (!selected_frame_sp)
4583 {
4584 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4585 return eExecutionSetupError;
4586 }
4587 }
4588
4589 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004590
4591 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4592 // so we should arrange to reset them as well.
4593
Greg Clayton567e7f32011-09-22 04:58:26 +00004594 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004595
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004596 uint32_t selected_tid;
4597 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004598 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004599 {
4600 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004601 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004602 }
4603 else
4604 {
4605 selected_tid = LLDB_INVALID_THREAD_ID;
4606 }
4607
Jim Ingham1831e782012-04-07 00:00:41 +00004608 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004609 lldb::StateType old_state;
4610 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004611
Greg Clayton952e9dc2013-03-27 23:08:40 +00004612 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004613 if (Host::GetCurrentThread() == m_private_state_thread)
4614 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004615 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4616 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004617 // 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 +00004618 // we are fielding public events here.
4619 if (log)
Jason Molenda559cf6e2012-11-17 01:41:04 +00004620 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 +00004621
4622
Jim Ingham1831e782012-04-07 00:00:41 +00004623 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004624
4625 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4626 // returning control here.
4627 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4628 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4629 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4630 // do just what we want.
4631 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4632 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4633 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4634 old_state = m_public_state.GetValue();
4635 m_public_state.SetValueNoLock(eStateStopped);
4636
4637 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004638 StartPrivateStateThread(true);
4639 }
4640
4641 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004642
Jim Ingham6ae318c2011-01-23 21:14:08 +00004643 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004644
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004645 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004646
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004647 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004648 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4649 // restored on exit to the function.
4650 //
4651 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4652 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004653
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004654 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004655
Jim Ingham360f53f2010-11-30 02:22:11 +00004656 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004657 {
4658 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004659 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004660 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004661 thread->GetIndexID(),
4662 thread->GetID(),
4663 s.GetData());
4664 }
4665
4666 bool got_event;
4667 lldb::EventSP event_sp;
4668 lldb::StateType stop_state = lldb::eStateInvalid;
4669
4670 TimeValue* timeout_ptr = NULL;
4671 TimeValue real_timeout;
4672
Jim Ingham89e248f2013-02-09 01:29:05 +00004673 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 +00004674 bool do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004675 bool handle_running_event = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004676 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004677
Jim Ingham89e248f2013-02-09 01:29:05 +00004678 // This is just for accounting:
4679 uint32_t num_resumes = 0;
4680
4681 TimeValue one_thread_timeout = TimeValue::Now();
4682 TimeValue final_timeout = one_thread_timeout;
4683
4684 if (run_others)
4685 {
4686 // If we are running all threads then we take half the time to run all threads, bounded by
4687 // .25 sec.
4688 if (timeout_usec == 0)
4689 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4690 else
4691 {
4692 uint64_t computed_timeout = computed_timeout = timeout_usec / 2;
4693 if (computed_timeout > default_one_thread_timeout_usec)
4694 computed_timeout = default_one_thread_timeout_usec;
4695 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4696 }
4697 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4698 }
4699 else
4700 {
4701 if (timeout_usec != 0)
4702 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4703 }
4704
Jim Ingham76b258d2012-11-26 23:52:18 +00004705 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4706 // So don't call return anywhere within it.
4707
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004708 while (1)
4709 {
4710 // We usually want to resume the process if we get to the top of the loop.
4711 // The only exception is if we get two running events with no intervening
4712 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham89e248f2013-02-09 01:29:05 +00004713 if (log)
4714 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4715 do_resume,
4716 handle_running_event,
4717 before_first_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004718
Jim Inghamb7940202013-01-15 02:47:48 +00004719 if (do_resume || handle_running_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004720 {
4721 // Do the initial resume and wait for the running event before going further.
4722
Jim Inghamb7940202013-01-15 02:47:48 +00004723 if (do_resume)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004724 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004725 num_resumes++;
Jim Inghamb7940202013-01-15 02:47:48 +00004726 Error resume_error = PrivateResume ();
4727 if (!resume_error.Success())
4728 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004729 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4730 num_resumes,
4731 resume_error.AsCString());
Jim Inghamb7940202013-01-15 02:47:48 +00004732 return_value = eExecutionSetupError;
4733 break;
4734 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004735 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004736
Jim Ingham89e248f2013-02-09 01:29:05 +00004737 TimeValue resume_timeout = TimeValue::Now();
4738 resume_timeout.OffsetWithMicroSeconds(500000);
4739
4740 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004741 if (!got_event)
4742 {
4743 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004744 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4745 num_resumes);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004746
Jim Ingham89e248f2013-02-09 01:29:05 +00004747 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004748 return_value = eExecutionSetupError;
4749 break;
4750 }
4751
4752 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham89e248f2013-02-09 01:29:05 +00004753
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004754 if (stop_state != eStateRunning)
4755 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004756 bool restarted = false;
4757
4758 if (stop_state == eStateStopped)
4759 {
4760 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4761 if (log)
4762 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4763 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4764 num_resumes,
4765 StateAsCString(stop_state),
4766 restarted,
4767 do_resume,
4768 handle_running_event);
4769 }
4770
4771 if (restarted)
4772 {
4773 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4774 // event here. But if I do, the best thing is to Halt and then get out of here.
4775 Halt();
4776 }
4777
Jim Ingham47beabb2012-10-16 21:41:58 +00004778 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4779 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004780 return_value = eExecutionSetupError;
4781 break;
4782 }
4783
4784 if (log)
4785 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4786 // We need to call the function synchronously, so spin waiting for it to return.
4787 // If we get interrupted while executing, we're going to lose our context, and
4788 // won't be able to gather the result at this point.
4789 // We set the timeout AFTER the resume, since the resume takes some time and we
4790 // don't want to charge that to the timeout.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004791 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004792 else
4793 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004794 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004795 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004796 }
Jim Ingham89e248f2013-02-09 01:29:05 +00004797
4798 if (before_first_timeout)
4799 {
4800 if (run_others)
4801 timeout_ptr = &one_thread_timeout;
4802 else
4803 {
4804 if (timeout_usec == 0)
4805 timeout_ptr = NULL;
4806 else
4807 timeout_ptr = &final_timeout;
4808 }
4809 }
4810 else
4811 {
4812 if (timeout_usec == 0)
4813 timeout_ptr = NULL;
4814 else
4815 timeout_ptr = &final_timeout;
4816 }
4817
4818 do_resume = true;
4819 handle_running_event = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004820
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004821 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004822 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004823
Jim Inghamf9f40c22011-02-08 05:20:59 +00004824 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004825 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004826 if (timeout_ptr)
4827 {
Matt Kopecfe21d4f2013-02-21 23:55:31 +00004828 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham89e248f2013-02-09 01:29:05 +00004829 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
4830 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004831 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004832 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004833 {
4834 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4835 }
4836 }
4837
4838 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4839
4840 if (got_event)
4841 {
4842 if (event_sp.get())
4843 {
4844 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004845 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004846 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004847 Halt();
Jim Ingham5d90ade2012-07-27 23:57:19 +00004848 return_value = eExecutionInterrupted;
4849 errors.Printf ("Execution halted by user interrupt.");
4850 if (log)
4851 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham89e248f2013-02-09 01:29:05 +00004852 break;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004853 }
4854 else
4855 {
4856 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4857 if (log)
4858 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4859
4860 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004861 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004862 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004863 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004864 // We stopped, figure out what we are going to do now.
Jim Ingham5d90ade2012-07-27 23:57:19 +00004865 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4866 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004867 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004868 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004869 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004870 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4871 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004872 }
4873 else
4874 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004875 // If we were restarted, we just need to go back up to fetch another event.
4876 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Ingham5d90ade2012-07-27 23:57:19 +00004877 {
4878 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004879 {
4880 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
4881 }
4882 keep_going = true;
4883 do_resume = false;
4884 handle_running_event = true;
4885
Jim Ingham5d90ade2012-07-27 23:57:19 +00004886 }
4887 else
4888 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004889
4890 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4891 StopReason stop_reason = eStopReasonInvalid;
4892 if (stop_info_sp)
4893 stop_reason = stop_info_sp->GetStopReason();
4894
4895
4896 // FIXME: We only check if the stop reason is plan complete, should we make sure that
4897 // it is OUR plan that is complete?
4898 if (stop_reason == eStopReasonPlanComplete)
Jim Inghamb7940202013-01-15 02:47:48 +00004899 {
4900 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004901 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4902 // Now mark this plan as private so it doesn't get reported as the stop reason
4903 // after this point.
4904 if (thread_plan_sp)
4905 thread_plan_sp->SetPrivate (orig_plan_private);
4906 return_value = eExecutionCompleted;
Jim Inghamb7940202013-01-15 02:47:48 +00004907 }
4908 else
4909 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004910 // Something restarted the target, so just wait for it to stop for real.
Jim Inghamb7940202013-01-15 02:47:48 +00004911 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham89e248f2013-02-09 01:29:05 +00004912 {
4913 if (log)
4914 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Inghamb7940202013-01-15 02:47:48 +00004915 return_value = eExecutionHitBreakpoint;
Jim Ingham89e248f2013-02-09 01:29:05 +00004916 }
Jim Inghamb7940202013-01-15 02:47:48 +00004917 else
Jim Ingham89e248f2013-02-09 01:29:05 +00004918 {
4919 if (log)
4920 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Inghamb7940202013-01-15 02:47:48 +00004921 return_value = eExecutionInterrupted;
Jim Ingham89e248f2013-02-09 01:29:05 +00004922 }
Jim Inghamb7940202013-01-15 02:47:48 +00004923 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004924 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004925 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004926 }
4927 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004928
Jim Ingham5d90ade2012-07-27 23:57:19 +00004929 case lldb::eStateRunning:
Jim Ingham89e248f2013-02-09 01:29:05 +00004930 // This shouldn't really happen, but sometimes we do get two running events without an
4931 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Ingham5d90ade2012-07-27 23:57:19 +00004932 do_resume = false;
4933 keep_going = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004934 handle_running_event = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004935 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004936
Jim Ingham5d90ade2012-07-27 23:57:19 +00004937 default:
4938 if (log)
4939 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4940
4941 if (stop_state == eStateExited)
4942 event_to_broadcast_sp = event_sp;
4943
Sean Callanan96abc622012-08-08 17:35:10 +00004944 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00004945 return_value = eExecutionInterrupted;
4946 break;
4947 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004948 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004949
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004950 if (keep_going)
4951 continue;
4952 else
4953 break;
4954 }
4955 else
4956 {
4957 if (log)
4958 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4959 return_value = eExecutionInterrupted;
4960 break;
4961 }
4962 }
4963 else
4964 {
4965 // If we didn't get an event that means we've timed out...
4966 // We will interrupt the process here. Depending on what we were asked to do we will
4967 // either exit, or try with all threads running for the same timeout.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004968
4969 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00004970 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004971 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004972 uint64_t remaining_time = final_timeout - TimeValue::Now();
4973 if (before_first_timeout)
4974 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
4975 "running till for %" PRId64 " usec with all threads enabled.",
4976 remaining_time);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004977 else
4978 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00004979 "and timeout: %d timed out, abandoning execution.",
4980 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004981 }
4982 else
4983 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004984 "abandoning execution.",
4985 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004986 }
4987
Jim Ingham89e248f2013-02-09 01:29:05 +00004988 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
4989 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
4990 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
4991 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
4992 // stopped event. That's what this while loop does.
4993
4994 bool back_to_top = true;
4995 uint32_t try_halt_again = 0;
4996 bool do_halt = true;
4997 const uint32_t num_retries = 5;
4998 while (try_halt_again < num_retries)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004999 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005000 Error halt_error;
5001 if (do_halt)
5002 {
5003 if (log)
5004 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5005 halt_error = Halt();
5006 }
5007 if (halt_error.Success())
5008 {
5009 if (log)
5010 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5011
5012 real_timeout = TimeValue::Now();
5013 real_timeout.OffsetWithMicroSeconds(500000);
5014
5015 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005016
Jim Ingham89e248f2013-02-09 01:29:05 +00005017 if (got_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005018 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005019 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5020 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005021 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005022 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5023 if (stop_state == lldb::eStateStopped
5024 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5025 log->PutCString (" Event was the Halt interruption event.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005026 }
5027
Jim Ingham89e248f2013-02-09 01:29:05 +00005028 if (stop_state == lldb::eStateStopped)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005029 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005030 // Between the time we initiated the Halt and the time we delivered it, the process could have
5031 // already finished its job. Check that here:
5032
5033 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5034 {
5035 if (log)
5036 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5037 "Exiting wait loop.");
5038 return_value = eExecutionCompleted;
5039 back_to_top = false;
5040 break;
5041 }
5042
5043 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5044 {
5045 if (log)
5046 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5047 "Exiting wait loop.");
5048 try_halt_again++;
5049 do_halt = false;
5050 continue;
5051 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005052
Jim Ingham89e248f2013-02-09 01:29:05 +00005053 if (!run_others)
5054 {
5055 if (log)
5056 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5057 return_value = eExecutionInterrupted;
5058 back_to_top = false;
5059 break;
5060 }
5061
5062 if (before_first_timeout)
5063 {
5064 // Set all the other threads to run, and return to the top of the loop, which will continue;
5065 before_first_timeout = false;
5066 thread_plan_sp->SetStopOthers (false);
5067 if (log)
5068 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005069
Jim Ingham89e248f2013-02-09 01:29:05 +00005070 back_to_top = true;
5071 break;
5072 }
5073 else
5074 {
5075 // Running all threads failed, so return Interrupted.
5076 if (log)
5077 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5078 return_value = eExecutionInterrupted;
5079 back_to_top = false;
5080 break;
5081 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005082 }
5083 }
5084 else
Jim Ingham89e248f2013-02-09 01:29:05 +00005085 { if (log)
5086 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5087 "I'm getting out of here passing Interrupted.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005088 return_value = eExecutionInterrupted;
Jim Ingham89e248f2013-02-09 01:29:05 +00005089 back_to_top = false;
5090 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005091 }
5092 }
Jim Ingham89e248f2013-02-09 01:29:05 +00005093 else
5094 {
5095 try_halt_again++;
5096 continue;
5097 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005098 }
Jim Ingham89e248f2013-02-09 01:29:05 +00005099
5100 if (!back_to_top || try_halt_again > num_retries)
5101 break;
5102 else
5103 continue;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005104 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005105 } // END WAIT LOOP
5106
5107 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5108 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5109 {
5110 StopPrivateStateThread();
5111 Error error;
5112 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00005113 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005114 {
5115 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5116 }
5117 m_public_state.SetValueNoLock(old_state);
5118
5119 }
5120
Jim Inghamb7940202013-01-15 02:47:48 +00005121 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5122 // could happen:
5123 // 1) The execution successfully completed
5124 // 2) We hit a breakpoint, and ignore_breakpoints was true
5125 // 3) We got some other error, and discard_on_error was true
5126 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
5127 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham76b258d2012-11-26 23:52:18 +00005128
Jim Inghamb7940202013-01-15 02:47:48 +00005129 if (return_value == eExecutionCompleted
5130 || should_unwind)
Jim Ingham76b258d2012-11-26 23:52:18 +00005131 {
5132 thread_plan_sp->RestoreThreadState();
5133 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005134
5135 // Now do some processing on the results of the run:
Jim Inghamb7940202013-01-15 02:47:48 +00005136 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005137 {
5138 if (log)
5139 {
5140 StreamString s;
5141 if (event_sp)
5142 event_sp->Dump (&s);
5143 else
5144 {
5145 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5146 }
5147
5148 StreamString ts;
5149
5150 const char *event_explanation = NULL;
5151
5152 do
5153 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005154 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005155 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005156 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005157 break;
5158 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005159 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005160 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005161 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005162 break;
5163 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005164 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005165 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005166 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5167
5168 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005169 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005170 event_explanation = "<no event data>";
5171 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005172 }
5173
Jim Ingham5d90ade2012-07-27 23:57:19 +00005174 Process *process = event_data->GetProcessSP().get();
5175
5176 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005177 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005178 event_explanation = "<no process>";
5179 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005180 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005181
5182 ThreadList &thread_list = process->GetThreadList();
5183
5184 uint32_t num_threads = thread_list.GetSize();
5185 uint32_t thread_index;
5186
5187 ts.Printf("<%u threads> ", num_threads);
5188
5189 for (thread_index = 0;
5190 thread_index < num_threads;
5191 ++thread_index)
5192 {
5193 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5194
5195 if (!thread)
5196 {
5197 ts.Printf("<?> ");
5198 continue;
5199 }
5200
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005201 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00005202 RegisterContext *register_context = thread->GetRegisterContext().get();
5203
5204 if (register_context)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005205 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Ingham5d90ade2012-07-27 23:57:19 +00005206 else
5207 ts.Printf("[ip unknown] ");
5208
5209 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5210 if (stop_info_sp)
5211 {
5212 const char *stop_desc = stop_info_sp->GetDescription();
5213 if (stop_desc)
5214 ts.PutCString (stop_desc);
5215 }
5216 ts.Printf(">");
5217 }
5218
5219 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005220 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005221 } while (0);
5222
Jim Ingham5d90ade2012-07-27 23:57:19 +00005223 if (event_explanation)
5224 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005225 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00005226 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5227 }
5228
Jim Inghamb7940202013-01-15 02:47:48 +00005229 if (should_unwind && thread_plan_sp)
Jim Ingham5d90ade2012-07-27 23:57:19 +00005230 {
5231 if (log)
5232 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5233 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5234 thread_plan_sp->SetPrivate (orig_plan_private);
5235 }
5236 else
5237 {
5238 if (log)
5239 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005240 }
5241 }
5242 else if (return_value == eExecutionSetupError)
5243 {
5244 if (log)
5245 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00005246
Jim Inghamb7940202013-01-15 02:47:48 +00005247 if (unwind_on_error && thread_plan_sp)
Jim Inghamf9f40c22011-02-08 05:20:59 +00005248 {
Greg Clayton567e7f32011-09-22 04:58:26 +00005249 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00005250 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00005251 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005252 }
5253 else
5254 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005255 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00005256 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00005257 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005258 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5259 return_value = eExecutionCompleted;
5260 }
5261 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5262 {
5263 if (log)
5264 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5265 return_value = eExecutionDiscarded;
5266 }
5267 else
5268 {
5269 if (log)
5270 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamb7940202013-01-15 02:47:48 +00005271 if (unwind_on_error && thread_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005272 {
5273 if (log)
Jim Inghamb7940202013-01-15 02:47:48 +00005274 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005275 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5276 thread_plan_sp->SetPrivate (orig_plan_private);
5277 }
5278 }
5279 }
5280
5281 // Thread we ran the function in may have gone away because we ran the target
5282 // Check that it's still there, and if it is put it back in the context. Also restore the
5283 // frame in the context if it is still present.
5284 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5285 if (thread)
5286 {
5287 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5288 }
5289
5290 // Also restore the current process'es selected frame & thread, since this function calling may
5291 // be done behind the user's back.
5292
5293 if (selected_tid != LLDB_INVALID_THREAD_ID)
5294 {
5295 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5296 {
5297 // We were able to restore the selected thread, now restore the frame:
5298 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5299 if (old_frame_sp)
5300 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00005301 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005302 }
5303 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005304
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005305 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00005306
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005307 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00005308 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005309 if (log)
5310 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5311 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00005312 }
5313
5314 return return_value;
5315}
5316
5317const char *
5318Process::ExecutionResultAsCString (ExecutionResults result)
5319{
5320 const char *result_name;
5321
5322 switch (result)
5323 {
Greg Claytonb3448432011-03-24 21:19:54 +00005324 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005325 result_name = "eExecutionCompleted";
5326 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005327 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00005328 result_name = "eExecutionDiscarded";
5329 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005330 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005331 result_name = "eExecutionInterrupted";
5332 break;
Jim Inghamb7940202013-01-15 02:47:48 +00005333 case eExecutionHitBreakpoint:
5334 result_name = "eExecutionHitBreakpoint";
5335 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005336 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00005337 result_name = "eExecutionSetupError";
5338 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005339 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00005340 result_name = "eExecutionTimedOut";
5341 break;
5342 }
5343 return result_name;
5344}
5345
Greg Claytonabe0fed2011-04-18 08:33:37 +00005346void
5347Process::GetStatus (Stream &strm)
5348{
5349 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00005350 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00005351 {
5352 if (state == eStateExited)
5353 {
5354 int exit_status = GetExitStatus();
5355 const char *exit_description = GetExitDescription();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005356 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00005357 GetID(),
5358 exit_status,
5359 exit_status,
5360 exit_description ? exit_description : "");
5361 }
5362 else
5363 {
5364 if (state == eStateConnected)
5365 strm.Printf ("Connected to remote target.\n");
5366 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005367 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00005368 }
5369 }
5370 else
5371 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005372 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005373 }
5374}
5375
5376size_t
5377Process::GetThreadStatus (Stream &strm,
5378 bool only_threads_with_stop_reason,
5379 uint32_t start_frame,
5380 uint32_t num_frames,
5381 uint32_t num_frames_with_source)
5382{
5383 size_t num_thread_infos_dumped = 0;
5384
Jim Inghamb9950592012-09-10 20:50:15 +00005385 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005386 const size_t num_threads = GetThreadList().GetSize();
5387 for (uint32_t i = 0; i < num_threads; i++)
5388 {
5389 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5390 if (thread)
5391 {
5392 if (only_threads_with_stop_reason)
5393 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00005394 StopInfoSP stop_info_sp = thread->GetStopInfo();
5395 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00005396 continue;
5397 }
5398 thread->GetStatus (strm,
5399 start_frame,
5400 num_frames,
5401 num_frames_with_source);
5402 ++num_thread_infos_dumped;
5403 }
5404 }
5405 return num_thread_infos_dumped;
5406}
5407
Greg Clayton76113302012-02-22 04:37:26 +00005408void
5409Process::AddInvalidMemoryRegion (const LoadRange &region)
5410{
5411 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5412}
5413
5414bool
5415Process::RemoveInvalidMemoryRange (const LoadRange &region)
5416{
5417 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5418}
5419
Jim Ingham1831e782012-04-07 00:00:41 +00005420void
5421Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5422{
5423 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5424}
5425
5426bool
5427Process::RunPreResumeActions ()
5428{
5429 bool result = true;
5430 while (!m_pre_resume_actions.empty())
5431 {
5432 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5433 m_pre_resume_actions.pop_back();
5434 bool this_result = action.callback (action.baton);
5435 if (result == true) result = this_result;
5436 }
5437 return result;
5438}
5439
5440void
5441Process::ClearPreResumeActions ()
5442{
5443 m_pre_resume_actions.clear();
5444}
Greg Clayton76113302012-02-22 04:37:26 +00005445
Greg Claytoncf5927e2012-05-18 02:38:05 +00005446void
5447Process::Flush ()
5448{
5449 m_thread_list.Flush();
5450}
Greg Clayton0bce9a22012-12-05 00:16:59 +00005451
5452void
5453Process::DidExec ()
5454{
5455 Target &target = GetTarget();
5456 target.CleanupProcess ();
5457 ModuleList unloaded_modules (target.GetImages());
5458 target.ModulesDidUnload (unloaded_modules);
5459 target.GetSectionLoadList().Clear();
5460 m_dynamic_checkers_ap.reset();
5461 m_abi_sp.reset();
5462 m_os_ap.reset();
5463 m_dyld_ap.reset();
5464 m_image_tokens.clear();
5465 m_allocated_memory_cache.Clear();
5466 m_language_runtimes.clear();
5467 DoDidExec();
5468 CompleteAttach ();
5469}