blob: 6ea3f01a6d4055e5f4871a9cb979fa73e8b3293d [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;\"" },
Greg Clayton507a6382012-11-29 18:48:47 +0000100 { "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." },
Greg Clayton73844aa2012-08-22 17:17:09 +0000101 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
102};
103
104enum {
105 ePropertyDisableMemCache,
Greg Clayton2e7f3132012-10-18 22:40:37 +0000106 ePropertyExtraStartCommand,
107 ePropertyPythonOSPluginPath
Greg Clayton73844aa2012-08-22 17:17:09 +0000108};
109
110ProcessProperties::ProcessProperties (bool is_global) :
111 Properties ()
112{
113 if (is_global)
114 {
115 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
116 m_collection_sp->Initialize(g_properties);
117 m_collection_sp->AppendProperty(ConstString("thread"),
118 ConstString("Settings specify to threads."),
119 true,
120 Thread::GetGlobalProperties()->GetValueProperties());
121 }
122 else
123 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
124}
125
126ProcessProperties::~ProcessProperties()
127{
128}
129
130bool
131ProcessProperties::GetDisableMemoryCache() const
132{
133 const uint32_t idx = ePropertyDisableMemCache;
134 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
135}
136
137Args
138ProcessProperties::GetExtraStartupCommands () const
139{
140 Args args;
141 const uint32_t idx = ePropertyExtraStartCommand;
142 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
143 return args;
144}
145
146void
147ProcessProperties::SetExtraStartupCommands (const Args &args)
148{
149 const uint32_t idx = ePropertyExtraStartCommand;
150 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
151}
152
Greg Clayton2e7f3132012-10-18 22:40:37 +0000153FileSpec
154ProcessProperties::GetPythonOSPluginPath () const
155{
156 const uint32_t idx = ePropertyPythonOSPluginPath;
157 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
158}
159
160void
161ProcessProperties::SetPythonOSPluginPath (const FileSpec &file)
162{
163 const uint32_t idx = ePropertyPythonOSPluginPath;
164 m_collection_sp->SetPropertyAtIndexAsFileSpec(NULL, idx, file);
165}
166
Greg Clayton24bc5d92011-03-30 18:16:51 +0000167void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000168ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000169{
170 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +0000171 if (m_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000172 s.Printf (" pid = %" PRIu64 "\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000173
174 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000175 s.Printf (" parent = %" PRIu64 "\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000176
177 if (m_executable)
178 {
179 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
180 s.PutCString (" file = ");
181 m_executable.Dump(&s);
182 s.EOL();
183 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000184 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000185 if (argc > 0)
186 {
187 for (uint32_t i=0; i<argc; i++)
188 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000189 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +0000190 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000191 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000192 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000193 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000194 }
195 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000196
197 const uint32_t envc = m_environment.GetArgumentCount();
198 if (envc > 0)
199 {
200 for (uint32_t i=0; i<envc; i++)
201 {
202 const char *env = m_environment.GetArgumentAtIndex(i);
203 if (i < 10)
204 s.Printf (" env[%u] = %s\n", i, env);
205 else
206 s.Printf ("env[%u] = %s\n", i, env);
207 }
208 }
209
Greg Claytonff39f742011-04-01 00:29:43 +0000210 if (m_arch.IsValid())
211 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
212
Greg Claytonb72d0f02011-04-12 05:54:46 +0000213 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000214 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000215 cstr = platform->GetUserName (m_uid);
216 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000217 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000218 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000219 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000220 cstr = platform->GetGroupName (m_gid);
221 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000222 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000223 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000224 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000225 cstr = platform->GetUserName (m_euid);
226 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000227 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000228 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000229 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000230 cstr = platform->GetGroupName (m_egid);
231 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000232 }
233}
234
235void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000236ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000237{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000238 const char *label;
239 if (show_args || verbose)
240 label = "ARGUMENTS";
241 else
242 label = "NAME";
243
Greg Claytonff39f742011-04-01 00:29:43 +0000244 if (verbose)
245 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000246 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000247 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
248 }
249 else
250 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000251 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000252 s.PutCString ("====== ====== ========== ======= ============================\n");
253 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000254}
255
256void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000257ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000258{
259 if (m_pid != LLDB_INVALID_PROCESS_ID)
260 {
261 const char *cstr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000262 s.Printf ("%-6" PRIu64 " %-6" PRIu64 " ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000263
Greg Clayton24bc5d92011-03-30 18:16:51 +0000264
Greg Claytonff39f742011-04-01 00:29:43 +0000265 if (verbose)
266 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000267 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000268 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
269 s.Printf ("%-10s ", cstr);
270 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000271 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000272
Greg Claytonb72d0f02011-04-12 05:54:46 +0000273 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000274 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
275 s.Printf ("%-10s ", cstr);
276 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000277 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000278
Greg Claytonb72d0f02011-04-12 05:54:46 +0000279 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000280 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
281 s.Printf ("%-10s ", cstr);
282 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000283 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000284
Greg Claytonb72d0f02011-04-12 05:54:46 +0000285 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000286 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
287 s.Printf ("%-10s ", cstr);
288 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000289 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000290 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
291 }
292 else
293 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000294 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000295 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000296 (int)m_arch.GetTriple().getArchName().size(),
297 m_arch.GetTriple().getArchName().data());
298 }
299
Greg Claytonb72d0f02011-04-12 05:54:46 +0000300 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000301 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000302 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000303 if (argc > 0)
304 {
305 for (uint32_t i=0; i<argc; i++)
306 {
307 if (i > 0)
308 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000309 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000310 }
311 }
312 }
313 else
314 {
315 s.PutCString (GetName());
316 }
317
318 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000319 }
320}
321
Greg Claytonb72d0f02011-04-12 05:54:46 +0000322
323void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000324ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000325{
326 m_arguments.SetArguments (argv);
327
328 // Is the first argument the executable?
329 if (first_arg_is_executable)
330 {
331 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
332 if (first_arg)
333 {
334 // Yes the first argument is an executable, set it as the executable
335 // in the launch options. Don't resolve the file path as the path
336 // could be a remote platform path
337 const bool resolve = false;
338 m_executable.SetFile(first_arg, resolve);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000339 }
340 }
341}
342void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000343ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000344{
345 // Copy all arguments
346 m_arguments = args;
347
348 // Is the first argument the executable?
349 if (first_arg_is_executable)
350 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000351 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000352 if (first_arg)
353 {
354 // Yes the first argument is an executable, set it as the executable
355 // in the launch options. Don't resolve the file path as the path
356 // could be a remote platform path
357 const bool resolve = false;
358 m_executable.SetFile(first_arg, resolve);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000359 }
360 }
361}
362
Greg Claytonabb33022011-11-08 02:43:13 +0000363void
Greg Clayton464c6162011-11-17 22:14:31 +0000364ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000365{
366 // If notthing was specified, then check the process for any default
367 // settings that were set with "settings set"
368 if (m_file_actions.empty())
369 {
Greg Claytonabb33022011-11-08 02:43:13 +0000370 if (m_flags.Test(eLaunchFlagDisableSTDIO))
371 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000372 AppendSuppressFileAction (STDIN_FILENO , true, false);
373 AppendSuppressFileAction (STDOUT_FILENO, false, true);
374 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000375 }
376 else
377 {
378 // Check for any values that might have gotten set with any of:
379 // (lldb) settings set target.input-path
380 // (lldb) settings set target.output-path
381 // (lldb) settings set target.error-path
Greg Clayton73844aa2012-08-22 17:17:09 +0000382 FileSpec in_path;
383 FileSpec out_path;
384 FileSpec err_path;
Greg Claytonabb33022011-11-08 02:43:13 +0000385 if (target)
386 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000387 in_path = target->GetStandardInputPath();
388 out_path = target->GetStandardOutputPath();
389 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000390 }
391
Greg Clayton73844aa2012-08-22 17:17:09 +0000392 if (in_path || out_path || err_path)
393 {
394 char path[PATH_MAX];
395 if (in_path && in_path.GetPath(path, sizeof(path)))
396 AppendOpenFileAction(STDIN_FILENO, path, true, false);
397
398 if (out_path && out_path.GetPath(path, sizeof(path)))
399 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
400
401 if (err_path && err_path.GetPath(path, sizeof(path)))
402 AppendOpenFileAction(STDERR_FILENO, path, false, true);
403 }
404 else if (default_to_use_pty)
Greg Clayton464c6162011-11-17 22:14:31 +0000405 {
406 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000407 {
Greg Clayton73844aa2012-08-22 17:17:09 +0000408 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
409 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
410 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
411 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000412 }
413 }
Greg Claytonabb33022011-11-08 02:43:13 +0000414 }
415 }
416}
417
Greg Clayton527154d2011-11-15 03:53:30 +0000418
419bool
Greg Clayton97471182012-04-14 01:42:46 +0000420ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
421 bool localhost,
422 bool will_debug,
423 bool first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000424{
425 error.Clear();
426
427 if (GetFlags().Test (eLaunchFlagLaunchInShell))
428 {
429 const char *shell_executable = GetShell();
430 if (shell_executable)
431 {
432 char shell_resolved_path[PATH_MAX];
433
434 if (localhost)
435 {
436 FileSpec shell_filespec (shell_executable, true);
437
438 if (!shell_filespec.Exists())
439 {
440 // Resolve the path in case we just got "bash", "sh" or "tcsh"
441 if (!shell_filespec.ResolveExecutableLocation ())
442 {
443 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
444 return false;
445 }
446 }
447 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
448 shell_executable = shell_resolved_path;
449 }
450
Greg Clayton0c8446c2012-10-17 22:57:12 +0000451 const char **argv = GetArguments().GetConstArgumentVector ();
452 if (argv == NULL || argv[0] == NULL)
453 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000454 Args shell_arguments;
455 std::string safe_arg;
456 shell_arguments.AppendArgument (shell_executable);
Greg Clayton527154d2011-11-15 03:53:30 +0000457 shell_arguments.AppendArgument ("-c");
Greg Clayton97471182012-04-14 01:42:46 +0000458 StreamString shell_command;
459 if (will_debug)
Greg Clayton527154d2011-11-15 03:53:30 +0000460 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000461 // Add a modified PATH environment variable in case argv[0]
462 // is a relative path
463 const char *argv0 = argv[0];
464 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
465 {
466 // We have a relative path to our executable which may not work if
467 // we just try to run "a.out" (without it being converted to "./a.out")
468 const char *working_dir = GetWorkingDirectory();
469 std::string new_path("PATH=");
470 const size_t empty_path_len = new_path.size();
471
472 if (working_dir && working_dir[0])
473 {
474 new_path += working_dir;
475 }
476 else
477 {
478 char current_working_dir[PATH_MAX];
479 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
480 if (cwd && cwd[0])
481 new_path += cwd;
482 }
483 const char *curr_path = getenv("PATH");
484 if (curr_path)
485 {
486 if (new_path.size() > empty_path_len)
487 new_path += ':';
488 new_path += curr_path;
489 }
490 new_path += ' ';
491 shell_command.PutCString(new_path.c_str());
492 }
493
Greg Clayton97471182012-04-14 01:42:46 +0000494 shell_command.PutCString ("exec");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000495
496#if defined(__APPLE__)
497 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Clayton97471182012-04-14 01:42:46 +0000498 if (GetArchitecture().IsValid())
499 {
500 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton0c8446c2012-10-17 22:57:12 +0000501 // Set the resume count to 2:
Greg Clayton97471182012-04-14 01:42:46 +0000502 // 1 - stop in shell
503 // 2 - stop in /usr/bin/arch
504 // 3 - then we will stop in our program
505 SetResumeCount(2);
506 }
507 else
508 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000509 // Set the resume count to 1:
Greg Clayton97471182012-04-14 01:42:46 +0000510 // 1 - stop in shell
511 // 2 - then we will stop in our program
512 SetResumeCount(1);
513 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000514#else
515 // Set the resume count to 1:
516 // 1 - stop in shell
517 // 2 - then we will stop in our program
518 SetResumeCount(1);
519#endif
Greg Clayton527154d2011-11-15 03:53:30 +0000520 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000521
522 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000523 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000524 // There should only be one argument that is the shell command itself to be used as is
525 if (argv[0] && !argv[1])
526 shell_command.Printf("%s", argv[0]);
Greg Clayton97471182012-04-14 01:42:46 +0000527 else
Greg Clayton0c8446c2012-10-17 22:57:12 +0000528 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000529 }
Greg Clayton97471182012-04-14 01:42:46 +0000530 else
531 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000532 for (size_t i=0; argv[i] != NULL; ++i)
533 {
534 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
535 shell_command.Printf(" %s", arg);
536 }
Greg Clayton97471182012-04-14 01:42:46 +0000537 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000538 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000539 m_executable.SetFile(shell_executable, false);
540 m_arguments = shell_arguments;
541 return true;
542 }
543 else
544 {
545 error.SetErrorString ("invalid shell path");
546 }
547 }
548 else
549 {
550 error.SetErrorString ("not launching in shell");
551 }
552 return false;
553}
554
555
Greg Clayton24bc5d92011-03-30 18:16:51 +0000556bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000557ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
558{
559 if ((read || write) && fd >= 0 && path && path[0])
560 {
561 m_action = eFileActionOpen;
562 m_fd = fd;
563 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000564 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000565 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000566 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000567 else
Greg Clayton527154d2011-11-15 03:53:30 +0000568 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000569 m_path.assign (path);
570 return true;
571 }
572 else
573 {
574 Clear();
575 }
576 return false;
577}
578
579bool
580ProcessLaunchInfo::FileAction::Close (int fd)
581{
582 Clear();
583 if (fd >= 0)
584 {
585 m_action = eFileActionClose;
586 m_fd = fd;
587 }
588 return m_fd >= 0;
589}
590
591
592bool
593ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
594{
595 Clear();
596 if (fd >= 0 && dup_fd >= 0)
597 {
598 m_action = eFileActionDuplicate;
599 m_fd = fd;
600 m_arg = dup_fd;
601 }
602 return m_fd >= 0;
603}
604
605
606
607bool
608ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
609 const FileAction *info,
610 Log *log,
611 Error& error)
612{
613 if (info == NULL)
614 return false;
615
616 switch (info->m_action)
617 {
618 case eFileActionNone:
619 error.Clear();
620 break;
621
622 case eFileActionClose:
623 if (info->m_fd == -1)
624 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
625 else
626 {
627 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
628 eErrorTypePOSIX);
629 if (log && (error.Fail() || log))
630 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
631 file_actions, info->m_fd);
632 }
633 break;
634
635 case eFileActionDuplicate:
636 if (info->m_fd == -1)
637 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
638 else if (info->m_arg == -1)
639 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
640 else
641 {
642 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
643 eErrorTypePOSIX);
644 if (log && (error.Fail() || log))
645 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
646 file_actions, info->m_fd, info->m_arg);
647 }
648 break;
649
650 case eFileActionOpen:
651 if (info->m_fd == -1)
652 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
653 else
654 {
655 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000656
Greg Claytonb72d0f02011-04-12 05:54:46 +0000657 mode_t mode = 0;
658
Greg Clayton527154d2011-11-15 03:53:30 +0000659 if (oflag & O_CREAT)
660 mode = 0640;
661
Greg Claytonb72d0f02011-04-12 05:54:46 +0000662 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
663 info->m_fd,
664 info->m_path.c_str(),
665 oflag,
666 mode),
667 eErrorTypePOSIX);
668 if (error.Fail() || log)
669 error.PutToLog(log,
670 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
671 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
672 }
673 break;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000674 }
675 return error.Success();
676}
677
678Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000679ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000680{
681 Error error;
Greg Clayton6475c422012-12-04 00:32:51 +0000682 const int short_option = m_getopt_table[option_idx].val;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000683
684 switch (short_option)
685 {
686 case 's': // Stop at program entry point
687 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
688 break;
689
Greg Claytonb72d0f02011-04-12 05:54:46 +0000690 case 'i': // STDIN for read only
691 {
692 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000693 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000694 launch_info.AppendFileAction (action);
695 }
696 break;
697
698 case 'o': // Open STDOUT for write only
699 {
700 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000701 if (action.Open (STDOUT_FILENO, option_arg, false, true))
702 launch_info.AppendFileAction (action);
703 }
704 break;
705
706 case 'e': // STDERR for write only
707 {
708 ProcessLaunchInfo::FileAction action;
709 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000710 launch_info.AppendFileAction (action);
711 }
712 break;
713
Greg Clayton95ec1682012-03-06 04:01:04 +0000714
Greg Claytonb72d0f02011-04-12 05:54:46 +0000715 case 'p': // Process plug-in name
716 launch_info.SetProcessPluginName (option_arg);
717 break;
718
719 case 'n': // Disable STDIO
720 {
721 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000722 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000723 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000724 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000725 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000726 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000727 launch_info.AppendFileAction (action);
728 }
729 break;
730
731 case 'w':
732 launch_info.SetWorkingDirectory (option_arg);
733 break;
734
735 case 't': // Open process in new terminal window
736 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
737 break;
738
739 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000740 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
741 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000742 break;
743
744 case 'A':
745 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
746 break;
747
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000748 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000749 if (option_arg && option_arg[0])
750 launch_info.SetShell (option_arg);
751 else
752 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000753 break;
754
Greg Claytonb72d0f02011-04-12 05:54:46 +0000755 case 'v':
756 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
757 break;
758
759 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000760 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000761 break;
762
763 }
764 return error;
765}
766
767OptionDefinition
768ProcessLaunchCommandOptions::g_option_table[] =
769{
770{ 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."},
771{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
772{ 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 +0000773{ 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 +0000774{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
775{ 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 +0000776{ 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 +0000777
Sean Callanan9a91ef62012-10-24 01:12:14 +0000778{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdin for the process to <filename>."},
779{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypeFilename, "Redirect stdout for the process to <filename>."},
780{ 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 +0000781
782{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
783
784{ 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."},
785
786{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
787};
788
789
790
791bool
792ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000793{
794 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
795 return true;
796 const char *match_name = m_match_info.GetName();
797 if (!match_name)
798 return true;
799
800 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
801}
802
803bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000804ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000805{
806 if (!NameMatches (proc_info.GetName()))
807 return false;
808
809 if (m_match_info.ProcessIDIsValid() &&
810 m_match_info.GetProcessID() != proc_info.GetProcessID())
811 return false;
812
813 if (m_match_info.ParentProcessIDIsValid() &&
814 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
815 return false;
816
Greg Claytonb72d0f02011-04-12 05:54:46 +0000817 if (m_match_info.UserIDIsValid () &&
818 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000819 return false;
820
Greg Claytonb72d0f02011-04-12 05:54:46 +0000821 if (m_match_info.GroupIDIsValid () &&
822 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000823 return false;
824
825 if (m_match_info.EffectiveUserIDIsValid () &&
826 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
827 return false;
828
829 if (m_match_info.EffectiveGroupIDIsValid () &&
830 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
831 return false;
832
833 if (m_match_info.GetArchitecture().IsValid() &&
Sean Callanan40e278c2012-12-13 22:07:14 +0000834 !m_match_info.GetArchitecture().IsCompatibleMatch(proc_info.GetArchitecture()))
Greg Clayton24bc5d92011-03-30 18:16:51 +0000835 return false;
836 return true;
837}
838
839bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000840ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000841{
842 if (m_name_match_type != eNameMatchIgnore)
843 return false;
844
845 if (m_match_info.ProcessIDIsValid())
846 return false;
847
848 if (m_match_info.ParentProcessIDIsValid())
849 return false;
850
Greg Claytonb72d0f02011-04-12 05:54:46 +0000851 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000852 return false;
853
Greg Claytonb72d0f02011-04-12 05:54:46 +0000854 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000855 return false;
856
857 if (m_match_info.EffectiveUserIDIsValid ())
858 return false;
859
860 if (m_match_info.EffectiveGroupIDIsValid ())
861 return false;
862
863 if (m_match_info.GetArchitecture().IsValid())
864 return false;
865
866 if (m_match_all_users)
867 return false;
868
869 return true;
870
871}
872
873void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000874ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000875{
876 m_match_info.Clear();
877 m_name_match_type = eNameMatchIgnore;
878 m_match_all_users = false;
879}
Greg Claytonfd119992011-01-07 06:08:19 +0000880
Greg Clayton46c9a352012-02-09 06:16:32 +0000881ProcessSP
882Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000883{
Greg Clayton46c9a352012-02-09 06:16:32 +0000884 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000885 ProcessCreateInstance create_callback = NULL;
886 if (plugin_name)
887 {
888 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
889 if (create_callback)
890 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000891 process_sp = create_callback(target, listener, crash_file_path);
892 if (process_sp)
893 {
894 if (!process_sp->CanDebug(target, true))
895 process_sp.reset();
896 }
Chris Lattner24943d22010-06-08 16:52:24 +0000897 }
898 }
899 else
900 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000901 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000902 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000903 process_sp = create_callback(target, listener, crash_file_path);
904 if (process_sp)
905 {
906 if (!process_sp->CanDebug(target, false))
907 process_sp.reset();
908 else
909 break;
910 }
Chris Lattner24943d22010-06-08 16:52:24 +0000911 }
912 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000913 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000914}
915
Jim Ingham5a15e692012-02-16 06:50:00 +0000916ConstString &
917Process::GetStaticBroadcasterClass ()
918{
919 static ConstString class_name ("lldb.process");
920 return class_name;
921}
Chris Lattner24943d22010-06-08 16:52:24 +0000922
923//----------------------------------------------------------------------
924// Process constructor
925//----------------------------------------------------------------------
926Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +0000927 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +0000928 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000929 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +0000930 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000931 m_public_state (eStateUnloaded),
932 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000933 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
934 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000935 m_private_state_listener ("lldb.process.internal_state_listener"),
936 m_private_state_control_wait(),
937 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000938 m_mod_id (),
Chris Lattner24943d22010-06-08 16:52:24 +0000939 m_thread_index_id (0),
Han Ming Ongccd5c4e2013-01-08 22:10:01 +0000940 m_thread_id_to_index_id_map (),
Chris Lattner24943d22010-06-08 16:52:24 +0000941 m_exit_status (-1),
942 m_exit_string (),
943 m_thread_list (this),
944 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000945 m_image_tokens (),
946 m_listener (listener),
947 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000948 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000949 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000950 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000951 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000952 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000953 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000954 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000955 m_stderr_data (),
Han Ming Ongfb9cee62012-11-17 00:21:04 +0000956 m_profile_data_comm_mutex (Mutex::eMutexTypeRecursive),
957 m_profile_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000958 m_memory_cache (*this),
959 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +0000960 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000961 m_next_event_action_ap(),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000962 m_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +0000963 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +0000964 m_finalize_called(false),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000965 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +0000966{
Jim Ingham5a15e692012-02-16 06:50:00 +0000967 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +0000968
Greg Claytone005f2c2010-11-06 01:53:30 +0000969 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000970 if (log)
971 log->Printf ("%p Process::Process()", this);
972
Greg Clayton49ce6822010-10-31 03:01:06 +0000973 SetEventName (eBroadcastBitStateChanged, "state-changed");
974 SetEventName (eBroadcastBitInterrupt, "interrupt");
975 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
976 SetEventName (eBroadcastBitSTDERR, "stderr-available");
Han Ming Ongfb9cee62012-11-17 00:21:04 +0000977 SetEventName (eBroadcastBitProfileData, "profile-data-available");
Greg Clayton49ce6822010-10-31 03:01:06 +0000978
Greg Clayton84332782012-10-29 20:52:08 +0000979 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlStop , "control-stop" );
980 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlPause , "control-pause" );
981 m_private_state_control_broadcaster.SetEventName (eBroadcastInternalStateControlResume, "control-resume");
982
Chris Lattner24943d22010-06-08 16:52:24 +0000983 listener.StartListeningForEvents (this,
984 eBroadcastBitStateChanged |
985 eBroadcastBitInterrupt |
986 eBroadcastBitSTDOUT |
Han Ming Ongfb9cee62012-11-17 00:21:04 +0000987 eBroadcastBitSTDERR |
988 eBroadcastBitProfileData);
Chris Lattner24943d22010-06-08 16:52:24 +0000989
990 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +0000991 eBroadcastBitStateChanged |
992 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +0000993
994 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
995 eBroadcastInternalStateControlStop |
996 eBroadcastInternalStateControlPause |
997 eBroadcastInternalStateControlResume);
998}
999
1000//----------------------------------------------------------------------
1001// Destructor
1002//----------------------------------------------------------------------
1003Process::~Process()
1004{
Greg Claytone005f2c2010-11-06 01:53:30 +00001005 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +00001006 if (log)
1007 log->Printf ("%p Process::~Process()", this);
1008 StopPrivateStateThread();
1009}
1010
Greg Clayton73844aa2012-08-22 17:17:09 +00001011const ProcessPropertiesSP &
1012Process::GetGlobalProperties()
1013{
1014 static ProcessPropertiesSP g_settings_sp;
1015 if (!g_settings_sp)
1016 g_settings_sp.reset (new ProcessProperties (true));
1017 return g_settings_sp;
1018}
1019
Chris Lattner24943d22010-06-08 16:52:24 +00001020void
1021Process::Finalize()
1022{
Greg Claytonffa43a62011-11-17 04:46:02 +00001023 switch (GetPrivateState())
1024 {
1025 case eStateConnected:
1026 case eStateAttaching:
1027 case eStateLaunching:
1028 case eStateStopped:
1029 case eStateRunning:
1030 case eStateStepping:
1031 case eStateCrashed:
1032 case eStateSuspended:
1033 if (GetShouldDetach())
1034 Detach();
1035 else
1036 Destroy();
1037 break;
1038
1039 case eStateInvalid:
1040 case eStateUnloaded:
1041 case eStateDetached:
1042 case eStateExited:
1043 break;
1044 }
1045
Greg Clayton2f57db02011-10-01 00:45:15 +00001046 // Clear our broadcaster before we proceed with destroying
1047 Broadcaster::Clear();
1048
Chris Lattner24943d22010-06-08 16:52:24 +00001049 // Do any cleanup needed prior to being destructed... Subclasses
1050 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001051
1052 // We need to destroy the loader before the derived Process class gets destroyed
1053 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001054 m_dynamic_checkers_ap.reset();
1055 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001056 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001057 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001058 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001059 std::vector<Notifications> empty_notifications;
1060 m_notifications.swap(empty_notifications);
1061 m_image_tokens.clear();
1062 m_memory_cache.Clear();
1063 m_allocated_memory_cache.Clear();
1064 m_language_runtimes.clear();
1065 m_next_event_action_ap.reset();
Greg Clayton84332782012-10-29 20:52:08 +00001066//#ifdef LLDB_CONFIGURATION_DEBUG
1067// StreamFile s(stdout, false);
1068// EventSP event_sp;
1069// while (m_private_state_listener.GetNextEvent(event_sp))
1070// {
1071// event_sp->Dump (&s);
1072// s.EOL();
1073// }
1074//#endif
1075 // We have to be very careful here as the m_private_state_listener might
1076 // contain events that have ProcessSP values in them which can keep this
1077 // process around forever. These events need to be cleared out.
1078 m_private_state_listener.Clear();
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001079 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001080}
1081
1082void
1083Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1084{
1085 m_notifications.push_back(callbacks);
1086 if (callbacks.initialize != NULL)
1087 callbacks.initialize (callbacks.baton, this);
1088}
1089
1090bool
1091Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1092{
1093 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1094 for (pos = m_notifications.begin(); pos != end; ++pos)
1095 {
1096 if (pos->baton == callbacks.baton &&
1097 pos->initialize == callbacks.initialize &&
1098 pos->process_state_changed == callbacks.process_state_changed)
1099 {
1100 m_notifications.erase(pos);
1101 return true;
1102 }
1103 }
1104 return false;
1105}
1106
1107void
1108Process::SynchronouslyNotifyStateChanged (StateType state)
1109{
1110 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1111 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1112 {
1113 if (notification_pos->process_state_changed)
1114 notification_pos->process_state_changed (notification_pos->baton, this, state);
1115 }
1116}
1117
1118// FIXME: We need to do some work on events before the general Listener sees them.
1119// For instance if we are continuing from a breakpoint, we need to ensure that we do
1120// the little "insert real insn, step & stop" trick. But we can't do that when the
1121// event is delivered by the broadcaster - since that is done on the thread that is
1122// waiting for new events, so if we needed more than one event for our handling, we would
1123// stall. So instead we do it when we fetch the event off of the queue.
1124//
1125
1126StateType
1127Process::GetNextEvent (EventSP &event_sp)
1128{
1129 StateType state = eStateInvalid;
1130
1131 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1132 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1133
1134 return state;
1135}
1136
1137
1138StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001139Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001140{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001141 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1142 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1143 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001144 if (event_sp_ptr)
1145 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001146 StateType state = GetState();
1147 // If we are exited or detached, we won't ever get back to any
1148 // other valid state...
1149 if (state == eStateDetached || state == eStateExited)
1150 return state;
1151
1152 while (state != eStateInvalid)
1153 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001154 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001155 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001156 if (event_sp_ptr && event_sp)
1157 *event_sp_ptr = event_sp;
1158
Jim Ingham21f37ad2011-08-09 02:12:22 +00001159 switch (state)
1160 {
1161 case eStateCrashed:
1162 case eStateDetached:
1163 case eStateExited:
1164 case eStateUnloaded:
1165 return state;
1166 case eStateStopped:
1167 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1168 continue;
1169 else
1170 return state;
1171 default:
1172 continue;
1173 }
1174 }
1175 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001176}
1177
1178
1179StateType
1180Process::WaitForState
1181(
1182 const TimeValue *timeout,
1183 const StateType *match_states, const uint32_t num_match_states
1184)
1185{
1186 EventSP event_sp;
1187 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001188 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001189 while (state != eStateInvalid)
1190 {
Greg Claytond8c62532010-10-07 04:19:01 +00001191 // If we are exited or detached, we won't ever get back to any
1192 // other valid state...
1193 if (state == eStateDetached || state == eStateExited)
1194 return state;
1195
Chris Lattner24943d22010-06-08 16:52:24 +00001196 state = WaitForStateChangedEvents (timeout, event_sp);
1197
1198 for (i=0; i<num_match_states; ++i)
1199 {
1200 if (match_states[i] == state)
1201 return state;
1202 }
1203 }
1204 return state;
1205}
1206
Jim Ingham63e24d72010-10-11 23:53:14 +00001207bool
1208Process::HijackProcessEvents (Listener *listener)
1209{
1210 if (listener != NULL)
1211 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001212 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001213 }
1214 else
1215 return false;
1216}
1217
1218void
1219Process::RestoreProcessEvents ()
1220{
1221 RestoreBroadcaster();
1222}
1223
Jim Inghamf9f40c22011-02-08 05:20:59 +00001224bool
1225Process::HijackPrivateProcessEvents (Listener *listener)
1226{
1227 if (listener != NULL)
1228 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001229 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001230 }
1231 else
1232 return false;
1233}
1234
1235void
1236Process::RestorePrivateProcessEvents ()
1237{
1238 m_private_state_broadcaster.RestoreBroadcaster();
1239}
1240
Chris Lattner24943d22010-06-08 16:52:24 +00001241StateType
1242Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1243{
Greg Claytone005f2c2010-11-06 01:53:30 +00001244 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001245
1246 if (log)
1247 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1248
1249 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001250 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1251 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001252 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001253 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001254 {
1255 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1256 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1257 else if (log)
1258 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1259 }
Chris Lattner24943d22010-06-08 16:52:24 +00001260
1261 if (log)
1262 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1263 __FUNCTION__,
1264 timeout,
1265 StateAsCString(state));
1266 return state;
1267}
1268
1269Event *
1270Process::PeekAtStateChangedEvents ()
1271{
Greg Claytone005f2c2010-11-06 01:53:30 +00001272 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001273
1274 if (log)
1275 log->Printf ("Process::%s...", __FUNCTION__);
1276
1277 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001278 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1279 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001280 if (log)
1281 {
1282 if (event_ptr)
1283 {
1284 log->Printf ("Process::%s (event_ptr) => %s",
1285 __FUNCTION__,
1286 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1287 }
1288 else
1289 {
1290 log->Printf ("Process::%s no events found",
1291 __FUNCTION__);
1292 }
1293 }
1294 return event_ptr;
1295}
1296
1297StateType
1298Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1299{
Greg Claytone005f2c2010-11-06 01:53:30 +00001300 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001301
1302 if (log)
1303 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1304
1305 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001306 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1307 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001308 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001309 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001310 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1311 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001312
1313 // This is a bit of a hack, but when we wait here we could very well return
1314 // to the command-line, and that could disable the log, which would render the
1315 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001316 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001317 {
1318 if (state == eStateInvalid)
1319 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1320 else
1321 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1322 }
Chris Lattner24943d22010-06-08 16:52:24 +00001323 return state;
1324}
1325
1326bool
1327Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1328{
Greg Claytone005f2c2010-11-06 01:53:30 +00001329 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001330
1331 if (log)
1332 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1333
1334 if (control_only)
1335 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1336 else
1337 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1338}
1339
1340bool
1341Process::IsRunning () const
1342{
1343 return StateIsRunningState (m_public_state.GetValue());
1344}
1345
1346int
1347Process::GetExitStatus ()
1348{
1349 if (m_public_state.GetValue() == eStateExited)
1350 return m_exit_status;
1351 return -1;
1352}
1353
Greg Clayton638351a2010-12-04 00:10:17 +00001354
Chris Lattner24943d22010-06-08 16:52:24 +00001355const char *
1356Process::GetExitDescription ()
1357{
1358 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1359 return m_exit_string.c_str();
1360 return NULL;
1361}
1362
Greg Clayton72e1c782011-01-22 23:43:18 +00001363bool
Chris Lattner24943d22010-06-08 16:52:24 +00001364Process::SetExitStatus (int status, const char *cstr)
1365{
Greg Clayton68ca8232011-01-25 02:58:48 +00001366 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1367 if (log)
1368 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1369 status, status,
1370 cstr ? "\"" : "",
1371 cstr ? cstr : "NULL",
1372 cstr ? "\"" : "");
1373
Greg Clayton72e1c782011-01-22 23:43:18 +00001374 // We were already in the exited state
1375 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001376 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001377 if (log)
1378 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001379 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001380 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001381
1382 m_exit_status = status;
1383 if (cstr)
1384 m_exit_string = cstr;
1385 else
1386 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001387
Greg Clayton72e1c782011-01-22 23:43:18 +00001388 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001389
Greg Clayton72e1c782011-01-22 23:43:18 +00001390 SetPrivateState (eStateExited);
1391 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001392}
1393
1394// This static callback can be used to watch for local child processes on
1395// the current host. The the child process exits, the process will be
1396// found in the global target list (we want to be completely sure that the
1397// lldb_private::Process doesn't go away before we can deliver the signal.
1398bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001399Process::SetProcessExitStatus (void *callback_baton,
1400 lldb::pid_t pid,
1401 bool exited,
1402 int signo, // Zero for no signal
1403 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001404)
1405{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001406 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1407 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001408 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%" PRIu64 ", exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001409 callback_baton,
1410 pid,
1411 exited,
1412 signo,
1413 exit_status);
1414
1415 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001416 {
Greg Clayton63094e02010-06-23 01:19:29 +00001417 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001418 if (target_sp)
1419 {
1420 ProcessSP process_sp (target_sp->GetProcessSP());
1421 if (process_sp)
1422 {
1423 const char *signal_cstr = NULL;
1424 if (signo)
1425 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1426
1427 process_sp->SetExitStatus (exit_status, signal_cstr);
1428 }
1429 }
1430 return true;
1431 }
1432 return false;
1433}
1434
1435
Greg Clayton37f962e2011-08-22 02:49:39 +00001436void
1437Process::UpdateThreadListIfNeeded ()
1438{
1439 const uint32_t stop_id = GetStopID();
1440 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1441 {
Greg Clayton20206082011-11-17 01:23:07 +00001442 const StateType state = GetPrivateState();
1443 if (StateIsStoppedState (state, true))
1444 {
1445 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001446 // m_thread_list does have its own mutex, but we need to
1447 // hold onto the mutex between the call to UpdateThreadList(...)
1448 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001449 ThreadList new_thread_list(this);
1450 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001451 // thread list, but only update if "true" is returned
1452 if (UpdateThreadList (m_thread_list, new_thread_list))
1453 {
1454 OperatingSystem *os = GetOperatingSystem ();
1455 if (os)
1456 os->UpdateThreadList (m_thread_list, new_thread_list);
1457 m_thread_list.Update (new_thread_list);
1458 m_thread_list.SetStopID (stop_id);
1459 }
Greg Clayton20206082011-11-17 01:23:07 +00001460 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001461 }
1462}
1463
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001464// This is obsoleted. Staged removal for Xcode.
Chris Lattner24943d22010-06-08 16:52:24 +00001465uint32_t
1466Process::GetNextThreadIndexID ()
1467{
1468 return ++m_thread_index_id;
1469}
1470
Han Ming Ongccd5c4e2013-01-08 22:10:01 +00001471uint32_t
1472Process::GetNextThreadIndexID (uint64_t thread_id)
1473{
1474 return AssignIndexIDToThread(thread_id);
1475}
1476
1477bool
1478Process::HasAssignedIndexIDToThread(uint64_t thread_id)
1479{
1480 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1481 if (iterator == m_thread_id_to_index_id_map.end())
1482 {
1483 return false;
1484 }
1485 else
1486 {
1487 return true;
1488 }
1489}
1490
1491uint32_t
1492Process::AssignIndexIDToThread(uint64_t thread_id)
1493{
1494 uint32_t result = 0;
1495 std::map<uint64_t, uint32_t>::iterator iterator = m_thread_id_to_index_id_map.find(thread_id);
1496 if (iterator == m_thread_id_to_index_id_map.end())
1497 {
1498 result = ++m_thread_index_id;
1499 m_thread_id_to_index_id_map[thread_id] = result;
1500 }
1501 else
1502 {
1503 result = iterator->second;
1504 }
1505
1506 return result;
1507}
1508
Chris Lattner24943d22010-06-08 16:52:24 +00001509StateType
1510Process::GetState()
1511{
1512 // If any other threads access this we will need a mutex for it
1513 return m_public_state.GetValue ();
1514}
1515
1516void
1517Process::SetPublicState (StateType new_state)
1518{
Greg Clayton68ca8232011-01-25 02:58:48 +00001519 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001520 if (log)
1521 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001522 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001523 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001524
1525 // On the transition from Run to Stopped, we unlock the writer end of the
1526 // run lock. The lock gets locked in Resume, which is the public API
1527 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001528 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1529 {
Sean Callanana3772862012-06-02 01:16:20 +00001530 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001531 {
Sean Callanana3772862012-06-02 01:16:20 +00001532 if (log)
1533 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1534 m_run_lock.WriteUnlock();
1535 }
1536 else
1537 {
1538 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1539 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1540 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001541 {
Sean Callanana3772862012-06-02 01:16:20 +00001542 if (new_state_is_stopped)
1543 {
1544 if (log)
1545 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1546 m_run_lock.WriteUnlock();
1547 }
Greg Claytona894fe72012-04-05 16:12:35 +00001548 }
Greg Claytona894fe72012-04-05 16:12:35 +00001549 }
1550 }
Chris Lattner24943d22010-06-08 16:52:24 +00001551}
1552
Jim Ingham027aaa72012-04-19 01:40:33 +00001553Error
1554Process::Resume ()
1555{
1556 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1557 if (log)
1558 log->Printf("Process::Resume -- locking run lock");
1559 if (!m_run_lock.WriteTryLock())
1560 {
1561 Error error("Resume request failed - process still running.");
1562 if (log)
1563 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1564 return error;
1565 }
1566 return PrivateResume();
1567}
1568
Chris Lattner24943d22010-06-08 16:52:24 +00001569StateType
1570Process::GetPrivateState ()
1571{
1572 return m_private_state.GetValue();
1573}
1574
1575void
1576Process::SetPrivateState (StateType new_state)
1577{
Greg Clayton68ca8232011-01-25 02:58:48 +00001578 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001579 bool state_changed = false;
1580
1581 if (log)
1582 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1583
1584 Mutex::Locker locker(m_private_state.GetMutex());
1585
1586 const StateType old_state = m_private_state.GetValueNoLock ();
1587 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001588 // This code is left commented out in case we ever need to control
1589 // the private process state with another run lock. Right now it doesn't
1590 // seem like we need to do this, but if we ever do, we can uncomment and
1591 // use this code.
1592// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1593// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1594// if (old_state_is_stopped != new_state_is_stopped)
1595// {
1596// if (new_state_is_stopped)
1597// m_private_run_lock.WriteUnlock();
1598// else
1599// m_private_run_lock.WriteLock();
1600// }
1601
Chris Lattner24943d22010-06-08 16:52:24 +00001602 if (state_changed)
1603 {
1604 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001605 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001606 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001607 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001608 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001609 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001610 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001611 }
1612 // Use our target to get a shared pointer to ourselves...
Greg Clayton84332782012-10-29 20:52:08 +00001613 if (m_finalize_called && PrivateStateThreadIsValid() == false)
1614 BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
1615 else
1616 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (shared_from_this(), new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001617 }
1618 else
1619 {
1620 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001621 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001622 }
1623}
1624
Jim Ingham0296fe72011-11-08 03:00:11 +00001625void
1626Process::SetRunningUserExpression (bool on)
1627{
1628 m_mod_id.SetRunningUserExpression (on);
1629}
1630
Chris Lattner24943d22010-06-08 16:52:24 +00001631addr_t
1632Process::GetImageInfoAddress()
1633{
1634 return LLDB_INVALID_ADDRESS;
1635}
1636
Greg Clayton0baa3942010-11-04 01:54:29 +00001637//----------------------------------------------------------------------
1638// LoadImage
1639//
1640// This function provides a default implementation that works for most
1641// unix variants. Any Process subclasses that need to do shared library
1642// loading differently should override LoadImage and UnloadImage and
1643// do what is needed.
1644//----------------------------------------------------------------------
1645uint32_t
1646Process::LoadImage (const FileSpec &image_spec, Error &error)
1647{
Greg Clayton77d40712012-04-18 00:05:19 +00001648 char path[PATH_MAX];
1649 image_spec.GetPath(path, sizeof(path));
1650
Greg Clayton0baa3942010-11-04 01:54:29 +00001651 DynamicLoader *loader = GetDynamicLoader();
1652 if (loader)
1653 {
1654 error = loader->CanLoadImage();
1655 if (error.Fail())
1656 return LLDB_INVALID_IMAGE_TOKEN;
1657 }
1658
1659 if (error.Success())
1660 {
1661 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001662
1663 if (thread_sp)
1664 {
1665 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1666
1667 if (frame_sp)
1668 {
1669 ExecutionContext exe_ctx;
1670 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001671 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001672 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001673 expr.Printf("dlopen (\"%s\", 2)", path);
1674 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001675 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001676 ClangUserExpression::Evaluate (exe_ctx,
1677 eExecutionPolicyAlways,
1678 lldb::eLanguageTypeUnknown,
1679 ClangUserExpression::eResultTypeAny,
1680 unwind_on_error,
1681 expr.GetData(),
1682 prefix,
1683 result_valobj_sp,
1684 true,
1685 ClangUserExpression::kDefaultTimeout);
Johnny Chenb14ec342011-09-09 00:01:43 +00001686 error = result_valobj_sp->GetError();
1687 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001688 {
1689 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001690 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001691 {
1692 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1693 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1694 {
1695 uint32_t image_token = m_image_tokens.size();
1696 m_image_tokens.push_back (image_ptr);
1697 return image_token;
1698 }
1699 }
1700 }
1701 }
1702 }
1703 }
Greg Clayton77d40712012-04-18 00:05:19 +00001704 if (!error.AsCString())
1705 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001706 return LLDB_INVALID_IMAGE_TOKEN;
1707}
1708
1709//----------------------------------------------------------------------
1710// UnloadImage
1711//
1712// This function provides a default implementation that works for most
1713// unix variants. Any Process subclasses that need to do shared library
1714// loading differently should override LoadImage and UnloadImage and
1715// do what is needed.
1716//----------------------------------------------------------------------
1717Error
1718Process::UnloadImage (uint32_t image_token)
1719{
1720 Error error;
1721 if (image_token < m_image_tokens.size())
1722 {
1723 const addr_t image_addr = m_image_tokens[image_token];
1724 if (image_addr == LLDB_INVALID_ADDRESS)
1725 {
1726 error.SetErrorString("image already unloaded");
1727 }
1728 else
1729 {
1730 DynamicLoader *loader = GetDynamicLoader();
1731 if (loader)
1732 error = loader->CanLoadImage();
1733
1734 if (error.Success())
1735 {
1736 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001737
1738 if (thread_sp)
1739 {
1740 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1741
1742 if (frame_sp)
1743 {
1744 ExecutionContext exe_ctx;
1745 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001746 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001747 StreamString expr;
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001748 expr.Printf("dlclose ((void *)0x%" PRIx64 ")", image_addr);
Greg Clayton0baa3942010-11-04 01:54:29 +00001749 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001750 lldb::ValueObjectSP result_valobj_sp;
Greg Clayton34507e42012-10-31 20:49:04 +00001751 ClangUserExpression::Evaluate (exe_ctx,
1752 eExecutionPolicyAlways,
1753 lldb::eLanguageTypeUnknown,
1754 ClangUserExpression::eResultTypeAny,
1755 unwind_on_error,
1756 expr.GetData(),
1757 prefix,
1758 result_valobj_sp,
1759 true,
1760 ClangUserExpression::kDefaultTimeout);
Greg Clayton0baa3942010-11-04 01:54:29 +00001761 if (result_valobj_sp->GetError().Success())
1762 {
1763 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001764 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001765 {
1766 if (scalar.UInt(1))
1767 {
1768 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1769 }
1770 else
1771 {
1772 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1773 }
1774 }
1775 }
1776 else
1777 {
1778 error = result_valobj_sp->GetError();
1779 }
1780 }
1781 }
1782 }
1783 }
1784 }
1785 else
1786 {
1787 error.SetErrorString("invalid image token");
1788 }
1789 return error;
1790}
1791
Greg Clayton75906e42011-05-11 18:39:18 +00001792const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001793Process::GetABI()
1794{
Greg Clayton75906e42011-05-11 18:39:18 +00001795 if (!m_abi_sp)
1796 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1797 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001798}
1799
Jim Ingham642036f2010-09-23 02:01:19 +00001800LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001801Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001802{
1803 LanguageRuntimeCollection::iterator pos;
1804 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001805 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001806 {
Jim Inghame3117662012-03-10 00:22:19 +00001807 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001808
Jim Inghame3117662012-03-10 00:22:19 +00001809 m_language_runtimes[language] = runtime_sp;
1810 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001811 }
1812 else
1813 return (*pos).second.get();
1814}
1815
1816CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001817Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001818{
Jim Inghame3117662012-03-10 00:22:19 +00001819 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001820 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1821 return static_cast<CPPLanguageRuntime *> (runtime);
1822 return NULL;
1823}
1824
1825ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001826Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001827{
Jim Inghame3117662012-03-10 00:22:19 +00001828 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001829 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1830 return static_cast<ObjCLanguageRuntime *> (runtime);
1831 return NULL;
1832}
1833
Enrico Granata6b1763b2012-05-21 16:51:35 +00001834bool
1835Process::IsPossibleDynamicValue (ValueObject& in_value)
1836{
1837 if (in_value.IsDynamic())
1838 return false;
1839 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1840
1841 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1842 {
1843 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1844 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1845 }
1846
1847 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1848 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1849 return true;
1850
1851 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1852 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1853}
1854
Chris Lattner24943d22010-06-08 16:52:24 +00001855BreakpointSiteList &
1856Process::GetBreakpointSiteList()
1857{
1858 return m_breakpoint_site_list;
1859}
1860
1861const BreakpointSiteList &
1862Process::GetBreakpointSiteList() const
1863{
1864 return m_breakpoint_site_list;
1865}
1866
1867
1868void
1869Process::DisableAllBreakpointSites ()
1870{
1871 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001872 size_t num_sites = m_breakpoint_site_list.GetSize();
1873 for (size_t i = 0; i < num_sites; i++)
1874 {
1875 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1876 }
Chris Lattner24943d22010-06-08 16:52:24 +00001877}
1878
1879Error
1880Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1881{
1882 Error error (DisableBreakpointSiteByID (break_id));
1883
1884 if (error.Success())
1885 m_breakpoint_site_list.Remove(break_id);
1886
1887 return error;
1888}
1889
1890Error
1891Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1892{
1893 Error error;
1894 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1895 if (bp_site_sp)
1896 {
1897 if (bp_site_sp->IsEnabled())
1898 error = DisableBreakpoint (bp_site_sp.get());
1899 }
1900 else
1901 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001902 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001903 }
1904
1905 return error;
1906}
1907
1908Error
1909Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1910{
1911 Error error;
1912 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1913 if (bp_site_sp)
1914 {
1915 if (!bp_site_sp->IsEnabled())
1916 error = EnableBreakpoint (bp_site_sp.get());
1917 }
1918 else
1919 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00001920 error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001921 }
1922 return error;
1923}
1924
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001925lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001926Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001927{
Greg Clayton265ab332011-05-19 18:17:41 +00001928 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001929 if (load_addr != LLDB_INVALID_ADDRESS)
1930 {
1931 BreakpointSiteSP bp_site_sp;
1932
1933 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1934 // create a new breakpoint site and add it.
1935
1936 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1937
1938 if (bp_site_sp)
1939 {
1940 bp_site_sp->AddOwner (owner);
1941 owner->SetBreakpointSite (bp_site_sp);
1942 return bp_site_sp->GetID();
1943 }
1944 else
1945 {
1946 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1947 if (bp_site_sp)
1948 {
1949 if (EnableBreakpoint (bp_site_sp.get()).Success())
1950 {
1951 owner->SetBreakpointSite (bp_site_sp);
1952 return m_breakpoint_site_list.Add (bp_site_sp);
1953 }
1954 }
1955 }
1956 }
1957 // We failed to enable the breakpoint
1958 return LLDB_INVALID_BREAK_ID;
1959
1960}
1961
1962void
1963Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1964{
1965 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1966 if (num_owners == 0)
1967 {
1968 DisableBreakpoint(bp_site_sp.get());
1969 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1970 }
1971}
1972
1973
1974size_t
1975Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1976{
1977 size_t bytes_removed = 0;
1978 addr_t intersect_addr;
1979 size_t intersect_size;
1980 size_t opcode_offset;
1981 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001982 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001983 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001984
Jim Ingham82820f92011-06-29 19:42:28 +00001985 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001986 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001987 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001988 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001989 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001990 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001991 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001992 {
1993 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1994 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001995 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001996 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001997 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001998 }
Chris Lattner24943d22010-06-08 16:52:24 +00001999 }
2000 }
2001 }
2002 return bytes_removed;
2003}
2004
2005
Greg Claytonb1888f22011-03-19 01:12:21 +00002006
2007size_t
2008Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
2009{
2010 PlatformSP platform_sp (m_target.GetPlatform());
2011 if (platform_sp)
2012 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
2013 return 0;
2014}
2015
Chris Lattner24943d22010-06-08 16:52:24 +00002016Error
2017Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
2018{
2019 Error error;
2020 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002021 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002022 const addr_t bp_addr = bp_site->GetLoadAddress();
2023 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002024 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, bp_site->GetID(), (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002025 if (bp_site->IsEnabled())
2026 {
2027 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002028 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 +00002029 return error;
2030 }
2031
2032 if (bp_addr == LLDB_INVALID_ADDRESS)
2033 {
2034 error.SetErrorString("BreakpointSite contains an invalid load address.");
2035 return error;
2036 }
2037 // Ask the lldb::Process subclass to fill in the correct software breakpoint
2038 // trap for the breakpoint site
2039 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2040
2041 if (bp_opcode_size == 0)
2042 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002043 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%" PRIx64, bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002044 }
2045 else
2046 {
2047 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
2048
2049 if (bp_opcode_bytes == NULL)
2050 {
2051 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
2052 return error;
2053 }
2054
2055 // Save the original opcode by reading it
2056 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
2057 {
2058 // Write a software breakpoint in place of the original opcode
2059 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2060 {
2061 uint8_t verify_bp_opcode_bytes[64];
2062 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
2063 {
2064 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
2065 {
2066 bp_site->SetEnabled(true);
2067 bp_site->SetType (BreakpointSite::eSoftware);
2068 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002069 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- SUCCESS",
Chris Lattner24943d22010-06-08 16:52:24 +00002070 bp_site->GetID(),
2071 (uint64_t)bp_addr);
2072 }
2073 else
Greg Clayton9c236732011-10-26 00:56:27 +00002074 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00002075 }
2076 else
2077 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
2078 }
2079 else
2080 error.SetErrorString("Unable to write breakpoint trap to memory.");
2081 }
2082 else
2083 error.SetErrorString("Unable to read memory at breakpoint address.");
2084 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00002085 if (log && error.Fail())
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002086 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002087 bp_site->GetID(),
2088 (uint64_t)bp_addr,
2089 error.AsCString());
2090 return error;
2091}
2092
2093Error
2094Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
2095{
2096 Error error;
2097 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002098 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002099 addr_t bp_addr = bp_site->GetLoadAddress();
2100 lldb::user_id_t breakID = bp_site->GetID();
2101 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002102 log->Printf ("Process::DisableBreakpoint (breakID = %" PRIu64 ") addr = 0x%" PRIx64, breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002103
2104 if (bp_site->IsHardware())
2105 {
2106 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2107 }
2108 else if (bp_site->IsEnabled())
2109 {
2110 const size_t break_op_size = bp_site->GetByteSize();
2111 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2112 if (break_op_size > 0)
2113 {
2114 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002115 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002116 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002117 bool break_op_found = false;
2118
2119 // Read the breakpoint opcode
2120 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2121 {
2122 bool verify = false;
2123 // Make sure we have the a breakpoint opcode exists at this address
2124 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2125 {
2126 break_op_found = true;
2127 // We found a valid breakpoint opcode at this address, now restore
2128 // the saved opcode.
2129 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2130 {
2131 verify = true;
2132 }
2133 else
2134 error.SetErrorString("Memory write failed when restoring original opcode.");
2135 }
2136 else
2137 {
2138 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2139 // Set verify to true and so we can check if the original opcode has already been restored
2140 verify = true;
2141 }
2142
2143 if (verify)
2144 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002145 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002146 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002147 // Verify that our original opcode made it back to the inferior
2148 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2149 {
2150 // compare the memory we just read with the original opcode
2151 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2152 {
2153 // SUCCESS
2154 bp_site->SetEnabled(false);
2155 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002156 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 +00002157 return error;
2158 }
2159 else
2160 {
2161 if (break_op_found)
2162 error.SetErrorString("Failed to restore original opcode.");
2163 }
2164 }
2165 else
2166 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2167 }
2168 }
2169 else
2170 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2171 }
2172 }
2173 else
2174 {
2175 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002176 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 +00002177 return error;
2178 }
2179
2180 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002181 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 " -- FAILED: %s",
Chris Lattner24943d22010-06-08 16:52:24 +00002182 bp_site->GetID(),
2183 (uint64_t)bp_addr,
2184 error.AsCString());
2185 return error;
2186
2187}
2188
Greg Claytonfd119992011-01-07 06:08:19 +00002189// Uncomment to verify memory caching works after making changes to caching code
2190//#define VERIFY_MEMORY_READS
2191
Sean Callananf90b5f32012-06-07 22:26:42 +00002192size_t
2193Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2194{
2195 if (!GetDisableMemoryCache())
2196 {
Greg Claytonfd119992011-01-07 06:08:19 +00002197#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002198 // Memory caching is enabled, with debug verification
2199
2200 if (buf && size)
2201 {
2202 // Uncomment the line below to make sure memory caching is working.
2203 // I ran this through the test suite and got no assertions, so I am
2204 // pretty confident this is working well. If any changes are made to
2205 // memory caching, uncomment the line below and test your changes!
2206
2207 // Verify all memory reads by using the cache first, then redundantly
2208 // reading the same memory from the inferior and comparing to make sure
2209 // everything is exactly the same.
2210 std::string verify_buf (size, '\0');
2211 assert (verify_buf.size() == size);
2212 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2213 Error verify_error;
2214 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2215 assert (cache_bytes_read == verify_bytes_read);
2216 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2217 assert (verify_error.Success() == error.Success());
2218 return cache_bytes_read;
2219 }
2220 return 0;
2221#else // !defined(VERIFY_MEMORY_READS)
2222 // Memory caching is enabled, without debug verification
2223
2224 return m_memory_cache.Read (addr, buf, size, error);
2225#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002226 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002227 else
2228 {
2229 // Memory caching is disabled
2230
2231 return ReadMemoryFromInferior (addr, buf, size, error);
2232 }
Greg Claytonfd119992011-01-07 06:08:19 +00002233}
Greg Claytonfd119992011-01-07 06:08:19 +00002234
Greg Claytondd29b972012-05-18 23:20:01 +00002235size_t
2236Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2237{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002238 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002239 out_str.clear();
2240 addr_t curr_addr = addr;
2241 while (1)
2242 {
2243 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2244 if (length == 0)
2245 break;
2246 out_str.append(buf, length);
2247 // If we got "length - 1" bytes, we didn't get the whole C string, we
2248 // need to read some more characters
2249 if (length == sizeof(buf) - 1)
2250 curr_addr += length;
2251 else
2252 break;
2253 }
2254 return out_str.size();
2255}
2256
Greg Claytonfd119992011-01-07 06:08:19 +00002257
2258size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002259Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002260{
2261 size_t total_cstr_len = 0;
2262 if (dst && dst_max_len)
2263 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002264 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002265 // NULL out everything just to be safe
2266 memset (dst, 0, dst_max_len);
2267 Error error;
2268 addr_t curr_addr = addr;
2269 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2270 size_t bytes_left = dst_max_len - 1;
2271 char *curr_dst = dst;
2272
2273 while (bytes_left > 0)
2274 {
2275 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2276 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2277 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2278
2279 if (bytes_read == 0)
2280 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002281 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002282 dst[total_cstr_len] = '\0';
2283 break;
2284 }
2285 const size_t len = strlen(curr_dst);
2286
2287 total_cstr_len += len;
2288
2289 if (len < bytes_to_read)
2290 break;
2291
2292 curr_dst += bytes_read;
2293 curr_addr += bytes_read;
2294 bytes_left -= bytes_read;
2295 }
2296 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002297 else
2298 {
2299 if (dst == NULL)
2300 result_error.SetErrorString("invalid arguments");
2301 else
2302 result_error.Clear();
2303 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002304 return total_cstr_len;
2305}
2306
2307size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002308Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2309{
Chris Lattner24943d22010-06-08 16:52:24 +00002310 if (buf == NULL || size == 0)
2311 return 0;
2312
2313 size_t bytes_read = 0;
2314 uint8_t *bytes = (uint8_t *)buf;
2315
2316 while (bytes_read < size)
2317 {
2318 const size_t curr_size = size - bytes_read;
2319 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2320 bytes + bytes_read,
2321 curr_size,
2322 error);
2323 bytes_read += curr_bytes_read;
2324 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2325 break;
2326 }
2327
2328 // Replace any software breakpoint opcodes that fall into this range back
2329 // into "buf" before we return
2330 if (bytes_read > 0)
2331 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2332 return bytes_read;
2333}
2334
Greg Claytonf72fdee2010-12-16 20:01:20 +00002335uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002336Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002337{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002338 Scalar scalar;
2339 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2340 return scalar.ULongLong(fail_value);
2341 return fail_value;
2342}
2343
2344addr_t
2345Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2346{
2347 Scalar scalar;
2348 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2349 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2350 return LLDB_INVALID_ADDRESS;
2351}
2352
2353
2354bool
2355Process::WritePointerToMemory (lldb::addr_t vm_addr,
2356 lldb::addr_t ptr_value,
2357 Error &error)
2358{
2359 Scalar scalar;
2360 const uint32_t addr_byte_size = GetAddressByteSize();
2361 if (addr_byte_size <= 4)
2362 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002363 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002364 scalar = ptr_value;
2365 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002366}
2367
Chris Lattner24943d22010-06-08 16:52:24 +00002368size_t
2369Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2370{
2371 size_t bytes_written = 0;
2372 const uint8_t *bytes = (const uint8_t *)buf;
2373
2374 while (bytes_written < size)
2375 {
2376 const size_t curr_size = size - bytes_written;
2377 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2378 bytes + bytes_written,
2379 curr_size,
2380 error);
2381 bytes_written += curr_bytes_written;
2382 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2383 break;
2384 }
2385 return bytes_written;
2386}
2387
2388size_t
2389Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2390{
Greg Claytonfd119992011-01-07 06:08:19 +00002391#if defined (ENABLE_MEMORY_CACHING)
2392 m_memory_cache.Flush (addr, size);
2393#endif
2394
Chris Lattner24943d22010-06-08 16:52:24 +00002395 if (buf == NULL || size == 0)
2396 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002397
Jim Ingham21f37ad2011-08-09 02:12:22 +00002398 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002399
Chris Lattner24943d22010-06-08 16:52:24 +00002400 // We need to write any data that would go where any current software traps
2401 // (enabled software breakpoints) any software traps (breakpoints) that we
2402 // may have placed in our tasks memory.
2403
2404 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2405 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2406
2407 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002408 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002409
2410 BreakpointSiteList::collection::const_iterator pos;
2411 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002412 addr_t intersect_addr = 0;
2413 size_t intersect_size = 0;
2414 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002415 const uint8_t *ubuf = (const uint8_t *)buf;
2416
2417 for (pos = iter; pos != end; ++pos)
2418 {
2419 BreakpointSiteSP bp;
2420 bp = pos->second;
2421
2422 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2423 assert(addr <= intersect_addr && intersect_addr < addr + size);
2424 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2425 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2426
2427 // Check for bytes before this breakpoint
2428 const addr_t curr_addr = addr + bytes_written;
2429 if (intersect_addr > curr_addr)
2430 {
2431 // There are some bytes before this breakpoint that we need to
2432 // just write to memory
2433 size_t curr_size = intersect_addr - curr_addr;
2434 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2435 ubuf + bytes_written,
2436 curr_size,
2437 error);
2438 bytes_written += curr_bytes_written;
2439 if (curr_bytes_written != curr_size)
2440 {
2441 // We weren't able to write all of the requested bytes, we
2442 // are done looping and will return the number of bytes that
2443 // we have written so far.
2444 break;
2445 }
2446 }
2447
2448 // Now write any bytes that would cover up any software breakpoints
2449 // directly into the breakpoint opcode buffer
2450 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2451 bytes_written += intersect_size;
2452 }
2453
2454 // Write any remaining bytes after the last breakpoint if we have any left
2455 if (bytes_written < size)
2456 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2457 ubuf + bytes_written,
2458 size - bytes_written,
2459 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002460
Chris Lattner24943d22010-06-08 16:52:24 +00002461 return bytes_written;
2462}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002463
2464size_t
2465Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2466{
2467 if (byte_size == UINT32_MAX)
2468 byte_size = scalar.GetByteSize();
2469 if (byte_size > 0)
2470 {
2471 uint8_t buf[32];
2472 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2473 if (mem_size > 0)
2474 return WriteMemory(addr, buf, mem_size, error);
2475 else
2476 error.SetErrorString ("failed to get scalar as memory data");
2477 }
2478 else
2479 {
2480 error.SetErrorString ("invalid scalar value");
2481 }
2482 return 0;
2483}
2484
2485size_t
2486Process::ReadScalarIntegerFromMemory (addr_t addr,
2487 uint32_t byte_size,
2488 bool is_signed,
2489 Scalar &scalar,
2490 Error &error)
2491{
2492 uint64_t uval;
2493
2494 if (byte_size <= sizeof(uval))
2495 {
2496 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2497 if (bytes_read == byte_size)
2498 {
2499 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2500 uint32_t offset = 0;
2501 if (byte_size <= 4)
2502 scalar = data.GetMaxU32 (&offset, byte_size);
2503 else
2504 scalar = data.GetMaxU64 (&offset, byte_size);
2505
2506 if (is_signed)
2507 scalar.SignExtend(byte_size * 8);
2508 return bytes_read;
2509 }
2510 }
2511 else
2512 {
2513 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2514 }
2515 return 0;
2516}
2517
Greg Clayton613b8732011-05-17 03:37:42 +00002518#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002519addr_t
2520Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2521{
Jim Inghame6bd1422011-06-20 17:32:44 +00002522 if (GetPrivateState() != eStateStopped)
2523 return LLDB_INVALID_ADDRESS;
2524
Greg Clayton613b8732011-05-17 03:37:42 +00002525#if defined (USE_ALLOCATE_MEMORY_CACHE)
2526 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2527#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002528 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2529 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2530 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002531 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 +00002532 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002533 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002534 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002535 m_mod_id.GetStopID(),
2536 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002537 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002538#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002539}
2540
Sean Callanan6cf6c472011-09-20 23:01:51 +00002541bool
2542Process::CanJIT ()
2543{
Sean Callanan04200f62012-02-14 22:50:38 +00002544 if (m_can_jit == eCanJITDontKnow)
2545 {
2546 Error err;
2547
2548 uint64_t allocated_memory = AllocateMemory(8,
2549 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2550 err);
2551
2552 if (err.Success())
2553 m_can_jit = eCanJITYes;
2554 else
2555 m_can_jit = eCanJITNo;
2556
2557 DeallocateMemory (allocated_memory);
2558 }
2559
Sean Callanan6cf6c472011-09-20 23:01:51 +00002560 return m_can_jit == eCanJITYes;
2561}
2562
2563void
2564Process::SetCanJIT (bool can_jit)
2565{
2566 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2567}
2568
Chris Lattner24943d22010-06-08 16:52:24 +00002569Error
2570Process::DeallocateMemory (addr_t ptr)
2571{
Greg Clayton613b8732011-05-17 03:37:42 +00002572 Error error;
2573#if defined (USE_ALLOCATE_MEMORY_CACHE)
2574 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2575 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002576 error.SetErrorStringWithFormat ("deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
Greg Clayton613b8732011-05-17 03:37:42 +00002577 }
2578#else
2579 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002580
2581 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2582 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00002583 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 +00002584 ptr,
2585 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002586 m_mod_id.GetStopID(),
2587 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002588#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002589 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002590}
2591
Han Ming Ong2529aa32012-11-17 00:33:14 +00002592
Greg Claytonb5a8f142012-02-05 02:38:54 +00002593ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002594Process::ReadModuleFromMemory (const FileSpec& file_spec,
2595 lldb::addr_t header_addr,
2596 bool add_image_to_target,
2597 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002598{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002599 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002600 if (module_sp)
2601 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002602 Error error;
2603 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2604 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002605 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002606 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002607 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002608 m_target.GetImages().Append(module_sp);
2609 if (load_sections_in_target)
2610 {
2611 bool changed = false;
2612 module_sp->SetLoadAddress (m_target, 0, changed);
2613 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002614 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002615 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002616 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002617 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002618 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002619}
Chris Lattner24943d22010-06-08 16:52:24 +00002620
2621Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002622Process::EnableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002623{
2624 Error error;
2625 error.SetErrorString("watchpoints are not supported");
2626 return error;
2627}
2628
2629Error
Jim Ingham9c970a32012-12-18 02:03:49 +00002630Process::DisableWatchpoint (Watchpoint *watchpoint, bool notify)
Chris Lattner24943d22010-06-08 16:52:24 +00002631{
2632 Error error;
2633 error.SetErrorString("watchpoints are not supported");
2634 return error;
2635}
2636
2637StateType
2638Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2639{
2640 StateType state;
2641 // Now wait for the process to launch and return control to us, and then
2642 // call DidLaunch:
2643 while (1)
2644 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002645 event_sp.reset();
2646 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2647
Greg Clayton20206082011-11-17 01:23:07 +00002648 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002649 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002650
2651 // If state is invalid, then we timed out
2652 if (state == eStateInvalid)
2653 break;
2654
2655 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002656 HandlePrivateEvent (event_sp);
2657 }
2658 return state;
2659}
2660
2661Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002662Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002663{
2664 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002665 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002666 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002667 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002668 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002669
Greg Clayton5beb99d2011-08-11 02:48:45 +00002670 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002671 if (exe_module)
2672 {
Greg Clayton180546b2011-04-30 01:09:13 +00002673 char local_exec_file_path[PATH_MAX];
2674 char platform_exec_file_path[PATH_MAX];
2675 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2676 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002677 if (exe_module->GetFileSpec().Exists())
2678 {
Greg Claytona2f74232011-02-24 22:24:29 +00002679 if (PrivateStateThreadIsValid ())
2680 PausePrivateStateThread ();
2681
Chris Lattner24943d22010-06-08 16:52:24 +00002682 error = WillLaunch (exe_module);
2683 if (error.Success())
2684 {
Greg Claytond8c62532010-10-07 04:19:01 +00002685 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002686 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002687
Greg Clayton777c6b72012-09-04 20:29:05 +00002688 if (m_run_lock.WriteTryLock())
2689 {
2690 // Now launch using these arguments.
2691 error = DoLaunch (exe_module, launch_info);
2692 }
2693 else
2694 {
2695 // This shouldn't happen
2696 error.SetErrorString("failed to acquire process run lock");
2697 }
Chris Lattner24943d22010-06-08 16:52:24 +00002698
2699 if (error.Fail())
2700 {
2701 if (GetID() != LLDB_INVALID_PROCESS_ID)
2702 {
2703 SetID (LLDB_INVALID_PROCESS_ID);
2704 const char *error_string = error.AsCString();
2705 if (error_string == NULL)
2706 error_string = "launch failed";
2707 SetExitStatus (-1, error_string);
2708 }
2709 }
2710 else
2711 {
2712 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002713 TimeValue timeout_time;
2714 timeout_time = TimeValue::Now();
2715 timeout_time.OffsetWithSeconds(10);
2716 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002717
Greg Clayton49859592011-06-22 01:42:17 +00002718 if (state == eStateInvalid || event_sp.get() == NULL)
2719 {
2720 // We were able to launch the process, but we failed to
2721 // catch the initial stop.
2722 SetExitStatus (0, "failed to catch stop after launch");
2723 Destroy();
2724 }
2725 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002726 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002727
Chris Lattner24943d22010-06-08 16:52:24 +00002728 DidLaunch ();
2729
Greg Clayton9ce95382012-02-13 23:10:39 +00002730 DynamicLoader *dyld = GetDynamicLoader ();
2731 if (dyld)
2732 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002733
Greg Clayton37f962e2011-08-22 02:49:39 +00002734 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002735 // This delays passing the stopped event to listeners till DidLaunch gets
2736 // a chance to complete...
2737 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002738
2739 if (PrivateStateThreadIsValid ())
2740 ResumePrivateStateThread ();
2741 else
2742 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002743 }
2744 else if (state == eStateExited)
2745 {
2746 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2747 // not likely to work, and return an invalid pid.
2748 HandlePrivateEvent (event_sp);
2749 }
2750 }
2751 }
2752 }
2753 else
2754 {
Greg Clayton9c236732011-10-26 00:56:27 +00002755 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002756 }
2757 }
2758 return error;
2759}
2760
Greg Clayton46c9a352012-02-09 06:16:32 +00002761
2762Error
2763Process::LoadCore ()
2764{
2765 Error error = DoLoadCore();
2766 if (error.Success())
2767 {
2768 if (PrivateStateThreadIsValid ())
2769 ResumePrivateStateThread ();
2770 else
2771 StartPrivateStateThread ();
2772
Greg Clayton9ce95382012-02-13 23:10:39 +00002773 DynamicLoader *dyld = GetDynamicLoader ();
2774 if (dyld)
2775 dyld->DidAttach();
2776
2777 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002778 // We successfully loaded a core file, now pretend we stopped so we can
2779 // show all of the threads in the core file and explore the crashed
2780 // state.
2781 SetPrivateState (eStateStopped);
2782
2783 }
2784 return error;
2785}
2786
Greg Clayton9ce95382012-02-13 23:10:39 +00002787DynamicLoader *
2788Process::GetDynamicLoader ()
2789{
2790 if (m_dyld_ap.get() == NULL)
2791 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2792 return m_dyld_ap.get();
2793}
Greg Clayton46c9a352012-02-09 06:16:32 +00002794
2795
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002796Process::NextEventAction::EventActionResult
2797Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002798{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002799 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2800 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002801 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002802 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002803 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002804 return eEventActionRetry;
2805
2806 case eStateStopped:
2807 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002808 {
2809 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002810 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002811 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2812 if (m_exec_count > 0)
2813 {
2814 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002815 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002816 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002817 return eEventActionRetry;
2818 }
2819 else
2820 {
2821 m_process->CompleteAttach ();
2822 return eEventActionSuccess;
2823 }
2824 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002825 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002826
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002827 default:
2828 case eStateExited:
2829 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002830 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002831 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002832
2833 m_exit_string.assign ("No valid Process");
2834 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002835}
Chris Lattner24943d22010-06-08 16:52:24 +00002836
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002837Process::NextEventAction::EventActionResult
2838Process::AttachCompletionHandler::HandleBeingInterrupted()
2839{
2840 return eEventActionSuccess;
2841}
2842
2843const char *
2844Process::AttachCompletionHandler::GetExitString ()
2845{
2846 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002847}
2848
2849Error
Greg Clayton527154d2011-11-15 03:53:30 +00002850Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002851{
Chris Lattner24943d22010-06-08 16:52:24 +00002852 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002853 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002854 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002855 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002856
Greg Clayton527154d2011-11-15 03:53:30 +00002857 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002858 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002859 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002860 {
Greg Clayton527154d2011-11-15 03:53:30 +00002861 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002862
Greg Clayton527154d2011-11-15 03:53:30 +00002863 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002864 {
Greg Clayton527154d2011-11-15 03:53:30 +00002865 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2866
2867 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002868 {
Greg Clayton527154d2011-11-15 03:53:30 +00002869 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2870 if (error.Success())
2871 {
Greg Claytond34a3b22012-10-12 16:10:12 +00002872 if (m_run_lock.WriteTryLock())
2873 {
2874 m_should_detach = true;
2875 SetPublicState (eStateAttaching);
2876 // Now attach using these arguments.
2877 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2878 }
2879 else
2880 {
2881 // This shouldn't happen
2882 error.SetErrorString("failed to acquire process run lock");
2883 }
Greg Claytonffa43a62011-11-17 04:46:02 +00002884
Greg Clayton527154d2011-11-15 03:53:30 +00002885 if (error.Fail())
2886 {
2887 if (GetID() != LLDB_INVALID_PROCESS_ID)
2888 {
2889 SetID (LLDB_INVALID_PROCESS_ID);
2890 if (error.AsCString() == NULL)
2891 error.SetErrorString("attach failed");
2892
2893 SetExitStatus(-1, error.AsCString());
2894 }
2895 }
2896 else
2897 {
2898 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2899 StartPrivateStateThread();
2900 }
2901 return error;
2902 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002903 }
Greg Clayton527154d2011-11-15 03:53:30 +00002904 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002905 {
Greg Clayton527154d2011-11-15 03:53:30 +00002906 ProcessInstanceInfoList process_infos;
2907 PlatformSP platform_sp (m_target.GetPlatform ());
2908
2909 if (platform_sp)
2910 {
2911 ProcessInstanceInfoMatch match_info;
2912 match_info.GetProcessInfo() = attach_info;
2913 match_info.SetNameMatchType (eNameMatchEquals);
2914 platform_sp->FindProcesses (match_info, process_infos);
2915 const uint32_t num_matches = process_infos.GetSize();
2916 if (num_matches == 1)
2917 {
2918 attach_pid = process_infos.GetProcessIDAtIndex(0);
2919 // Fall through and attach using the above process ID
2920 }
2921 else
2922 {
2923 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2924 if (num_matches > 1)
2925 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2926 else
2927 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2928 }
2929 }
2930 else
2931 {
2932 error.SetErrorString ("invalid platform, can't find processes by name");
2933 return error;
2934 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002935 }
Chris Lattner24943d22010-06-08 16:52:24 +00002936 }
2937 else
Greg Clayton527154d2011-11-15 03:53:30 +00002938 {
2939 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002940 }
2941 }
Greg Clayton527154d2011-11-15 03:53:30 +00002942
2943 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002944 {
Greg Clayton527154d2011-11-15 03:53:30 +00002945 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002946 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002947 {
Greg Clayton527154d2011-11-15 03:53:30 +00002948
Greg Claytond34a3b22012-10-12 16:10:12 +00002949 if (m_run_lock.WriteTryLock())
2950 {
2951 // Now attach using these arguments.
2952 m_should_detach = true;
2953 SetPublicState (eStateAttaching);
2954 error = DoAttachToProcessWithID (attach_pid, attach_info);
2955 }
2956 else
2957 {
2958 // This shouldn't happen
2959 error.SetErrorString("failed to acquire process run lock");
2960 }
2961
Greg Clayton527154d2011-11-15 03:53:30 +00002962 if (error.Success())
2963 {
2964
2965 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2966 StartPrivateStateThread();
2967 }
2968 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002969 {
2970 if (GetID() != LLDB_INVALID_PROCESS_ID)
2971 {
2972 SetID (LLDB_INVALID_PROCESS_ID);
2973 const char *error_string = error.AsCString();
2974 if (error_string == NULL)
2975 error_string = "attach failed";
2976
2977 SetExitStatus(-1, error_string);
2978 }
2979 }
Chris Lattner24943d22010-06-08 16:52:24 +00002980 }
2981 }
2982 return error;
2983}
2984
Greg Clayton75c703d2011-02-16 04:46:07 +00002985void
2986Process::CompleteAttach ()
2987{
2988 // Let the process subclass figure out at much as it can about the process
2989 // before we go looking for a dynamic loader plug-in.
2990 DidAttach();
2991
Jim Ingham0d7f7772011-09-15 01:10:17 +00002992 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2993 // the same as the one we've already set, switch architectures.
2994 PlatformSP platform_sp (m_target.GetPlatform ());
2995 assert (platform_sp.get());
2996 if (platform_sp)
2997 {
Greg Claytonb170aee2012-05-08 01:45:38 +00002998 const ArchSpec &target_arch = m_target.GetArchitecture();
2999 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
3000 {
3001 ArchSpec platform_arch;
3002 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
3003 if (platform_sp)
3004 {
3005 m_target.SetPlatform (platform_sp);
3006 m_target.SetArchitecture(platform_arch);
3007 }
3008 }
3009 else
3010 {
3011 ProcessInstanceInfo process_info;
3012 platform_sp->GetProcessInfo (GetID(), process_info);
3013 const ArchSpec &process_arch = process_info.GetArchitecture();
Sean Callanan40e278c2012-12-13 22:07:14 +00003014 if (process_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(process_arch))
Greg Claytonb170aee2012-05-08 01:45:38 +00003015 m_target.SetArchitecture (process_arch);
3016 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00003017 }
3018
3019 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00003020 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00003021 DynamicLoader *dyld = GetDynamicLoader ();
3022 if (dyld)
3023 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00003024
Greg Clayton37f962e2011-08-22 02:49:39 +00003025 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00003026 // Figure out which one is the executable, and set that in our target:
Enrico Granata146d9522012-11-08 02:22:02 +00003027 const ModuleList &target_modules = m_target.GetImages();
Jim Ingham93367902012-05-30 02:19:25 +00003028 Mutex::Locker modules_locker(target_modules.GetMutex());
3029 size_t num_modules = target_modules.GetSize();
3030 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003031
Greg Clayton75c703d2011-02-16 04:46:07 +00003032 for (int i = 0; i < num_modules; i++)
3033 {
Jim Ingham93367902012-05-30 02:19:25 +00003034 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00003035 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00003036 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00003037 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00003038 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00003039 break;
3040 }
3041 }
Jim Ingham93367902012-05-30 02:19:25 +00003042 if (new_executable_module_sp)
3043 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00003044}
3045
Chris Lattner24943d22010-06-08 16:52:24 +00003046Error
Jason Molendafac2e622012-09-29 04:02:01 +00003047Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00003048{
Greg Claytone71e2582011-02-04 01:58:07 +00003049 m_abi_sp.reset();
3050 m_process_input_reader.reset();
3051
3052 // Find the process and its architecture. Make sure it matches the architecture
3053 // of the current Target, and if not adjust it.
3054
Jason Molendafac2e622012-09-29 04:02:01 +00003055 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00003056 if (error.Success())
3057 {
Greg Claytona2f74232011-02-24 22:24:29 +00003058 if (GetID() != LLDB_INVALID_PROCESS_ID)
3059 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00003060 EventSP event_sp;
3061 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
3062
3063 if (state == eStateStopped || state == eStateCrashed)
3064 {
3065 // If we attached and actually have a process on the other end, then
3066 // this ended up being the equivalent of an attach.
3067 CompleteAttach ();
3068
3069 // This delays passing the stopped event to listeners till
3070 // CompleteAttach gets a chance to complete...
3071 HandlePrivateEvent (event_sp);
3072
3073 }
Greg Claytona2f74232011-02-24 22:24:29 +00003074 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00003075
3076 if (PrivateStateThreadIsValid ())
3077 ResumePrivateStateThread ();
3078 else
3079 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00003080 }
3081 return error;
3082}
3083
3084
3085Error
Jim Ingham027aaa72012-04-19 01:40:33 +00003086Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00003087{
Jim Inghame1a654b2012-09-06 19:24:17 +00003088 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00003089 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00003090 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00003091 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00003092 StateAsCString(m_public_state.GetValue()),
3093 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00003094
3095 Error error (WillResume());
3096 // Tell the process it is about to resume before the thread list
3097 if (error.Success())
3098 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003099 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003100 // can let all of our threads know that they are about to be
3101 // resumed. Threads will each be called with
3102 // Thread::WillResume(StateType) where StateType contains the state
3103 // that they are supposed to have when the process is resumed
3104 // (suspended/running/stepping). Threads should also check
3105 // their resume signal in lldb::Thread::GetResumeSignal()
3106 // to see if they are suppoed to start back up with a signal.
3107 if (m_thread_list.WillResume())
3108 {
Jim Ingham1831e782012-04-07 00:00:41 +00003109 // Last thing, do the PreResumeActions.
3110 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003111 {
Jim Ingham1831e782012-04-07 00:00:41 +00003112 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3113 }
3114 else
3115 {
3116 m_mod_id.BumpResumeID();
3117 error = DoResume();
3118 if (error.Success())
3119 {
3120 DidResume();
3121 m_thread_list.DidResume();
3122 if (log)
3123 log->Printf ("Process thinks the process has resumed.");
3124 }
Chris Lattner24943d22010-06-08 16:52:24 +00003125 }
3126 }
3127 else
3128 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003129 // Somebody wanted to run without running. So generate a continue & a stopped event,
3130 // and let the world handle them.
3131 if (log)
3132 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3133
3134 SetPrivateState(eStateRunning);
3135 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003136 }
3137 }
Jim Inghamac959662011-01-24 06:34:17 +00003138 else if (log)
3139 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003140 return error;
3141}
3142
3143Error
3144Process::Halt ()
3145{
Jim Ingham43892562012-06-06 00:29:30 +00003146 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3147 // we could just straightaway get another event. It just narrows the window...
3148 m_currently_handling_event.WaitForValueEqualTo(false);
3149
3150
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003151 // Pause our private state thread so we can ensure no one else eats
3152 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003153 Listener halt_listener ("lldb.process.halt_listener");
3154 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003155
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003156 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003157 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003158
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003159 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003160 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003161
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003162 bool caused_stop = false;
3163
3164 // Ask the process subclass to actually halt our process
3165 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003166 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003167 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003168 if (m_public_state.GetValue() == eStateAttaching)
3169 {
3170 SetExitStatus(SIGKILL, "Cancelled async attach.");
3171 Destroy ();
3172 }
3173 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003174 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003175 // If "caused_stop" is true, then DoHalt stopped the process. If
3176 // "caused_stop" is false, the process was already stopped.
3177 // If the DoHalt caused the process to stop, then we want to catch
3178 // this event and set the interrupted bool to true before we pass
3179 // this along so clients know that the process was interrupted by
3180 // a halt command.
3181 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003182 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003183 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003184 TimeValue timeout_time;
3185 timeout_time = TimeValue::Now();
3186 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003187 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3188 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003189
Jim Inghamf9f40c22011-02-08 05:20:59 +00003190 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003191 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003192 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003193 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003194 }
3195 else
3196 {
Greg Clayton20206082011-11-17 01:23:07 +00003197 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003198 {
3199 // We caused the process to interrupt itself, so mark this
3200 // as such in the stop event so clients can tell an interrupted
3201 // process from a natural stop
3202 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3203 }
3204 else
3205 {
3206 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3207 if (log)
3208 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3209 error.SetErrorString ("Did not get stopped event after halt.");
3210 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003211 }
3212 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003213 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003214 }
3215 }
Chris Lattner24943d22010-06-08 16:52:24 +00003216 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003217 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003218 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003219
3220 // Post any event we might have consumed. If all goes well, we will have
3221 // stopped the process, intercepted the event and set the interrupted
3222 // bool in the event. Post it to the private event queue and that will end up
3223 // correctly setting the state.
3224 if (event_sp)
3225 m_private_state_broadcaster.BroadcastEvent(event_sp);
3226
Chris Lattner24943d22010-06-08 16:52:24 +00003227 return error;
3228}
3229
3230Error
3231Process::Detach ()
3232{
3233 Error error (WillDetach());
3234
3235 if (error.Success())
3236 {
3237 DisableAllBreakpointSites();
3238 error = DoDetach();
3239 if (error.Success())
3240 {
3241 DidDetach();
3242 StopPrivateStateThread();
3243 }
3244 }
3245 return error;
3246}
3247
3248Error
3249Process::Destroy ()
3250{
3251 Error error (WillDestroy());
3252 if (error.Success())
3253 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003254 EventSP exit_event_sp;
Jim Inghamf4928de2012-05-23 15:46:31 +00003255 if (m_public_state.GetValue() == eStateRunning)
3256 {
Greg Clayton38ae5b92012-09-05 00:37:58 +00003257 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003258 if (log)
3259 log->Printf("Process::Destroy() About to halt.");
Jim Inghamf4928de2012-05-23 15:46:31 +00003260 error = Halt();
3261 if (error.Success())
3262 {
3263 // Consume the halt event.
Jim Inghamf4928de2012-05-23 15:46:31 +00003264 TimeValue timeout (TimeValue::Now());
Jim Ingham43892562012-06-06 00:29:30 +00003265 timeout.OffsetWithSeconds(1);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003266 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3267 if (state != eStateExited)
3268 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3269
Jim Inghamf4928de2012-05-23 15:46:31 +00003270 if (state != eStateStopped)
3271 {
Jim Inghamf4928de2012-05-23 15:46:31 +00003272 if (log)
3273 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Ingham43892562012-06-06 00:29:30 +00003274 // If we really couldn't stop the process then we should just error out here, but if the
3275 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3276 StateType private_state = m_private_state.GetValue();
3277 if (private_state != eStateStopped && private_state != eStateExited)
3278 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003279 // If we exited when we were waiting for a process to stop, then
3280 // forward the event here so we don't lose the event
Jim Ingham43892562012-06-06 00:29:30 +00003281 return error;
3282 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003283 }
3284 }
3285 else
3286 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003287 if (log)
3288 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3289 return error;
Jim Inghamf4928de2012-05-23 15:46:31 +00003290 }
3291 }
Jim Ingham43892562012-06-06 00:29:30 +00003292
3293 if (m_public_state.GetValue() != eStateRunning)
3294 {
3295 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3296 // kill it, we don't want it hitting a breakpoint...
3297 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3298 // we're not going to have much luck doing this now.
3299 m_thread_list.DiscardThreadPlans();
3300 DisableAllBreakpointSites();
3301 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003302
Chris Lattner24943d22010-06-08 16:52:24 +00003303 error = DoDestroy();
3304 if (error.Success())
3305 {
3306 DidDestroy();
3307 StopPrivateStateThread();
3308 }
Caroline Tice861efb32010-11-16 05:07:41 +00003309 m_stdio_communication.StopReadThread();
3310 m_stdio_communication.Disconnect();
3311 if (m_process_input_reader && m_process_input_reader->IsActive())
3312 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3313 if (m_process_input_reader)
3314 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003315
3316 // If we exited when we were waiting for a process to stop, then
3317 // forward the event here so we don't lose the event
3318 if (exit_event_sp)
3319 {
3320 // Directly broadcast our exited event because we shut down our
3321 // private state thread above
3322 BroadcastEvent(exit_event_sp);
3323 }
3324
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003325 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3326 // the last events through the event system, in which case we might strand the write lock. Unlock
3327 // it here so when we do to tear down the process we don't get an error destroying the lock.
3328 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003329 }
3330 return error;
3331}
3332
3333Error
3334Process::Signal (int signal)
3335{
3336 Error error (WillSignal());
3337 if (error.Success())
3338 {
3339 error = DoSignal(signal);
3340 if (error.Success())
3341 DidSignal();
3342 }
3343 return error;
3344}
3345
Greg Clayton395fc332011-02-15 21:59:32 +00003346lldb::ByteOrder
3347Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003348{
Greg Clayton395fc332011-02-15 21:59:32 +00003349 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003350}
3351
3352uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003353Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003354{
Greg Clayton395fc332011-02-15 21:59:32 +00003355 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003356}
3357
Greg Clayton395fc332011-02-15 21:59:32 +00003358
Chris Lattner24943d22010-06-08 16:52:24 +00003359bool
3360Process::ShouldBroadcastEvent (Event *event_ptr)
3361{
3362 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3363 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00003364 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003365
3366 switch (state)
3367 {
Greg Claytone71e2582011-02-04 01:58:07 +00003368 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003369 case eStateAttaching:
3370 case eStateLaunching:
3371 case eStateDetached:
3372 case eStateExited:
3373 case eStateUnloaded:
3374 // These events indicate changes in the state of the debugging session, always report them.
3375 return_value = true;
3376 break;
3377 case eStateInvalid:
3378 // We stopped for no apparent reason, don't report it.
3379 return_value = false;
3380 break;
3381 case eStateRunning:
3382 case eStateStepping:
3383 // If we've started the target running, we handle the cases where we
3384 // are already running and where there is a transition from stopped to
3385 // running differently.
3386 // running -> running: Automatically suppress extra running events
3387 // stopped -> running: Report except when there is one or more no votes
3388 // and no yes votes.
3389 SynchronouslyNotifyStateChanged (state);
3390 switch (m_public_state.GetValue())
3391 {
3392 case eStateRunning:
3393 case eStateStepping:
3394 // We always suppress multiple runnings with no PUBLIC stop in between.
3395 return_value = false;
3396 break;
3397 default:
3398 // TODO: make this work correctly. For now always report
3399 // run if we aren't running so we don't miss any runnning
3400 // events. If I run the lldb/test/thread/a.out file and
3401 // break at main.cpp:58, run and hit the breakpoints on
3402 // multiple threads, then somehow during the stepping over
3403 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003404
3405 // This is a transition from stop to run.
3406 switch (m_thread_list.ShouldReportRun (event_ptr))
3407 {
3408 case eVoteYes:
3409 case eVoteNoOpinion:
3410 return_value = true;
3411 break;
3412 case eVoteNo:
3413 return_value = false;
3414 break;
3415 }
3416 break;
3417 }
3418 break;
3419 case eStateStopped:
3420 case eStateCrashed:
3421 case eStateSuspended:
3422 {
3423 // We've stopped. First see if we're going to restart the target.
3424 // If we are going to stop, then we always broadcast the event.
3425 // 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 +00003426 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003427
3428 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003429 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003430 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003431 if (log)
3432 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003433 return true;
3434 }
3435 else
3436 {
Chris Lattner24943d22010-06-08 16:52:24 +00003437
3438 if (m_thread_list.ShouldStop (event_ptr) == false)
3439 {
Jim Ingham8290bba2012-09-05 21:13:56 +00003440 // ShouldStop may have restarted the target already. If so, don't
3441 // resume it twice.
3442 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00003443 switch (m_thread_list.ShouldReportStop (event_ptr))
3444 {
3445 case eVoteYes:
3446 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003447 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003448 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003449 case eVoteNo:
3450 return_value = false;
3451 break;
3452 }
3453
3454 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003455 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham8290bba2012-09-05 21:13:56 +00003456 if (!was_restarted)
3457 PrivateResume ();
Chris Lattner24943d22010-06-08 16:52:24 +00003458 }
3459 else
3460 {
3461 return_value = true;
3462 SynchronouslyNotifyStateChanged (state);
3463 }
3464 }
3465 }
3466 }
3467
3468 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003469 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003470 return return_value;
3471}
3472
Chris Lattner24943d22010-06-08 16:52:24 +00003473
3474bool
Jim Ingham1831e782012-04-07 00:00:41 +00003475Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003476{
Greg Claytone005f2c2010-11-06 01:53:30 +00003477 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003478
Greg Claytonb72d0f02011-04-12 05:54:46 +00003479 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003480 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003481 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3482
Jim Ingham1831e782012-04-07 00:00:41 +00003483 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003484 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003485
3486 // Create a thread that watches our internal state and controls which
3487 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003488 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003489 if (already_running)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003490 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%" PRIu64 ")>", GetID());
Jim Ingham1831e782012-04-07 00:00:41 +00003491 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003492 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003493
3494 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003495 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003496 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3497 if (success)
3498 {
3499 ResumePrivateStateThread();
3500 return true;
3501 }
3502 else
3503 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003504}
3505
3506void
3507Process::PausePrivateStateThread ()
3508{
3509 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3510}
3511
3512void
3513Process::ResumePrivateStateThread ()
3514{
3515 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3516}
3517
3518void
3519Process::StopPrivateStateThread ()
3520{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003521 if (PrivateStateThreadIsValid ())
3522 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003523 else
3524 {
3525 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3526 if (log)
3527 printf ("Went to stop the private state thread, but it was already invalid.");
3528 }
Chris Lattner24943d22010-06-08 16:52:24 +00003529}
3530
3531void
3532Process::ControlPrivateStateThread (uint32_t signal)
3533{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003534 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003535
3536 assert (signal == eBroadcastInternalStateControlStop ||
3537 signal == eBroadcastInternalStateControlPause ||
3538 signal == eBroadcastInternalStateControlResume);
3539
3540 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003541 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003542
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003543 // Signal the private state thread. First we should copy this is case the
3544 // thread starts exiting since the private state thread will NULL this out
3545 // when it exits
3546 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003547 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003548 {
3549 TimeValue timeout_time;
3550 bool timed_out;
3551
3552 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3553
3554 timeout_time = TimeValue::Now();
3555 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003556 if (log)
3557 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003558 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3559 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3560
3561 if (signal == eBroadcastInternalStateControlStop)
3562 {
3563 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003564 {
3565 Error error;
3566 Host::ThreadCancel (private_state_thread, &error);
3567 if (log)
3568 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3569 }
3570 else
3571 {
3572 if (log)
3573 log->Printf ("The control event killed the private state thread without having to cancel.");
3574 }
Chris Lattner24943d22010-06-08 16:52:24 +00003575
3576 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003577 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003578 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003579 }
3580 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003581 else
3582 {
3583 if (log)
3584 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3585 }
Chris Lattner24943d22010-06-08 16:52:24 +00003586}
3587
3588void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003589Process::SendAsyncInterrupt ()
3590{
3591 if (PrivateStateThreadIsValid())
3592 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3593 else
3594 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3595}
3596
3597void
Chris Lattner24943d22010-06-08 16:52:24 +00003598Process::HandlePrivateEvent (EventSP &event_sp)
3599{
Greg Claytone005f2c2010-11-06 01:53:30 +00003600 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003601 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003602
Greg Clayton68ca8232011-01-25 02:58:48 +00003603 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003604
3605 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003606 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003607 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003608 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003609 switch (action_result)
3610 {
3611 case NextEventAction::eEventActionSuccess:
3612 SetNextEventAction(NULL);
3613 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003614
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003615 case NextEventAction::eEventActionRetry:
3616 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003617
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003618 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003619 // Handle Exiting Here. If we already got an exited event,
3620 // we should just propagate it. Otherwise, swallow this event,
3621 // and set our state to exit so the next event will kill us.
3622 if (new_state != eStateExited)
3623 {
3624 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003625 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003626 SetNextEventAction(NULL);
3627 return;
3628 }
3629 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003630 break;
3631 }
3632 }
3633
Chris Lattner24943d22010-06-08 16:52:24 +00003634 // See if we should broadcast this state to external clients?
3635 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003636
3637 if (should_broadcast)
3638 {
3639 if (log)
3640 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003641 log->Printf ("Process::%s (pid = %" PRIu64 ") broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003642 __FUNCTION__,
3643 GetID(),
3644 StateAsCString(new_state),
3645 StateAsCString (GetState ()),
3646 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003647 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003648 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003649 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003650 PushProcessInputReader ();
3651 else
3652 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003653
Chris Lattner24943d22010-06-08 16:52:24 +00003654 BroadcastEvent (event_sp);
3655 }
3656 else
3657 {
3658 if (log)
3659 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003660 log->Printf ("Process::%s (pid = %" PRIu64 ") suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003661 __FUNCTION__,
3662 GetID(),
3663 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003664 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003665 }
3666 }
Jim Ingham43892562012-06-06 00:29:30 +00003667 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003668}
3669
3670void *
3671Process::PrivateStateThread (void *arg)
3672{
3673 Process *proc = static_cast<Process*> (arg);
3674 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003675 return result;
3676}
3677
3678void *
3679Process::RunPrivateStateThread ()
3680{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003681 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003682 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003683
Greg Claytone005f2c2010-11-06 01:53:30 +00003684 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003685 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003686 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003687
3688 bool exit_now = false;
3689 while (!exit_now)
3690 {
3691 EventSP event_sp;
3692 WaitForEventsPrivate (NULL, event_sp, control_only);
3693 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3694 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003695 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003696 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 +00003697
Chris Lattner24943d22010-06-08 16:52:24 +00003698 switch (event_sp->GetType())
3699 {
3700 case eBroadcastInternalStateControlStop:
3701 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003702 break; // doing any internal state managment below
3703
3704 case eBroadcastInternalStateControlPause:
3705 control_only = true;
3706 break;
3707
3708 case eBroadcastInternalStateControlResume:
3709 control_only = false;
3710 break;
3711 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003712
Chris Lattner24943d22010-06-08 16:52:24 +00003713 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003714 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003715 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003716 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3717 {
3718 if (m_public_state.GetValue() == eStateAttaching)
3719 {
3720 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003721 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 +00003722 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3723 }
3724 else
3725 {
3726 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003727 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00003728 Halt();
3729 }
3730 continue;
3731 }
Chris Lattner24943d22010-06-08 16:52:24 +00003732
3733 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3734
3735 if (internal_state != eStateInvalid)
3736 {
3737 HandlePrivateEvent (event_sp);
3738 }
3739
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003740 if (internal_state == eStateInvalid ||
3741 internal_state == eStateExited ||
3742 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003743 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003744 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003745 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 +00003746
Chris Lattner24943d22010-06-08 16:52:24 +00003747 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003748 }
Chris Lattner24943d22010-06-08 16:52:24 +00003749 }
3750
Caroline Tice926060e2010-10-29 21:48:37 +00003751 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003752 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003753 log->Printf ("Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003754
Greg Claytona4881d02011-01-22 07:12:45 +00003755 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3756 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003757 return NULL;
3758}
3759
Chris Lattner24943d22010-06-08 16:52:24 +00003760//------------------------------------------------------------------
3761// Process Event Data
3762//------------------------------------------------------------------
3763
3764Process::ProcessEventData::ProcessEventData () :
3765 EventData (),
3766 m_process_sp (),
3767 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003768 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003769 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003770 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003771{
3772}
3773
3774Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3775 EventData (),
3776 m_process_sp (process_sp),
3777 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003778 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003779 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003780 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003781{
3782}
3783
3784Process::ProcessEventData::~ProcessEventData()
3785{
3786}
3787
3788const ConstString &
3789Process::ProcessEventData::GetFlavorString ()
3790{
3791 static ConstString g_flavor ("Process::ProcessEventData");
3792 return g_flavor;
3793}
3794
3795const ConstString &
3796Process::ProcessEventData::GetFlavor () const
3797{
3798 return ProcessEventData::GetFlavorString ();
3799}
3800
Chris Lattner24943d22010-06-08 16:52:24 +00003801void
3802Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3803{
3804 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003805 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3806 // the public event queue, then other times when we're pretending that this is where we stopped at the
3807 // end of expression evaluation. m_update_state is used to distinguish these
3808 // three cases; it is 0 when we're just pulling it off for private handling,
3809 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003810
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003811 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003812 return;
3813
3814 m_process_sp->SetPublicState (m_state);
3815
3816 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3817 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003818 {
3819 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003820 uint32_t num_threads = curr_thread_list.GetSize();
3821 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003822
Jim Ingham21f37ad2011-08-09 02:12:22 +00003823 // The actions might change one of the thread's stop_info's opinions about whether we should
3824 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003825
3826 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3827 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3828 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3829 // 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
3830 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003831 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003832 for (idx = 0; idx < num_threads; ++idx)
3833 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3834
Jim Inghamb6059b22012-12-13 22:24:15 +00003835 // Use this to track whether we should continue from here. We will only continue the target running if
3836 // no thread says we should stop. Of course if some thread's PerformAction actually sets the target running,
3837 // then it doesn't matter what the other threads say...
3838
3839 bool still_should_stop = false;
Jim Ingham21f37ad2011-08-09 02:12:22 +00003840
Chris Lattner24943d22010-06-08 16:52:24 +00003841 for (idx = 0; idx < num_threads; ++idx)
3842 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003843 curr_thread_list = m_process_sp->GetThreadList();
3844 if (curr_thread_list.GetSize() != num_threads)
3845 {
3846 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003847 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003848 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 +00003849 break;
3850 }
3851
3852 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3853
3854 if (thread_sp->GetIndexID() != thread_index_array[idx])
3855 {
3856 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003857 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003858 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003859 idx,
3860 thread_index_array[idx],
3861 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003862 break;
3863 }
3864
Jim Ingham6297a3a2010-10-20 00:39:53 +00003865 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00003866 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00003867 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003868 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003869 // The stop action might restart the target. If it does, then we want to mark that in the
3870 // event so that whoever is receiving it will know to wait for the running event and reflect
3871 // that state appropriately.
3872 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003873
3874 // FIXME: we might have run.
3875 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003876 {
3877 SetRestarted (true);
3878 break;
3879 }
Jim Inghamb6059b22012-12-13 22:24:15 +00003880
3881 bool this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
3882 if (still_should_stop == false)
3883 still_should_stop = this_thread_wants_to_stop;
Chris Lattner24943d22010-06-08 16:52:24 +00003884 }
3885 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003886
Jim Ingham21f37ad2011-08-09 02:12:22 +00003887
3888 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003889 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003890 if (!still_should_stop)
3891 {
3892 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003893 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00003894 // Use the public resume method here, since this is just
3895 // extending a public resume.
Jim Ingham21f37ad2011-08-09 02:12:22 +00003896 m_process_sp->Resume();
3897 }
3898 else
3899 {
3900 // If we didn't restart, run the Stop Hooks here:
3901 // They might also restart the target, so watch for that.
3902 m_process_sp->GetTarget().RunStopHooks();
3903 if (m_process_sp->GetPrivateState() == eStateRunning)
3904 SetRestarted(true);
3905 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003906 }
3907
Chris Lattner24943d22010-06-08 16:52:24 +00003908 }
3909}
3910
3911void
3912Process::ProcessEventData::Dump (Stream *s) const
3913{
3914 if (m_process_sp)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00003915 s->Printf(" process = %p (pid = %" PRIu64 "), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003916
Greg Claytonb72d0f02011-04-12 05:54:46 +00003917 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003918}
3919
3920const Process::ProcessEventData *
3921Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3922{
3923 if (event_ptr)
3924 {
3925 const EventData *event_data = event_ptr->GetData();
3926 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3927 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3928 }
3929 return NULL;
3930}
3931
3932ProcessSP
3933Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3934{
3935 ProcessSP process_sp;
3936 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3937 if (data)
3938 process_sp = data->GetProcessSP();
3939 return process_sp;
3940}
3941
3942StateType
3943Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3944{
3945 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3946 if (data == NULL)
3947 return eStateInvalid;
3948 else
3949 return data->GetState();
3950}
3951
3952bool
3953Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3954{
3955 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3956 if (data == NULL)
3957 return false;
3958 else
3959 return data->GetRestarted();
3960}
3961
3962void
3963Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3964{
3965 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3966 if (data != NULL)
3967 data->SetRestarted(new_value);
3968}
3969
3970bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003971Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3972{
3973 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3974 if (data == NULL)
3975 return false;
3976 else
3977 return data->GetInterrupted ();
3978}
3979
3980void
3981Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3982{
3983 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3984 if (data != NULL)
3985 data->SetInterrupted(new_value);
3986}
3987
3988bool
Chris Lattner24943d22010-06-08 16:52:24 +00003989Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3990{
3991 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3992 if (data)
3993 {
3994 data->SetUpdateStateOnRemoval();
3995 return true;
3996 }
3997 return false;
3998}
3999
Greg Clayton289afcb2012-02-18 05:35:26 +00004000lldb::TargetSP
4001Process::CalculateTarget ()
4002{
4003 return m_target.shared_from_this();
4004}
4005
Chris Lattner24943d22010-06-08 16:52:24 +00004006void
Greg Claytona830adb2010-10-04 01:05:56 +00004007Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00004008{
Greg Clayton567e7f32011-09-22 04:58:26 +00004009 exe_ctx.SetTargetPtr (&m_target);
4010 exe_ctx.SetProcessPtr (this);
4011 exe_ctx.SetThreadPtr(NULL);
4012 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00004013}
4014
Greg Claytone4b9c1f2011-03-08 22:40:15 +00004015//uint32_t
4016//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
4017//{
4018// return 0;
4019//}
4020//
4021//ArchSpec
4022//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4023//{
4024// return Host::GetArchSpecForExistingProcess (pid);
4025//}
4026//
4027//ArchSpec
4028//Process::GetArchSpecForExistingProcess (const char *process_name)
4029//{
4030// return Host::GetArchSpecForExistingProcess (process_name);
4031//}
4032//
Caroline Tice861efb32010-11-16 05:07:41 +00004033void
4034Process::AppendSTDOUT (const char * s, size_t len)
4035{
Greg Clayton20d338f2010-11-18 05:57:03 +00004036 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00004037 m_stdout_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004038 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (shared_from_this(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00004039}
4040
4041void
Greg Claytonbd06ff42011-11-13 04:45:22 +00004042Process::AppendSTDERR (const char * s, size_t len)
4043{
4044 Mutex::Locker locker (m_stdio_communication_mutex);
4045 m_stderr_data.append (s, len);
Greg Clayton84332782012-10-29 20:52:08 +00004046 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (shared_from_this(), GetState()));
Greg Claytonbd06ff42011-11-13 04:45:22 +00004047}
4048
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004049void
4050Process::BroadcastAsyncProfileData(const char *s, size_t len)
4051{
4052 Mutex::Locker locker (m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004053 m_profile_data.push_back(s);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004054 BroadcastEventIfUnique (eBroadcastBitProfileData, new ProcessEventData (shared_from_this(), GetState()));
4055}
4056
4057size_t
4058Process::GetAsyncProfileData (char *buf, size_t buf_size, Error &error)
4059{
4060 Mutex::Locker locker(m_profile_data_comm_mutex);
Han Ming Ongf14269a2012-11-29 22:14:45 +00004061 if (m_profile_data.empty())
4062 return 0;
4063
4064 size_t bytes_available = m_profile_data.front().size();
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004065 if (bytes_available > 0)
4066 {
4067 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4068 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004069 log->Printf ("Process::GetProfileData (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004070 if (bytes_available > buf_size)
4071 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004072 memcpy(buf, m_profile_data.front().data(), buf_size);
4073 m_profile_data.front().erase(0, buf_size);
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004074 bytes_available = buf_size;
4075 }
4076 else
4077 {
Han Ming Ongf14269a2012-11-29 22:14:45 +00004078 memcpy(buf, m_profile_data.front().data(), bytes_available);
4079 m_profile_data.erase(m_profile_data.begin());
Han Ming Ongfb9cee62012-11-17 00:21:04 +00004080 }
4081 }
4082 return bytes_available;
4083}
4084
4085
Greg Claytonbd06ff42011-11-13 04:45:22 +00004086//------------------------------------------------------------------
4087// Process STDIO
4088//------------------------------------------------------------------
4089
4090size_t
4091Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
4092{
4093 Mutex::Locker locker(m_stdio_communication_mutex);
4094 size_t bytes_available = m_stdout_data.size();
4095 if (bytes_available > 0)
4096 {
4097 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4098 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004099 log->Printf ("Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004100 if (bytes_available > buf_size)
4101 {
4102 memcpy(buf, m_stdout_data.c_str(), buf_size);
4103 m_stdout_data.erase(0, buf_size);
4104 bytes_available = buf_size;
4105 }
4106 else
4107 {
4108 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4109 m_stdout_data.clear();
4110 }
4111 }
4112 return bytes_available;
4113}
4114
4115
4116size_t
4117Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
4118{
4119 Mutex::Locker locker(m_stdio_communication_mutex);
4120 size_t bytes_available = m_stderr_data.size();
4121 if (bytes_available > 0)
4122 {
4123 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
4124 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004125 log->Printf ("Process::GetSTDERR (buf = %p, size = %" PRIu64 ")", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00004126 if (bytes_available > buf_size)
4127 {
4128 memcpy(buf, m_stderr_data.c_str(), buf_size);
4129 m_stderr_data.erase(0, buf_size);
4130 bytes_available = buf_size;
4131 }
4132 else
4133 {
4134 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4135 m_stderr_data.clear();
4136 }
4137 }
4138 return bytes_available;
4139}
4140
4141void
Caroline Tice861efb32010-11-16 05:07:41 +00004142Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4143{
4144 Process *process = (Process *) baton;
4145 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4146}
4147
4148size_t
4149Process::ProcessInputReaderCallback (void *baton,
4150 InputReader &reader,
4151 lldb::InputReaderAction notification,
4152 const char *bytes,
4153 size_t bytes_len)
4154{
4155 Process *process = (Process *) baton;
4156
4157 switch (notification)
4158 {
4159 case eInputReaderActivate:
4160 break;
4161
4162 case eInputReaderDeactivate:
4163 break;
4164
4165 case eInputReaderReactivate:
4166 break;
4167
Caroline Tice4a348082011-05-02 20:41:46 +00004168 case eInputReaderAsynchronousOutputWritten:
4169 break;
4170
Caroline Tice861efb32010-11-16 05:07:41 +00004171 case eInputReaderGotToken:
4172 {
4173 Error error;
4174 process->PutSTDIN (bytes, bytes_len, error);
4175 }
4176 break;
4177
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004178 case eInputReaderInterrupt:
4179 process->Halt ();
4180 break;
4181
4182 case eInputReaderEndOfFile:
4183 process->AppendSTDOUT ("^D", 2);
4184 break;
4185
Caroline Tice861efb32010-11-16 05:07:41 +00004186 case eInputReaderDone:
4187 break;
4188
4189 }
4190
4191 return bytes_len;
4192}
4193
4194void
4195Process::ResetProcessInputReader ()
4196{
4197 m_process_input_reader.reset();
4198}
4199
4200void
Greg Clayton464c6162011-11-17 22:14:31 +00004201Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004202{
4203 // First set up the Read Thread for reading/handling process I/O
4204
4205 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4206
4207 if (conn_ap.get())
4208 {
4209 m_stdio_communication.SetConnection (conn_ap.release());
4210 if (m_stdio_communication.IsConnected())
4211 {
4212 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4213 m_stdio_communication.StartReadThread();
4214
4215 // Now read thread is set up, set up input reader.
4216
4217 if (!m_process_input_reader.get())
4218 {
4219 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4220 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4221 this,
4222 eInputReaderGranularityByte,
4223 NULL,
4224 NULL,
4225 false));
4226
4227 if (err.Fail())
4228 m_process_input_reader.reset();
4229 }
4230 }
4231 }
4232}
4233
4234void
4235Process::PushProcessInputReader ()
4236{
4237 if (m_process_input_reader && !m_process_input_reader->IsActive())
4238 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4239}
4240
4241void
4242Process::PopProcessInputReader ()
4243{
4244 if (m_process_input_reader && m_process_input_reader->IsActive())
4245 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4246}
4247
Greg Claytond284b662011-02-18 01:44:25 +00004248// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004249void
Caroline Tice2a456812011-03-10 22:14:10 +00004250Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004251{
Greg Clayton73844aa2012-08-22 17:17:09 +00004252// static std::vector<OptionEnumValueElement> g_plugins;
4253//
4254// int i=0;
4255// const char *name;
4256// OptionEnumValueElement option_enum;
4257// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4258// {
4259// if (name)
4260// {
4261// option_enum.value = i;
4262// option_enum.string_value = name;
4263// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4264// g_plugins.push_back (option_enum);
4265// }
4266// ++i;
4267// }
4268// option_enum.value = 0;
4269// option_enum.string_value = NULL;
4270// option_enum.usage = NULL;
4271// g_plugins.push_back (option_enum);
4272//
4273// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4274// {
4275// if (::strcmp (name, "plugin") == 0)
4276// {
4277// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4278// break;
4279// }
4280// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004281//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004282 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004283}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004284
Greg Clayton990de7b2010-11-18 23:32:35 +00004285void
Caroline Tice2a456812011-03-10 22:14:10 +00004286Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004287{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004288 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004289}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004290
Greg Clayton427f2902010-12-14 02:59:59 +00004291ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004292Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004293 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004294 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004295 bool run_others,
Jim Ingham360f53f2010-11-30 02:22:11 +00004296 bool discard_on_error,
Jim Ingham47beabb2012-10-16 21:41:58 +00004297 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004298 Stream &errors)
4299{
4300 ExecutionResults return_value = eExecutionSetupError;
4301
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004302 if (thread_plan_sp.get() == NULL)
4303 {
4304 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004305 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004306 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004307
4308 if (exe_ctx.GetProcessPtr() != this)
4309 {
4310 errors.Printf("RunThreadPlan called on wrong process.");
4311 return eExecutionSetupError;
4312 }
4313
4314 Thread *thread = exe_ctx.GetThreadPtr();
4315 if (thread == NULL)
4316 {
4317 errors.Printf("RunThreadPlan called with invalid thread.");
4318 return eExecutionSetupError;
4319 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004320
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004321 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4322 // For that to be true the plan can't be private - since private plans suppress themselves in the
4323 // GetCompletedPlan call.
4324
4325 bool orig_plan_private = thread_plan_sp->GetPrivate();
4326 thread_plan_sp->SetPrivate(false);
4327
Jim Inghamac959662011-01-24 06:34:17 +00004328 if (m_private_state.GetValue() != eStateStopped)
4329 {
4330 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004331 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004332 }
4333
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004334 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004335 const uint32_t thread_idx_id = thread->GetIndexID();
4336 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004337
4338 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4339 // so we should arrange to reset them as well.
4340
Greg Clayton567e7f32011-09-22 04:58:26 +00004341 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004342
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004343 uint32_t selected_tid;
4344 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004345 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004346 {
4347 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004348 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004349 }
4350 else
4351 {
4352 selected_tid = LLDB_INVALID_THREAD_ID;
4353 }
4354
Jim Ingham1831e782012-04-07 00:00:41 +00004355 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004356 lldb::StateType old_state;
4357 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004358
Jim Inghamd21d98b2012-04-10 01:21:57 +00004359 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004360 if (Host::GetCurrentThread() == m_private_state_thread)
4361 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004362 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4363 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004364 // 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 +00004365 // we are fielding public events here.
4366 if (log)
Jason Molenda559cf6e2012-11-17 01:41:04 +00004367 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 +00004368
4369
Jim Ingham1831e782012-04-07 00:00:41 +00004370 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004371
4372 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4373 // returning control here.
4374 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4375 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4376 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4377 // do just what we want.
4378 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4379 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4380 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4381 old_state = m_public_state.GetValue();
4382 m_public_state.SetValueNoLock(eStateStopped);
4383
4384 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004385 StartPrivateStateThread(true);
4386 }
4387
4388 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004389
Jim Ingham6ae318c2011-01-23 21:14:08 +00004390 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004391
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004392 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004393
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004394 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004395 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4396 // restored on exit to the function.
4397 //
4398 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4399 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004400
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004401 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004402
Jim Ingham360f53f2010-11-30 02:22:11 +00004403 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004404 {
4405 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004406 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004407 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64 " to run thread plan \"%s\".",
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004408 thread->GetIndexID(),
4409 thread->GetID(),
4410 s.GetData());
4411 }
4412
4413 bool got_event;
4414 lldb::EventSP event_sp;
4415 lldb::StateType stop_state = lldb::eStateInvalid;
4416
4417 TimeValue* timeout_ptr = NULL;
4418 TimeValue real_timeout;
4419
4420 bool first_timeout = true;
4421 bool do_resume = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004422 const uint64_t default_one_thread_timeout_usec = 250000;
4423 uint64_t computed_timeout = 0;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004424
Jim Ingham76b258d2012-11-26 23:52:18 +00004425 // This while loop must exit out the bottom, there's cleanup that we need to do when we are done.
4426 // So don't call return anywhere within it.
4427
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004428 while (1)
4429 {
4430 // We usually want to resume the process if we get to the top of the loop.
4431 // The only exception is if we get two running events with no intervening
4432 // stop, which can happen, we will just wait for then next stop event.
4433
4434 if (do_resume)
4435 {
4436 // Do the initial resume and wait for the running event before going further.
4437
4438 Error resume_error = PrivateResume ();
4439 if (!resume_error.Success())
4440 {
4441 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4442 return_value = eExecutionSetupError;
4443 break;
4444 }
4445
4446 real_timeout = TimeValue::Now();
4447 real_timeout.OffsetWithMicroSeconds(500000);
4448 timeout_ptr = &real_timeout;
4449
4450 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4451 if (!got_event)
4452 {
4453 if (log)
4454 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4455
4456 errors.Printf("Didn't get any event after initial resume, exiting.");
4457 return_value = eExecutionSetupError;
4458 break;
4459 }
4460
4461 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4462 if (stop_state != eStateRunning)
4463 {
4464 if (log)
Jim Ingham47beabb2012-10-16 21:41:58 +00004465 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4466 "initial resume, got %s instead.",
4467 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004468
Jim Ingham47beabb2012-10-16 21:41:58 +00004469 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4470 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004471 return_value = eExecutionSetupError;
4472 break;
4473 }
4474
4475 if (log)
4476 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4477 // We need to call the function synchronously, so spin waiting for it to return.
4478 // If we get interrupted while executing, we're going to lose our context, and
4479 // won't be able to gather the result at this point.
4480 // We set the timeout AFTER the resume, since the resume takes some time and we
4481 // don't want to charge that to the timeout.
4482
Jim Ingham47beabb2012-10-16 21:41:58 +00004483 if (first_timeout)
4484 {
4485 if (run_others)
4486 {
4487 // If we are running all threads then we take half the time to run all threads, bounded by
4488 // .25 sec.
4489 if (timeout_usec == 0)
4490 computed_timeout = default_one_thread_timeout_usec;
4491 else
4492 {
4493 computed_timeout = timeout_usec / 2;
4494 if (computed_timeout > default_one_thread_timeout_usec)
4495 {
4496 computed_timeout = default_one_thread_timeout_usec;
4497 }
4498 timeout_usec -= computed_timeout;
4499 }
4500 }
4501 else
4502 {
4503 computed_timeout = timeout_usec;
4504 }
4505 }
4506 else
4507 {
4508 computed_timeout = timeout_usec;
4509 }
4510
4511 if (computed_timeout != 0)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004512 {
Enrico Granata6cca9692012-07-16 23:10:35 +00004513 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004514 real_timeout = TimeValue::Now();
Jim Ingham47beabb2012-10-16 21:41:58 +00004515 real_timeout.OffsetWithMicroSeconds(computed_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004516
4517 timeout_ptr = &real_timeout;
4518 }
Enrico Granata6cca9692012-07-16 23:10:35 +00004519 else
4520 {
Jim Ingham47beabb2012-10-16 21:41:58 +00004521 timeout_ptr = NULL;
Enrico Granata6cca9692012-07-16 23:10:35 +00004522 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004523 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004524 else
4525 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004526 if (log)
4527 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4528 do_resume = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004529 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004530
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004531 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004532 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004533
Jim Inghamf9f40c22011-02-08 05:20:59 +00004534 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004535 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004536 if (timeout_ptr)
4537 {
4538 StreamString s;
4539 s.Printf ("about to wait - timeout is:\n ");
4540 timeout_ptr->Dump (&s, 120);
4541 s.Printf ("\nNow is:\n ");
4542 TimeValue::Now().Dump (&s, 120);
4543 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4544 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004545 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004546 {
4547 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4548 }
4549 }
4550
4551 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4552
4553 if (got_event)
4554 {
4555 if (event_sp.get())
4556 {
4557 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004558 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004559 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004560 Halt();
4561 keep_going = false;
4562 return_value = eExecutionInterrupted;
4563 errors.Printf ("Execution halted by user interrupt.");
4564 if (log)
4565 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4566 }
4567 else
4568 {
4569 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4570 if (log)
4571 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4572
4573 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004574 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004575 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004576 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004577 // Yay, we're done. Now make sure that our thread plan actually completed.
4578 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4579 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004580 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004581 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004582 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004583 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4584 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004585 }
4586 else
4587 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004588 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4589 StopReason stop_reason = eStopReasonInvalid;
4590 if (stop_info_sp)
4591 stop_reason = stop_info_sp->GetStopReason();
4592 if (stop_reason == eStopReasonPlanComplete)
4593 {
4594 if (log)
4595 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4596 // Now mark this plan as private so it doesn't get reported as the stop reason
4597 // after this point.
4598 if (thread_plan_sp)
4599 thread_plan_sp->SetPrivate (orig_plan_private);
4600 return_value = eExecutionCompleted;
4601 }
4602 else
4603 {
4604 if (log)
4605 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004606
Jim Ingham5d90ade2012-07-27 23:57:19 +00004607 return_value = eExecutionInterrupted;
4608 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004609 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004610 }
4611 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004612
Jim Ingham5d90ade2012-07-27 23:57:19 +00004613 case lldb::eStateCrashed:
4614 if (log)
4615 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4616 return_value = eExecutionInterrupted;
4617 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004618
Jim Ingham5d90ade2012-07-27 23:57:19 +00004619 case lldb::eStateRunning:
4620 do_resume = false;
4621 keep_going = true;
4622 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004623
Jim Ingham5d90ade2012-07-27 23:57:19 +00004624 default:
4625 if (log)
4626 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4627
4628 if (stop_state == eStateExited)
4629 event_to_broadcast_sp = event_sp;
4630
Sean Callanan96abc622012-08-08 17:35:10 +00004631 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00004632 return_value = eExecutionInterrupted;
4633 break;
4634 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004635 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004636
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004637 if (keep_going)
4638 continue;
4639 else
4640 break;
4641 }
4642 else
4643 {
4644 if (log)
4645 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4646 return_value = eExecutionInterrupted;
4647 break;
4648 }
4649 }
4650 else
4651 {
4652 // If we didn't get an event that means we've timed out...
4653 // We will interrupt the process here. Depending on what we were asked to do we will
4654 // either exit, or try with all threads running for the same timeout.
4655 // Not really sure what to do if Halt fails here...
4656
4657 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00004658 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004659 {
4660 if (first_timeout)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004661 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %" PRId64 " timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004662 "trying for %d usec with all threads enabled.",
4663 computed_timeout, timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004664 else
4665 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00004666 "and timeout: %d timed out, abandoning execution.",
4667 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004668 }
4669 else
4670 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004671 "abandoning execution.",
4672 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004673 }
4674
4675 Error halt_error = Halt();
4676 if (halt_error.Success())
4677 {
4678 if (log)
4679 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4680
4681 // If halt succeeds, it always produces a stopped event. Wait for that:
4682
4683 real_timeout = TimeValue::Now();
4684 real_timeout.OffsetWithMicroSeconds(500000);
4685
4686 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4687
4688 if (got_event)
4689 {
4690 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4691 if (log)
4692 {
4693 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4694 if (stop_state == lldb::eStateStopped
4695 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4696 log->PutCString (" Event was the Halt interruption event.");
4697 }
4698
4699 if (stop_state == lldb::eStateStopped)
4700 {
4701 // Between the time we initiated the Halt and the time we delivered it, the process could have
4702 // already finished its job. Check that here:
4703
4704 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4705 {
4706 if (log)
4707 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4708 "Exiting wait loop.");
4709 return_value = eExecutionCompleted;
4710 break;
4711 }
4712
Jim Ingham47beabb2012-10-16 21:41:58 +00004713 if (!run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004714 {
4715 if (log)
4716 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4717 return_value = eExecutionInterrupted;
4718 break;
4719 }
4720
4721 if (first_timeout)
4722 {
4723 // Set all the other threads to run, and return to the top of the loop, which will continue;
4724 first_timeout = false;
4725 thread_plan_sp->SetStopOthers (false);
4726 if (log)
4727 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4728
4729 continue;
4730 }
4731 else
4732 {
4733 // Running all threads failed, so return Interrupted.
4734 if (log)
4735 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4736 return_value = eExecutionInterrupted;
4737 break;
4738 }
4739 }
4740 }
4741 else
4742 { if (log)
4743 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4744 "I'm getting out of here passing Interrupted.");
4745 return_value = eExecutionInterrupted;
4746 break;
4747 }
4748 }
4749 else
4750 {
4751 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4752 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4753 if (log)
4754 log->Printf ("Process::RunThreadPlan(): halt failed: error = \"%s\", I'm just going to wait a little longer and see if I get a stopped event.",
4755 halt_error.AsCString());
4756 real_timeout = TimeValue::Now();
4757 real_timeout.OffsetWithMicroSeconds(500000);
4758 timeout_ptr = &real_timeout;
4759 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4760 if (!got_event || event_sp.get() == NULL)
4761 {
4762 // This is not going anywhere, bag out.
4763 if (log)
4764 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4765 return_value = eExecutionInterrupted;
4766 break;
4767 }
4768 else
4769 {
4770 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4771 if (log)
4772 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4773 if (stop_state == lldb::eStateStopped)
4774 {
4775 // Between the time we initiated the Halt and the time we delivered it, the process could have
4776 // already finished its job. Check that here:
4777
4778 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4779 {
4780 if (log)
4781 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4782 "Exiting wait loop.");
4783 return_value = eExecutionCompleted;
4784 break;
4785 }
4786
4787 if (first_timeout)
4788 {
4789 // Set all the other threads to run, and return to the top of the loop, which will continue;
4790 first_timeout = false;
4791 thread_plan_sp->SetStopOthers (false);
4792 if (log)
4793 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4794
4795 continue;
4796 }
4797 else
4798 {
4799 // Running all threads failed, so return Interrupted.
4800 if (log)
4801 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4802 return_value = eExecutionInterrupted;
4803 break;
4804 }
4805 }
4806 else
4807 {
4808 if (log)
4809 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4810 " a stopped event, instead got %s.", StateAsCString(stop_state));
4811 return_value = eExecutionInterrupted;
4812 break;
4813 }
4814 }
4815 }
4816
4817 }
4818
4819 } // END WAIT LOOP
4820
4821 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4822 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4823 {
4824 StopPrivateStateThread();
4825 Error error;
4826 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00004827 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004828 {
4829 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4830 }
4831 m_public_state.SetValueNoLock(old_state);
4832
4833 }
4834
Jim Ingham76b258d2012-11-26 23:52:18 +00004835 // Restore the thread state if we are going to discard the plan execution.
4836
4837 if (return_value == eExecutionCompleted || discard_on_error)
4838 {
4839 thread_plan_sp->RestoreThreadState();
4840 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004841
4842 // Now do some processing on the results of the run:
4843 if (return_value == eExecutionInterrupted)
4844 {
4845 if (log)
4846 {
4847 StreamString s;
4848 if (event_sp)
4849 event_sp->Dump (&s);
4850 else
4851 {
4852 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4853 }
4854
4855 StreamString ts;
4856
4857 const char *event_explanation = NULL;
4858
4859 do
4860 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004861 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004862 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004863 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004864 break;
4865 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004866 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004867 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004868 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004869 break;
4870 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004871 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004872 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004873 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4874
4875 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004876 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004877 event_explanation = "<no event data>";
4878 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004879 }
4880
Jim Ingham5d90ade2012-07-27 23:57:19 +00004881 Process *process = event_data->GetProcessSP().get();
4882
4883 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004884 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004885 event_explanation = "<no process>";
4886 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004887 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004888
4889 ThreadList &thread_list = process->GetThreadList();
4890
4891 uint32_t num_threads = thread_list.GetSize();
4892 uint32_t thread_index;
4893
4894 ts.Printf("<%u threads> ", num_threads);
4895
4896 for (thread_index = 0;
4897 thread_index < num_threads;
4898 ++thread_index)
4899 {
4900 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4901
4902 if (!thread)
4903 {
4904 ts.Printf("<?> ");
4905 continue;
4906 }
4907
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004908 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
Jim Ingham5d90ade2012-07-27 23:57:19 +00004909 RegisterContext *register_context = thread->GetRegisterContext().get();
4910
4911 if (register_context)
Daniel Malea5f35a4b2012-11-29 21:49:15 +00004912 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
Jim Ingham5d90ade2012-07-27 23:57:19 +00004913 else
4914 ts.Printf("[ip unknown] ");
4915
4916 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4917 if (stop_info_sp)
4918 {
4919 const char *stop_desc = stop_info_sp->GetDescription();
4920 if (stop_desc)
4921 ts.PutCString (stop_desc);
4922 }
4923 ts.Printf(">");
4924 }
4925
4926 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004927 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004928 } while (0);
4929
Jim Ingham5d90ade2012-07-27 23:57:19 +00004930 if (event_explanation)
4931 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004932 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00004933 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4934 }
4935
4936 if (discard_on_error && thread_plan_sp)
4937 {
4938 if (log)
4939 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4940 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4941 thread_plan_sp->SetPrivate (orig_plan_private);
4942 }
4943 else
4944 {
4945 if (log)
4946 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004947 }
4948 }
4949 else if (return_value == eExecutionSetupError)
4950 {
4951 if (log)
4952 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004953
4954 if (discard_on_error && thread_plan_sp)
4955 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004956 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004957 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004958 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004959 }
4960 else
4961 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004962 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004963 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004964 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004965 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4966 return_value = eExecutionCompleted;
4967 }
4968 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4969 {
4970 if (log)
4971 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4972 return_value = eExecutionDiscarded;
4973 }
4974 else
4975 {
4976 if (log)
4977 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4978 if (discard_on_error && thread_plan_sp)
4979 {
4980 if (log)
4981 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4982 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4983 thread_plan_sp->SetPrivate (orig_plan_private);
4984 }
4985 }
4986 }
4987
4988 // Thread we ran the function in may have gone away because we ran the target
4989 // Check that it's still there, and if it is put it back in the context. Also restore the
4990 // frame in the context if it is still present.
4991 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4992 if (thread)
4993 {
4994 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4995 }
4996
4997 // Also restore the current process'es selected frame & thread, since this function calling may
4998 // be done behind the user's back.
4999
5000 if (selected_tid != LLDB_INVALID_THREAD_ID)
5001 {
5002 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
5003 {
5004 // We were able to restore the selected thread, now restore the frame:
5005 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
5006 if (old_frame_sp)
5007 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00005008 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005009 }
5010 }
Jim Ingham360f53f2010-11-30 02:22:11 +00005011
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005012 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00005013
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005014 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00005015 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00005016 if (log)
5017 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5018 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00005019 }
5020
5021 return return_value;
5022}
5023
5024const char *
5025Process::ExecutionResultAsCString (ExecutionResults result)
5026{
5027 const char *result_name;
5028
5029 switch (result)
5030 {
Greg Claytonb3448432011-03-24 21:19:54 +00005031 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005032 result_name = "eExecutionCompleted";
5033 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005034 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00005035 result_name = "eExecutionDiscarded";
5036 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005037 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00005038 result_name = "eExecutionInterrupted";
5039 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005040 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00005041 result_name = "eExecutionSetupError";
5042 break;
Greg Claytonb3448432011-03-24 21:19:54 +00005043 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00005044 result_name = "eExecutionTimedOut";
5045 break;
5046 }
5047 return result_name;
5048}
5049
Greg Claytonabe0fed2011-04-18 08:33:37 +00005050void
5051Process::GetStatus (Stream &strm)
5052{
5053 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00005054 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00005055 {
5056 if (state == eStateExited)
5057 {
5058 int exit_status = GetExitStatus();
5059 const char *exit_description = GetExitDescription();
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005060 strm.Printf ("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00005061 GetID(),
5062 exit_status,
5063 exit_status,
5064 exit_description ? exit_description : "");
5065 }
5066 else
5067 {
5068 if (state == eStateConnected)
5069 strm.Printf ("Connected to remote target.\n");
5070 else
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005071 strm.Printf ("Process %" PRIu64 " %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00005072 }
5073 }
5074 else
5075 {
Daniel Malea5f35a4b2012-11-29 21:49:15 +00005076 strm.Printf ("Process %" PRIu64 " is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005077 }
5078}
5079
5080size_t
5081Process::GetThreadStatus (Stream &strm,
5082 bool only_threads_with_stop_reason,
5083 uint32_t start_frame,
5084 uint32_t num_frames,
5085 uint32_t num_frames_with_source)
5086{
5087 size_t num_thread_infos_dumped = 0;
5088
Jim Inghamb9950592012-09-10 20:50:15 +00005089 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00005090 const size_t num_threads = GetThreadList().GetSize();
5091 for (uint32_t i = 0; i < num_threads; i++)
5092 {
5093 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
5094 if (thread)
5095 {
5096 if (only_threads_with_stop_reason)
5097 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00005098 StopInfoSP stop_info_sp = thread->GetStopInfo();
5099 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00005100 continue;
5101 }
5102 thread->GetStatus (strm,
5103 start_frame,
5104 num_frames,
5105 num_frames_with_source);
5106 ++num_thread_infos_dumped;
5107 }
5108 }
5109 return num_thread_infos_dumped;
5110}
5111
Greg Clayton76113302012-02-22 04:37:26 +00005112void
5113Process::AddInvalidMemoryRegion (const LoadRange &region)
5114{
5115 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5116}
5117
5118bool
5119Process::RemoveInvalidMemoryRange (const LoadRange &region)
5120{
5121 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
5122}
5123
Jim Ingham1831e782012-04-07 00:00:41 +00005124void
5125Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
5126{
5127 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
5128}
5129
5130bool
5131Process::RunPreResumeActions ()
5132{
5133 bool result = true;
5134 while (!m_pre_resume_actions.empty())
5135 {
5136 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5137 m_pre_resume_actions.pop_back();
5138 bool this_result = action.callback (action.baton);
5139 if (result == true) result = this_result;
5140 }
5141 return result;
5142}
5143
5144void
5145Process::ClearPreResumeActions ()
5146{
5147 m_pre_resume_actions.clear();
5148}
Greg Clayton76113302012-02-22 04:37:26 +00005149
Greg Claytoncf5927e2012-05-18 02:38:05 +00005150void
5151Process::Flush ()
5152{
5153 m_thread_list.Flush();
5154}
Greg Clayton0bce9a22012-12-05 00:16:59 +00005155
5156void
5157Process::DidExec ()
5158{
5159 Target &target = GetTarget();
5160 target.CleanupProcess ();
5161 ModuleList unloaded_modules (target.GetImages());
5162 target.ModulesDidUnload (unloaded_modules);
5163 target.GetSectionLoadList().Clear();
5164 m_dynamic_checkers_ap.reset();
5165 m_abi_sp.reset();
5166 m_os_ap.reset();
5167 m_dyld_ap.reset();
5168 m_image_tokens.clear();
5169 m_allocated_memory_cache.Clear();
5170 m_language_runtimes.clear();
5171 DoDidExec();
5172 CompleteAttach ();
5173}