blob: 95abb7945b3a425bcf3f5cf516b13794a6b05497 [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,
Daniel Malea411ab472013-05-01 19:11:56 +0000113 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 Clayton061ca652013-04-18 16:57:27 +00001022 m_public_run_lock (),
1023#if defined(__APPLE__)
1024 m_private_run_lock (),
1025#endif
Jim Ingham43892562012-06-06 00:29:30 +00001026 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001027 m_finalize_called(false),
Jim Ingham89e248f2013-02-09 01:29:05 +00001028 m_last_broadcast_state (eStateInvalid),
Jason Molenda1d9c8022013-03-05 03:33:59 +00001029 m_destroy_in_process (false),
1030 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +00001031{
Jim Ingham5a15e692012-02-16 06:50:00 +00001032 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +00001033
Greg Clayton952e9dc2013-03-27 23:08:40 +00001034 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001035 if (log)
1036 log->Printf ("%p Process::Process()", this);
1037
Greg Clayton49ce6822010-10-31 03:01:06 +00001038 SetEventName (eBroadcastBitStateChanged, "state-changed");
1039 SetEventName (eBroadcastBitInterrupt, "interrupt");
1040 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
1041 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001042 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Clayton49ce6822010-10-31 03:01:06 +00001043
Greg Clayton84332782012-10-29 20:52:08 +00001044 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
1045 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
1046 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
1047
Chris Lattner24943d22010-06-08 16:52:24 +00001048 listener.StartListeningForEvents (this,
1049 eBroadcastBitStateChanged |
1050 eBroadcastBitInterrupt |
1051 eBroadcastBitSTDOUT |
Han Ming Ongfb9cee62012-11-17 00:21:04 +00001052 eBroadcastBitSTDERR |
1053 eBroadcastBitProfileData);
Chris Lattner24943d22010-06-08 16:52:24 +00001054
1055 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001056 eBroadcastBitStateChanged |
1057 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +00001058
1059 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
1060 eBroadcastInternalStateControlStop |
1061 eBroadcastInternalStateControlPause |
1062 eBroadcastInternalStateControlResume);
1063}
1064
1065//----------------------------------------------------------------------
1066// Destructor
1067//----------------------------------------------------------------------
1068Process::~Process()
1069{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001070 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001071 if (log)
1072 log->Printf ("%p Process::~Process()", this);
1073 StopPrivateStateThread();
1074}
1075
Greg Clayton73844aa2012-08-22 17:17:09 +00001076const ProcessPropertiesSP &
1077Process::GetGlobalProperties()
1078{
1079 static ProcessPropertiesSP g_settings_sp;
1080 if (!g_settings_sp)
1081 g_settings_sp.reset (new ProcessProperties (true));
1082 return g_settings_sp;
1083}
1084
Chris Lattner24943d22010-06-08 16:52:24 +00001085void
1086Process::Finalize()
1087{
Greg Claytonffa43a62011-11-17 04:46:02 +00001088 switch (GetPrivateState())
1089 {
1090 case eStateConnected:
1091 case eStateAttaching:
1092 case eStateLaunching:
1093 case eStateStopped:
1094 case eStateRunning:
1095 case eStateStepping:
1096 case eStateCrashed:
1097 case eStateSuspended:
1098 if (GetShouldDetach())
Daniel Malea411ab472013-05-01 19:11:56 +00001099 Detach();
Greg Claytonffa43a62011-11-17 04:46:02 +00001100 else
1101 Destroy();
1102 break;
1103
1104 case eStateInvalid:
1105 case eStateUnloaded:
1106 case eStateDetached:
1107 case eStateExited:
1108 break;
1109 }
1110
Greg Clayton2f57db02011-10-01 00:45:15 +00001111 // Clear our broadcaster before we proceed with destroying
1112 Broadcaster::Clear();
1113
Chris Lattner24943d22010-06-08 16:52:24 +00001114 // Do any cleanup needed prior to being destructed... Subclasses
1115 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001116
1117 // We need to destroy the loader before the derived Process class gets destroyed
1118 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001119 m_dynamic_checkers_ap.reset();
1120 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001121 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001122 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001123 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001124 std::vector<Notifications> empty_notifications;
1125 m_notifications.swap(empty_notifications);
1126 m_image_tokens.clear();
1127 m_memory_cache.Clear();
1128 m_allocated_memory_cache.Clear();
1129 m_language_runtimes.clear();
1130 m_next_event_action_ap.reset();
Greg Clayton84332782012-10-29 20:52:08 +00001131//#ifdef LLDB_CONFIGURATION_DEBUG
1132// StreamFile s(stdout, false);
1133// EventSP event_sp;
1134// while (m_private_state_listener.GetNextEvent(event_sp))
1135// {
1136// event_sp->Dump (&s);
1137// s.EOL();
1138// }
1139//#endif
1140 // We have to be very careful here as the m_private_state_listener might
1141 // contain events that have ProcessSP values in them which can keep this
1142 // process around forever. These events need to be cleared out.
1143 m_private_state_listener.Clear();
Greg Clayton061ca652013-04-18 16:57:27 +00001144 m_public_run_lock.WriteUnlock();
1145#if defined(__APPLE__)
1146 m_private_run_lock.WriteUnlock();
1147#endif
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001148 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001149}
1150
1151void
1152Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1153{
1154 m_notifications.push_back(callbacks);
1155 if (callbacks.initialize != NULL)
1156 callbacks.initialize (callbacks.baton, this);
1157}
1158
1159bool
1160Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1161{
1162 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1163 for (pos = m_notifications.begin(); pos != end; ++pos)
1164 {
1165 if (pos->baton == callbacks.baton &&
1166 pos->initialize == callbacks.initialize &&
1167 pos->process_state_changed == callbacks.process_state_changed)
1168 {
1169 m_notifications.erase(pos);
1170 return true;
1171 }
1172 }
1173 return false;
1174}
1175
1176void
1177Process::SynchronouslyNotifyStateChanged (StateType state)
1178{
1179 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1180 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1181 {
1182 if (notification_pos->process_state_changed)
1183 notification_pos->process_state_changed (notification_pos->baton, this, state);
1184 }
1185}
1186
1187// FIXME: We need to do some work on events before the general Listener sees them.
1188// For instance if we are continuing from a breakpoint, we need to ensure that we do
1189// the little "insert real insn, step & stop" trick. But we can't do that when the
1190// event is delivered by the broadcaster - since that is done on the thread that is
1191// waiting for new events, so if we needed more than one event for our handling, we would
1192// stall. So instead we do it when we fetch the event off of the queue.
1193//
1194
1195StateType
1196Process::GetNextEvent (EventSP &event_sp)
1197{
1198 StateType state = eStateInvalid;
1199
1200 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1201 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1202
1203 return state;
1204}
1205
1206
1207StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001208Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001209{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001210 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1211 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1212 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001213 if (event_sp_ptr)
1214 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001215 StateType state = GetState();
1216 // If we are exited or detached, we won't ever get back to any
1217 // other valid state...
1218 if (state == eStateDetached || state == eStateExited)
1219 return state;
1220
1221 while (state != eStateInvalid)
1222 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001223 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001224 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001225 if (event_sp_ptr && event_sp)
1226 *event_sp_ptr = event_sp;
1227
Jim Ingham21f37ad2011-08-09 02:12:22 +00001228 switch (state)
1229 {
1230 case eStateCrashed:
1231 case eStateDetached:
1232 case eStateExited:
1233 case eStateUnloaded:
1234 return state;
1235 case eStateStopped:
1236 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1237 continue;
1238 else
1239 return state;
1240 default:
1241 continue;
1242 }
1243 }
1244 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001245}
1246
1247
1248StateType
1249Process::WaitForState
1250(
1251 const TimeValue *timeout,
1252 const StateType *match_states, const uint32_t num_match_states
1253)
1254{
1255 EventSP event_sp;
1256 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001257 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001258 while (state != eStateInvalid)
1259 {
Greg Claytond8c62532010-10-07 04:19:01 +00001260 // If we are exited or detached, we won't ever get back to any
1261 // other valid state...
1262 if (state == eStateDetached || state == eStateExited)
1263 return state;
1264
Chris Lattner24943d22010-06-08 16:52:24 +00001265 state = WaitForStateChangedEvents (timeout, event_sp);
1266
1267 for (i=0; i<num_match_states; ++i)
1268 {
1269 if (match_states[i] == state)
1270 return state;
1271 }
1272 }
1273 return state;
1274}
1275
Jim Ingham63e24d72010-10-11 23:53:14 +00001276bool
1277Process::HijackProcessEvents (Listener *listener)
1278{
1279 if (listener != NULL)
1280 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001281 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001282 }
1283 else
1284 return false;
1285}
1286
1287void
1288Process::RestoreProcessEvents ()
1289{
1290 RestoreBroadcaster();
1291}
1292
Jim Inghamf9f40c22011-02-08 05:20:59 +00001293bool
1294Process::HijackPrivateProcessEvents (Listener *listener)
1295{
1296 if (listener != NULL)
1297 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001298 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001299 }
1300 else
1301 return false;
1302}
1303
1304void
1305Process::RestorePrivateProcessEvents ()
1306{
1307 m_private_state_broadcaster.RestoreBroadcaster();
1308}
1309
Chris Lattner24943d22010-06-08 16:52:24 +00001310StateType
1311Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1312{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001313 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001314
1315 if (log)
1316 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1317
1318 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001319 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1320 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001321 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001322 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001323 {
1324 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1325 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1326 else if (log)
1327 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1328 }
Chris Lattner24943d22010-06-08 16:52:24 +00001329
1330 if (log)
1331 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1332 __FUNCTION__,
1333 timeout,
1334 StateAsCString(state));
1335 return state;
1336}
1337
1338Event *
1339Process::PeekAtStateChangedEvents ()
1340{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001341 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001342
1343 if (log)
1344 log->Printf ("Process::%s...", __FUNCTION__);
1345
1346 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001347 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1348 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001349 if (log)
1350 {
1351 if (event_ptr)
1352 {
1353 log->Printf ("Process::%s (event_ptr) => %s",
1354 __FUNCTION__,
1355 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1356 }
1357 else
1358 {
1359 log->Printf ("Process::%s no events found",
1360 __FUNCTION__);
1361 }
1362 }
1363 return event_ptr;
1364}
1365
1366StateType
1367Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1368{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001369 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001370
1371 if (log)
1372 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1373
1374 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001375 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1376 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001377 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001378 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001379 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1380 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001381
1382 // This is a bit of a hack, but when we wait here we could very well return
1383 // to the command-line, and that could disable the log, which would render the
1384 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001385 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001386 {
1387 if (state == eStateInvalid)
1388 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1389 else
1390 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1391 }
Chris Lattner24943d22010-06-08 16:52:24 +00001392 return state;
1393}
1394
1395bool
1396Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1397{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001398 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001399
1400 if (log)
1401 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1402
1403 if (control_only)
1404 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1405 else
1406 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1407}
1408
1409bool
1410Process::IsRunning () const
1411{
1412 return StateIsRunningState (m_public_state.GetValue());
1413}
1414
1415int
1416Process::GetExitStatus ()
1417{
1418 if (m_public_state.GetValue() == eStateExited)
1419 return m_exit_status;
1420 return -1;
1421}
1422
Greg Clayton638351a2010-12-04 00:10:17 +00001423
Chris Lattner24943d22010-06-08 16:52:24 +00001424const char *
1425Process::GetExitDescription ()
1426{
1427 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1428 return m_exit_string.c_str();
1429 return NULL;
1430}
1431
Greg Clayton72e1c782011-01-22 23:43:18 +00001432bool
Chris Lattner24943d22010-06-08 16:52:24 +00001433Process::SetExitStatus (int status, const char *cstr)
1434{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001435 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Greg Clayton68ca8232011-01-25 02:58:48 +00001436 if (log)
1437 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1438 status, status,
1439 cstr ? "\"" : "",
1440 cstr ? cstr : "NULL",
1441 cstr ? "\"" : "");
1442
Greg Clayton72e1c782011-01-22 23:43:18 +00001443 // We were already in the exited state
1444 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001445 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001446 if (log)
1447 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001448 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001449 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001450
1451 m_exit_status = status;
1452 if (cstr)
1453 m_exit_string = cstr;
1454 else
1455 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001456
Greg Clayton72e1c782011-01-22 23:43:18 +00001457 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001458
Greg Clayton72e1c782011-01-22 23:43:18 +00001459 SetPrivateState (eStateExited);
1460 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001461}
1462
1463// This static callback can be used to watch for local child processes on
1464// the current host. The the child process exits, the process will be
1465// found in the global target list (we want to be completely sure that the
1466// lldb_private::Process doesn't go away before we can deliver the signal.
1467bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001468Process::SetProcessExitStatus (void *callback_baton,
1469 lldb::pid_t pid,
1470 bool exited,
1471 int signo, // Zero for no signal
1472 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001473)
1474{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001475 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton1c4642c2011-11-16 05:37:56 +00001476 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001477 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001478 callback_baton,
1479 pid,
1480 exited,
1481 signo,
1482 exit_status);
1483
1484 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001485 {
Greg Clayton63094e02010-06-23 01:19:29 +00001486 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001487 if (target_sp)
1488 {
1489 ProcessSP process_sp (target_sp->GetProcessSP());
1490 if (process_sp)
1491 {
1492 const char *signal_cstr = NULL;
1493 if (signo)
1494 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1495
1496 process_sp->SetExitStatus (exit_status, signal_cstr);
1497 }
1498 }
1499 return true;
1500 }
1501 return false;
1502}
1503
1504
Greg Clayton37f962e2011-08-22 02:49:39 +00001505void
1506Process::UpdateThreadListIfNeeded ()
1507{
1508 const uint32_t stop_id = GetStopID();
1509 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1510 {
Greg Clayton20206082011-11-17 01:23:07 +00001511 const StateType state = GetPrivateState();
1512 if (StateIsStoppedState (state, true))
1513 {
1514 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001515 // m_thread_list does have its own mutex, but we need to
1516 // hold onto the mutex between the call to UpdateThreadList(...)
1517 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001518 ThreadList new_thread_list(this);
1519 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001520 // thread list, but only update if "true" is returned
1521 if (UpdateThreadList (m_thread_list, new_thread_list))
1522 {
Jim Inghameb175302013-03-01 20:04:25 +00001523 // Don't call into the OperatingSystem to update the thread list if we are shutting down, since
1524 // that may call back into the SBAPI's, requiring the API lock which is already held by whoever is
1525 // shutting us down, causing a deadlock.
1526 if (!m_destroy_in_process)
1527 {
1528 OperatingSystem *os = GetOperatingSystem ();
1529 if (os)
Greg Clayton9acf3692013-04-12 20:07:46 +00001530 {
1531 // Clear any old backing threads where memory threads might have been
1532 // backed by actual threads from the lldb_private::Process subclass
1533 size_t num_old_threads = m_thread_list.GetSize(false);
1534 for (size_t i=0; i<num_old_threads; ++i)
1535 m_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1536
1537 // Now let the OperatingSystem plug-in update the thread list
Jim Inghameb175302013-03-01 20:04:25 +00001538 os->UpdateThreadList (m_thread_list, new_thread_list);
Greg Clayton9acf3692013-04-12 20:07:46 +00001539 }
Jim Inghameb175302013-03-01 20:04:25 +00001540 m_thread_list.Update (new_thread_list);
1541 m_thread_list.SetStopID (stop_id);
1542 }
Greg Claytonae932352012-04-10 00:18:59 +00001543 }
Greg Clayton20206082011-11-17 01:23:07 +00001544 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001545 }
1546}
1547
Greg Clayton52ebc0a2013-01-18 23:41:08 +00001548ThreadSP
1549Process::CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context)
1550{
1551 OperatingSystem *os = GetOperatingSystem ();
1552 if (os)
1553 return os->CreateThread(tid, context);
1554 return ThreadSP();
1555}
1556
1557
1558
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001559// This is obsoleted. Staged removal for Xcode.
Chris Lattner24943d22010-06-08 16:52:24 +00001560uint32_t
1561Process::GetNextThreadIndexID ()
1562{
1563 return ++m_thread_index_id;
1564}
1565
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001566uint32_t
1567Process::GetNextThreadIndexID (uint64_t thread_id)
1568{
1569 return AssignIndexIDToThread(thread_id);
1570}
1571
1572bool
1573Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1574{
1575 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1576 if (iterator == m_thread_id_to_index_id_map.end())
1577 {
1578 return false;
1579 }
1580 else
1581 {
1582 return true;
1583 }
1584}
1585
1586uint32_t
1587Process::AssignIndexIDToThread(uint64_t thread_id)
1588{
1589 uint32_t result = 0;
1590 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1591 if (iterator == m_thread_id_to_index_id_map.end())
1592 {
1593 result = ++m_thread_index_id;
1594 m_thread_id_to_index_id_map[thread_id] = result;
1595 }
1596 else
1597 {
1598 result = iterator->second;
1599 }
1600
1601 return result;
1602}
1603
Chris Lattner24943d22010-06-08 16:52:24 +00001604StateType
1605Process::GetState()
1606{
1607 // If any other threads access this we will need a mutex for it
1608 return m_public_state.GetValue ();
1609}
1610
1611void
1612Process::SetPublicState (StateType new_state)
1613{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001614 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001615 if (log)
1616 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001617 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001618 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001619
1620 // On the transition from Run to Stopped, we unlock the writer end of the
1621 // run lock. The lock gets locked in Resume, which is the public API
1622 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001623 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1624 {
Sean Callanana3772862012-06-02 01:16:20 +00001625 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001626 {
Sean Callanana3772862012-06-02 01:16:20 +00001627 if (log)
1628 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
Greg Clayton061ca652013-04-18 16:57:27 +00001629 m_public_run_lock.WriteUnlock();
Sean Callanana3772862012-06-02 01:16:20 +00001630 }
1631 else
1632 {
1633 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1634 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1635 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001636 {
Sean Callanana3772862012-06-02 01:16:20 +00001637 if (new_state_is_stopped)
1638 {
1639 if (log)
1640 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
Greg Clayton061ca652013-04-18 16:57:27 +00001641 m_public_run_lock.WriteUnlock();
Sean Callanana3772862012-06-02 01:16:20 +00001642 }
Greg Claytona894fe72012-04-05 16:12:35 +00001643 }
Greg Claytona894fe72012-04-05 16:12:35 +00001644 }
1645 }
Chris Lattner24943d22010-06-08 16:52:24 +00001646}
1647
Jim Ingham027aaa72012-04-19 01:40:33 +00001648Error
1649Process::Resume ()
1650{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001651 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Jim Ingham027aaa72012-04-19 01:40:33 +00001652 if (log)
1653 log->Printf("Process::Resume -- locking run lock");
Greg Clayton061ca652013-04-18 16:57:27 +00001654 if (!m_public_run_lock.WriteTryLock())
Jim Ingham027aaa72012-04-19 01:40:33 +00001655 {
1656 Error error("Resume request failed - process still running.");
1657 if (log)
1658 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1659 return error;
1660 }
1661 return PrivateResume();
1662}
1663
Chris Lattner24943d22010-06-08 16:52:24 +00001664StateType
1665Process::GetPrivateState ()
1666{
1667 return m_private_state.GetValue();
1668}
1669
1670void
1671Process::SetPrivateState (StateType new_state)
1672{
Greg Clayton952e9dc2013-03-27 23:08:40 +00001673 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001674 bool state_changed = false;
1675
1676 if (log)
1677 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1678
1679 Mutex::Locker locker(m_private_state.GetMutex());
1680
1681 const StateType old_state = m_private_state.GetValueNoLock ();
1682 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001683 // This code is left commented out in case we ever need to control
1684 // the private process state with another run lock. Right now it doesn't
1685 // seem like we need to do this, but if we ever do, we can uncomment and
1686 // use this code.
1687// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1688// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1689// if (old_state_is_stopped != new_state_is_stopped)
1690// {
1691// if (new_state_is_stopped)
1692// m_private_run_lock.WriteUnlock();
1693// else
1694// m_private_run_lock.WriteLock();
1695// }
1696
Chris Lattner24943d22010-06-08 16:52:24 +00001697 if (state_changed)
1698 {
1699 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001700 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001701 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001702 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001703 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001704 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001705 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001706 }
1707 // Use our target to get a shared pointer to ourselves...
Greg Clayton84332782012-10-29 20:52:08 +00001708 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1709 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1710 else
1711 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001712 }
1713 else
1714 {
1715 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001716 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001717 }
1718}
1719
Jim Ingham0296fe72011-11-08 03:00:11 +00001720void
1721Process::SetRunningUserExpression (bool on)
1722{
1723 m_mod_id.SetRunningUserExpression (on);
1724}
1725
Chris Lattner24943d22010-06-08 16:52:24 +00001726addr_t
1727Process::GetImageInfoAddress()
1728{
1729 return LLDB_INVALID_ADDRESS;
1730}
1731
Greg Clayton0baa3942010-11-04 01:54:29 +00001732//----------------------------------------------------------------------
1733// LoadImage
1734//
1735// This function provides a default implementation that works for most
1736// unix variants. Any Process subclasses that need to do shared library
1737// loading differently should override LoadImage and UnloadImage and
1738// do what is needed.
1739//----------------------------------------------------------------------
1740uint32_t
1741Process::LoadImage (const FileSpec &image_spec, Error &error)
1742{
Greg Clayton77d40712012-04-18 00:05:19 +00001743 char path[PATH_MAX];
1744 image_spec.GetPath(path, sizeof(path));
1745
Greg Clayton0baa3942010-11-04 01:54:29 +00001746 DynamicLoader *loader = GetDynamicLoader();
1747 if (loader)
1748 {
1749 error = loader->CanLoadImage();
1750 if (error.Fail())
1751 return LLDB_INVALID_IMAGE_TOKEN;
1752 }
1753
1754 if (error.Success())
1755 {
1756 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001757
1758 if (thread_sp)
1759 {
1760 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1761
1762 if (frame_sp)
1763 {
1764 ExecutionContext exe_ctx;
1765 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001766 const bool unwind_on_error = true;
1767 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001768 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001769 expr.Printf("dlopen (\"%s\", 2)", path);
1770 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001771 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001772 ClangUserExpression::Evaluate (exe_ctx,
1773 eExecutionPolicyAlways,
1774 lldb::eLanguageTypeUnknown,
1775 ClangUserExpression::eResultTypeAny,
1776 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001777 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001778 expr.GetData(),
1779 prefix,
1780 result_valobj_sp,
1781 true,
1782 ClangUserExpression::kDefaultTimeout);
Johnny Chenb14ec342011-09-09 00:01:43 +00001783 error = result_valobj_sp->GetError();
1784 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001785 {
1786 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001787 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001788 {
1789 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1790 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1791 {
1792 uint32_t image_token = m_image_tokens.size();
1793 m_image_tokens.push_back (image_ptr);
1794 return image_token;
1795 }
1796 }
1797 }
1798 }
1799 }
1800 }
Greg Clayton77d40712012-04-18 00:05:19 +00001801 if (!error.AsCString())
1802 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001803 return LLDB_INVALID_IMAGE_TOKEN;
1804}
1805
1806//----------------------------------------------------------------------
1807// UnloadImage
1808//
1809// This function provides a default implementation that works for most
1810// unix variants. Any Process subclasses that need to do shared library
1811// loading differently should override LoadImage and UnloadImage and
1812// do what is needed.
1813//----------------------------------------------------------------------
1814Error
1815Process::UnloadImage (uint32_t image_token)
1816{
1817 Error error;
1818 if (image_token < m_image_tokens.size())
1819 {
1820 const addr_t image_addr = m_image_tokens[image_token];
1821 if (image_addr == LLDB_INVALID_ADDRESS)
1822 {
1823 error.SetErrorString("image already unloaded");
1824 }
1825 else
1826 {
1827 DynamicLoader *loader = GetDynamicLoader();
1828 if (loader)
1829 error = loader->CanLoadImage();
1830
1831 if (error.Success())
1832 {
1833 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001834
1835 if (thread_sp)
1836 {
1837 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1838
1839 if (frame_sp)
1840 {
1841 ExecutionContext exe_ctx;
1842 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamb7940202013-01-15 02:47:48 +00001843 const bool unwind_on_error = true;
1844 const bool ignore_breakpoints = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001845 StreamString expr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001846 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton0baa3942010-11-04 01:54:29 +00001847 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001848 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001849 ClangUserExpression::Evaluate (exe_ctx,
1850 eExecutionPolicyAlways,
1851 lldb::eLanguageTypeUnknown,
1852 ClangUserExpression::eResultTypeAny,
1853 unwind_on_error,
Jim Inghamb7940202013-01-15 02:47:48 +00001854 ignore_breakpoints,
Greg Clayton34507e42012-10-31 20:49:04 +00001855 expr.GetData(),
1856 prefix,
1857 result_valobj_sp,
1858 true,
1859 ClangUserExpression::kDefaultTimeout);
Greg Clayton0baa3942010-11-04 01:54:29 +00001860 if (result_valobj_sp->GetError().Success())
1861 {
1862 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001863 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001864 {
1865 if (scalar.UInt(1))
1866 {
1867 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1868 }
1869 else
1870 {
1871 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1872 }
1873 }
1874 }
1875 else
1876 {
1877 error = result_valobj_sp->GetError();
1878 }
1879 }
1880 }
1881 }
1882 }
1883 }
1884 else
1885 {
1886 error.SetErrorString("invalid image token");
1887 }
1888 return error;
1889}
1890
Greg Clayton75906e42011-05-11 18:39:18 +00001891const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001892Process::GetABI()
1893{
Greg Clayton75906e42011-05-11 18:39:18 +00001894 if (!m_abi_sp)
1895 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1896 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001897}
1898
Jim Ingham642036f2010-09-23 02:01:19 +00001899LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001900Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001901{
1902 LanguageRuntimeCollection::iterator pos;
1903 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001904 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001905 {
Jim Inghame3117662012-03-10 00:22:19 +00001906 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001907
Jim Inghame3117662012-03-10 00:22:19 +00001908 m_language_runtimes[language] = runtime_sp;
1909 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001910 }
1911 else
1912 return (*pos).second.get();
1913}
1914
1915CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001916Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001917{
Jim Inghame3117662012-03-10 00:22:19 +00001918 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001919 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1920 return static_cast<CPPLanguageRuntime *> (runtime);
1921 return NULL;
1922}
1923
1924ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001925Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001926{
Jim Inghame3117662012-03-10 00:22:19 +00001927 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001928 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1929 return static_cast<ObjCLanguageRuntime *> (runtime);
1930 return NULL;
1931}
1932
Enrico Granata6b1763b2012-05-21 16:51:35 +00001933bool
1934Process::IsPossibleDynamicValue (ValueObject& in_value)
1935{
1936 if (in_value.IsDynamic())
1937 return false;
1938 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1939
1940 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1941 {
1942 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1943 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1944 }
1945
1946 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1947 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1948 return true;
1949
1950 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1951 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1952}
1953
Chris Lattner24943d22010-06-08 16:52:24 +00001954BreakpointSiteList &
1955Process::GetBreakpointSiteList()
1956{
1957 return m_breakpoint_site_list;
1958}
1959
1960const BreakpointSiteList &
1961Process::GetBreakpointSiteList() const
1962{
1963 return m_breakpoint_site_list;
1964}
1965
1966
1967void
1968Process::DisableAllBreakpointSites ()
1969{
1970 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001971 size_t num_sites = m_breakpoint_site_list.GetSize();
1972 for (size_t i = 0; i < num_sites; i++)
1973 {
Jim Inghamefb4aeb2013-02-15 02:06:30 +00001974 DisableBreakpointSite (m_breakpoint_site_list.GetByIndex(i).get());
Jim Ingham06b84492012-07-04 00:35:43 +00001975 }
Chris Lattner24943d22010-06-08 16:52:24 +00001976}
1977
1978Error
1979Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1980{
1981 Error error (DisableBreakpointSiteByID (break_id));
1982
1983 if (error.Success())
1984 m_breakpoint_site_list.Remove(break_id);
1985
1986 return error;
1987}
1988
1989Error
1990Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1991{
1992 Error error;
1993 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1994 if (bp_site_sp)
1995 {
1996 if (bp_site_sp->IsEnabled())
Jim Inghamefb4aeb2013-02-15 02:06:30 +00001997 error = DisableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001998 }
1999 else
2000 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002001 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00002002 }
2003
2004 return error;
2005}
2006
2007Error
2008Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
2009{
2010 Error error;
2011 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
2012 if (bp_site_sp)
2013 {
2014 if (!bp_site_sp->IsEnabled())
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002015 error = EnableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002016 }
2017 else
2018 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002019 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00002020 }
2021 return error;
2022}
2023
Stephen Wilson3fd1f362010-07-17 00:56:13 +00002024lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00002025Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00002026{
Greg Clayton265ab332011-05-19 18:17:41 +00002027 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00002028 if (load_addr != LLDB_INVALID_ADDRESS)
2029 {
2030 BreakpointSiteSP bp_site_sp;
2031
2032 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
2033 // create a new breakpoint site and add it.
2034
2035 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
2036
2037 if (bp_site_sp)
2038 {
2039 bp_site_sp->AddOwner (owner);
2040 owner->SetBreakpointSite (bp_site_sp);
2041 return bp_site_sp->GetID();
2042 }
2043 else
2044 {
Greg Clayton36da2aa2013-01-25 18:06:21 +00002045 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, use_hardware));
Chris Lattner24943d22010-06-08 16:52:24 +00002046 if (bp_site_sp)
2047 {
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002048 if (EnableBreakpointSite (bp_site_sp.get()).Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002049 {
2050 owner->SetBreakpointSite (bp_site_sp);
2051 return m_breakpoint_site_list.Add (bp_site_sp);
2052 }
2053 }
2054 }
2055 }
2056 // We failed to enable the breakpoint
2057 return LLDB_INVALID_BREAK_ID;
2058
2059}
2060
2061void
2062Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
2063{
2064 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
2065 if (num_owners == 0)
2066 {
Jim Ingham700ff7e2013-04-06 00:16:39 +00002067 // Don't try to disable the site if we don't have a live process anymore.
2068 if (IsAlive())
2069 DisableBreakpointSite (bp_site_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002070 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
2071 }
2072}
2073
2074
2075size_t
2076Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
2077{
2078 size_t bytes_removed = 0;
2079 addr_t intersect_addr;
2080 size_t intersect_size;
2081 size_t opcode_offset;
2082 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002083 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00002084 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00002085
Jim Ingham82820f92011-06-29 19:42:28 +00002086 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00002087 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002088 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00002089 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002090 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00002091 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00002092 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00002093 {
2094 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
2095 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00002096 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00002097 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00002098 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00002099 }
Chris Lattner24943d22010-06-08 16:52:24 +00002100 }
2101 }
2102 }
2103 return bytes_removed;
2104}
2105
2106
Greg Claytonb1888f22011-03-19 01:12:21 +00002107
2108size_t
2109Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2110{
2111 PlatformSP platform_sp (m_target.GetPlatform());
2112 if (platform_sp)
2113 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2114 return 0;
2115}
2116
Chris Lattner24943d22010-06-08 16:52:24 +00002117Error
2118Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2119{
2120 Error error;
2121 assert (bp_site != NULL);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002122 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002123 const addr_t bp_addr = bp_site->GetLoadAddress();
2124 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002125 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002126 if (bp_site->IsEnabled())
2127 {
2128 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002129 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 +00002130 return error;
2131 }
2132
2133 if (bp_addr == LLDB_INVALID_ADDRESS)
2134 {
2135 error.SetErrorString("BreakpointSite contains an invalid load address.");
2136 return error;
2137 }
2138 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2139 // trap for the breakpoint site
2140 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2141
2142 if (bp_opcode_size == 0)
2143 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002144 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002145 }
2146 else
2147 {
2148 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2149
2150 if (bp_opcode_bytes == NULL)
2151 {
2152 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2153 return error;
2154 }
2155
2156 // Save the original opcode by reading it
2157 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2158 {
2159 // Write a software breakpoint in place of the original opcode
2160 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2161 {
2162 uint8_t verify_bp_opcode_bytes[64];
2163 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2164 {
2165 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2166 {
2167 bp_site->SetEnabled(true);
2168 bp_site->SetType (BreakpointSite::eSoftware);
2169 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002170 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner24943d22010-06-08 16:52:24 +00002171 bp_site->GetID(),
2172 (uint64_t)bp_addr);
2173 }
2174 else
Greg Clayton9c236732011-10-26 00:56:27 +00002175 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00002176 }
2177 else
2178 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2179 }
2180 else
2181 error.SetErrorString("Unable to write breakpoint trap to memory.");
2182 }
2183 else
2184 error.SetErrorString("Unable to read memory at breakpoint address.");
2185 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002186 if (log && error.Fail())
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002187 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002188 bp_site->GetID(),
2189 (uint64_t)bp_addr,
2190 error.AsCString());
2191 return error;
2192}
2193
2194Error
2195Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2196{
2197 Error error;
2198 assert (bp_site != NULL);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002199 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002200 addr_t bp_addr = bp_site->GetLoadAddress();
2201 lldb::user_id_t breakID = bp_site->GetID();
2202 if (log)
Jim Inghamefb4aeb2013-02-15 02:06:30 +00002203 log->Printf ("Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002204
2205 if (bp_site->IsHardware())
2206 {
2207 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2208 }
2209 else if (bp_site->IsEnabled())
2210 {
2211 const size_t break_op_size = bp_site->GetByteSize();
2212 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2213 if (break_op_size > 0)
2214 {
2215 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002216 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002217 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002218 bool break_op_found = false;
2219
2220 // Read the breakpoint opcode
2221 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2222 {
2223 bool verify = false;
2224 // Make sure we have the a breakpoint opcode exists at this address
2225 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2226 {
2227 break_op_found = true;
2228 // We found a valid breakpoint opcode at this address, now restore
2229 // the saved opcode.
2230 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2231 {
2232 verify = true;
2233 }
2234 else
2235 error.SetErrorString("Memory write failed when restoring original opcode.");
2236 }
2237 else
2238 {
2239 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2240 // Set verify to true and so we can check if the original opcode has already been restored
2241 verify = true;
2242 }
2243
2244 if (verify)
2245 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002246 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002247 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002248 // Verify that our original opcode made it back to the inferior
2249 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2250 {
2251 // compare the memory we just read with the original opcode
2252 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2253 {
2254 // SUCCESS
2255 bp_site->SetEnabled(false);
2256 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002257 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 +00002258 return error;
2259 }
2260 else
2261 {
2262 if (break_op_found)
2263 error.SetErrorString("Failed to restore original opcode.");
2264 }
2265 }
2266 else
2267 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2268 }
2269 }
2270 else
2271 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2272 }
2273 }
2274 else
2275 {
2276 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002277 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 +00002278 return error;
2279 }
2280
2281 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002282 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002283 bp_site->GetID(),
2284 (uint64_t)bp_addr,
2285 error.AsCString());
2286 return error;
2287
2288}
2289
Greg Claytonfd119992011-01-07 06:08:19 +00002290// Uncomment to verify memory caching works after making changes to caching code
2291//#define VERIFY_MEMORY_READS
2292
Sean Callananf90b5f32012-06-07 22:26:42 +00002293size_t
2294Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2295{
2296 if (!GetDisableMemoryCache())
2297 {
Greg Claytonfd119992011-01-07 06:08:19 +00002298#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002299 // Memory caching is enabled, with debug verification
2300
2301 if (buf && size)
2302 {
2303 // Uncomment the line below to make sure memory caching is working.
2304 // I ran this through the test suite and got no assertions, so I am
2305 // pretty confident this is working well. If any changes are made to
2306 // memory caching, uncomment the line below and test your changes!
2307
2308 // Verify all memory reads by using the cache first, then redundantly
2309 // reading the same memory from the inferior and comparing to make sure
2310 // everything is exactly the same.
2311 std::string verify_buf (size, '\0');
2312 assert (verify_buf.size() == size);
2313 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2314 Error verify_error;
2315 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2316 assert (cache_bytes_read == verify_bytes_read);
2317 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2318 assert (verify_error.Success() == error.Success());
2319 return cache_bytes_read;
2320 }
2321 return 0;
2322#else // !defined(VERIFY_MEMORY_READS)
2323 // Memory caching is enabled, without debug verification
2324
2325 return m_memory_cache.Read (addr, buf, size, error);
2326#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002327 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002328 else
2329 {
2330 // Memory caching is disabled
2331
2332 return ReadMemoryFromInferior (addr, buf, size, error);
2333 }
Greg Claytonfd119992011-01-07 06:08:19 +00002334}
Greg Claytonfd119992011-01-07 06:08:19 +00002335
Greg Claytondd29b972012-05-18 23:20:01 +00002336size_t
2337Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2338{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002339 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002340 out_str.clear();
2341 addr_t curr_addr = addr;
2342 while (1)
2343 {
2344 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2345 if (length == 0)
2346 break;
2347 out_str.append(buf, length);
2348 // If we got "length - 1" bytes, we didn't get the whole C string, we
2349 // need to read some more characters
2350 if (length == sizeof(buf) - 1)
2351 curr_addr += length;
2352 else
2353 break;
2354 }
2355 return out_str.size();
2356}
2357
Greg Claytonfd119992011-01-07 06:08:19 +00002358
2359size_t
Ashok Thirumurthi347d7222013-04-19 15:58:38 +00002360Process::ReadStringFromMemory (addr_t addr, char *dst, size_t max_bytes, Error &error,
2361 size_t type_width)
2362{
2363 size_t total_bytes_read = 0;
2364 if (dst && max_bytes && type_width && max_bytes >= type_width)
2365 {
2366 // Ensure a null terminator independent of the number of bytes that is read.
2367 memset (dst, 0, max_bytes);
2368 size_t bytes_left = max_bytes - type_width;
2369
2370 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2371 assert(sizeof(terminator) >= type_width &&
2372 "Attempting to validate a string with more than 4 bytes per character!");
2373
2374 addr_t curr_addr = addr;
2375 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2376 char *curr_dst = dst;
2377
2378 error.Clear();
2379 while (bytes_left > 0 && error.Success())
2380 {
2381 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2382 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2383 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2384
2385 if (bytes_read == 0)
2386 break;
2387
2388 // Search for a null terminator of correct size and alignment in bytes_read
2389 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2390 for (size_t i = aligned_start; i + type_width <= total_bytes_read + bytes_read; i += type_width)
2391 if (::strncmp(&dst[i], terminator, type_width) == 0)
2392 {
2393 error.Clear();
2394 return i;
2395 }
2396
2397 total_bytes_read += bytes_read;
2398 curr_dst += bytes_read;
2399 curr_addr += bytes_read;
2400 bytes_left -= bytes_read;
2401 }
2402 }
2403 else
2404 {
2405 if (max_bytes)
2406 error.SetErrorString("invalid arguments");
2407 }
2408 return total_bytes_read;
2409}
2410
2411// Deprecated in favor of ReadStringFromMemory which has wchar support and correct code to find
2412// null terminators.
2413size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002414Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002415{
2416 size_t total_cstr_len = 0;
2417 if (dst && dst_max_len)
2418 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002419 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002420 // NULL out everything just to be safe
2421 memset (dst, 0, dst_max_len);
2422 Error error;
2423 addr_t curr_addr = addr;
2424 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2425 size_t bytes_left = dst_max_len - 1;
2426 char *curr_dst = dst;
2427
2428 while (bytes_left > 0)
2429 {
2430 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2431 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2432 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2433
2434 if (bytes_read == 0)
2435 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002436 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002437 dst[total_cstr_len] = '\0';
2438 break;
2439 }
2440 const size_t len = strlen(curr_dst);
2441
2442 total_cstr_len += len;
2443
2444 if (len < bytes_to_read)
2445 break;
2446
2447 curr_dst += bytes_read;
2448 curr_addr += bytes_read;
2449 bytes_left -= bytes_read;
2450 }
2451 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002452 else
2453 {
2454 if (dst == NULL)
2455 result_error.SetErrorString("invalid arguments");
2456 else
2457 result_error.Clear();
2458 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002459 return total_cstr_len;
2460}
2461
2462size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002463Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2464{
Chris Lattner24943d22010-06-08 16:52:24 +00002465 if (buf == NULL || size == 0)
2466 return 0;
2467
2468 size_t bytes_read = 0;
2469 uint8_t *bytes = (uint8_t *)buf;
2470
2471 while (bytes_read < size)
2472 {
2473 const size_t curr_size = size - bytes_read;
2474 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2475 bytes + bytes_read,
2476 curr_size,
2477 error);
2478 bytes_read += curr_bytes_read;
2479 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2480 break;
2481 }
2482
2483 // Replace any software breakpoint opcodes that fall into this range back
2484 // into "buf" before we return
2485 if (bytes_read > 0)
2486 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2487 return bytes_read;
2488}
2489
Greg Claytonf72fdee2010-12-16 20:01:20 +00002490uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002491Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002492{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002493 Scalar scalar;
2494 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2495 return scalar.ULongLong(fail_value);
2496 return fail_value;
2497}
2498
2499addr_t
2500Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2501{
2502 Scalar scalar;
2503 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2504 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2505 return LLDB_INVALID_ADDRESS;
2506}
2507
2508
2509bool
2510Process::WritePointerToMemory (lldb::addr_t vm_addr,
2511 lldb::addr_t ptr_value,
2512 Error &error)
2513{
2514 Scalar scalar;
2515 const uint32_t addr_byte_size = GetAddressByteSize();
2516 if (addr_byte_size <= 4)
2517 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002518 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002519 scalar = ptr_value;
2520 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002521}
2522
Chris Lattner24943d22010-06-08 16:52:24 +00002523size_t
2524Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2525{
2526 size_t bytes_written = 0;
2527 const uint8_t *bytes = (const uint8_t *)buf;
2528
2529 while (bytes_written < size)
2530 {
2531 const size_t curr_size = size - bytes_written;
2532 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2533 bytes + bytes_written,
2534 curr_size,
2535 error);
2536 bytes_written += curr_bytes_written;
2537 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2538 break;
2539 }
2540 return bytes_written;
2541}
2542
2543size_t
2544Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2545{
Greg Claytonfd119992011-01-07 06:08:19 +00002546#if defined (ENABLE_MEMORY_CACHING)
2547 m_memory_cache.Flush (addr, size);
2548#endif
2549
Chris Lattner24943d22010-06-08 16:52:24 +00002550 if (buf == NULL || size == 0)
2551 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002552
Jim Ingham21f37ad2011-08-09 02:12:22 +00002553 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002554
Chris Lattner24943d22010-06-08 16:52:24 +00002555 // We need to write any data that would go where any current software traps
2556 // (enabled software breakpoints) any software traps (breakpoints) that we
2557 // may have placed in our tasks memory.
2558
2559 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2560 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2561
2562 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002563 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002564
2565 BreakpointSiteList::collection::const_iterator pos;
2566 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002567 addr_t intersect_addr = 0;
2568 size_t intersect_size = 0;
2569 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002570 const uint8_t *ubuf = (const uint8_t *)buf;
2571
2572 for (pos = iter; pos != end; ++pos)
2573 {
2574 BreakpointSiteSP bp;
2575 bp = pos->second;
2576
2577 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2578 assert(addr <= intersect_addr && intersect_addr < addr + size);
2579 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2580 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2581
2582 // Check for bytes before this breakpoint
2583 const addr_t curr_addr = addr + bytes_written;
2584 if (intersect_addr > curr_addr)
2585 {
2586 // There are some bytes before this breakpoint that we need to
2587 // just write to memory
2588 size_t curr_size = intersect_addr - curr_addr;
2589 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2590 ubuf + bytes_written,
2591 curr_size,
2592 error);
2593 bytes_written += curr_bytes_written;
2594 if (curr_bytes_written != curr_size)
2595 {
2596 // We weren't able to write all of the requested bytes, we
2597 // are done looping and will return the number of bytes that
2598 // we have written so far.
2599 break;
2600 }
2601 }
2602
2603 // Now write any bytes that would cover up any software breakpoints
2604 // directly into the breakpoint opcode buffer
2605 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2606 bytes_written += intersect_size;
2607 }
2608
2609 // Write any remaining bytes after the last breakpoint if we have any left
2610 if (bytes_written < size)
2611 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2612 ubuf + bytes_written,
2613 size - bytes_written,
2614 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002615
Chris Lattner24943d22010-06-08 16:52:24 +00002616 return bytes_written;
2617}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002618
2619size_t
Greg Clayton36da2aa2013-01-25 18:06:21 +00002620Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, size_t byte_size, Error &error)
Greg Claytonc0fa5332011-05-22 22:46:53 +00002621{
2622 if (byte_size == UINT32_MAX)
2623 byte_size = scalar.GetByteSize();
2624 if (byte_size > 0)
2625 {
2626 uint8_t buf[32];
2627 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2628 if (mem_size > 0)
2629 return WriteMemory(addr, buf, mem_size, error);
2630 else
2631 error.SetErrorString ("failed to get scalar as memory data");
2632 }
2633 else
2634 {
2635 error.SetErrorString ("invalid scalar value");
2636 }
2637 return 0;
2638}
2639
2640size_t
2641Process::ReadScalarIntegerFromMemory (addr_t addr,
2642 uint32_t byte_size,
2643 bool is_signed,
2644 Scalar &scalar,
2645 Error &error)
2646{
2647 uint64_t uval;
2648
2649 if (byte_size <= sizeof(uval))
2650 {
2651 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2652 if (bytes_read == byte_size)
2653 {
2654 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
Greg Clayton36da2aa2013-01-25 18:06:21 +00002655 lldb::offset_t offset = 0;
Sean Callananf408e992013-05-01 22:01:40 +00002656
2657 if (byte_size == 0)
2658 {
2659 error.SetErrorString ("byte size is zero");
2660 }
2661 else if (byte_size & (byte_size - 1))
2662 {
2663 error.SetErrorStringWithFormat ("byte size %u is not a power of 2", byte_size);
2664 }
Greg Claytonc0fa5332011-05-22 22:46:53 +00002665 else
Sean Callananf408e992013-05-01 22:01:40 +00002666 {
2667 if (byte_size <= 4)
2668 scalar = data.GetMaxU32 (&offset, byte_size);
2669 else
2670 scalar = data.GetMaxU64 (&offset, byte_size);
2671 }
Greg Claytonc0fa5332011-05-22 22:46:53 +00002672
2673 if (is_signed)
2674 scalar.SignExtend(byte_size * 8);
2675 return bytes_read;
2676 }
2677 }
2678 else
2679 {
2680 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2681 }
2682 return 0;
2683}
2684
Greg Clayton613b8732011-05-17 03:37:42 +00002685#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002686addr_t
2687Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2688{
Jim Inghame6bd1422011-06-20 17:32:44 +00002689 if (GetPrivateState() != eStateStopped)
2690 return LLDB_INVALID_ADDRESS;
2691
Greg Clayton613b8732011-05-17 03:37:42 +00002692#if defined (USE_ALLOCATE_MEMORY_CACHE)
2693 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2694#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002695 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
Greg Clayton952e9dc2013-03-27 23:08:40 +00002696 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2860ba92011-01-23 19:58:49 +00002697 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002698 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 +00002699 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002700 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002701 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002702 m_mod_id.GetStopID(),
2703 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002704 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002705#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002706}
2707
Sean Callanan6cf6c472011-09-20 23:01:51 +00002708bool
2709Process::CanJIT ()
2710{
Sean Callanan04200f62012-02-14 22:50:38 +00002711 if (m_can_jit == eCanJITDontKnow)
2712 {
2713 Error err;
2714
2715 uint64_t allocated_memory = AllocateMemory(8,
2716 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2717 err);
2718
2719 if (err.Success())
2720 m_can_jit = eCanJITYes;
2721 else
2722 m_can_jit = eCanJITNo;
2723
2724 DeallocateMemory (allocated_memory);
2725 }
2726
Sean Callanan6cf6c472011-09-20 23:01:51 +00002727 return m_can_jit == eCanJITYes;
2728}
2729
2730void
2731Process::SetCanJIT (bool can_jit)
2732{
2733 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2734}
2735
Chris Lattner24943d22010-06-08 16:52:24 +00002736Error
2737Process::DeallocateMemory (addr_t ptr)
2738{
Greg Clayton613b8732011-05-17 03:37:42 +00002739 Error error;
2740#if defined (USE_ALLOCATE_MEMORY_CACHE)
2741 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2742 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002743 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Clayton613b8732011-05-17 03:37:42 +00002744 }
2745#else
2746 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002747
Greg Clayton952e9dc2013-03-27 23:08:40 +00002748 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2860ba92011-01-23 19:58:49 +00002749 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002750 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 +00002751 ptr,
2752 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002753 m_mod_id.GetStopID(),
2754 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002755#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002756 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002757}
2758
Han Ming Ong2529aa32012-11-17 00:33:14 +00002759
Greg Claytonb5a8f142012-02-05 02:38:54 +00002760ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002761Process::ReadModuleFromMemory (const FileSpec& file_spec,
Greg Clayton2ddb2b82013-02-01 21:38:35 +00002762 lldb::addr_t header_addr)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002763{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002764 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002765 if (module_sp)
2766 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002767 Error error;
2768 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2769 if (objfile)
Greg Clayton6c5438b2012-02-24 21:55:59 +00002770 return module_sp;
Greg Claytonb5a8f142012-02-05 02:38:54 +00002771 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002772 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002773}
Chris Lattner24943d22010-06-08 16:52:24 +00002774
2775Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002776Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002777{
2778 Error error;
2779 error.SetErrorString("watchpoints are not supported");
2780 return error;
2781}
2782
2783Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002784Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002785{
2786 Error error;
2787 error.SetErrorString("watchpoints are not supported");
2788 return error;
2789}
2790
2791StateType
2792Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2793{
2794 StateType state;
2795 // Now wait for the process to launch and return control to us, and then
2796 // call DidLaunch:
2797 while (1)
2798 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002799 event_sp.reset();
2800 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2801
Greg Clayton20206082011-11-17 01:23:07 +00002802 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002803 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002804
2805 // If state is invalid, then we timed out
2806 if (state == eStateInvalid)
2807 break;
2808
2809 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002810 HandlePrivateEvent (event_sp);
2811 }
2812 return state;
2813}
2814
2815Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002816Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002817{
2818 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002819 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002820 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002821 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002822 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002823
Greg Clayton5beb99d2011-08-11 02:48:45 +00002824 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002825 if (exe_module)
2826 {
Greg Clayton180546b2011-04-30 01:09:13 +00002827 char local_exec_file_path[PATH_MAX];
2828 char platform_exec_file_path[PATH_MAX];
2829 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2830 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002831 if (exe_module->GetFileSpec().Exists())
2832 {
Greg Claytona2f74232011-02-24 22:24:29 +00002833 if (PrivateStateThreadIsValid ())
2834 PausePrivateStateThread ();
2835
Chris Lattner24943d22010-06-08 16:52:24 +00002836 error = WillLaunch (exe_module);
2837 if (error.Success())
2838 {
Greg Claytond8c62532010-10-07 04:19:01 +00002839 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002840 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002841
Greg Clayton061ca652013-04-18 16:57:27 +00002842 if (m_public_run_lock.WriteTryLock())
Greg Clayton777c6b72012-09-04 20:29:05 +00002843 {
2844 // Now launch using these arguments.
2845 error = DoLaunch (exe_module, launch_info);
2846 }
2847 else
2848 {
2849 // This shouldn't happen
2850 error.SetErrorString("failed to acquire process run lock");
2851 }
Chris Lattner24943d22010-06-08 16:52:24 +00002852
2853 if (error.Fail())
2854 {
2855 if (GetID() != LLDB_INVALID_PROCESS_ID)
2856 {
2857 SetID (LLDB_INVALID_PROCESS_ID);
2858 const char *error_string = error.AsCString();
2859 if (error_string == NULL)
2860 error_string = "launch failed";
2861 SetExitStatus (-1, error_string);
2862 }
2863 }
2864 else
2865 {
2866 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002867 TimeValue timeout_time;
2868 timeout_time = TimeValue::Now();
2869 timeout_time.OffsetWithSeconds(10);
2870 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002871
Greg Clayton49859592011-06-22 01:42:17 +00002872 if (state == eStateInvalid || event_sp.get() == NULL)
2873 {
2874 // We were able to launch the process, but we failed to
2875 // catch the initial stop.
2876 SetExitStatus (0, "failed to catch stop after launch");
2877 Destroy();
2878 }
2879 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002880 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002881
Chris Lattner24943d22010-06-08 16:52:24 +00002882 DidLaunch ();
2883
Greg Clayton9ce95382012-02-13 23:10:39 +00002884 DynamicLoader *dyld = GetDynamicLoader ();
2885 if (dyld)
2886 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002887
Greg Clayton37f962e2011-08-22 02:49:39 +00002888 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002889 // This delays passing the stopped event to listeners till DidLaunch gets
2890 // a chance to complete...
2891 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002892
2893 if (PrivateStateThreadIsValid ())
2894 ResumePrivateStateThread ();
2895 else
2896 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002897 }
2898 else if (state == eStateExited)
2899 {
2900 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2901 // not likely to work, and return an invalid pid.
2902 HandlePrivateEvent (event_sp);
2903 }
2904 }
2905 }
2906 }
2907 else
2908 {
Greg Clayton9c236732011-10-26 00:56:27 +00002909 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002910 }
2911 }
2912 return error;
2913}
2914
Greg Clayton46c9a352012-02-09 06:16:32 +00002915
2916Error
2917Process::LoadCore ()
2918{
2919 Error error = DoLoadCore();
2920 if (error.Success())
2921 {
2922 if (PrivateStateThreadIsValid ())
2923 ResumePrivateStateThread ();
2924 else
2925 StartPrivateStateThread ();
2926
Greg Clayton9ce95382012-02-13 23:10:39 +00002927 DynamicLoader *dyld = GetDynamicLoader ();
2928 if (dyld)
2929 dyld->DidAttach();
2930
2931 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002932 // We successfully loaded a core file, now pretend we stopped so we can
2933 // show all of the threads in the core file and explore the crashed
2934 // state.
2935 SetPrivateState (eStateStopped);
2936
2937 }
2938 return error;
2939}
2940
Greg Clayton9ce95382012-02-13 23:10:39 +00002941DynamicLoader *
2942Process::GetDynamicLoader ()
2943{
2944 if (m_dyld_ap.get() == NULL)
2945 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2946 return m_dyld_ap.get();
2947}
Greg Clayton46c9a352012-02-09 06:16:32 +00002948
2949
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002950Process::NextEventAction::EventActionResult
2951Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002952{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002953 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2954 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002955 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002956 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002957 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002958 return eEventActionRetry;
2959
2960 case eStateStopped:
2961 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002962 {
2963 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002964 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002965 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2966 if (m_exec_count > 0)
2967 {
2968 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002969 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002970 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002971 return eEventActionRetry;
2972 }
2973 else
2974 {
2975 m_process->CompleteAttach ();
2976 return eEventActionSuccess;
2977 }
2978 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002979 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002980
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002981 default:
2982 case eStateExited:
2983 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002984 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002985 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002986
2987 m_exit_string.assign ("No valid Process");
2988 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002989}
Chris Lattner24943d22010-06-08 16:52:24 +00002990
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002991Process::NextEventAction::EventActionResult
2992Process::AttachCompletionHandler::HandleBeingInterrupted()
2993{
2994 return eEventActionSuccess;
2995}
2996
2997const char *
2998Process::AttachCompletionHandler::GetExitString ()
2999{
3000 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00003001}
3002
3003Error
Greg Clayton527154d2011-11-15 03:53:30 +00003004Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00003005{
Chris Lattner24943d22010-06-08 16:52:24 +00003006 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00003007 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00003008 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00003009 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00003010
Greg Clayton527154d2011-11-15 03:53:30 +00003011 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003012 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00003013 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00003014 {
Greg Clayton527154d2011-11-15 03:53:30 +00003015 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00003016
Greg Clayton527154d2011-11-15 03:53:30 +00003017 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00003018 {
Greg Clayton527154d2011-11-15 03:53:30 +00003019 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3020
3021 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00003022 {
Greg Clayton527154d2011-11-15 03:53:30 +00003023 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3024 if (error.Success())
3025 {
Greg Clayton061ca652013-04-18 16:57:27 +00003026 if (m_public_run_lock.WriteTryLock())
Greg Claytond34a3b22012-10-12 16:10:12 +00003027 {
3028 m_should_detach = true;
3029 SetPublicState (eStateAttaching);
3030 // Now attach using these arguments.
3031 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
3032 }
3033 else
3034 {
3035 // This shouldn't happen
3036 error.SetErrorString("failed to acquire process run lock");
3037 }
Greg Claytonffa43a62011-11-17 04:46:02 +00003038
Greg Clayton527154d2011-11-15 03:53:30 +00003039 if (error.Fail())
3040 {
3041 if (GetID() != LLDB_INVALID_PROCESS_ID)
3042 {
3043 SetID (LLDB_INVALID_PROCESS_ID);
3044 if (error.AsCString() == NULL)
3045 error.SetErrorString("attach failed");
3046
3047 SetExitStatus(-1, error.AsCString());
3048 }
3049 }
3050 else
3051 {
3052 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3053 StartPrivateStateThread();
3054 }
3055 return error;
3056 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003057 }
Greg Clayton527154d2011-11-15 03:53:30 +00003058 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003059 {
Greg Clayton527154d2011-11-15 03:53:30 +00003060 ProcessInstanceInfoList process_infos;
3061 PlatformSP platform_sp (m_target.GetPlatform ());
3062
3063 if (platform_sp)
3064 {
3065 ProcessInstanceInfoMatch match_info;
3066 match_info.GetProcessInfo() = attach_info;
3067 match_info.SetNameMatchType (eNameMatchEquals);
3068 platform_sp->FindProcesses (match_info, process_infos);
3069 const uint32_t num_matches = process_infos.GetSize();
3070 if (num_matches == 1)
3071 {
3072 attach_pid = process_infos.GetProcessIDAtIndex(0);
3073 // Fall through and attach using the above process ID
3074 }
3075 else
3076 {
3077 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
3078 if (num_matches > 1)
3079 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
3080 else
3081 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
3082 }
3083 }
3084 else
3085 {
3086 error.SetErrorString ("invalid platform, can't find processes by name");
3087 return error;
3088 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003089 }
Chris Lattner24943d22010-06-08 16:52:24 +00003090 }
3091 else
Greg Clayton527154d2011-11-15 03:53:30 +00003092 {
3093 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003094 }
3095 }
Greg Clayton527154d2011-11-15 03:53:30 +00003096
3097 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003098 {
Greg Clayton527154d2011-11-15 03:53:30 +00003099 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003100 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00003101 {
Greg Clayton527154d2011-11-15 03:53:30 +00003102
Greg Clayton061ca652013-04-18 16:57:27 +00003103 if (m_public_run_lock.WriteTryLock())
Greg Claytond34a3b22012-10-12 16:10:12 +00003104 {
3105 // Now attach using these arguments.
3106 m_should_detach = true;
3107 SetPublicState (eStateAttaching);
3108 error = DoAttachToProcessWithID (attach_pid, attach_info);
3109 }
3110 else
3111 {
3112 // This shouldn't happen
3113 error.SetErrorString("failed to acquire process run lock");
3114 }
3115
Greg Clayton527154d2011-11-15 03:53:30 +00003116 if (error.Success())
3117 {
3118
3119 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
3120 StartPrivateStateThread();
3121 }
3122 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003123 {
3124 if (GetID() != LLDB_INVALID_PROCESS_ID)
3125 {
3126 SetID (LLDB_INVALID_PROCESS_ID);
3127 const char *error_string = error.AsCString();
3128 if (error_string == NULL)
3129 error_string = "attach failed";
3130
3131 SetExitStatus(-1, error_string);
3132 }
3133 }
Chris Lattner24943d22010-06-08 16:52:24 +00003134 }
3135 }
3136 return error;
3137}
3138
Greg Clayton75c703d2011-02-16 04:46:07 +00003139void
3140Process::CompleteAttach ()
3141{
3142 // Let the process subclass figure out at much as it can about the process
3143 // before we go looking for a dynamic loader plug-in.
3144 DidAttach();
3145
Jim Ingham0d7f7772011-09-15 01:10:17 +00003146 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
3147 // the same as the one we've already set, switch architectures.
3148 PlatformSP platform_sp (m_target.GetPlatform ());
3149 assert (platform_sp.get());
3150 if (platform_sp)
3151 {
Greg Claytonb170aee2012-05-08 01:45:38 +00003152 const ArchSpec &target_arch = m_target.GetArchitecture();
Greg Claytonaad2b0f2013-01-11 20:49:54 +00003153 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch, false, NULL))
Greg Claytonb170aee2012-05-08 01:45:38 +00003154 {
3155 ArchSpec platform_arch;
3156 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3157 if (platform_sp)
3158 {
3159 m_target.SetPlatform (platform_sp);
3160 m_target.SetArchitecture(platform_arch);
3161 }
3162 }
3163 else
3164 {
3165 ProcessInstanceInfo process_info;
3166 platform_sp->GetProcessInfo (GetID(), process_info);
3167 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callanan40e278c2012-12-13 22:07:14 +00003168 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Claytonb170aee2012-05-08 01:45:38 +00003169 m_target.SetArchitecture (process_arch);
3170 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00003171 }
3172
3173 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00003174 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00003175 DynamicLoader *dyld = GetDynamicLoader ();
3176 if (dyld)
3177 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00003178
Greg Clayton37f962e2011-08-22 02:49:39 +00003179 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00003180 // Figure out which one is the executable, and set that in our target:
Enrico Granata146d9522012-11-08 02:22:02 +00003181 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham93367902012-05-30 02:19:25 +00003182 Mutex::Locker modules_locker(target_modules.GetMutex());
3183 size_t num_modules = target_modules.GetSize();
3184 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003185
Greg Clayton75c703d2011-02-16 04:46:07 +00003186 for (int i = 0; i < num_modules; i++)
3187 {
Jim Ingham93367902012-05-30 02:19:25 +00003188 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00003189 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00003190 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00003191 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00003192 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003193 break;
3194 }
3195 }
Jim Ingham93367902012-05-30 02:19:25 +00003196 if (new_executable_module_sp)
3197 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00003198}
3199
Chris Lattner24943d22010-06-08 16:52:24 +00003200Error
Jason Molendafac2e622012-09-29 04:02:01 +00003201Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00003202{
Greg Claytone71e2582011-02-04 01:58:07 +00003203 m_abi_sp.reset();
3204 m_process_input_reader.reset();
3205
3206 // Find the process and its architecture. Make sure it matches the architecture
3207 // of the current Target, and if not adjust it.
3208
Jason Molendafac2e622012-09-29 04:02:01 +00003209 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00003210 if (error.Success())
3211 {
Greg Claytona2f74232011-02-24 22:24:29 +00003212 if (GetID() != LLDB_INVALID_PROCESS_ID)
3213 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00003214 EventSP event_sp;
3215 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3216
3217 if (state == eStateStopped || state == eStateCrashed)
3218 {
3219 // If we attached and actually have a process on the other end, then
3220 // this ended up being the equivalent of an attach.
3221 CompleteAttach ();
3222
3223 // This delays passing the stopped event to listeners till
3224 // CompleteAttach gets a chance to complete...
3225 HandlePrivateEvent (event_sp);
3226
3227 }
Greg Claytona2f74232011-02-24 22:24:29 +00003228 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00003229
3230 if (PrivateStateThreadIsValid ())
3231 ResumePrivateStateThread ();
3232 else
3233 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00003234 }
3235 return error;
3236}
3237
3238
3239Error
Jim Ingham027aaa72012-04-19 01:40:33 +00003240Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00003241{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003242 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00003243 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003244 log->Printf("Process::PrivateResume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00003245 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00003246 StateAsCString(m_public_state.GetValue()),
3247 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00003248
3249 Error error (WillResume());
3250 // Tell the process it is about to resume before the thread list
3251 if (error.Success())
3252 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003253 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003254 // can let all of our threads know that they are about to be
3255 // resumed. Threads will each be called with
3256 // Thread::WillResume(StateType) where StateType contains the state
3257 // that they are supposed to have when the process is resumed
3258 // (suspended/running/stepping). Threads should also check
3259 // their resume signal in lldb::Thread::GetResumeSignal()
3260 // to see if they are suppoed to start back up with a signal.
3261 if (m_thread_list.WillResume())
3262 {
Jim Ingham1831e782012-04-07 00:00:41 +00003263 // Last thing, do the PreResumeActions.
3264 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003265 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003266 error.SetErrorStringWithFormat ("Process::PrivateResume PreResumeActions failed, not resuming.");
Jim Ingham1831e782012-04-07 00:00:41 +00003267 }
3268 else
3269 {
3270 m_mod_id.BumpResumeID();
Greg Clayton061ca652013-04-18 16:57:27 +00003271#if defined(__APPLE__)
3272 m_private_run_lock.WriteLock();
3273#endif
Jim Ingham1831e782012-04-07 00:00:41 +00003274 error = DoResume();
3275 if (error.Success())
3276 {
3277 DidResume();
3278 m_thread_list.DidResume();
3279 if (log)
3280 log->Printf ("Process thinks the process has resumed.");
3281 }
Greg Clayton061ca652013-04-18 16:57:27 +00003282#if defined(__APPLE__)
3283 else
3284 {
3285 m_private_run_lock.WriteUnlock();
3286 }
3287#endif
Chris Lattner24943d22010-06-08 16:52:24 +00003288 }
3289 }
3290 else
3291 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003292 // Somebody wanted to run without running. So generate a continue & a stopped event,
3293 // and let the world handle them.
3294 if (log)
3295 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3296
3297 SetPrivateState(eStateRunning);
3298 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003299 }
3300 }
Jim Inghamac959662011-01-24 06:34:17 +00003301 else if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003302 log->Printf ("Process::PrivateResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003303 return error;
3304}
3305
3306Error
3307Process::Halt ()
3308{
Jim Ingham43892562012-06-06 00:29:30 +00003309 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3310 // we could just straightaway get another event. It just narrows the window...
3311 m_currently_handling_event.WaitForValueEqualTo(false);
3312
3313
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003314 // Pause our private state thread so we can ensure no one else eats
3315 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003316 Listener halt_listener ("lldb.process.halt_listener");
3317 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003318
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003319 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003320 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003321
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003322 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003323 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003324
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003325 bool caused_stop = false;
3326
3327 // Ask the process subclass to actually halt our process
3328 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003329 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003330 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003331 if (m_public_state.GetValue() == eStateAttaching)
3332 {
3333 SetExitStatus(SIGKILL, "Cancelled async attach.");
3334 Destroy ();
3335 }
3336 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003337 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003338 // If "caused_stop" is true, then DoHalt stopped the process. If
3339 // "caused_stop" is false, the process was already stopped.
3340 // If the DoHalt caused the process to stop, then we want to catch
3341 // this event and set the interrupted bool to true before we pass
3342 // this along so clients know that the process was interrupted by
3343 // a halt command.
3344 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003345 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003346 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003347 TimeValue timeout_time;
3348 timeout_time = TimeValue::Now();
3349 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003350 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3351 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003352
Jim Inghamf9f40c22011-02-08 05:20:59 +00003353 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003354 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003355 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003356 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003357 }
3358 else
3359 {
Greg Clayton20206082011-11-17 01:23:07 +00003360 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003361 {
3362 // We caused the process to interrupt itself, so mark this
3363 // as such in the stop event so clients can tell an interrupted
3364 // process from a natural stop
3365 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3366 }
3367 else
3368 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00003369 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003370 if (log)
3371 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3372 error.SetErrorString ("Did not get stopped event after halt.");
3373 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003374 }
3375 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003376 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003377 }
3378 }
Chris Lattner24943d22010-06-08 16:52:24 +00003379 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003380 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003381 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003382
3383 // Post any event we might have consumed. If all goes well, we will have
3384 // stopped the process, intercepted the event and set the interrupted
3385 // bool in the event. Post it to the private event queue and that will end up
3386 // correctly setting the state.
3387 if (event_sp)
3388 m_private_state_broadcaster.BroadcastEvent(event_sp);
3389
Chris Lattner24943d22010-06-08 16:52:24 +00003390 return error;
3391}
3392
3393Error
Jim Inghame33bb5b2013-03-29 01:18:12 +00003394Process::HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp)
3395{
3396 Error error;
3397 if (m_public_state.GetValue() == eStateRunning)
3398 {
3399 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3400 if (log)
3401 log->Printf("Process::Destroy() About to halt.");
3402 error = Halt();
3403 if (error.Success())
3404 {
3405 // Consume the halt event.
3406 TimeValue timeout (TimeValue::Now());
3407 timeout.OffsetWithSeconds(1);
3408 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3409
3410 // If the process exited while we were waiting for it to stop, put the exited event into
3411 // the shared pointer passed in and return. Our caller doesn't need to do anything else, since
3412 // they don't have a process anymore...
3413
3414 if (state == eStateExited || m_private_state.GetValue() == eStateExited)
3415 {
3416 if (log)
3417 log->Printf("Process::HaltForDestroyOrDetach() Process exited while waiting to Halt.");
3418 return error;
3419 }
3420 else
3421 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3422
3423 if (state != eStateStopped)
3424 {
3425 if (log)
3426 log->Printf("Process::HaltForDestroyOrDetach() Halt failed to stop, state is: %s", StateAsCString(state));
3427 // If we really couldn't stop the process then we should just error out here, but if the
3428 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3429 StateType private_state = m_private_state.GetValue();
3430 if (private_state != eStateStopped)
3431 {
3432 return error;
3433 }
3434 }
3435 }
3436 else
3437 {
3438 if (log)
3439 log->Printf("Process::HaltForDestroyOrDetach() Halt got error: %s", error.AsCString());
3440 }
3441 }
3442 return error;
3443}
3444
3445Error
Daniel Malea411ab472013-05-01 19:11:56 +00003446Process::Detach ()
Chris Lattner24943d22010-06-08 16:52:24 +00003447{
Jim Inghame33bb5b2013-03-29 01:18:12 +00003448 EventSP exit_event_sp;
3449 Error error;
3450 m_destroy_in_process = true;
3451
3452 error = WillDetach();
Chris Lattner24943d22010-06-08 16:52:24 +00003453
3454 if (error.Success())
3455 {
Jim Inghame33bb5b2013-03-29 01:18:12 +00003456 if (DetachRequiresHalt())
3457 {
3458 error = HaltForDestroyOrDetach (exit_event_sp);
3459 if (!error.Success())
3460 {
3461 m_destroy_in_process = false;
3462 return error;
3463 }
3464 else if (exit_event_sp)
3465 {
3466 // We shouldn't need to do anything else here. There's no process left to detach from...
3467 StopPrivateStateThread();
3468 m_destroy_in_process = false;
3469 return error;
3470 }
3471 }
3472
Daniel Malea411ab472013-05-01 19:11:56 +00003473 error = DoDetach();
Chris Lattner24943d22010-06-08 16:52:24 +00003474 if (error.Success())
3475 {
3476 DidDetach();
3477 StopPrivateStateThread();
3478 }
3479 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003480 m_destroy_in_process = false;
3481
3482 // If we exited when we were waiting for a process to stop, then
3483 // forward the event here so we don't lose the event
3484 if (exit_event_sp)
3485 {
3486 // Directly broadcast our exited event because we shut down our
3487 // private state thread above
3488 BroadcastEvent(exit_event_sp);
3489 }
3490
3491 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3492 // the last events through the event system, in which case we might strand the write lock. Unlock
3493 // it here so when we do to tear down the process we don't get an error destroying the lock.
3494
Greg Clayton061ca652013-04-18 16:57:27 +00003495 m_public_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003496 return error;
3497}
3498
3499Error
3500Process::Destroy ()
3501{
Jim Inghameb175302013-03-01 20:04:25 +00003502
3503 // Tell ourselves we are in the process of destroying the process, so that we don't do any unnecessary work
3504 // that might hinder the destruction. Remember to set this back to false when we are done. That way if the attempt
3505 // failed and the process stays around for some reason it won't be in a confused state.
3506
3507 m_destroy_in_process = true;
3508
Chris Lattner24943d22010-06-08 16:52:24 +00003509 Error error (WillDestroy());
3510 if (error.Success())
3511 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003512 EventSP exit_event_sp;
Jim Inghame33bb5b2013-03-29 01:18:12 +00003513 if (DestroyRequiresHalt())
Jim Inghamf4928de2012-05-23 15:46:31 +00003514 {
Jim Inghame33bb5b2013-03-29 01:18:12 +00003515 error = HaltForDestroyOrDetach(exit_event_sp);
Jim Inghamf4928de2012-05-23 15:46:31 +00003516 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003517
Jim Ingham43892562012-06-06 00:29:30 +00003518 if (m_public_state.GetValue() != eStateRunning)
3519 {
3520 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3521 // kill it, we don't want it hitting a breakpoint...
3522 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3523 // we're not going to have much luck doing this now.
3524 m_thread_list.DiscardThreadPlans();
3525 DisableAllBreakpointSites();
3526 }
Jim Inghame33bb5b2013-03-29 01:18:12 +00003527
Chris Lattner24943d22010-06-08 16:52:24 +00003528 error = DoDestroy();
3529 if (error.Success())
3530 {
3531 DidDestroy();
3532 StopPrivateStateThread();
3533 }
Caroline Tice861efb32010-11-16 05:07:41 +00003534 m_stdio_communication.StopReadThread();
3535 m_stdio_communication.Disconnect();
3536 if (m_process_input_reader && m_process_input_reader->IsActive())
3537 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3538 if (m_process_input_reader)
3539 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003540
3541 // If we exited when we were waiting for a process to stop, then
3542 // forward the event here so we don't lose the event
3543 if (exit_event_sp)
3544 {
3545 // Directly broadcast our exited event because we shut down our
3546 // private state thread above
3547 BroadcastEvent(exit_event_sp);
3548 }
3549
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003550 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3551 // the last events through the event system, in which case we might strand the write lock. Unlock
3552 // it here so when we do to tear down the process we don't get an error destroying the lock.
Greg Clayton061ca652013-04-18 16:57:27 +00003553 m_public_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003554 }
Jim Inghameb175302013-03-01 20:04:25 +00003555
3556 m_destroy_in_process = false;
3557
Chris Lattner24943d22010-06-08 16:52:24 +00003558 return error;
3559}
3560
3561Error
3562Process::Signal (int signal)
3563{
3564 Error error (WillSignal());
3565 if (error.Success())
3566 {
3567 error = DoSignal(signal);
3568 if (error.Success())
3569 DidSignal();
3570 }
3571 return error;
3572}
3573
Greg Clayton395fc332011-02-15 21:59:32 +00003574lldb::ByteOrder
3575Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003576{
Greg Clayton395fc332011-02-15 21:59:32 +00003577 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003578}
3579
3580uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003581Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003582{
Greg Clayton395fc332011-02-15 21:59:32 +00003583 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003584}
3585
Greg Clayton395fc332011-02-15 21:59:32 +00003586
Chris Lattner24943d22010-06-08 16:52:24 +00003587bool
3588Process::ShouldBroadcastEvent (Event *event_ptr)
3589{
3590 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3591 bool return_value = true;
Greg Clayton952e9dc2013-03-27 23:08:40 +00003592 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS | LIBLLDB_LOG_PROCESS));
Jim Ingham89e248f2013-02-09 01:29:05 +00003593
Chris Lattner24943d22010-06-08 16:52:24 +00003594 switch (state)
3595 {
Greg Claytone71e2582011-02-04 01:58:07 +00003596 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003597 case eStateAttaching:
3598 case eStateLaunching:
3599 case eStateDetached:
3600 case eStateExited:
3601 case eStateUnloaded:
3602 // These events indicate changes in the state of the debugging session, always report them.
3603 return_value = true;
3604 break;
3605 case eStateInvalid:
3606 // We stopped for no apparent reason, don't report it.
3607 return_value = false;
3608 break;
3609 case eStateRunning:
3610 case eStateStepping:
3611 // If we've started the target running, we handle the cases where we
3612 // are already running and where there is a transition from stopped to
3613 // running differently.
3614 // running -> running: Automatically suppress extra running events
3615 // stopped -> running: Report except when there is one or more no votes
3616 // and no yes votes.
3617 SynchronouslyNotifyStateChanged (state);
Jim Ingham89e248f2013-02-09 01:29:05 +00003618 switch (m_last_broadcast_state)
Chris Lattner24943d22010-06-08 16:52:24 +00003619 {
3620 case eStateRunning:
3621 case eStateStepping:
3622 // We always suppress multiple runnings with no PUBLIC stop in between.
3623 return_value = false;
3624 break;
3625 default:
3626 // TODO: make this work correctly. For now always report
3627 // run if we aren't running so we don't miss any runnning
3628 // events. If I run the lldb/test/thread/a.out file and
3629 // break at main.cpp:58, run and hit the breakpoints on
3630 // multiple threads, then somehow during the stepping over
3631 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003632
3633 // This is a transition from stop to run.
3634 switch (m_thread_list.ShouldReportRun (event_ptr))
3635 {
3636 case eVoteYes:
3637 case eVoteNoOpinion:
3638 return_value = true;
3639 break;
3640 case eVoteNo:
3641 return_value = false;
3642 break;
3643 }
3644 break;
3645 }
3646 break;
3647 case eStateStopped:
3648 case eStateCrashed:
3649 case eStateSuspended:
3650 {
3651 // We've stopped. First see if we're going to restart the target.
3652 // If we are going to stop, then we always broadcast the event.
3653 // 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 +00003654 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003655
Greg Clayton061ca652013-04-18 16:57:27 +00003656#if defined(__APPLE__)
3657 m_private_run_lock.WriteUnlock();
3658#endif
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003659 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003660 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003661 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003662 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003663 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s",
3664 event_ptr,
3665 StateAsCString(state));
3666 return_value = true;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003667 }
3668 else
3669 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003670 // It makes no sense to ask "ShouldStop" if we've already been restarted...
3671 // Asking the thread list is also not likely to go well, since we are running again.
3672 // So in that case just report the event.
3673
3674 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
3675 bool should_resume = false;
3676 if (!was_restarted)
3677 should_resume = m_thread_list.ShouldStop (event_ptr) == false;
3678 if (was_restarted || should_resume)
Chris Lattner24943d22010-06-08 16:52:24 +00003679 {
Jim Ingham89e248f2013-02-09 01:29:05 +00003680 Vote stop_vote = m_thread_list.ShouldReportStop (event_ptr);
3681 if (log)
3682 log->Printf ("Process::ShouldBroadcastEvent: should_stop: %i state: %s was_restarted: %i stop_vote: %d.",
3683 should_resume,
3684 StateAsCString(state),
3685 was_restarted,
3686 stop_vote);
3687
3688 switch (stop_vote)
Chris Lattner24943d22010-06-08 16:52:24 +00003689 {
3690 case eVoteYes:
Jim Ingham89e248f2013-02-09 01:29:05 +00003691 return_value = true;
3692 break;
Chris Lattner24943d22010-06-08 16:52:24 +00003693 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003694 case eVoteNo:
3695 return_value = false;
3696 break;
3697 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003698
Jim Ingham8290bba2012-09-05 21:13:56 +00003699 if (!was_restarted)
Jim Ingham89e248f2013-02-09 01:29:05 +00003700 {
3701 if (log)
3702 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
3703 ProcessEventData::SetRestartedInEvent(event_ptr, true);
Jim Ingham8290bba2012-09-05 21:13:56 +00003704 PrivateResume ();
Jim Ingham89e248f2013-02-09 01:29:05 +00003705 }
3706
Chris Lattner24943d22010-06-08 16:52:24 +00003707 }
3708 else
3709 {
3710 return_value = true;
3711 SynchronouslyNotifyStateChanged (state);
3712 }
3713 }
3714 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003715 break;
Chris Lattner24943d22010-06-08 16:52:24 +00003716 }
Jim Ingham89e248f2013-02-09 01:29:05 +00003717
3718 // We do some coalescing of events (for instance two consecutive running events get coalesced.)
3719 // But we only coalesce against events we actually broadcast. So we use m_last_broadcast_state
3720 // to track that. NB - you can't use "m_public_state.GetValue()" for that purpose, as was originally done,
3721 // because the PublicState reflects the last event pulled off the queue, and there may be several
3722 // events stacked up on the queue unserviced. So the PublicState may not reflect the last broadcasted event
3723 // yet. m_last_broadcast_state gets updated here.
3724
3725 if (return_value)
3726 m_last_broadcast_state = state;
3727
Chris Lattner24943d22010-06-08 16:52:24 +00003728 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003729 log->Printf ("Process::ShouldBroadcastEvent (%p) => new state: %s, last broadcast state: %s - %s",
3730 event_ptr,
3731 StateAsCString(state),
3732 StateAsCString(m_last_broadcast_state),
3733 return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003734 return return_value;
3735}
3736
Chris Lattner24943d22010-06-08 16:52:24 +00003737
3738bool
Jim Ingham1831e782012-04-07 00:00:41 +00003739Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003740{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003741 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003742
Greg Claytonb72d0f02011-04-12 05:54:46 +00003743 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003744 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003745 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3746
Jim Ingham1831e782012-04-07 00:00:41 +00003747 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003748 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003749
3750 // Create a thread that watches our internal state and controls which
3751 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003752 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003753 if (already_running)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003754 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham1831e782012-04-07 00:00:41 +00003755 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003756 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003757
3758 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003759 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003760 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3761 if (success)
3762 {
3763 ResumePrivateStateThread();
3764 return true;
3765 }
3766 else
3767 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003768}
3769
3770void
3771Process::PausePrivateStateThread ()
3772{
3773 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3774}
3775
3776void
3777Process::ResumePrivateStateThread ()
3778{
3779 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3780}
3781
3782void
3783Process::StopPrivateStateThread ()
3784{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003785 if (PrivateStateThreadIsValid ())
3786 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003787 else
3788 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00003789 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003790 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00003791 log->Printf ("Went to stop the private state thread, but it was already invalid.");
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003792 }
Chris Lattner24943d22010-06-08 16:52:24 +00003793}
3794
3795void
3796Process::ControlPrivateStateThread (uint32_t signal)
3797{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003798 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003799
3800 assert (signal == eBroadcastInternalStateControlStop ||
3801 signal == eBroadcastInternalStateControlPause ||
3802 signal == eBroadcastInternalStateControlResume);
3803
3804 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003805 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003806
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003807 // Signal the private state thread. First we should copy this is case the
3808 // thread starts exiting since the private state thread will NULL this out
3809 // when it exits
3810 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003811 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003812 {
3813 TimeValue timeout_time;
3814 bool timed_out;
3815
3816 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3817
3818 timeout_time = TimeValue::Now();
3819 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003820 if (log)
3821 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003822 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3823 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3824
3825 if (signal == eBroadcastInternalStateControlStop)
3826 {
3827 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003828 {
3829 Error error;
3830 Host::ThreadCancel (private_state_thread, &error);
3831 if (log)
3832 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3833 }
3834 else
3835 {
3836 if (log)
3837 log->Printf ("The control event killed the private state thread without having to cancel.");
3838 }
Chris Lattner24943d22010-06-08 16:52:24 +00003839
3840 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003841 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003842 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003843 }
3844 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003845 else
3846 {
3847 if (log)
3848 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3849 }
Chris Lattner24943d22010-06-08 16:52:24 +00003850}
3851
3852void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003853Process::SendAsyncInterrupt ()
3854{
3855 if (PrivateStateThreadIsValid())
3856 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3857 else
3858 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3859}
3860
3861void
Chris Lattner24943d22010-06-08 16:52:24 +00003862Process::HandlePrivateEvent (EventSP &event_sp)
3863{
Greg Clayton952e9dc2013-03-27 23:08:40 +00003864 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003865 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003866
Greg Clayton68ca8232011-01-25 02:58:48 +00003867 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003868
3869 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003870 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003871 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003872 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Ingham89e248f2013-02-09 01:29:05 +00003873 if (log)
3874 log->Printf ("Ran next event action, result was %d.", action_result);
3875
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003876 switch (action_result)
3877 {
3878 case NextEventAction::eEventActionSuccess:
3879 SetNextEventAction(NULL);
3880 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003881
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003882 case NextEventAction::eEventActionRetry:
3883 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003884
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003885 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003886 // Handle Exiting Here. If we already got an exited event,
3887 // we should just propagate it. Otherwise, swallow this event,
3888 // and set our state to exit so the next event will kill us.
3889 if (new_state != eStateExited)
3890 {
3891 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003892 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003893 SetNextEventAction(NULL);
3894 return;
3895 }
3896 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003897 break;
3898 }
3899 }
3900
Chris Lattner24943d22010-06-08 16:52:24 +00003901 // See if we should broadcast this state to external clients?
3902 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003903
3904 if (should_broadcast)
3905 {
3906 if (log)
3907 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003908 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003909 __FUNCTION__,
3910 GetID(),
3911 StateAsCString(new_state),
3912 StateAsCString (GetState ()),
3913 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003914 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003915 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003916 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003917 PushProcessInputReader ();
3918 else
3919 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003920
Chris Lattner24943d22010-06-08 16:52:24 +00003921 BroadcastEvent (event_sp);
3922 }
3923 else
3924 {
3925 if (log)
3926 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003927 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003928 __FUNCTION__,
3929 GetID(),
3930 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003931 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003932 }
3933 }
Jim Ingham43892562012-06-06 00:29:30 +00003934 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003935}
3936
3937void *
3938Process::PrivateStateThread (void *arg)
3939{
3940 Process *proc = static_cast<Process*> (arg);
3941 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003942 return result;
3943}
3944
3945void *
3946Process::RunPrivateStateThread ()
3947{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003948 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003949 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003950
Greg Clayton952e9dc2013-03-27 23:08:40 +00003951 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003952 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003953 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003954
3955 bool exit_now = false;
3956 while (!exit_now)
3957 {
3958 EventSP event_sp;
3959 WaitForEventsPrivate (NULL, event_sp, control_only);
3960 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3961 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003962 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003963 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 +00003964
Chris Lattner24943d22010-06-08 16:52:24 +00003965 switch (event_sp->GetType())
3966 {
3967 case eBroadcastInternalStateControlStop:
3968 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003969 break; // doing any internal state managment below
3970
3971 case eBroadcastInternalStateControlPause:
3972 control_only = true;
3973 break;
3974
3975 case eBroadcastInternalStateControlResume:
3976 control_only = false;
3977 break;
3978 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003979
Chris Lattner24943d22010-06-08 16:52:24 +00003980 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003981 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003982 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003983 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3984 {
3985 if (m_public_state.GetValue() == eStateAttaching)
3986 {
3987 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003988 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 +00003989 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3990 }
3991 else
3992 {
3993 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003994 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00003995 Halt();
3996 }
3997 continue;
3998 }
Chris Lattner24943d22010-06-08 16:52:24 +00003999
4000 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4001
4002 if (internal_state != eStateInvalid)
4003 {
4004 HandlePrivateEvent (event_sp);
4005 }
4006
Greg Clayton3b2c41c2010-10-18 04:14:23 +00004007 if (internal_state == eStateInvalid ||
4008 internal_state == eStateExited ||
4009 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00004010 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00004011 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004012 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 +00004013
Chris Lattner24943d22010-06-08 16:52:24 +00004014 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00004015 }
Chris Lattner24943d22010-06-08 16:52:24 +00004016 }
4017
Caroline Tice926060e2010-10-29 21:48:37 +00004018 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00004019 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004020 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00004021
Greg Clayton061ca652013-04-18 16:57:27 +00004022 m_public_run_lock.WriteUnlock();
Greg Claytona4881d02011-01-22 07:12:45 +00004023 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
4024 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00004025 return NULL;
4026}
4027
Chris Lattner24943d22010-06-08 16:52:24 +00004028//------------------------------------------------------------------
4029// Process Event Data
4030//------------------------------------------------------------------
4031
4032Process::ProcessEventData::ProcessEventData () :
4033 EventData (),
4034 m_process_sp (),
4035 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00004036 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00004037 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00004038 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00004039{
4040}
4041
4042Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
4043 EventData (),
4044 m_process_sp (process_sp),
4045 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00004046 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00004047 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00004048 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00004049{
4050}
4051
4052Process::ProcessEventData::~ProcessEventData()
4053{
4054}
4055
4056const ConstString &
4057Process::ProcessEventData::GetFlavorString ()
4058{
4059 static ConstString g_flavor ("Process::ProcessEventData");
4060 return g_flavor;
4061}
4062
4063const ConstString &
4064Process::ProcessEventData::GetFlavor () const
4065{
4066 return ProcessEventData::GetFlavorString ();
4067}
4068
Chris Lattner24943d22010-06-08 16:52:24 +00004069void
4070Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
4071{
4072 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00004073 // off of the private process event queue, and then any number of times, first when it gets pulled off of
4074 // the public event queue, then other times when we're pretending that this is where we stopped at the
4075 // end of expression evaluation. m_update_state is used to distinguish these
4076 // three cases; it is 0 when we're just pulling it off for private handling,
4077 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00004078
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00004079 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00004080 return;
Jim Ingham89e248f2013-02-09 01:29:05 +00004081
Chris Lattner24943d22010-06-08 16:52:24 +00004082 m_process_sp->SetPublicState (m_state);
4083
4084 // If we're stopped and haven't restarted, then do the breakpoint commands here:
4085 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00004086 {
4087 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00004088 uint32_t num_threads = curr_thread_list.GetSize();
4089 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00004090
Jim Ingham21f37ad2011-08-09 02:12:22 +00004091 // The actions might change one of the thread's stop_info's opinions about whether we should
4092 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00004093
4094 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
4095 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
4096 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
4097 // 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
4098 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00004099 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00004100 for (idx = 0; idx < num_threads; ++idx)
4101 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
4102
Jim Inghamb6059b22012-12-13 22:24:15 +00004103 // Use this to track whether we should continue from here. We will only continue the target running if
4104 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
4105 // then it doesn't matter what the other threads say...
4106
4107 bool still_should_stop = false;
Jim Ingham21f37ad2011-08-09 02:12:22 +00004108
Jim Ingham68899da2013-04-25 02:04:59 +00004109 // Sometimes - for instance if we have a bug in the stub we are talking to, we stop but no thread has a
4110 // valid stop reason. In that case we should just stop, because we have no way of telling what the right
4111 // thing to do is, and it's better to let the user decide than continue behind their backs.
4112
4113 bool does_anybody_have_an_opinion = false;
4114
Chris Lattner24943d22010-06-08 16:52:24 +00004115 for (idx = 0; idx < num_threads; ++idx)
4116 {
Jim Ingham0296fe72011-11-08 03:00:11 +00004117 curr_thread_list = m_process_sp->GetThreadList();
4118 if (curr_thread_list.GetSize() != num_threads)
4119 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004120 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00004121 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00004122 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 +00004123 break;
4124 }
4125
4126 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4127
4128 if (thread_sp->GetIndexID() != thread_index_array[idx])
4129 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004130 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00004131 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00004132 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00004133 idx,
4134 thread_index_array[idx],
4135 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00004136 break;
4137 }
4138
Jim Ingham6297a3a2010-10-20 00:39:53 +00004139 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00004140 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00004141 {
Jim Ingham68899da2013-04-25 02:04:59 +00004142 does_anybody_have_an_opinion = true;
Jim Ingham89e248f2013-02-09 01:29:05 +00004143 bool this_thread_wants_to_stop;
4144 if (stop_info_sp->GetOverrideShouldStop())
Jim Ingham21f37ad2011-08-09 02:12:22 +00004145 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004146 this_thread_wants_to_stop = stop_info_sp->GetOverriddenShouldStopValue();
4147 }
4148 else
4149 {
4150 stop_info_sp->PerformAction(event_ptr);
4151 // The stop action might restart the target. If it does, then we want to mark that in the
4152 // event so that whoever is receiving it will know to wait for the running event and reflect
4153 // that state appropriately.
4154 // We also need to stop processing actions, since they aren't expecting the target to be running.
4155
4156 // FIXME: we might have run.
4157 if (stop_info_sp->HasTargetRunSinceMe())
4158 {
4159 SetRestarted (true);
4160 break;
4161 }
4162
4163 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004164 }
Jim Inghamb6059b22012-12-13 22:24:15 +00004165
Jim Inghamb6059b22012-12-13 22:24:15 +00004166 if (still_should_stop == false)
4167 still_should_stop = this_thread_wants_to_stop;
Chris Lattner24943d22010-06-08 16:52:24 +00004168 }
4169 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00004170
Ashok Thirumurthi6b47bca2013-04-18 14:38:20 +00004171
4172 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00004173 {
Jim Ingham68899da2013-04-25 02:04:59 +00004174 if (!still_should_stop && does_anybody_have_an_opinion)
Jim Ingham21f37ad2011-08-09 02:12:22 +00004175 {
4176 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00004177 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00004178 // Use the public resume method here, since this is just
4179 // extending a public resume.
Jim Ingham89e248f2013-02-09 01:29:05 +00004180 m_process_sp->PrivateResume();
Jim Ingham21f37ad2011-08-09 02:12:22 +00004181 }
4182 else
4183 {
4184 // If we didn't restart, run the Stop Hooks here:
4185 // They might also restart the target, so watch for that.
4186 m_process_sp->GetTarget().RunStopHooks();
4187 if (m_process_sp->GetPrivateState() == eStateRunning)
4188 SetRestarted(true);
4189 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00004190 }
Chris Lattner24943d22010-06-08 16:52:24 +00004191 }
4192}
4193
4194void
4195Process::ProcessEventData::Dump (Stream *s) const
4196{
4197 if (m_process_sp)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004198 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00004199
Greg Claytonb72d0f02011-04-12 05:54:46 +00004200 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00004201}
4202
4203const Process::ProcessEventData *
4204Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
4205{
4206 if (event_ptr)
4207 {
4208 const EventData *event_data = event_ptr->GetData();
4209 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4210 return static_cast <const ProcessEventData *> (event_ptr->GetData());
4211 }
4212 return NULL;
4213}
4214
4215ProcessSP
4216Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
4217{
4218 ProcessSP process_sp;
4219 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4220 if (data)
4221 process_sp = data->GetProcessSP();
4222 return process_sp;
4223}
4224
4225StateType
4226Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
4227{
4228 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4229 if (data == NULL)
4230 return eStateInvalid;
4231 else
4232 return data->GetState();
4233}
4234
4235bool
4236Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
4237{
4238 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4239 if (data == NULL)
4240 return false;
4241 else
4242 return data->GetRestarted();
4243}
4244
4245void
4246Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
4247{
4248 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4249 if (data != NULL)
4250 data->SetRestarted(new_value);
4251}
4252
Jim Ingham89e248f2013-02-09 01:29:05 +00004253size_t
4254Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr)
4255{
4256 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4257 if (data != NULL)
4258 return data->GetNumRestartedReasons();
4259 else
4260 return 0;
4261}
4262
4263const char *
4264Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx)
4265{
4266 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4267 if (data != NULL)
4268 return data->GetRestartedReasonAtIndex(idx);
4269 else
4270 return NULL;
4271}
4272
4273void
4274Process::ProcessEventData::AddRestartedReason (Event *event_ptr, const char *reason)
4275{
4276 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4277 if (data != NULL)
4278 data->AddRestartedReason(reason);
4279}
4280
Chris Lattner24943d22010-06-08 16:52:24 +00004281bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00004282Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
4283{
4284 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
4285 if (data == NULL)
4286 return false;
4287 else
4288 return data->GetInterrupted ();
4289}
4290
4291void
4292Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
4293{
4294 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4295 if (data != NULL)
4296 data->SetInterrupted(new_value);
4297}
4298
4299bool
Chris Lattner24943d22010-06-08 16:52:24 +00004300Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
4301{
4302 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
4303 if (data)
4304 {
4305 data->SetUpdateStateOnRemoval();
4306 return true;
4307 }
4308 return false;
4309}
4310
Greg Clayton289afcb2012-02-18 05:35:26 +00004311lldb::TargetSP
4312Process::CalculateTarget ()
4313{
4314 return m_target.shared_from_this();
4315}
4316
Chris Lattner24943d22010-06-08 16:52:24 +00004317void
Greg Claytona830adb2010-10-04 01:05:56 +00004318Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00004319{
Greg Clayton567e7f32011-09-22 04:58:26 +00004320 exe_ctx.SetTargetPtr (&m_target);
4321 exe_ctx.SetProcessPtr (this);
4322 exe_ctx.SetThreadPtr(NULL);
4323 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00004324}
4325
Greg Claytone4b9c1f2011-03-08 22:40:15 +00004326//uint32_t
4327//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4328//{
4329// return 0;
4330//}
4331//
4332//ArchSpec
4333//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4334//{
4335// return Host::GetArchSpecForExistingProcess (pid);
4336//}
4337//
4338//ArchSpec
4339//Process::GetArchSpecForExistingProcess (const char *process_name)
4340//{
4341// return Host::GetArchSpecForExistingProcess (process_name);
4342//}
4343//
Caroline Tice861efb32010-11-16 05:07:41 +00004344void
4345Process::AppendSTDOUT (const char * s, size_t len)
4346{
Greg Clayton20d338f2010-11-18 05:57:03 +00004347 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00004348 m_stdout_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004349 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00004350}
4351
4352void
Greg Claytonbd06ff42011-11-13 04:45:22 +00004353Process::AppendSTDERR (const char * s, size_t len)
4354{
4355 Mutex::Locker locker (m_stdio_communication_mutex);
4356 m_stderr_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004357 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004358}
4359
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004360void
4361Process::BroadcastAsyncProfileData(const char *s, size_t len)
4362{
4363 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004364 m_profile_data.push_back(s);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004365 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4366}
4367
4368size_t
4369Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4370{
4371 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004372 if (m_profile_data.empty())
4373 return 0;
4374
4375 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004376 if (bytes_available > 0)
4377 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004378 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004379 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004380 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004381 if (bytes_available > buf_size)
4382 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004383 memcpy(buf, m_profile_data.front().data(), buf_size);
4384 m_profile_data.front().erase(0, buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004385 bytes_available = buf_size;
4386 }
4387 else
4388 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004389 memcpy(buf, m_profile_data.front().data(), bytes_available);
4390 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004391 }
4392 }
4393 return bytes_available;
4394}
4395
4396
Greg Claytonbd06ff42011-11-13 04:45:22 +00004397//------------------------------------------------------------------
4398// Process STDIO
4399//------------------------------------------------------------------
4400
4401size_t
4402Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4403{
4404 Mutex::Locker locker(m_stdio_communication_mutex);
4405 size_t bytes_available = m_stdout_data.size();
4406 if (bytes_available > 0)
4407 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004408 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004409 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004410 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004411 if (bytes_available > buf_size)
4412 {
4413 memcpy(buf, m_stdout_data.c_str(), buf_size);
4414 m_stdout_data.erase(0, buf_size);
4415 bytes_available = buf_size;
4416 }
4417 else
4418 {
4419 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4420 m_stdout_data.clear();
4421 }
4422 }
4423 return bytes_available;
4424}
4425
4426
4427size_t
4428Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4429{
4430 Mutex::Locker locker(m_stdio_communication_mutex);
4431 size_t bytes_available = m_stderr_data.size();
4432 if (bytes_available > 0)
4433 {
Greg Clayton952e9dc2013-03-27 23:08:40 +00004434 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004435 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004436 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004437 if (bytes_available > buf_size)
4438 {
4439 memcpy(buf, m_stderr_data.c_str(), buf_size);
4440 m_stderr_data.erase(0, buf_size);
4441 bytes_available = buf_size;
4442 }
4443 else
4444 {
4445 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4446 m_stderr_data.clear();
4447 }
4448 }
4449 return bytes_available;
4450}
4451
4452void
Caroline Tice861efb32010-11-16 05:07:41 +00004453Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4454{
4455 Process *process = (Process *) baton;
4456 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4457}
4458
4459size_t
4460Process::ProcessInputReaderCallback (void *baton,
4461 InputReader &reader,
4462 lldb::InputReaderAction notification,
4463 const char *bytes,
4464 size_t bytes_len)
4465{
4466 Process *process = (Process *) baton;
4467
4468 switch (notification)
4469 {
4470 case eInputReaderActivate:
4471 break;
4472
4473 case eInputReaderDeactivate:
4474 break;
4475
4476 case eInputReaderReactivate:
4477 break;
4478
Caroline Tice4a348082011-05-02 20:41:46 +00004479 case eInputReaderAsynchronousOutputWritten:
4480 break;
4481
Caroline Tice861efb32010-11-16 05:07:41 +00004482 case eInputReaderGotToken:
4483 {
4484 Error error;
4485 process->PutSTDIN (bytes, bytes_len, error);
4486 }
4487 break;
4488
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004489 case eInputReaderInterrupt:
4490 process->Halt ();
4491 break;
4492
4493 case eInputReaderEndOfFile:
4494 process->AppendSTDOUT ("^D", 2);
4495 break;
4496
Caroline Tice861efb32010-11-16 05:07:41 +00004497 case eInputReaderDone:
4498 break;
4499
4500 }
4501
4502 return bytes_len;
4503}
4504
4505void
4506Process::ResetProcessInputReader ()
4507{
4508 m_process_input_reader.reset();
4509}
4510
4511void
Greg Clayton464c6162011-11-17 22:14:31 +00004512Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004513{
4514 // First set up the Read Thread for reading/handling process I/O
4515
Greg Clayton102b2c22013-04-18 22:45:39 +00004516 std::unique_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
Caroline Tice861efb32010-11-16 05:07:41 +00004517
4518 if (conn_ap.get())
4519 {
4520 m_stdio_communication.SetConnection (conn_ap.release());
4521 if (m_stdio_communication.IsConnected())
4522 {
4523 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4524 m_stdio_communication.StartReadThread();
4525
4526 // Now read thread is set up, set up input reader.
4527
4528 if (!m_process_input_reader.get())
4529 {
4530 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4531 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4532 this,
4533 eInputReaderGranularityByte,
4534 NULL,
4535 NULL,
4536 false));
4537
4538 if (err.Fail())
4539 m_process_input_reader.reset();
4540 }
4541 }
4542 }
4543}
4544
4545void
4546Process::PushProcessInputReader ()
4547{
4548 if (m_process_input_reader && !m_process_input_reader->IsActive())
4549 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4550}
4551
4552void
4553Process::PopProcessInputReader ()
4554{
4555 if (m_process_input_reader && m_process_input_reader->IsActive())
4556 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4557}
4558
Greg Claytond284b662011-02-18 01:44:25 +00004559// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004560void
Caroline Tice2a456812011-03-10 22:14:10 +00004561Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004562{
Greg Clayton73844aa2012-08-22 17:17:09 +00004563// static std::vector<OptionEnumValueElement> g_plugins;
4564//
4565// int i=0;
4566// const char *name;
4567// OptionEnumValueElement option_enum;
4568// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4569// {
4570// if (name)
4571// {
4572// option_enum.value = i;
4573// option_enum.string_value = name;
4574// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4575// g_plugins.push_back (option_enum);
4576// }
4577// ++i;
4578// }
4579// option_enum.value = 0;
4580// option_enum.string_value = NULL;
4581// option_enum.usage = NULL;
4582// g_plugins.push_back (option_enum);
4583//
4584// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4585// {
4586// if (::strcmp (name, "plugin") == 0)
4587// {
4588// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4589// break;
4590// }
4591// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004592//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004593 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004594}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004595
Greg Clayton990de7b2010-11-18 23:32:35 +00004596void
Caroline Tice2a456812011-03-10 22:14:10 +00004597Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004598{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004599 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004600}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004601
Greg Clayton427f2902010-12-14 02:59:59 +00004602ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004603Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004604 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004605 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004606 bool run_others,
Jim Inghamb7940202013-01-15 02:47:48 +00004607 bool unwind_on_error,
4608 bool ignore_breakpoints,
Jim Ingham47beabb2012-10-16 21:41:58 +00004609 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004610 Stream &errors)
4611{
4612 ExecutionResults return_value = eExecutionSetupError;
4613
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004614 if (thread_plan_sp.get() == NULL)
4615 {
4616 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004617 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004618 }
Jim Ingham698194c2013-03-28 00:05:34 +00004619
4620 if (!thread_plan_sp->ValidatePlan(NULL))
4621 {
4622 errors.Printf ("RunThreadPlan called with an invalid thread plan.");
4623 return eExecutionSetupError;
4624 }
4625
Greg Clayton567e7f32011-09-22 04:58:26 +00004626 if (exe_ctx.GetProcessPtr() != this)
4627 {
4628 errors.Printf("RunThreadPlan called on wrong process.");
4629 return eExecutionSetupError;
4630 }
4631
4632 Thread *thread = exe_ctx.GetThreadPtr();
4633 if (thread == NULL)
4634 {
4635 errors.Printf("RunThreadPlan called with invalid thread.");
4636 return eExecutionSetupError;
4637 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004638
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004639 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4640 // For that to be true the plan can't be private - since private plans suppress themselves in the
4641 // GetCompletedPlan call.
4642
4643 bool orig_plan_private = thread_plan_sp->GetPrivate();
4644 thread_plan_sp->SetPrivate(false);
4645
Jim Inghamac959662011-01-24 06:34:17 +00004646 if (m_private_state.GetValue() != eStateStopped)
4647 {
4648 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004649 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004650 }
4651
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004652 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004653 const uint32_t thread_idx_id = thread->GetIndexID();
Jim Ingham9da225f2013-02-19 23:22:45 +00004654 StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4655 if (!selected_frame_sp)
4656 {
4657 thread->SetSelectedFrame(0);
4658 selected_frame_sp = thread->GetSelectedFrame();
4659 if (!selected_frame_sp)
4660 {
4661 errors.Printf("RunThreadPlan called without a selected frame on thread %d", thread_idx_id);
4662 return eExecutionSetupError;
4663 }
4664 }
4665
4666 StackID ctx_frame_id = selected_frame_sp->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004667
4668 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4669 // so we should arrange to reset them as well.
4670
Greg Clayton567e7f32011-09-22 04:58:26 +00004671 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004672
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004673 uint32_t selected_tid;
4674 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004675 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004676 {
4677 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004678 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004679 }
4680 else
4681 {
4682 selected_tid = LLDB_INVALID_THREAD_ID;
4683 }
4684
Jim Ingham1831e782012-04-07 00:00:41 +00004685 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004686 lldb::StateType old_state;
4687 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004688
Greg Clayton952e9dc2013-03-27 23:08:40 +00004689 Log *log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004690 if (Host::GetCurrentThread() == m_private_state_thread)
4691 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004692 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4693 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004694 // 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 +00004695 // we are fielding public events here.
4696 if (log)
Jason Molenda559cf6e2012-11-17 01:41:04 +00004697 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 +00004698
4699
Jim Ingham1831e782012-04-07 00:00:41 +00004700 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004701
4702 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4703 // returning control here.
4704 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4705 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4706 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4707 // do just what we want.
4708 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4709 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4710 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4711 old_state = m_public_state.GetValue();
4712 m_public_state.SetValueNoLock(eStateStopped);
4713
4714 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004715 StartPrivateStateThread(true);
4716 }
4717
4718 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004719
Jim Ingham6ae318c2011-01-23 21:14:08 +00004720 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004721
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004722 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004723
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004724 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004725 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4726 // restored on exit to the function.
4727 //
4728 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4729 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004730
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004731 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004732
Jim Ingham360f53f2010-11-30 02:22:11 +00004733 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004734 {
4735 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004736 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004737 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004738 thread->GetIndexID(),
4739 thread->GetID(),
4740 s.GetData());
4741 }
4742
4743 bool got_event;
4744 lldb::EventSP event_sp;
4745 lldb::StateType stop_state = lldb::eStateInvalid;
4746
4747 TimeValue* timeout_ptr = NULL;
4748 TimeValue real_timeout;
4749
Jim Ingham89e248f2013-02-09 01:29:05 +00004750 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 +00004751 bool do_resume = true;
Jim Inghamb7940202013-01-15 02:47:48 +00004752 bool handle_running_event = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004753 const uint64_t default_one_thread_timeout_usec = 250000;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004754
Jim Ingham89e248f2013-02-09 01:29:05 +00004755 // This is just for accounting:
4756 uint32_t num_resumes = 0;
4757
4758 TimeValue one_thread_timeout = TimeValue::Now();
4759 TimeValue final_timeout = one_thread_timeout;
4760
4761 if (run_others)
4762 {
4763 // If we are running all threads then we take half the time to run all threads, bounded by
4764 // .25 sec.
4765 if (timeout_usec == 0)
4766 one_thread_timeout.OffsetWithMicroSeconds(default_one_thread_timeout_usec);
4767 else
4768 {
Greg Claytond387b462013-04-19 21:31:16 +00004769 uint64_t computed_timeout = timeout_usec / 2;
Jim Ingham89e248f2013-02-09 01:29:05 +00004770 if (computed_timeout > default_one_thread_timeout_usec)
4771 computed_timeout = default_one_thread_timeout_usec;
4772 one_thread_timeout.OffsetWithMicroSeconds(computed_timeout);
4773 }
4774 final_timeout.OffsetWithMicroSeconds (timeout_usec);
4775 }
4776 else
4777 {
4778 if (timeout_usec != 0)
4779 final_timeout.OffsetWithMicroSeconds(timeout_usec);
4780 }
4781
Jim Ingham76b258d2012-11-26 23:52:18 +00004782 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4783 // So don't call return anywhere within it.
4784
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004785 while (1)
4786 {
4787 // We usually want to resume the process if we get to the top of the loop.
4788 // The only exception is if we get two running events with no intervening
4789 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham89e248f2013-02-09 01:29:05 +00004790 if (log)
4791 log->Printf ("Top of while loop: do_resume: %i handle_running_event: %i before_first_timeout: %i.",
4792 do_resume,
4793 handle_running_event,
4794 before_first_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004795
Jim Inghamb7940202013-01-15 02:47:48 +00004796 if (do_resume || handle_running_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004797 {
4798 // Do the initial resume and wait for the running event before going further.
4799
Jim Inghamb7940202013-01-15 02:47:48 +00004800 if (do_resume)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004801 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004802 num_resumes++;
Jim Inghamb7940202013-01-15 02:47:48 +00004803 Error resume_error = PrivateResume ();
4804 if (!resume_error.Success())
4805 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004806 errors.Printf("Error resuming inferior the %d time: \"%s\".\n",
4807 num_resumes,
4808 resume_error.AsCString());
Jim Inghamb7940202013-01-15 02:47:48 +00004809 return_value = eExecutionSetupError;
4810 break;
4811 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004812 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004813
Jim Ingham89e248f2013-02-09 01:29:05 +00004814 TimeValue resume_timeout = TimeValue::Now();
4815 resume_timeout.OffsetWithMicroSeconds(500000);
4816
4817 got_event = listener.WaitForEvent(&resume_timeout, event_sp);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004818 if (!got_event)
4819 {
4820 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004821 log->Printf ("Process::RunThreadPlan(): didn't get any event after resume %d, exiting.",
4822 num_resumes);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004823
Jim Ingham89e248f2013-02-09 01:29:05 +00004824 errors.Printf("Didn't get any event after resume %d, exiting.", num_resumes);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004825 return_value = eExecutionSetupError;
4826 break;
4827 }
4828
4829 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Ingham89e248f2013-02-09 01:29:05 +00004830
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004831 if (stop_state != eStateRunning)
4832 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004833 bool restarted = false;
4834
4835 if (stop_state == eStateStopped)
4836 {
4837 restarted = Process::ProcessEventData::GetRestartedFromEvent(event_sp.get());
4838 if (log)
4839 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4840 "resume %d, got %s instead (restarted: %i, do_resume: %i, handle_running_event: %i).",
4841 num_resumes,
4842 StateAsCString(stop_state),
4843 restarted,
4844 do_resume,
4845 handle_running_event);
4846 }
4847
4848 if (restarted)
4849 {
4850 // This is probably an overabundance of caution, I don't think I should ever get a stopped & restarted
4851 // event here. But if I do, the best thing is to Halt and then get out of here.
4852 Halt();
4853 }
4854
Jim Ingham47beabb2012-10-16 21:41:58 +00004855 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4856 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004857 return_value = eExecutionSetupError;
4858 break;
4859 }
4860
4861 if (log)
4862 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4863 // We need to call the function synchronously, so spin waiting for it to return.
4864 // If we get interrupted while executing, we're going to lose our context, and
4865 // won't be able to gather the result at this point.
4866 // We set the timeout AFTER the resume, since the resume takes some time and we
4867 // don't want to charge that to the timeout.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004868 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004869 else
4870 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004871 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004872 log->PutCString ("Process::RunThreadPlan(): waiting for next event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004873 }
Jim Ingham89e248f2013-02-09 01:29:05 +00004874
4875 if (before_first_timeout)
4876 {
4877 if (run_others)
4878 timeout_ptr = &one_thread_timeout;
4879 else
4880 {
4881 if (timeout_usec == 0)
4882 timeout_ptr = NULL;
4883 else
4884 timeout_ptr = &final_timeout;
4885 }
4886 }
4887 else
4888 {
4889 if (timeout_usec == 0)
4890 timeout_ptr = NULL;
4891 else
4892 timeout_ptr = &final_timeout;
4893 }
4894
4895 do_resume = true;
4896 handle_running_event = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004897
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004898 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004899 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004900
Jim Inghamf9f40c22011-02-08 05:20:59 +00004901 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004902 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004903 if (timeout_ptr)
4904 {
Matt Kopecfe21d4f2013-02-21 23:55:31 +00004905 log->Printf ("Process::RunThreadPlan(): about to wait - now is %" PRIu64 " - endpoint is %" PRIu64,
Jim Ingham89e248f2013-02-09 01:29:05 +00004906 TimeValue::Now().GetAsMicroSecondsSinceJan1_1970(),
4907 timeout_ptr->GetAsMicroSecondsSinceJan1_1970());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004908 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004909 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004910 {
4911 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4912 }
4913 }
4914
4915 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4916
4917 if (got_event)
4918 {
4919 if (event_sp.get())
4920 {
4921 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004922 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004923 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004924 Halt();
Jim Ingham5d90ade2012-07-27 23:57:19 +00004925 return_value = eExecutionInterrupted;
4926 errors.Printf ("Execution halted by user interrupt.");
4927 if (log)
4928 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
Jim Ingham89e248f2013-02-09 01:29:05 +00004929 break;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004930 }
4931 else
4932 {
4933 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4934 if (log)
4935 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4936
4937 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004938 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004939 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004940 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004941 // We stopped, figure out what we are going to do now.
Jim Ingham5d90ade2012-07-27 23:57:19 +00004942 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4943 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004944 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004945 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004946 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004947 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4948 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004949 }
4950 else
4951 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004952 // If we were restarted, we just need to go back up to fetch another event.
4953 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
Jim Ingham5d90ade2012-07-27 23:57:19 +00004954 {
4955 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004956 {
4957 log->Printf ("Process::RunThreadPlan(): Got a stop and restart, so we'll continue waiting.");
4958 }
4959 keep_going = true;
4960 do_resume = false;
4961 handle_running_event = true;
4962
Jim Ingham5d90ade2012-07-27 23:57:19 +00004963 }
4964 else
4965 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004966
4967 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4968 StopReason stop_reason = eStopReasonInvalid;
4969 if (stop_info_sp)
4970 stop_reason = stop_info_sp->GetStopReason();
4971
4972
4973 // FIXME: We only check if the stop reason is plan complete, should we make sure that
4974 // it is OUR plan that is complete?
4975 if (stop_reason == eStopReasonPlanComplete)
Jim Inghamb7940202013-01-15 02:47:48 +00004976 {
4977 if (log)
Jim Ingham89e248f2013-02-09 01:29:05 +00004978 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4979 // Now mark this plan as private so it doesn't get reported as the stop reason
4980 // after this point.
4981 if (thread_plan_sp)
4982 thread_plan_sp->SetPrivate (orig_plan_private);
4983 return_value = eExecutionCompleted;
Jim Inghamb7940202013-01-15 02:47:48 +00004984 }
4985 else
4986 {
Jim Ingham89e248f2013-02-09 01:29:05 +00004987 // Something restarted the target, so just wait for it to stop for real.
Jim Inghamb7940202013-01-15 02:47:48 +00004988 if (stop_reason == eStopReasonBreakpoint)
Jim Ingham89e248f2013-02-09 01:29:05 +00004989 {
4990 if (log)
4991 log->Printf ("Process::RunThreadPlan() stopped for breakpoint: %s.", stop_info_sp->GetDescription());
Jim Inghamb7940202013-01-15 02:47:48 +00004992 return_value = eExecutionHitBreakpoint;
Jim Ingham89e248f2013-02-09 01:29:05 +00004993 }
Jim Inghamb7940202013-01-15 02:47:48 +00004994 else
Jim Ingham89e248f2013-02-09 01:29:05 +00004995 {
4996 if (log)
4997 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Jim Inghamb7940202013-01-15 02:47:48 +00004998 return_value = eExecutionInterrupted;
Jim Ingham89e248f2013-02-09 01:29:05 +00004999 }
Jim Inghamb7940202013-01-15 02:47:48 +00005000 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005001 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005002 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005003 }
5004 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005005
Jim Ingham5d90ade2012-07-27 23:57:19 +00005006 case lldb::eStateRunning:
Jim Ingham89e248f2013-02-09 01:29:05 +00005007 // This shouldn't really happen, but sometimes we do get two running events without an
5008 // intervening stop, and in that case we should just go back to waiting for the stop.
Jim Ingham5d90ade2012-07-27 23:57:19 +00005009 do_resume = false;
5010 keep_going = true;
Jim Inghamb7940202013-01-15 02:47:48 +00005011 handle_running_event = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00005012 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005013
Jim Ingham5d90ade2012-07-27 23:57:19 +00005014 default:
5015 if (log)
5016 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
5017
5018 if (stop_state == eStateExited)
5019 event_to_broadcast_sp = event_sp;
5020
Sean Callanan96abc622012-08-08 17:35:10 +00005021 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00005022 return_value = eExecutionInterrupted;
5023 break;
5024 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005025 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005026
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005027 if (keep_going)
5028 continue;
5029 else
5030 break;
5031 }
5032 else
5033 {
5034 if (log)
5035 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
5036 return_value = eExecutionInterrupted;
5037 break;
5038 }
5039 }
5040 else
5041 {
5042 // If we didn't get an event that means we've timed out...
5043 // We will interrupt the process here. Depending on what we were asked to do we will
5044 // either exit, or try with all threads running for the same timeout.
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005045
5046 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00005047 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005048 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005049 uint64_t remaining_time = final_timeout - TimeValue::Now();
5050 if (before_first_timeout)
5051 log->Printf ("Process::RunThreadPlan(): Running function with one thread timeout timed out, "
5052 "running till for %" PRId64 " usec with all threads enabled.",
5053 remaining_time);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005054 else
5055 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00005056 "and timeout: %d timed out, abandoning execution.",
5057 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005058 }
5059 else
5060 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00005061 "abandoning execution.",
5062 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005063 }
5064
Jim Ingham89e248f2013-02-09 01:29:05 +00005065 // It is possible that between the time we issued the Halt, and we get around to calling Halt the target
5066 // could have stopped. That's fine, Halt will figure that out and send the appropriate Stopped event.
5067 // BUT it is also possible that we stopped & restarted (e.g. hit a signal with "stop" set to false.) In
5068 // that case, we'll get the stopped & restarted event, and we should go back to waiting for the Halt's
5069 // stopped event. That's what this while loop does.
5070
5071 bool back_to_top = true;
5072 uint32_t try_halt_again = 0;
5073 bool do_halt = true;
5074 const uint32_t num_retries = 5;
5075 while (try_halt_again < num_retries)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005076 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005077 Error halt_error;
5078 if (do_halt)
5079 {
5080 if (log)
5081 log->Printf ("Process::RunThreadPlan(): Running Halt.");
5082 halt_error = Halt();
5083 }
5084 if (halt_error.Success())
5085 {
5086 if (log)
5087 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
5088
5089 real_timeout = TimeValue::Now();
5090 real_timeout.OffsetWithMicroSeconds(500000);
5091
5092 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005093
Jim Ingham89e248f2013-02-09 01:29:05 +00005094 if (got_event)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005095 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005096 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5097 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005098 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005099 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
5100 if (stop_state == lldb::eStateStopped
5101 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
5102 log->PutCString (" Event was the Halt interruption event.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005103 }
5104
Jim Ingham89e248f2013-02-09 01:29:05 +00005105 if (stop_state == lldb::eStateStopped)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005106 {
Jim Ingham89e248f2013-02-09 01:29:05 +00005107 // Between the time we initiated the Halt and the time we delivered it, the process could have
5108 // already finished its job. Check that here:
5109
5110 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
5111 {
5112 if (log)
5113 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
5114 "Exiting wait loop.");
5115 return_value = eExecutionCompleted;
5116 back_to_top = false;
5117 break;
5118 }
5119
5120 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
5121 {
5122 if (log)
5123 log->PutCString ("Process::RunThreadPlan(): Went to halt but got a restarted event, there must be an un-restarted stopped event so try again... "
5124 "Exiting wait loop.");
5125 try_halt_again++;
5126 do_halt = false;
5127 continue;
5128 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005129
Jim Ingham89e248f2013-02-09 01:29:05 +00005130 if (!run_others)
5131 {
5132 if (log)
5133 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
5134 return_value = eExecutionInterrupted;
5135 back_to_top = false;
5136 break;
5137 }
5138
5139 if (before_first_timeout)
5140 {
5141 // Set all the other threads to run, and return to the top of the loop, which will continue;
5142 before_first_timeout = false;
5143 thread_plan_sp->SetStopOthers (false);
5144 if (log)
5145 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005146
Jim Ingham89e248f2013-02-09 01:29:05 +00005147 back_to_top = true;
5148 break;
5149 }
5150 else
5151 {
5152 // Running all threads failed, so return Interrupted.
5153 if (log)
5154 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
5155 return_value = eExecutionInterrupted;
5156 back_to_top = false;
5157 break;
5158 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005159 }
5160 }
5161 else
Jim Ingham89e248f2013-02-09 01:29:05 +00005162 { if (log)
5163 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
5164 "I'm getting out of here passing Interrupted.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005165 return_value = eExecutionInterrupted;
Jim Ingham89e248f2013-02-09 01:29:05 +00005166 back_to_top = false;
5167 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005168 }
5169 }
Jim Ingham89e248f2013-02-09 01:29:05 +00005170 else
5171 {
5172 try_halt_again++;
5173 continue;
5174 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005175 }
Jim Ingham89e248f2013-02-09 01:29:05 +00005176
5177 if (!back_to_top || try_halt_again > num_retries)
5178 break;
5179 else
5180 continue;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005181 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005182 } // END WAIT LOOP
5183
5184 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
5185 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
5186 {
5187 StopPrivateStateThread();
5188 Error error;
5189 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00005190 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005191 {
5192 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5193 }
5194 m_public_state.SetValueNoLock(old_state);
5195
5196 }
5197
Jim Inghamb7940202013-01-15 02:47:48 +00005198 // Restore the thread state if we are going to discard the plan execution. There are three cases where this
5199 // could happen:
5200 // 1) The execution successfully completed
5201 // 2) We hit a breakpoint, and ignore_breakpoints was true
5202 // 3) We got some other error, and discard_on_error was true
5203 bool should_unwind = (return_value == eExecutionInterrupted && unwind_on_error)
5204 || (return_value == eExecutionHitBreakpoint && ignore_breakpoints);
Jim Ingham76b258d2012-11-26 23:52:18 +00005205
Jim Inghamb7940202013-01-15 02:47:48 +00005206 if (return_value == eExecutionCompleted
5207 || should_unwind)
Jim Ingham76b258d2012-11-26 23:52:18 +00005208 {
5209 thread_plan_sp->RestoreThreadState();
5210 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005211
5212 // Now do some processing on the results of the run:
Jim Inghamb7940202013-01-15 02:47:48 +00005213 if (return_value == eExecutionInterrupted || return_value == eExecutionHitBreakpoint)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005214 {
5215 if (log)
5216 {
5217 StreamString s;
5218 if (event_sp)
5219 event_sp->Dump (&s);
5220 else
5221 {
5222 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
5223 }
5224
5225 StreamString ts;
5226
5227 const char *event_explanation = NULL;
5228
5229 do
5230 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005231 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005232 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005233 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005234 break;
5235 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005236 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005237 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005238 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005239 break;
5240 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005241 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005242 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005243 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
5244
5245 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005246 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005247 event_explanation = "<no event data>";
5248 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005249 }
5250
Jim Ingham5d90ade2012-07-27 23:57:19 +00005251 Process *process = event_data->GetProcessSP().get();
5252
5253 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005254 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00005255 event_explanation = "<no process>";
5256 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005257 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00005258
5259 ThreadList &thread_list = process->GetThreadList();
5260
5261 uint32_t num_threads = thread_list.GetSize();
5262 uint32_t thread_index;
5263
5264 ts.Printf("<%u threads> ", num_threads);
5265
5266 for (thread_index = 0;
5267 thread_index < num_threads;
5268 ++thread_index)
5269 {
5270 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5271
5272 if (!thread)
5273 {
5274 ts.Printf("<?> ");
5275 continue;
5276 }
5277
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005278 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00005279 RegisterContext *register_context = thread->GetRegisterContext().get();
5280
5281 if (register_context)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005282 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Ingham5d90ade2012-07-27 23:57:19 +00005283 else
5284 ts.Printf("[ip unknown] ");
5285
5286 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
5287 if (stop_info_sp)
5288 {
5289 const char *stop_desc = stop_info_sp->GetDescription();
5290 if (stop_desc)
5291 ts.PutCString (stop_desc);
5292 }
5293 ts.Printf(">");
5294 }
5295
5296 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005297 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005298 } while (0);
5299
Jim Ingham5d90ade2012-07-27 23:57:19 +00005300 if (event_explanation)
5301 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005302 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00005303 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
5304 }
5305
Jim Inghamb7940202013-01-15 02:47:48 +00005306 if (should_unwind && thread_plan_sp)
Jim Ingham5d90ade2012-07-27 23:57:19 +00005307 {
5308 if (log)
5309 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
5310 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5311 thread_plan_sp->SetPrivate (orig_plan_private);
5312 }
5313 else
5314 {
5315 if (log)
5316 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005317 }
5318 }
5319 else if (return_value == eExecutionSetupError)
5320 {
5321 if (log)
5322 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00005323
Jim Inghamb7940202013-01-15 02:47:48 +00005324 if (unwind_on_error && thread_plan_sp)
Jim Inghamf9f40c22011-02-08 05:20:59 +00005325 {
Greg Clayton567e7f32011-09-22 04:58:26 +00005326 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00005327 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00005328 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005329 }
5330 else
5331 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005332 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00005333 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00005334 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005335 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5336 return_value = eExecutionCompleted;
5337 }
5338 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
5339 {
5340 if (log)
5341 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
5342 return_value = eExecutionDiscarded;
5343 }
5344 else
5345 {
5346 if (log)
5347 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamb7940202013-01-15 02:47:48 +00005348 if (unwind_on_error && thread_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005349 {
5350 if (log)
Jim Inghamb7940202013-01-15 02:47:48 +00005351 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause unwind_on_error is set.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005352 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
5353 thread_plan_sp->SetPrivate (orig_plan_private);
5354 }
5355 }
5356 }
5357
5358 // Thread we ran the function in may have gone away because we ran the target
5359 // Check that it's still there, and if it is put it back in the context. Also restore the
5360 // frame in the context if it is still present.
5361 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5362 if (thread)
5363 {
5364 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
5365 }
5366
5367 // Also restore the current process'es selected frame & thread, since this function calling may
5368 // be done behind the user's back.
5369
5370 if (selected_tid != LLDB_INVALID_THREAD_ID)
5371 {
5372 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5373 {
5374 // We were able to restore the selected thread, now restore the frame:
5375 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5376 if (old_frame_sp)
5377 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00005378 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005379 }
5380 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005381
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005382 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00005383
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005384 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00005385 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005386 if (log)
5387 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5388 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00005389 }
5390
5391 return return_value;
5392}
5393
5394const char *
5395Process::ExecutionResultAsCString (ExecutionResults result)
5396{
5397 const char *result_name;
5398
5399 switch (result)
5400 {
Greg Claytonb3448432011-03-24 21:19:54 +00005401 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005402 result_name = "eExecutionCompleted";
5403 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005404 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00005405 result_name = "eExecutionDiscarded";
5406 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005407 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005408 result_name = "eExecutionInterrupted";
5409 break;
Jim Inghamb7940202013-01-15 02:47:48 +00005410 case eExecutionHitBreakpoint:
5411 result_name = "eExecutionHitBreakpoint";
5412 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005413 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00005414 result_name = "eExecutionSetupError";
5415 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005416 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00005417 result_name = "eExecutionTimedOut";
5418 break;
5419 }
5420 return result_name;
5421}
5422
Greg Claytonabe0fed2011-04-18 08:33:37 +00005423void
5424Process::GetStatus (Stream &strm)
5425{
5426 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00005427 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00005428 {
5429 if (state == eStateExited)
5430 {
5431 int exit_status = GetExitStatus();
5432 const char *exit_description = GetExitDescription();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005433 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00005434 GetID(),
5435 exit_status,
5436 exit_status,
5437 exit_description ? exit_description : "");
5438 }
5439 else
5440 {
5441 if (state == eStateConnected)
5442 strm.Printf ("Connected to remote target.\n");
5443 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005444 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00005445 }
5446 }
5447 else
5448 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005449 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005450 }
5451}
5452
5453size_t
5454Process::GetThreadStatus (Stream &strm,
5455 bool only_threads_with_stop_reason,
5456 uint32_t start_frame,
5457 uint32_t num_frames,
5458 uint32_t num_frames_with_source)
5459{
5460 size_t num_thread_infos_dumped = 0;
5461
Jim Inghamb9950592012-09-10 20:50:15 +00005462 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005463 const size_t num_threads = GetThreadList().GetSize();
5464 for (uint32_t i = 0; i < num_threads; i++)
5465 {
5466 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5467 if (thread)
5468 {
5469 if (only_threads_with_stop_reason)
5470 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00005471 StopInfoSP stop_info_sp = thread->GetStopInfo();
5472 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00005473 continue;
5474 }
5475 thread->GetStatus (strm,
5476 start_frame,
5477 num_frames,
5478 num_frames_with_source);
5479 ++num_thread_infos_dumped;
5480 }
5481 }
5482 return num_thread_infos_dumped;
5483}
5484
Greg Clayton76113302012-02-22 04:37:26 +00005485void
5486Process::AddInvalidMemoryRegion (const LoadRange &region)
5487{
5488 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5489}
5490
5491bool
5492Process::RemoveInvalidMemoryRange (const LoadRange &region)
5493{
5494 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5495}
5496
Jim Ingham1831e782012-04-07 00:00:41 +00005497void
5498Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5499{
5500 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5501}
5502
5503bool
5504Process::RunPreResumeActions ()
5505{
5506 bool result = true;
5507 while (!m_pre_resume_actions.empty())
5508 {
5509 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5510 m_pre_resume_actions.pop_back();
5511 bool this_result = action.callback (action.baton);
5512 if (result == true) result = this_result;
5513 }
5514 return result;
5515}
5516
5517void
5518Process::ClearPreResumeActions ()
5519{
5520 m_pre_resume_actions.clear();
5521}
Greg Clayton76113302012-02-22 04:37:26 +00005522
Greg Claytoncf5927e2012-05-18 02:38:05 +00005523void
5524Process::Flush ()
5525{
5526 m_thread_list.Flush();
5527}
Greg Clayton0bce9a22012-12-05 00:16:59 +00005528
5529void
5530Process::DidExec ()
5531{
5532 Target &target = GetTarget();
5533 target.CleanupProcess ();
5534 ModuleList unloaded_modules (target.GetImages());
5535 target.ModulesDidUnload (unloaded_modules);
5536 target.GetSectionLoadList().Clear();
5537 m_dynamic_checkers_ap.reset();
5538 m_abi_sp.reset();
5539 m_os_ap.reset();
5540 m_dyld_ap.reset();
5541 m_image_tokens.clear();
5542 m_allocated_memory_cache.Clear();
5543 m_language_runtimes.clear();
5544 DoDidExec();
5545 CompleteAttach ();
5546}