blob: dd28cc1edebd6d149609f364174c41ea6ffae4ef [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
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
Greg Clayton49ce8962012-08-29 21:13:06 +000021#include "lldb/Core/Module.h"
Chris Lattner24943d22010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
23#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000024#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000025#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000026#include "lldb/Host/Host.h"
27#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000028#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000029#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000030#include "lldb/Target/LanguageRuntime.h"
31#include "lldb/Target/CPPLanguageRuntime.h"
32#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000033#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000035#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Target/Target.h"
37#include "lldb/Target/TargetList.h"
38#include "lldb/Target/Thread.h"
39#include "lldb/Target/ThreadPlan.h"
Jim Inghamd21d98b2012-04-10 01:21:57 +000040#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
42using namespace lldb;
43using namespace lldb_private;
44
Greg Clayton73844aa2012-08-22 17:17:09 +000045
46// Comment out line below to disable memory caching, overriding the process setting
47// target.process.disable-memory-cache
48#define ENABLE_MEMORY_CACHING
49
50#ifdef ENABLE_MEMORY_CACHING
51#define DISABLE_MEM_CACHE_DEFAULT false
52#else
53#define DISABLE_MEM_CACHE_DEFAULT true
54#endif
55
56class ProcessOptionValueProperties : public OptionValueProperties
57{
58public:
59 ProcessOptionValueProperties (const ConstString &name) :
60 OptionValueProperties (name)
61 {
62 }
63
64 // This constructor is used when creating ProcessOptionValueProperties when it
65 // is part of a new lldb_private::Process instance. It will copy all current
66 // global property values as needed
67 ProcessOptionValueProperties (ProcessProperties *global_properties) :
68 OptionValueProperties(*global_properties->GetValueProperties())
69 {
70 }
71
72 virtual const Property *
73 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
74 {
75 // When gettings the value for a key from the process options, we will always
76 // try and grab the setting from the current process if there is one. Else we just
77 // use the one from this instance.
78 if (exe_ctx)
79 {
80 Process *process = exe_ctx->GetProcessPtr();
81 if (process)
82 {
83 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
84 if (this != instance_properties)
85 return instance_properties->ProtectedGetPropertyAtIndex (idx);
86 }
87 }
88 return ProtectedGetPropertyAtIndex (idx);
89 }
90};
91
92static PropertyDefinition
93g_properties[] =
94{
95 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
96 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used." },
97 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
98};
99
100enum {
101 ePropertyDisableMemCache,
102 ePropertyExtraStartCommand
103};
104
105ProcessProperties::ProcessProperties (bool is_global) :
106 Properties ()
107{
108 if (is_global)
109 {
110 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
111 m_collection_sp->Initialize(g_properties);
112 m_collection_sp->AppendProperty(ConstString("thread"),
113 ConstString("Settings specify to threads."),
114 true,
115 Thread::GetGlobalProperties()->GetValueProperties());
116 }
117 else
118 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
119}
120
121ProcessProperties::~ProcessProperties()
122{
123}
124
125bool
126ProcessProperties::GetDisableMemoryCache() const
127{
128 const uint32_t idx = ePropertyDisableMemCache;
129 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
130}
131
132Args
133ProcessProperties::GetExtraStartupCommands () const
134{
135 Args args;
136 const uint32_t idx = ePropertyExtraStartCommand;
137 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
138 return args;
139}
140
141void
142ProcessProperties::SetExtraStartupCommands (const Args &args)
143{
144 const uint32_t idx = ePropertyExtraStartCommand;
145 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
146}
147
Greg Clayton24bc5d92011-03-30 18:16:51 +0000148void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000149ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000150{
151 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +0000152 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +0000153 s.Printf (" pid = %llu\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000154
155 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +0000156 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +0000157
158 if (m_executable)
159 {
160 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
161 s.PutCString (" file = ");
162 m_executable.Dump(&s);
163 s.EOL();
164 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000165 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000166 if (argc > 0)
167 {
168 for (uint32_t i=0; i<argc; i++)
169 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000170 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +0000171 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000172 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000173 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000174 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +0000175 }
176 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000177
178 const uint32_t envc = m_environment.GetArgumentCount();
179 if (envc > 0)
180 {
181 for (uint32_t i=0; i<envc; i++)
182 {
183 const char *env = m_environment.GetArgumentAtIndex(i);
184 if (i < 10)
185 s.Printf (" env[%u] = %s\n", i, env);
186 else
187 s.Printf ("env[%u] = %s\n", i, env);
188 }
189 }
190
Greg Claytonff39f742011-04-01 00:29:43 +0000191 if (m_arch.IsValid())
192 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
193
Greg Claytonb72d0f02011-04-12 05:54:46 +0000194 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000195 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000196 cstr = platform->GetUserName (m_uid);
197 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000198 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000199 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000200 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000201 cstr = platform->GetGroupName (m_gid);
202 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000203 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000204 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000205 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000206 cstr = platform->GetUserName (m_euid);
207 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000208 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000209 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000210 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000211 cstr = platform->GetGroupName (m_egid);
212 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000213 }
214}
215
216void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000217ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000218{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000219 const char *label;
220 if (show_args || verbose)
221 label = "ARGUMENTS";
222 else
223 label = "NAME";
224
Greg Claytonff39f742011-04-01 00:29:43 +0000225 if (verbose)
226 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000227 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000228 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
229 }
230 else
231 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000232 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000233 s.PutCString ("====== ====== ========== ======= ============================\n");
234 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000235}
236
237void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000238ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000239{
240 if (m_pid != LLDB_INVALID_PROCESS_ID)
241 {
242 const char *cstr;
Greg Claytond9919d32011-12-01 23:28:38 +0000243 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000244
Greg Clayton24bc5d92011-03-30 18:16:51 +0000245
Greg Claytonff39f742011-04-01 00:29:43 +0000246 if (verbose)
247 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000248 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000249 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
250 s.Printf ("%-10s ", cstr);
251 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000252 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000253
Greg Claytonb72d0f02011-04-12 05:54:46 +0000254 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000255 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
256 s.Printf ("%-10s ", cstr);
257 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000258 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000259
Greg Claytonb72d0f02011-04-12 05:54:46 +0000260 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000261 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
262 s.Printf ("%-10s ", cstr);
263 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000264 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000265
Greg Claytonb72d0f02011-04-12 05:54:46 +0000266 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000267 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
268 s.Printf ("%-10s ", cstr);
269 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000270 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000271 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
272 }
273 else
274 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000275 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000276 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000277 (int)m_arch.GetTriple().getArchName().size(),
278 m_arch.GetTriple().getArchName().data());
279 }
280
Greg Claytonb72d0f02011-04-12 05:54:46 +0000281 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000282 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000283 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000284 if (argc > 0)
285 {
286 for (uint32_t i=0; i<argc; i++)
287 {
288 if (i > 0)
289 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000290 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000291 }
292 }
293 }
294 else
295 {
296 s.PutCString (GetName());
297 }
298
299 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000300 }
301}
302
Greg Claytonb72d0f02011-04-12 05:54:46 +0000303
304void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000305ProcessInfo::SetArguments (char const **argv, bool first_arg_is_executable)
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000306{
307 m_arguments.SetArguments (argv);
308
309 // Is the first argument the executable?
310 if (first_arg_is_executable)
311 {
312 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
313 if (first_arg)
314 {
315 // Yes the first argument is an executable, set it as the executable
316 // in the launch options. Don't resolve the file path as the path
317 // could be a remote platform path
318 const bool resolve = false;
319 m_executable.SetFile(first_arg, resolve);
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000320 }
321 }
322}
323void
Greg Clayton0c8446c2012-10-17 22:57:12 +0000324ProcessInfo::SetArguments (const Args& args, bool first_arg_is_executable)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000325{
326 // Copy all arguments
327 m_arguments = args;
328
329 // Is the first argument the executable?
330 if (first_arg_is_executable)
331 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000332 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000333 if (first_arg)
334 {
335 // Yes the first argument is an executable, set it as the executable
336 // in the launch options. Don't resolve the file path as the path
337 // could be a remote platform path
338 const bool resolve = false;
339 m_executable.SetFile(first_arg, resolve);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000340 }
341 }
342}
343
Greg Claytonabb33022011-11-08 02:43:13 +0000344void
Greg Clayton464c6162011-11-17 22:14:31 +0000345ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000346{
347 // If notthing was specified, then check the process for any default
348 // settings that were set with "settings set"
349 if (m_file_actions.empty())
350 {
Greg Claytonabb33022011-11-08 02:43:13 +0000351 if (m_flags.Test(eLaunchFlagDisableSTDIO))
352 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000353 AppendSuppressFileAction (STDIN_FILENO , true, false);
354 AppendSuppressFileAction (STDOUT_FILENO, false, true);
355 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000356 }
357 else
358 {
359 // Check for any values that might have gotten set with any of:
360 // (lldb) settings set target.input-path
361 // (lldb) settings set target.output-path
362 // (lldb) settings set target.error-path
Greg Clayton73844aa2012-08-22 17:17:09 +0000363 FileSpec in_path;
364 FileSpec out_path;
365 FileSpec err_path;
Greg Claytonabb33022011-11-08 02:43:13 +0000366 if (target)
367 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000368 in_path = target->GetStandardInputPath();
369 out_path = target->GetStandardOutputPath();
370 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000371 }
372
Greg Clayton73844aa2012-08-22 17:17:09 +0000373 if (in_path || out_path || err_path)
374 {
375 char path[PATH_MAX];
376 if (in_path && in_path.GetPath(path, sizeof(path)))
377 AppendOpenFileAction(STDIN_FILENO, path, true, false);
378
379 if (out_path && out_path.GetPath(path, sizeof(path)))
380 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
381
382 if (err_path && err_path.GetPath(path, sizeof(path)))
383 AppendOpenFileAction(STDERR_FILENO, path, false, true);
384 }
385 else if (default_to_use_pty)
Greg Clayton464c6162011-11-17 22:14:31 +0000386 {
387 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000388 {
Greg Clayton73844aa2012-08-22 17:17:09 +0000389 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
390 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
391 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
392 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000393 }
394 }
Greg Claytonabb33022011-11-08 02:43:13 +0000395 }
396 }
397}
398
Greg Clayton527154d2011-11-15 03:53:30 +0000399
400bool
Greg Clayton97471182012-04-14 01:42:46 +0000401ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
402 bool localhost,
403 bool will_debug,
404 bool first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000405{
406 error.Clear();
407
408 if (GetFlags().Test (eLaunchFlagLaunchInShell))
409 {
410 const char *shell_executable = GetShell();
411 if (shell_executable)
412 {
413 char shell_resolved_path[PATH_MAX];
414
415 if (localhost)
416 {
417 FileSpec shell_filespec (shell_executable, true);
418
419 if (!shell_filespec.Exists())
420 {
421 // Resolve the path in case we just got "bash", "sh" or "tcsh"
422 if (!shell_filespec.ResolveExecutableLocation ())
423 {
424 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
425 return false;
426 }
427 }
428 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
429 shell_executable = shell_resolved_path;
430 }
431
Greg Clayton0c8446c2012-10-17 22:57:12 +0000432 const char **argv = GetArguments().GetConstArgumentVector ();
433 if (argv == NULL || argv[0] == NULL)
434 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000435 Args shell_arguments;
436 std::string safe_arg;
437 shell_arguments.AppendArgument (shell_executable);
Greg Clayton527154d2011-11-15 03:53:30 +0000438 shell_arguments.AppendArgument ("-c");
Greg Clayton97471182012-04-14 01:42:46 +0000439 StreamString shell_command;
440 if (will_debug)
Greg Clayton527154d2011-11-15 03:53:30 +0000441 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000442 // Add a modified PATH environment variable in case argv[0]
443 // is a relative path
444 const char *argv0 = argv[0];
445 if (argv0 && (argv0[0] != '/' && argv0[0] != '~'))
446 {
447 // We have a relative path to our executable which may not work if
448 // we just try to run "a.out" (without it being converted to "./a.out")
449 const char *working_dir = GetWorkingDirectory();
450 std::string new_path("PATH=");
451 const size_t empty_path_len = new_path.size();
452
453 if (working_dir && working_dir[0])
454 {
455 new_path += working_dir;
456 }
457 else
458 {
459 char current_working_dir[PATH_MAX];
460 const char *cwd = getcwd(current_working_dir, sizeof(current_working_dir));
461 if (cwd && cwd[0])
462 new_path += cwd;
463 }
464 const char *curr_path = getenv("PATH");
465 if (curr_path)
466 {
467 if (new_path.size() > empty_path_len)
468 new_path += ':';
469 new_path += curr_path;
470 }
471 new_path += ' ';
472 shell_command.PutCString(new_path.c_str());
473 }
474
Greg Clayton97471182012-04-14 01:42:46 +0000475 shell_command.PutCString ("exec");
Greg Clayton0c8446c2012-10-17 22:57:12 +0000476
477#if defined(__APPLE__)
478 // Only Apple supports /usr/bin/arch being able to specify the architecture
Greg Clayton97471182012-04-14 01:42:46 +0000479 if (GetArchitecture().IsValid())
480 {
481 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
Greg Clayton0c8446c2012-10-17 22:57:12 +0000482 // Set the resume count to 2:
Greg Clayton97471182012-04-14 01:42:46 +0000483 // 1 - stop in shell
484 // 2 - stop in /usr/bin/arch
485 // 3 - then we will stop in our program
486 SetResumeCount(2);
487 }
488 else
489 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000490 // Set the resume count to 1:
Greg Clayton97471182012-04-14 01:42:46 +0000491 // 1 - stop in shell
492 // 2 - then we will stop in our program
493 SetResumeCount(1);
494 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000495#else
496 // Set the resume count to 1:
497 // 1 - stop in shell
498 // 2 - then we will stop in our program
499 SetResumeCount(1);
500#endif
Greg Clayton527154d2011-11-15 03:53:30 +0000501 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000502
503 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000504 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000505 // There should only be one argument that is the shell command itself to be used as is
506 if (argv[0] && !argv[1])
507 shell_command.Printf("%s", argv[0]);
Greg Clayton97471182012-04-14 01:42:46 +0000508 else
Greg Clayton0c8446c2012-10-17 22:57:12 +0000509 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000510 }
Greg Clayton97471182012-04-14 01:42:46 +0000511 else
512 {
Greg Clayton0c8446c2012-10-17 22:57:12 +0000513 for (size_t i=0; argv[i] != NULL; ++i)
514 {
515 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
516 shell_command.Printf(" %s", arg);
517 }
Greg Clayton97471182012-04-14 01:42:46 +0000518 }
Greg Clayton0c8446c2012-10-17 22:57:12 +0000519 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000520 m_executable.SetFile(shell_executable, false);
521 m_arguments = shell_arguments;
522 return true;
523 }
524 else
525 {
526 error.SetErrorString ("invalid shell path");
527 }
528 }
529 else
530 {
531 error.SetErrorString ("not launching in shell");
532 }
533 return false;
534}
535
536
Greg Clayton24bc5d92011-03-30 18:16:51 +0000537bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000538ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
539{
540 if ((read || write) && fd >= 0 && path && path[0])
541 {
542 m_action = eFileActionOpen;
543 m_fd = fd;
544 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000545 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000546 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000547 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000548 else
Greg Clayton527154d2011-11-15 03:53:30 +0000549 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000550 m_path.assign (path);
551 return true;
552 }
553 else
554 {
555 Clear();
556 }
557 return false;
558}
559
560bool
561ProcessLaunchInfo::FileAction::Close (int fd)
562{
563 Clear();
564 if (fd >= 0)
565 {
566 m_action = eFileActionClose;
567 m_fd = fd;
568 }
569 return m_fd >= 0;
570}
571
572
573bool
574ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
575{
576 Clear();
577 if (fd >= 0 && dup_fd >= 0)
578 {
579 m_action = eFileActionDuplicate;
580 m_fd = fd;
581 m_arg = dup_fd;
582 }
583 return m_fd >= 0;
584}
585
586
587
588bool
589ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
590 const FileAction *info,
591 Log *log,
592 Error& error)
593{
594 if (info == NULL)
595 return false;
596
597 switch (info->m_action)
598 {
599 case eFileActionNone:
600 error.Clear();
601 break;
602
603 case eFileActionClose:
604 if (info->m_fd == -1)
605 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
606 else
607 {
608 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
609 eErrorTypePOSIX);
610 if (log && (error.Fail() || log))
611 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
612 file_actions, info->m_fd);
613 }
614 break;
615
616 case eFileActionDuplicate:
617 if (info->m_fd == -1)
618 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
619 else if (info->m_arg == -1)
620 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
621 else
622 {
623 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
624 eErrorTypePOSIX);
625 if (log && (error.Fail() || log))
626 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
627 file_actions, info->m_fd, info->m_arg);
628 }
629 break;
630
631 case eFileActionOpen:
632 if (info->m_fd == -1)
633 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
634 else
635 {
636 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000637
Greg Claytonb72d0f02011-04-12 05:54:46 +0000638 mode_t mode = 0;
639
Greg Clayton527154d2011-11-15 03:53:30 +0000640 if (oflag & O_CREAT)
641 mode = 0640;
642
Greg Claytonb72d0f02011-04-12 05:54:46 +0000643 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
644 info->m_fd,
645 info->m_path.c_str(),
646 oflag,
647 mode),
648 eErrorTypePOSIX);
649 if (error.Fail() || log)
650 error.PutToLog(log,
651 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
652 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
653 }
654 break;
655
656 default:
657 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
658 break;
659 }
660 return error.Success();
661}
662
663Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000664ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000665{
666 Error error;
667 char short_option = (char) m_getopt_table[option_idx].val;
668
669 switch (short_option)
670 {
671 case 's': // Stop at program entry point
672 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
673 break;
674
Greg Claytonb72d0f02011-04-12 05:54:46 +0000675 case 'i': // STDIN for read only
676 {
677 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000678 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000679 launch_info.AppendFileAction (action);
680 }
681 break;
682
683 case 'o': // Open STDOUT for write only
684 {
685 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000686 if (action.Open (STDOUT_FILENO, option_arg, false, true))
687 launch_info.AppendFileAction (action);
688 }
689 break;
690
691 case 'e': // STDERR for write only
692 {
693 ProcessLaunchInfo::FileAction action;
694 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000695 launch_info.AppendFileAction (action);
696 }
697 break;
698
Greg Clayton95ec1682012-03-06 04:01:04 +0000699
Greg Claytonb72d0f02011-04-12 05:54:46 +0000700 case 'p': // Process plug-in name
701 launch_info.SetProcessPluginName (option_arg);
702 break;
703
704 case 'n': // Disable STDIO
705 {
706 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000707 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000708 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000709 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000710 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000711 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000712 launch_info.AppendFileAction (action);
713 }
714 break;
715
716 case 'w':
717 launch_info.SetWorkingDirectory (option_arg);
718 break;
719
720 case 't': // Open process in new terminal window
721 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
722 break;
723
724 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000725 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
726 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000727 break;
728
729 case 'A':
730 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
731 break;
732
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000733 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000734 if (option_arg && option_arg[0])
735 launch_info.SetShell (option_arg);
736 else
737 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000738 break;
739
Greg Claytonb72d0f02011-04-12 05:54:46 +0000740 case 'v':
741 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
742 break;
743
744 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000745 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000746 break;
747
748 }
749 return error;
750}
751
752OptionDefinition
753ProcessLaunchCommandOptions::g_option_table[] =
754{
755{ 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."},
756{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
757{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
758{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
759{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
760{ 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."},
Greg Clayton527154d2011-11-15 03:53:30 +0000761{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypePath, "Run the process in a shell (not supported on all platforms)."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000762
763{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
764{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
765{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
766
767{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
768
769{ 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."},
770
771{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
772};
773
774
775
776bool
777ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000778{
779 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
780 return true;
781 const char *match_name = m_match_info.GetName();
782 if (!match_name)
783 return true;
784
785 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
786}
787
788bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000789ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000790{
791 if (!NameMatches (proc_info.GetName()))
792 return false;
793
794 if (m_match_info.ProcessIDIsValid() &&
795 m_match_info.GetProcessID() != proc_info.GetProcessID())
796 return false;
797
798 if (m_match_info.ParentProcessIDIsValid() &&
799 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
800 return false;
801
Greg Claytonb72d0f02011-04-12 05:54:46 +0000802 if (m_match_info.UserIDIsValid () &&
803 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000804 return false;
805
Greg Claytonb72d0f02011-04-12 05:54:46 +0000806 if (m_match_info.GroupIDIsValid () &&
807 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000808 return false;
809
810 if (m_match_info.EffectiveUserIDIsValid () &&
811 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
812 return false;
813
814 if (m_match_info.EffectiveGroupIDIsValid () &&
815 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
816 return false;
817
818 if (m_match_info.GetArchitecture().IsValid() &&
819 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
820 return false;
821 return true;
822}
823
824bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000825ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000826{
827 if (m_name_match_type != eNameMatchIgnore)
828 return false;
829
830 if (m_match_info.ProcessIDIsValid())
831 return false;
832
833 if (m_match_info.ParentProcessIDIsValid())
834 return false;
835
Greg Claytonb72d0f02011-04-12 05:54:46 +0000836 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000837 return false;
838
Greg Claytonb72d0f02011-04-12 05:54:46 +0000839 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000840 return false;
841
842 if (m_match_info.EffectiveUserIDIsValid ())
843 return false;
844
845 if (m_match_info.EffectiveGroupIDIsValid ())
846 return false;
847
848 if (m_match_info.GetArchitecture().IsValid())
849 return false;
850
851 if (m_match_all_users)
852 return false;
853
854 return true;
855
856}
857
858void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000859ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000860{
861 m_match_info.Clear();
862 m_name_match_type = eNameMatchIgnore;
863 m_match_all_users = false;
864}
Greg Claytonfd119992011-01-07 06:08:19 +0000865
Greg Clayton46c9a352012-02-09 06:16:32 +0000866ProcessSP
867Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000868{
Greg Clayton46c9a352012-02-09 06:16:32 +0000869 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000870 ProcessCreateInstance create_callback = NULL;
871 if (plugin_name)
872 {
873 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
874 if (create_callback)
875 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000876 process_sp = create_callback(target, listener, crash_file_path);
877 if (process_sp)
878 {
879 if (!process_sp->CanDebug(target, true))
880 process_sp.reset();
881 }
Chris Lattner24943d22010-06-08 16:52:24 +0000882 }
883 }
884 else
885 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000886 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000887 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000888 process_sp = create_callback(target, listener, crash_file_path);
889 if (process_sp)
890 {
891 if (!process_sp->CanDebug(target, false))
892 process_sp.reset();
893 else
894 break;
895 }
Chris Lattner24943d22010-06-08 16:52:24 +0000896 }
897 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000898 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000899}
900
Jim Ingham5a15e692012-02-16 06:50:00 +0000901ConstString &
902Process::GetStaticBroadcasterClass ()
903{
904 static ConstString class_name ("lldb.process");
905 return class_name;
906}
Chris Lattner24943d22010-06-08 16:52:24 +0000907
908//----------------------------------------------------------------------
909// Process constructor
910//----------------------------------------------------------------------
911Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +0000912 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +0000913 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000914 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +0000915 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000916 m_public_state (eStateUnloaded),
917 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000918 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
919 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000920 m_private_state_listener ("lldb.process.internal_state_listener"),
921 m_private_state_control_wait(),
922 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000923 m_mod_id (),
Chris Lattner24943d22010-06-08 16:52:24 +0000924 m_thread_index_id (0),
925 m_exit_status (-1),
926 m_exit_string (),
927 m_thread_list (this),
928 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000929 m_image_tokens (),
930 m_listener (listener),
931 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000932 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000933 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000934 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000935 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000936 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000937 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000938 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000939 m_stderr_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000940 m_memory_cache (*this),
941 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +0000942 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000943 m_next_event_action_ap(),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000944 m_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +0000945 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +0000946 m_finalize_called(false),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000947 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +0000948{
Jim Ingham5a15e692012-02-16 06:50:00 +0000949 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +0000950
Greg Claytone005f2c2010-11-06 01:53:30 +0000951 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000952 if (log)
953 log->Printf ("%p Process::Process()", this);
954
Greg Clayton49ce6822010-10-31 03:01:06 +0000955 SetEventName (eBroadcastBitStateChanged, "state-changed");
956 SetEventName (eBroadcastBitInterrupt, "interrupt");
957 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
958 SetEventName (eBroadcastBitSTDERR, "stderr-available");
959
Chris Lattner24943d22010-06-08 16:52:24 +0000960 listener.StartListeningForEvents (this,
961 eBroadcastBitStateChanged |
962 eBroadcastBitInterrupt |
963 eBroadcastBitSTDOUT |
964 eBroadcastBitSTDERR);
965
966 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +0000967 eBroadcastBitStateChanged |
968 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +0000969
970 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
971 eBroadcastInternalStateControlStop |
972 eBroadcastInternalStateControlPause |
973 eBroadcastInternalStateControlResume);
974}
975
976//----------------------------------------------------------------------
977// Destructor
978//----------------------------------------------------------------------
979Process::~Process()
980{
Greg Claytone005f2c2010-11-06 01:53:30 +0000981 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000982 if (log)
983 log->Printf ("%p Process::~Process()", this);
984 StopPrivateStateThread();
985}
986
Greg Clayton73844aa2012-08-22 17:17:09 +0000987const ProcessPropertiesSP &
988Process::GetGlobalProperties()
989{
990 static ProcessPropertiesSP g_settings_sp;
991 if (!g_settings_sp)
992 g_settings_sp.reset (new ProcessProperties (true));
993 return g_settings_sp;
994}
995
Chris Lattner24943d22010-06-08 16:52:24 +0000996void
997Process::Finalize()
998{
Greg Claytonffa43a62011-11-17 04:46:02 +0000999 switch (GetPrivateState())
1000 {
1001 case eStateConnected:
1002 case eStateAttaching:
1003 case eStateLaunching:
1004 case eStateStopped:
1005 case eStateRunning:
1006 case eStateStepping:
1007 case eStateCrashed:
1008 case eStateSuspended:
1009 if (GetShouldDetach())
1010 Detach();
1011 else
1012 Destroy();
1013 break;
1014
1015 case eStateInvalid:
1016 case eStateUnloaded:
1017 case eStateDetached:
1018 case eStateExited:
1019 break;
1020 }
1021
Greg Clayton2f57db02011-10-01 00:45:15 +00001022 // Clear our broadcaster before we proceed with destroying
1023 Broadcaster::Clear();
1024
Chris Lattner24943d22010-06-08 16:52:24 +00001025 // Do any cleanup needed prior to being destructed... Subclasses
1026 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001027
1028 // We need to destroy the loader before the derived Process class gets destroyed
1029 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001030 m_dynamic_checkers_ap.reset();
1031 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001032 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001033 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001034 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001035 std::vector<Notifications> empty_notifications;
1036 m_notifications.swap(empty_notifications);
1037 m_image_tokens.clear();
1038 m_memory_cache.Clear();
1039 m_allocated_memory_cache.Clear();
1040 m_language_runtimes.clear();
1041 m_next_event_action_ap.reset();
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001042 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001043}
1044
1045void
1046Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1047{
1048 m_notifications.push_back(callbacks);
1049 if (callbacks.initialize != NULL)
1050 callbacks.initialize (callbacks.baton, this);
1051}
1052
1053bool
1054Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1055{
1056 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1057 for (pos = m_notifications.begin(); pos != end; ++pos)
1058 {
1059 if (pos->baton == callbacks.baton &&
1060 pos->initialize == callbacks.initialize &&
1061 pos->process_state_changed == callbacks.process_state_changed)
1062 {
1063 m_notifications.erase(pos);
1064 return true;
1065 }
1066 }
1067 return false;
1068}
1069
1070void
1071Process::SynchronouslyNotifyStateChanged (StateType state)
1072{
1073 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1074 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1075 {
1076 if (notification_pos->process_state_changed)
1077 notification_pos->process_state_changed (notification_pos->baton, this, state);
1078 }
1079}
1080
1081// FIXME: We need to do some work on events before the general Listener sees them.
1082// For instance if we are continuing from a breakpoint, we need to ensure that we do
1083// the little "insert real insn, step & stop" trick. But we can't do that when the
1084// event is delivered by the broadcaster - since that is done on the thread that is
1085// waiting for new events, so if we needed more than one event for our handling, we would
1086// stall. So instead we do it when we fetch the event off of the queue.
1087//
1088
1089StateType
1090Process::GetNextEvent (EventSP &event_sp)
1091{
1092 StateType state = eStateInvalid;
1093
1094 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1095 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1096
1097 return state;
1098}
1099
1100
1101StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001102Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001103{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001104 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1105 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1106 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001107 if (event_sp_ptr)
1108 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001109 StateType state = GetState();
1110 // If we are exited or detached, we won't ever get back to any
1111 // other valid state...
1112 if (state == eStateDetached || state == eStateExited)
1113 return state;
1114
1115 while (state != eStateInvalid)
1116 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001117 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001118 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001119 if (event_sp_ptr && event_sp)
1120 *event_sp_ptr = event_sp;
1121
Jim Ingham21f37ad2011-08-09 02:12:22 +00001122 switch (state)
1123 {
1124 case eStateCrashed:
1125 case eStateDetached:
1126 case eStateExited:
1127 case eStateUnloaded:
1128 return state;
1129 case eStateStopped:
1130 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1131 continue;
1132 else
1133 return state;
1134 default:
1135 continue;
1136 }
1137 }
1138 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001139}
1140
1141
1142StateType
1143Process::WaitForState
1144(
1145 const TimeValue *timeout,
1146 const StateType *match_states, const uint32_t num_match_states
1147)
1148{
1149 EventSP event_sp;
1150 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001151 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001152 while (state != eStateInvalid)
1153 {
Greg Claytond8c62532010-10-07 04:19:01 +00001154 // If we are exited or detached, we won't ever get back to any
1155 // other valid state...
1156 if (state == eStateDetached || state == eStateExited)
1157 return state;
1158
Chris Lattner24943d22010-06-08 16:52:24 +00001159 state = WaitForStateChangedEvents (timeout, event_sp);
1160
1161 for (i=0; i<num_match_states; ++i)
1162 {
1163 if (match_states[i] == state)
1164 return state;
1165 }
1166 }
1167 return state;
1168}
1169
Jim Ingham63e24d72010-10-11 23:53:14 +00001170bool
1171Process::HijackProcessEvents (Listener *listener)
1172{
1173 if (listener != NULL)
1174 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001175 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001176 }
1177 else
1178 return false;
1179}
1180
1181void
1182Process::RestoreProcessEvents ()
1183{
1184 RestoreBroadcaster();
1185}
1186
Jim Inghamf9f40c22011-02-08 05:20:59 +00001187bool
1188Process::HijackPrivateProcessEvents (Listener *listener)
1189{
1190 if (listener != NULL)
1191 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001192 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001193 }
1194 else
1195 return false;
1196}
1197
1198void
1199Process::RestorePrivateProcessEvents ()
1200{
1201 m_private_state_broadcaster.RestoreBroadcaster();
1202}
1203
Chris Lattner24943d22010-06-08 16:52:24 +00001204StateType
1205Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1206{
Greg Claytone005f2c2010-11-06 01:53:30 +00001207 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001208
1209 if (log)
1210 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1211
1212 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001213 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1214 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001215 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001216 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001217 {
1218 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1219 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1220 else if (log)
1221 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1222 }
Chris Lattner24943d22010-06-08 16:52:24 +00001223
1224 if (log)
1225 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1226 __FUNCTION__,
1227 timeout,
1228 StateAsCString(state));
1229 return state;
1230}
1231
1232Event *
1233Process::PeekAtStateChangedEvents ()
1234{
Greg Claytone005f2c2010-11-06 01:53:30 +00001235 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001236
1237 if (log)
1238 log->Printf ("Process::%s...", __FUNCTION__);
1239
1240 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001241 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1242 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001243 if (log)
1244 {
1245 if (event_ptr)
1246 {
1247 log->Printf ("Process::%s (event_ptr) => %s",
1248 __FUNCTION__,
1249 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1250 }
1251 else
1252 {
1253 log->Printf ("Process::%s no events found",
1254 __FUNCTION__);
1255 }
1256 }
1257 return event_ptr;
1258}
1259
1260StateType
1261Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1262{
Greg Claytone005f2c2010-11-06 01:53:30 +00001263 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001264
1265 if (log)
1266 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1267
1268 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001269 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1270 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001271 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001272 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001273 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1274 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001275
1276 // This is a bit of a hack, but when we wait here we could very well return
1277 // to the command-line, and that could disable the log, which would render the
1278 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001279 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001280 {
1281 if (state == eStateInvalid)
1282 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1283 else
1284 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1285 }
Chris Lattner24943d22010-06-08 16:52:24 +00001286 return state;
1287}
1288
1289bool
1290Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1291{
Greg Claytone005f2c2010-11-06 01:53:30 +00001292 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001293
1294 if (log)
1295 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1296
1297 if (control_only)
1298 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1299 else
1300 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1301}
1302
1303bool
1304Process::IsRunning () const
1305{
1306 return StateIsRunningState (m_public_state.GetValue());
1307}
1308
1309int
1310Process::GetExitStatus ()
1311{
1312 if (m_public_state.GetValue() == eStateExited)
1313 return m_exit_status;
1314 return -1;
1315}
1316
Greg Clayton638351a2010-12-04 00:10:17 +00001317
Chris Lattner24943d22010-06-08 16:52:24 +00001318const char *
1319Process::GetExitDescription ()
1320{
1321 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1322 return m_exit_string.c_str();
1323 return NULL;
1324}
1325
Greg Clayton72e1c782011-01-22 23:43:18 +00001326bool
Chris Lattner24943d22010-06-08 16:52:24 +00001327Process::SetExitStatus (int status, const char *cstr)
1328{
Greg Clayton68ca8232011-01-25 02:58:48 +00001329 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1330 if (log)
1331 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1332 status, status,
1333 cstr ? "\"" : "",
1334 cstr ? cstr : "NULL",
1335 cstr ? "\"" : "");
1336
Greg Clayton72e1c782011-01-22 23:43:18 +00001337 // We were already in the exited state
1338 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001339 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001340 if (log)
1341 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001342 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001343 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001344
1345 m_exit_status = status;
1346 if (cstr)
1347 m_exit_string = cstr;
1348 else
1349 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001350
Greg Clayton72e1c782011-01-22 23:43:18 +00001351 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001352
Greg Clayton72e1c782011-01-22 23:43:18 +00001353 SetPrivateState (eStateExited);
1354 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001355}
1356
1357// This static callback can be used to watch for local child processes on
1358// the current host. The the child process exits, the process will be
1359// found in the global target list (we want to be completely sure that the
1360// lldb_private::Process doesn't go away before we can deliver the signal.
1361bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001362Process::SetProcessExitStatus (void *callback_baton,
1363 lldb::pid_t pid,
1364 bool exited,
1365 int signo, // Zero for no signal
1366 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001367)
1368{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001369 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1370 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00001371 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001372 callback_baton,
1373 pid,
1374 exited,
1375 signo,
1376 exit_status);
1377
1378 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001379 {
Greg Clayton63094e02010-06-23 01:19:29 +00001380 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001381 if (target_sp)
1382 {
1383 ProcessSP process_sp (target_sp->GetProcessSP());
1384 if (process_sp)
1385 {
1386 const char *signal_cstr = NULL;
1387 if (signo)
1388 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1389
1390 process_sp->SetExitStatus (exit_status, signal_cstr);
1391 }
1392 }
1393 return true;
1394 }
1395 return false;
1396}
1397
1398
Greg Clayton37f962e2011-08-22 02:49:39 +00001399void
1400Process::UpdateThreadListIfNeeded ()
1401{
1402 const uint32_t stop_id = GetStopID();
1403 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1404 {
Greg Clayton20206082011-11-17 01:23:07 +00001405 const StateType state = GetPrivateState();
1406 if (StateIsStoppedState (state, true))
1407 {
1408 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001409 // m_thread_list does have its own mutex, but we need to
1410 // hold onto the mutex between the call to UpdateThreadList(...)
1411 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001412 ThreadList new_thread_list(this);
1413 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001414 // thread list, but only update if "true" is returned
1415 if (UpdateThreadList (m_thread_list, new_thread_list))
1416 {
1417 OperatingSystem *os = GetOperatingSystem ();
1418 if (os)
1419 os->UpdateThreadList (m_thread_list, new_thread_list);
1420 m_thread_list.Update (new_thread_list);
1421 m_thread_list.SetStopID (stop_id);
1422 }
Greg Clayton20206082011-11-17 01:23:07 +00001423 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001424 }
1425}
1426
Chris Lattner24943d22010-06-08 16:52:24 +00001427uint32_t
1428Process::GetNextThreadIndexID ()
1429{
1430 return ++m_thread_index_id;
1431}
1432
1433StateType
1434Process::GetState()
1435{
1436 // If any other threads access this we will need a mutex for it
1437 return m_public_state.GetValue ();
1438}
1439
1440void
1441Process::SetPublicState (StateType new_state)
1442{
Greg Clayton68ca8232011-01-25 02:58:48 +00001443 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001444 if (log)
1445 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001446 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001447 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001448
1449 // On the transition from Run to Stopped, we unlock the writer end of the
1450 // run lock. The lock gets locked in Resume, which is the public API
1451 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001452 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1453 {
Sean Callanana3772862012-06-02 01:16:20 +00001454 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001455 {
Sean Callanana3772862012-06-02 01:16:20 +00001456 if (log)
1457 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1458 m_run_lock.WriteUnlock();
1459 }
1460 else
1461 {
1462 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1463 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1464 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001465 {
Sean Callanana3772862012-06-02 01:16:20 +00001466 if (new_state_is_stopped)
1467 {
1468 if (log)
1469 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1470 m_run_lock.WriteUnlock();
1471 }
Greg Claytona894fe72012-04-05 16:12:35 +00001472 }
Greg Claytona894fe72012-04-05 16:12:35 +00001473 }
1474 }
Chris Lattner24943d22010-06-08 16:52:24 +00001475}
1476
Jim Ingham027aaa72012-04-19 01:40:33 +00001477Error
1478Process::Resume ()
1479{
1480 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1481 if (log)
1482 log->Printf("Process::Resume -- locking run lock");
1483 if (!m_run_lock.WriteTryLock())
1484 {
1485 Error error("Resume request failed - process still running.");
1486 if (log)
1487 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1488 return error;
1489 }
1490 return PrivateResume();
1491}
1492
Chris Lattner24943d22010-06-08 16:52:24 +00001493StateType
1494Process::GetPrivateState ()
1495{
1496 return m_private_state.GetValue();
1497}
1498
1499void
1500Process::SetPrivateState (StateType new_state)
1501{
Greg Clayton68ca8232011-01-25 02:58:48 +00001502 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001503 bool state_changed = false;
1504
1505 if (log)
1506 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1507
1508 Mutex::Locker locker(m_private_state.GetMutex());
1509
1510 const StateType old_state = m_private_state.GetValueNoLock ();
1511 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001512 // This code is left commented out in case we ever need to control
1513 // the private process state with another run lock. Right now it doesn't
1514 // seem like we need to do this, but if we ever do, we can uncomment and
1515 // use this code.
1516// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1517// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1518// if (old_state_is_stopped != new_state_is_stopped)
1519// {
1520// if (new_state_is_stopped)
1521// m_private_run_lock.WriteUnlock();
1522// else
1523// m_private_run_lock.WriteLock();
1524// }
1525
Chris Lattner24943d22010-06-08 16:52:24 +00001526 if (state_changed)
1527 {
1528 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001529 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001530 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001531 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001532 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001533 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001534 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001535 }
1536 // Use our target to get a shared pointer to ourselves...
1537 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1538 }
1539 else
1540 {
1541 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001542 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001543 }
1544}
1545
Jim Ingham0296fe72011-11-08 03:00:11 +00001546void
1547Process::SetRunningUserExpression (bool on)
1548{
1549 m_mod_id.SetRunningUserExpression (on);
1550}
1551
Chris Lattner24943d22010-06-08 16:52:24 +00001552addr_t
1553Process::GetImageInfoAddress()
1554{
1555 return LLDB_INVALID_ADDRESS;
1556}
1557
Greg Clayton0baa3942010-11-04 01:54:29 +00001558//----------------------------------------------------------------------
1559// LoadImage
1560//
1561// This function provides a default implementation that works for most
1562// unix variants. Any Process subclasses that need to do shared library
1563// loading differently should override LoadImage and UnloadImage and
1564// do what is needed.
1565//----------------------------------------------------------------------
1566uint32_t
1567Process::LoadImage (const FileSpec &image_spec, Error &error)
1568{
Greg Clayton77d40712012-04-18 00:05:19 +00001569 char path[PATH_MAX];
1570 image_spec.GetPath(path, sizeof(path));
1571
Greg Clayton0baa3942010-11-04 01:54:29 +00001572 DynamicLoader *loader = GetDynamicLoader();
1573 if (loader)
1574 {
1575 error = loader->CanLoadImage();
1576 if (error.Fail())
1577 return LLDB_INVALID_IMAGE_TOKEN;
1578 }
1579
1580 if (error.Success())
1581 {
1582 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001583
1584 if (thread_sp)
1585 {
1586 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1587
1588 if (frame_sp)
1589 {
1590 ExecutionContext exe_ctx;
1591 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001592 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001593 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001594 expr.Printf("dlopen (\"%s\", 2)", path);
1595 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001596 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001597 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chenb14ec342011-09-09 00:01:43 +00001598 error = result_valobj_sp->GetError();
1599 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001600 {
1601 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001602 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001603 {
1604 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1605 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1606 {
1607 uint32_t image_token = m_image_tokens.size();
1608 m_image_tokens.push_back (image_ptr);
1609 return image_token;
1610 }
1611 }
1612 }
1613 }
1614 }
1615 }
Greg Clayton77d40712012-04-18 00:05:19 +00001616 if (!error.AsCString())
1617 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001618 return LLDB_INVALID_IMAGE_TOKEN;
1619}
1620
1621//----------------------------------------------------------------------
1622// UnloadImage
1623//
1624// This function provides a default implementation that works for most
1625// unix variants. Any Process subclasses that need to do shared library
1626// loading differently should override LoadImage and UnloadImage and
1627// do what is needed.
1628//----------------------------------------------------------------------
1629Error
1630Process::UnloadImage (uint32_t image_token)
1631{
1632 Error error;
1633 if (image_token < m_image_tokens.size())
1634 {
1635 const addr_t image_addr = m_image_tokens[image_token];
1636 if (image_addr == LLDB_INVALID_ADDRESS)
1637 {
1638 error.SetErrorString("image already unloaded");
1639 }
1640 else
1641 {
1642 DynamicLoader *loader = GetDynamicLoader();
1643 if (loader)
1644 error = loader->CanLoadImage();
1645
1646 if (error.Success())
1647 {
1648 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001649
1650 if (thread_sp)
1651 {
1652 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1653
1654 if (frame_sp)
1655 {
1656 ExecutionContext exe_ctx;
1657 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001658 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001659 StreamString expr;
1660 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1661 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001662 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001663 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +00001664 if (result_valobj_sp->GetError().Success())
1665 {
1666 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001667 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001668 {
1669 if (scalar.UInt(1))
1670 {
1671 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1672 }
1673 else
1674 {
1675 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1676 }
1677 }
1678 }
1679 else
1680 {
1681 error = result_valobj_sp->GetError();
1682 }
1683 }
1684 }
1685 }
1686 }
1687 }
1688 else
1689 {
1690 error.SetErrorString("invalid image token");
1691 }
1692 return error;
1693}
1694
Greg Clayton75906e42011-05-11 18:39:18 +00001695const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001696Process::GetABI()
1697{
Greg Clayton75906e42011-05-11 18:39:18 +00001698 if (!m_abi_sp)
1699 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1700 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001701}
1702
Jim Ingham642036f2010-09-23 02:01:19 +00001703LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001704Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001705{
1706 LanguageRuntimeCollection::iterator pos;
1707 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001708 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001709 {
Jim Inghame3117662012-03-10 00:22:19 +00001710 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001711
Jim Inghame3117662012-03-10 00:22:19 +00001712 m_language_runtimes[language] = runtime_sp;
1713 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001714 }
1715 else
1716 return (*pos).second.get();
1717}
1718
1719CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001720Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001721{
Jim Inghame3117662012-03-10 00:22:19 +00001722 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001723 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1724 return static_cast<CPPLanguageRuntime *> (runtime);
1725 return NULL;
1726}
1727
1728ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001729Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001730{
Jim Inghame3117662012-03-10 00:22:19 +00001731 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001732 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1733 return static_cast<ObjCLanguageRuntime *> (runtime);
1734 return NULL;
1735}
1736
Enrico Granata6b1763b2012-05-21 16:51:35 +00001737bool
1738Process::IsPossibleDynamicValue (ValueObject& in_value)
1739{
1740 if (in_value.IsDynamic())
1741 return false;
1742 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1743
1744 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1745 {
1746 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1747 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1748 }
1749
1750 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1751 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1752 return true;
1753
1754 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1755 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1756}
1757
Chris Lattner24943d22010-06-08 16:52:24 +00001758BreakpointSiteList &
1759Process::GetBreakpointSiteList()
1760{
1761 return m_breakpoint_site_list;
1762}
1763
1764const BreakpointSiteList &
1765Process::GetBreakpointSiteList() const
1766{
1767 return m_breakpoint_site_list;
1768}
1769
1770
1771void
1772Process::DisableAllBreakpointSites ()
1773{
1774 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001775 size_t num_sites = m_breakpoint_site_list.GetSize();
1776 for (size_t i = 0; i < num_sites; i++)
1777 {
1778 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1779 }
Chris Lattner24943d22010-06-08 16:52:24 +00001780}
1781
1782Error
1783Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1784{
1785 Error error (DisableBreakpointSiteByID (break_id));
1786
1787 if (error.Success())
1788 m_breakpoint_site_list.Remove(break_id);
1789
1790 return error;
1791}
1792
1793Error
1794Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1795{
1796 Error error;
1797 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1798 if (bp_site_sp)
1799 {
1800 if (bp_site_sp->IsEnabled())
1801 error = DisableBreakpoint (bp_site_sp.get());
1802 }
1803 else
1804 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001805 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001806 }
1807
1808 return error;
1809}
1810
1811Error
1812Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1813{
1814 Error error;
1815 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1816 if (bp_site_sp)
1817 {
1818 if (!bp_site_sp->IsEnabled())
1819 error = EnableBreakpoint (bp_site_sp.get());
1820 }
1821 else
1822 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001823 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001824 }
1825 return error;
1826}
1827
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001828lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001829Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001830{
Greg Clayton265ab332011-05-19 18:17:41 +00001831 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001832 if (load_addr != LLDB_INVALID_ADDRESS)
1833 {
1834 BreakpointSiteSP bp_site_sp;
1835
1836 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1837 // create a new breakpoint site and add it.
1838
1839 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1840
1841 if (bp_site_sp)
1842 {
1843 bp_site_sp->AddOwner (owner);
1844 owner->SetBreakpointSite (bp_site_sp);
1845 return bp_site_sp->GetID();
1846 }
1847 else
1848 {
1849 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1850 if (bp_site_sp)
1851 {
1852 if (EnableBreakpoint (bp_site_sp.get()).Success())
1853 {
1854 owner->SetBreakpointSite (bp_site_sp);
1855 return m_breakpoint_site_list.Add (bp_site_sp);
1856 }
1857 }
1858 }
1859 }
1860 // We failed to enable the breakpoint
1861 return LLDB_INVALID_BREAK_ID;
1862
1863}
1864
1865void
1866Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1867{
1868 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1869 if (num_owners == 0)
1870 {
1871 DisableBreakpoint(bp_site_sp.get());
1872 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1873 }
1874}
1875
1876
1877size_t
1878Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1879{
1880 size_t bytes_removed = 0;
1881 addr_t intersect_addr;
1882 size_t intersect_size;
1883 size_t opcode_offset;
1884 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001885 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001886 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001887
Jim Ingham82820f92011-06-29 19:42:28 +00001888 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001889 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001890 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001891 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001892 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001893 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001894 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001895 {
1896 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1897 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001898 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001899 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001900 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001901 }
Chris Lattner24943d22010-06-08 16:52:24 +00001902 }
1903 }
1904 }
1905 return bytes_removed;
1906}
1907
1908
Greg Claytonb1888f22011-03-19 01:12:21 +00001909
1910size_t
1911Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1912{
1913 PlatformSP platform_sp (m_target.GetPlatform());
1914 if (platform_sp)
1915 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1916 return 0;
1917}
1918
Chris Lattner24943d22010-06-08 16:52:24 +00001919Error
1920Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1921{
1922 Error error;
1923 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001924 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001925 const addr_t bp_addr = bp_site->GetLoadAddress();
1926 if (log)
1927 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1928 if (bp_site->IsEnabled())
1929 {
1930 if (log)
1931 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1932 return error;
1933 }
1934
1935 if (bp_addr == LLDB_INVALID_ADDRESS)
1936 {
1937 error.SetErrorString("BreakpointSite contains an invalid load address.");
1938 return error;
1939 }
1940 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1941 // trap for the breakpoint site
1942 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1943
1944 if (bp_opcode_size == 0)
1945 {
Greg Clayton9c236732011-10-26 00:56:27 +00001946 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001947 }
1948 else
1949 {
1950 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1951
1952 if (bp_opcode_bytes == NULL)
1953 {
1954 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1955 return error;
1956 }
1957
1958 // Save the original opcode by reading it
1959 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1960 {
1961 // Write a software breakpoint in place of the original opcode
1962 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1963 {
1964 uint8_t verify_bp_opcode_bytes[64];
1965 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1966 {
1967 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1968 {
1969 bp_site->SetEnabled(true);
1970 bp_site->SetType (BreakpointSite::eSoftware);
1971 if (log)
1972 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1973 bp_site->GetID(),
1974 (uint64_t)bp_addr);
1975 }
1976 else
Greg Clayton9c236732011-10-26 00:56:27 +00001977 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00001978 }
1979 else
1980 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1981 }
1982 else
1983 error.SetErrorString("Unable to write breakpoint trap to memory.");
1984 }
1985 else
1986 error.SetErrorString("Unable to read memory at breakpoint address.");
1987 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001988 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001989 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1990 bp_site->GetID(),
1991 (uint64_t)bp_addr,
1992 error.AsCString());
1993 return error;
1994}
1995
1996Error
1997Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1998{
1999 Error error;
2000 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00002001 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002002 addr_t bp_addr = bp_site->GetLoadAddress();
2003 lldb::user_id_t breakID = bp_site->GetID();
2004 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002005 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00002006
2007 if (bp_site->IsHardware())
2008 {
2009 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
2010 }
2011 else if (bp_site->IsEnabled())
2012 {
2013 const size_t break_op_size = bp_site->GetByteSize();
2014 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
2015 if (break_op_size > 0)
2016 {
2017 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00002018 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002019 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00002020 bool break_op_found = false;
2021
2022 // Read the breakpoint opcode
2023 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2024 {
2025 bool verify = false;
2026 // Make sure we have the a breakpoint opcode exists at this address
2027 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2028 {
2029 break_op_found = true;
2030 // We found a valid breakpoint opcode at this address, now restore
2031 // the saved opcode.
2032 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2033 {
2034 verify = true;
2035 }
2036 else
2037 error.SetErrorString("Memory write failed when restoring original opcode.");
2038 }
2039 else
2040 {
2041 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2042 // Set verify to true and so we can check if the original opcode has already been restored
2043 verify = true;
2044 }
2045
2046 if (verify)
2047 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002048 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002049 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002050 // Verify that our original opcode made it back to the inferior
2051 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2052 {
2053 // compare the memory we just read with the original opcode
2054 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2055 {
2056 // SUCCESS
2057 bp_site->SetEnabled(false);
2058 if (log)
2059 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2060 return error;
2061 }
2062 else
2063 {
2064 if (break_op_found)
2065 error.SetErrorString("Failed to restore original opcode.");
2066 }
2067 }
2068 else
2069 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2070 }
2071 }
2072 else
2073 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2074 }
2075 }
2076 else
2077 {
2078 if (log)
2079 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2080 return error;
2081 }
2082
2083 if (log)
2084 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2085 bp_site->GetID(),
2086 (uint64_t)bp_addr,
2087 error.AsCString());
2088 return error;
2089
2090}
2091
Greg Claytonfd119992011-01-07 06:08:19 +00002092// Uncomment to verify memory caching works after making changes to caching code
2093//#define VERIFY_MEMORY_READS
2094
Sean Callananf90b5f32012-06-07 22:26:42 +00002095size_t
2096Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2097{
2098 if (!GetDisableMemoryCache())
2099 {
Greg Claytonfd119992011-01-07 06:08:19 +00002100#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002101 // Memory caching is enabled, with debug verification
2102
2103 if (buf && size)
2104 {
2105 // Uncomment the line below to make sure memory caching is working.
2106 // I ran this through the test suite and got no assertions, so I am
2107 // pretty confident this is working well. If any changes are made to
2108 // memory caching, uncomment the line below and test your changes!
2109
2110 // Verify all memory reads by using the cache first, then redundantly
2111 // reading the same memory from the inferior and comparing to make sure
2112 // everything is exactly the same.
2113 std::string verify_buf (size, '\0');
2114 assert (verify_buf.size() == size);
2115 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2116 Error verify_error;
2117 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2118 assert (cache_bytes_read == verify_bytes_read);
2119 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2120 assert (verify_error.Success() == error.Success());
2121 return cache_bytes_read;
2122 }
2123 return 0;
2124#else // !defined(VERIFY_MEMORY_READS)
2125 // Memory caching is enabled, without debug verification
2126
2127 return m_memory_cache.Read (addr, buf, size, error);
2128#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002129 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002130 else
2131 {
2132 // Memory caching is disabled
2133
2134 return ReadMemoryFromInferior (addr, buf, size, error);
2135 }
Greg Claytonfd119992011-01-07 06:08:19 +00002136}
Greg Claytonfd119992011-01-07 06:08:19 +00002137
Greg Claytondd29b972012-05-18 23:20:01 +00002138size_t
2139Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2140{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002141 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002142 out_str.clear();
2143 addr_t curr_addr = addr;
2144 while (1)
2145 {
2146 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2147 if (length == 0)
2148 break;
2149 out_str.append(buf, length);
2150 // If we got "length - 1" bytes, we didn't get the whole C string, we
2151 // need to read some more characters
2152 if (length == sizeof(buf) - 1)
2153 curr_addr += length;
2154 else
2155 break;
2156 }
2157 return out_str.size();
2158}
2159
Greg Claytonfd119992011-01-07 06:08:19 +00002160
2161size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002162Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002163{
2164 size_t total_cstr_len = 0;
2165 if (dst && dst_max_len)
2166 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002167 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002168 // NULL out everything just to be safe
2169 memset (dst, 0, dst_max_len);
2170 Error error;
2171 addr_t curr_addr = addr;
2172 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2173 size_t bytes_left = dst_max_len - 1;
2174 char *curr_dst = dst;
2175
2176 while (bytes_left > 0)
2177 {
2178 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2179 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2180 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2181
2182 if (bytes_read == 0)
2183 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002184 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002185 dst[total_cstr_len] = '\0';
2186 break;
2187 }
2188 const size_t len = strlen(curr_dst);
2189
2190 total_cstr_len += len;
2191
2192 if (len < bytes_to_read)
2193 break;
2194
2195 curr_dst += bytes_read;
2196 curr_addr += bytes_read;
2197 bytes_left -= bytes_read;
2198 }
2199 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002200 else
2201 {
2202 if (dst == NULL)
2203 result_error.SetErrorString("invalid arguments");
2204 else
2205 result_error.Clear();
2206 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002207 return total_cstr_len;
2208}
2209
2210size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002211Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2212{
Chris Lattner24943d22010-06-08 16:52:24 +00002213 if (buf == NULL || size == 0)
2214 return 0;
2215
2216 size_t bytes_read = 0;
2217 uint8_t *bytes = (uint8_t *)buf;
2218
2219 while (bytes_read < size)
2220 {
2221 const size_t curr_size = size - bytes_read;
2222 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2223 bytes + bytes_read,
2224 curr_size,
2225 error);
2226 bytes_read += curr_bytes_read;
2227 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2228 break;
2229 }
2230
2231 // Replace any software breakpoint opcodes that fall into this range back
2232 // into "buf" before we return
2233 if (bytes_read > 0)
2234 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2235 return bytes_read;
2236}
2237
Greg Claytonf72fdee2010-12-16 20:01:20 +00002238uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002239Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002240{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002241 Scalar scalar;
2242 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2243 return scalar.ULongLong(fail_value);
2244 return fail_value;
2245}
2246
2247addr_t
2248Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2249{
2250 Scalar scalar;
2251 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2252 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2253 return LLDB_INVALID_ADDRESS;
2254}
2255
2256
2257bool
2258Process::WritePointerToMemory (lldb::addr_t vm_addr,
2259 lldb::addr_t ptr_value,
2260 Error &error)
2261{
2262 Scalar scalar;
2263 const uint32_t addr_byte_size = GetAddressByteSize();
2264 if (addr_byte_size <= 4)
2265 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002266 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002267 scalar = ptr_value;
2268 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002269}
2270
Chris Lattner24943d22010-06-08 16:52:24 +00002271size_t
2272Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2273{
2274 size_t bytes_written = 0;
2275 const uint8_t *bytes = (const uint8_t *)buf;
2276
2277 while (bytes_written < size)
2278 {
2279 const size_t curr_size = size - bytes_written;
2280 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2281 bytes + bytes_written,
2282 curr_size,
2283 error);
2284 bytes_written += curr_bytes_written;
2285 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2286 break;
2287 }
2288 return bytes_written;
2289}
2290
2291size_t
2292Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2293{
Greg Claytonfd119992011-01-07 06:08:19 +00002294#if defined (ENABLE_MEMORY_CACHING)
2295 m_memory_cache.Flush (addr, size);
2296#endif
2297
Chris Lattner24943d22010-06-08 16:52:24 +00002298 if (buf == NULL || size == 0)
2299 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002300
Jim Ingham21f37ad2011-08-09 02:12:22 +00002301 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002302
Chris Lattner24943d22010-06-08 16:52:24 +00002303 // We need to write any data that would go where any current software traps
2304 // (enabled software breakpoints) any software traps (breakpoints) that we
2305 // may have placed in our tasks memory.
2306
2307 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2308 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2309
2310 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002311 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002312
2313 BreakpointSiteList::collection::const_iterator pos;
2314 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002315 addr_t intersect_addr = 0;
2316 size_t intersect_size = 0;
2317 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002318 const uint8_t *ubuf = (const uint8_t *)buf;
2319
2320 for (pos = iter; pos != end; ++pos)
2321 {
2322 BreakpointSiteSP bp;
2323 bp = pos->second;
2324
2325 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2326 assert(addr <= intersect_addr && intersect_addr < addr + size);
2327 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2328 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2329
2330 // Check for bytes before this breakpoint
2331 const addr_t curr_addr = addr + bytes_written;
2332 if (intersect_addr > curr_addr)
2333 {
2334 // There are some bytes before this breakpoint that we need to
2335 // just write to memory
2336 size_t curr_size = intersect_addr - curr_addr;
2337 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2338 ubuf + bytes_written,
2339 curr_size,
2340 error);
2341 bytes_written += curr_bytes_written;
2342 if (curr_bytes_written != curr_size)
2343 {
2344 // We weren't able to write all of the requested bytes, we
2345 // are done looping and will return the number of bytes that
2346 // we have written so far.
2347 break;
2348 }
2349 }
2350
2351 // Now write any bytes that would cover up any software breakpoints
2352 // directly into the breakpoint opcode buffer
2353 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2354 bytes_written += intersect_size;
2355 }
2356
2357 // Write any remaining bytes after the last breakpoint if we have any left
2358 if (bytes_written < size)
2359 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2360 ubuf + bytes_written,
2361 size - bytes_written,
2362 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002363
Chris Lattner24943d22010-06-08 16:52:24 +00002364 return bytes_written;
2365}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002366
2367size_t
2368Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2369{
2370 if (byte_size == UINT32_MAX)
2371 byte_size = scalar.GetByteSize();
2372 if (byte_size > 0)
2373 {
2374 uint8_t buf[32];
2375 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2376 if (mem_size > 0)
2377 return WriteMemory(addr, buf, mem_size, error);
2378 else
2379 error.SetErrorString ("failed to get scalar as memory data");
2380 }
2381 else
2382 {
2383 error.SetErrorString ("invalid scalar value");
2384 }
2385 return 0;
2386}
2387
2388size_t
2389Process::ReadScalarIntegerFromMemory (addr_t addr,
2390 uint32_t byte_size,
2391 bool is_signed,
2392 Scalar &scalar,
2393 Error &error)
2394{
2395 uint64_t uval;
2396
2397 if (byte_size <= sizeof(uval))
2398 {
2399 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2400 if (bytes_read == byte_size)
2401 {
2402 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2403 uint32_t offset = 0;
2404 if (byte_size <= 4)
2405 scalar = data.GetMaxU32 (&offset, byte_size);
2406 else
2407 scalar = data.GetMaxU64 (&offset, byte_size);
2408
2409 if (is_signed)
2410 scalar.SignExtend(byte_size * 8);
2411 return bytes_read;
2412 }
2413 }
2414 else
2415 {
2416 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2417 }
2418 return 0;
2419}
2420
Greg Clayton613b8732011-05-17 03:37:42 +00002421#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002422addr_t
2423Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2424{
Jim Inghame6bd1422011-06-20 17:32:44 +00002425 if (GetPrivateState() != eStateStopped)
2426 return LLDB_INVALID_ADDRESS;
2427
Greg Clayton613b8732011-05-17 03:37:42 +00002428#if defined (USE_ALLOCATE_MEMORY_CACHE)
2429 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2430#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002431 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2432 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2433 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002434 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002435 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002436 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002437 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002438 m_mod_id.GetStopID(),
2439 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002440 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002441#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002442}
2443
Sean Callanan6cf6c472011-09-20 23:01:51 +00002444bool
2445Process::CanJIT ()
2446{
Sean Callanan04200f62012-02-14 22:50:38 +00002447 if (m_can_jit == eCanJITDontKnow)
2448 {
2449 Error err;
2450
2451 uint64_t allocated_memory = AllocateMemory(8,
2452 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2453 err);
2454
2455 if (err.Success())
2456 m_can_jit = eCanJITYes;
2457 else
2458 m_can_jit = eCanJITNo;
2459
2460 DeallocateMemory (allocated_memory);
2461 }
2462
Sean Callanan6cf6c472011-09-20 23:01:51 +00002463 return m_can_jit == eCanJITYes;
2464}
2465
2466void
2467Process::SetCanJIT (bool can_jit)
2468{
2469 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2470}
2471
Chris Lattner24943d22010-06-08 16:52:24 +00002472Error
2473Process::DeallocateMemory (addr_t ptr)
2474{
Greg Clayton613b8732011-05-17 03:37:42 +00002475 Error error;
2476#if defined (USE_ALLOCATE_MEMORY_CACHE)
2477 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2478 {
2479 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2480 }
2481#else
2482 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002483
2484 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2485 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002486 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002487 ptr,
2488 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002489 m_mod_id.GetStopID(),
2490 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002491#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002492 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002493}
2494
Greg Claytonb5a8f142012-02-05 02:38:54 +00002495ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002496Process::ReadModuleFromMemory (const FileSpec& file_spec,
2497 lldb::addr_t header_addr,
2498 bool add_image_to_target,
2499 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002500{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002501 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002502 if (module_sp)
2503 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002504 Error error;
2505 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2506 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002507 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002508 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002509 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002510 m_target.GetImages().Append(module_sp);
2511 if (load_sections_in_target)
2512 {
2513 bool changed = false;
2514 module_sp->SetLoadAddress (m_target, 0, changed);
2515 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002516 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002517 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002518 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002519 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002520 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002521}
Chris Lattner24943d22010-06-08 16:52:24 +00002522
2523Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002524Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002525{
2526 Error error;
2527 error.SetErrorString("watchpoints are not supported");
2528 return error;
2529}
2530
2531Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002532Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002533{
2534 Error error;
2535 error.SetErrorString("watchpoints are not supported");
2536 return error;
2537}
2538
2539StateType
2540Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2541{
2542 StateType state;
2543 // Now wait for the process to launch and return control to us, and then
2544 // call DidLaunch:
2545 while (1)
2546 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002547 event_sp.reset();
2548 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2549
Greg Clayton20206082011-11-17 01:23:07 +00002550 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002551 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002552
2553 // If state is invalid, then we timed out
2554 if (state == eStateInvalid)
2555 break;
2556
2557 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002558 HandlePrivateEvent (event_sp);
2559 }
2560 return state;
2561}
2562
2563Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002564Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002565{
2566 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002567 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002568 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002569 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002570 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002571
Greg Clayton5beb99d2011-08-11 02:48:45 +00002572 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002573 if (exe_module)
2574 {
Greg Clayton180546b2011-04-30 01:09:13 +00002575 char local_exec_file_path[PATH_MAX];
2576 char platform_exec_file_path[PATH_MAX];
2577 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2578 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002579 if (exe_module->GetFileSpec().Exists())
2580 {
Greg Claytona2f74232011-02-24 22:24:29 +00002581 if (PrivateStateThreadIsValid ())
2582 PausePrivateStateThread ();
2583
Chris Lattner24943d22010-06-08 16:52:24 +00002584 error = WillLaunch (exe_module);
2585 if (error.Success())
2586 {
Greg Claytond8c62532010-10-07 04:19:01 +00002587 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002588 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002589
Greg Clayton777c6b72012-09-04 20:29:05 +00002590 if (m_run_lock.WriteTryLock())
2591 {
2592 // Now launch using these arguments.
2593 error = DoLaunch (exe_module, launch_info);
2594 }
2595 else
2596 {
2597 // This shouldn't happen
2598 error.SetErrorString("failed to acquire process run lock");
2599 }
Chris Lattner24943d22010-06-08 16:52:24 +00002600
2601 if (error.Fail())
2602 {
2603 if (GetID() != LLDB_INVALID_PROCESS_ID)
2604 {
2605 SetID (LLDB_INVALID_PROCESS_ID);
2606 const char *error_string = error.AsCString();
2607 if (error_string == NULL)
2608 error_string = "launch failed";
2609 SetExitStatus (-1, error_string);
2610 }
2611 }
2612 else
2613 {
2614 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002615 TimeValue timeout_time;
2616 timeout_time = TimeValue::Now();
2617 timeout_time.OffsetWithSeconds(10);
2618 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002619
Greg Clayton49859592011-06-22 01:42:17 +00002620 if (state == eStateInvalid || event_sp.get() == NULL)
2621 {
2622 // We were able to launch the process, but we failed to
2623 // catch the initial stop.
2624 SetExitStatus (0, "failed to catch stop after launch");
2625 Destroy();
2626 }
2627 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002628 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002629
Chris Lattner24943d22010-06-08 16:52:24 +00002630 DidLaunch ();
2631
Greg Clayton9ce95382012-02-13 23:10:39 +00002632 DynamicLoader *dyld = GetDynamicLoader ();
2633 if (dyld)
2634 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002635
Greg Clayton37f962e2011-08-22 02:49:39 +00002636 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002637 // This delays passing the stopped event to listeners till DidLaunch gets
2638 // a chance to complete...
2639 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002640
2641 if (PrivateStateThreadIsValid ())
2642 ResumePrivateStateThread ();
2643 else
2644 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002645 }
2646 else if (state == eStateExited)
2647 {
2648 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2649 // not likely to work, and return an invalid pid.
2650 HandlePrivateEvent (event_sp);
2651 }
2652 }
2653 }
2654 }
2655 else
2656 {
Greg Clayton9c236732011-10-26 00:56:27 +00002657 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002658 }
2659 }
2660 return error;
2661}
2662
Greg Clayton46c9a352012-02-09 06:16:32 +00002663
2664Error
2665Process::LoadCore ()
2666{
2667 Error error = DoLoadCore();
2668 if (error.Success())
2669 {
2670 if (PrivateStateThreadIsValid ())
2671 ResumePrivateStateThread ();
2672 else
2673 StartPrivateStateThread ();
2674
Greg Clayton9ce95382012-02-13 23:10:39 +00002675 DynamicLoader *dyld = GetDynamicLoader ();
2676 if (dyld)
2677 dyld->DidAttach();
2678
2679 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002680 // We successfully loaded a core file, now pretend we stopped so we can
2681 // show all of the threads in the core file and explore the crashed
2682 // state.
2683 SetPrivateState (eStateStopped);
2684
2685 }
2686 return error;
2687}
2688
Greg Clayton9ce95382012-02-13 23:10:39 +00002689DynamicLoader *
2690Process::GetDynamicLoader ()
2691{
2692 if (m_dyld_ap.get() == NULL)
2693 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2694 return m_dyld_ap.get();
2695}
Greg Clayton46c9a352012-02-09 06:16:32 +00002696
2697
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002698Process::NextEventAction::EventActionResult
2699Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002700{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002701 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2702 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002703 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002704 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002705 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002706 return eEventActionRetry;
2707
2708 case eStateStopped:
2709 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002710 {
2711 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002712 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002713 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2714 if (m_exec_count > 0)
2715 {
2716 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002717 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002718 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002719 return eEventActionRetry;
2720 }
2721 else
2722 {
2723 m_process->CompleteAttach ();
2724 return eEventActionSuccess;
2725 }
2726 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002727 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002728
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002729 default:
2730 case eStateExited:
2731 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002732 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002733 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002734
2735 m_exit_string.assign ("No valid Process");
2736 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002737}
Chris Lattner24943d22010-06-08 16:52:24 +00002738
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002739Process::NextEventAction::EventActionResult
2740Process::AttachCompletionHandler::HandleBeingInterrupted()
2741{
2742 return eEventActionSuccess;
2743}
2744
2745const char *
2746Process::AttachCompletionHandler::GetExitString ()
2747{
2748 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002749}
2750
2751Error
Greg Clayton527154d2011-11-15 03:53:30 +00002752Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002753{
Chris Lattner24943d22010-06-08 16:52:24 +00002754 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002755 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002756 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002757 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002758
Greg Clayton527154d2011-11-15 03:53:30 +00002759 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002760 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002761 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002762 {
Greg Clayton527154d2011-11-15 03:53:30 +00002763 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002764
Greg Clayton527154d2011-11-15 03:53:30 +00002765 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002766 {
Greg Clayton527154d2011-11-15 03:53:30 +00002767 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2768
2769 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002770 {
Greg Clayton527154d2011-11-15 03:53:30 +00002771 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2772 if (error.Success())
2773 {
Greg Claytond34a3b22012-10-12 16:10:12 +00002774 if (m_run_lock.WriteTryLock())
2775 {
2776 m_should_detach = true;
2777 SetPublicState (eStateAttaching);
2778 // Now attach using these arguments.
2779 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2780 }
2781 else
2782 {
2783 // This shouldn't happen
2784 error.SetErrorString("failed to acquire process run lock");
2785 }
Greg Claytonffa43a62011-11-17 04:46:02 +00002786
Greg Clayton527154d2011-11-15 03:53:30 +00002787 if (error.Fail())
2788 {
2789 if (GetID() != LLDB_INVALID_PROCESS_ID)
2790 {
2791 SetID (LLDB_INVALID_PROCESS_ID);
2792 if (error.AsCString() == NULL)
2793 error.SetErrorString("attach failed");
2794
2795 SetExitStatus(-1, error.AsCString());
2796 }
2797 }
2798 else
2799 {
2800 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2801 StartPrivateStateThread();
2802 }
2803 return error;
2804 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002805 }
Greg Clayton527154d2011-11-15 03:53:30 +00002806 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002807 {
Greg Clayton527154d2011-11-15 03:53:30 +00002808 ProcessInstanceInfoList process_infos;
2809 PlatformSP platform_sp (m_target.GetPlatform ());
2810
2811 if (platform_sp)
2812 {
2813 ProcessInstanceInfoMatch match_info;
2814 match_info.GetProcessInfo() = attach_info;
2815 match_info.SetNameMatchType (eNameMatchEquals);
2816 platform_sp->FindProcesses (match_info, process_infos);
2817 const uint32_t num_matches = process_infos.GetSize();
2818 if (num_matches == 1)
2819 {
2820 attach_pid = process_infos.GetProcessIDAtIndex(0);
2821 // Fall through and attach using the above process ID
2822 }
2823 else
2824 {
2825 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2826 if (num_matches > 1)
2827 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2828 else
2829 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2830 }
2831 }
2832 else
2833 {
2834 error.SetErrorString ("invalid platform, can't find processes by name");
2835 return error;
2836 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002837 }
Chris Lattner24943d22010-06-08 16:52:24 +00002838 }
2839 else
Greg Clayton527154d2011-11-15 03:53:30 +00002840 {
2841 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002842 }
2843 }
Greg Clayton527154d2011-11-15 03:53:30 +00002844
2845 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002846 {
Greg Clayton527154d2011-11-15 03:53:30 +00002847 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002848 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002849 {
Greg Clayton527154d2011-11-15 03:53:30 +00002850
Greg Claytond34a3b22012-10-12 16:10:12 +00002851 if (m_run_lock.WriteTryLock())
2852 {
2853 // Now attach using these arguments.
2854 m_should_detach = true;
2855 SetPublicState (eStateAttaching);
2856 error = DoAttachToProcessWithID (attach_pid, attach_info);
2857 }
2858 else
2859 {
2860 // This shouldn't happen
2861 error.SetErrorString("failed to acquire process run lock");
2862 }
2863
Greg Clayton527154d2011-11-15 03:53:30 +00002864 if (error.Success())
2865 {
2866
2867 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2868 StartPrivateStateThread();
2869 }
2870 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002871 {
2872 if (GetID() != LLDB_INVALID_PROCESS_ID)
2873 {
2874 SetID (LLDB_INVALID_PROCESS_ID);
2875 const char *error_string = error.AsCString();
2876 if (error_string == NULL)
2877 error_string = "attach failed";
2878
2879 SetExitStatus(-1, error_string);
2880 }
2881 }
Chris Lattner24943d22010-06-08 16:52:24 +00002882 }
2883 }
2884 return error;
2885}
2886
Greg Clayton75c703d2011-02-16 04:46:07 +00002887void
2888Process::CompleteAttach ()
2889{
2890 // Let the process subclass figure out at much as it can about the process
2891 // before we go looking for a dynamic loader plug-in.
2892 DidAttach();
2893
Jim Ingham0d7f7772011-09-15 01:10:17 +00002894 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2895 // the same as the one we've already set, switch architectures.
2896 PlatformSP platform_sp (m_target.GetPlatform ());
2897 assert (platform_sp.get());
2898 if (platform_sp)
2899 {
Greg Claytonb170aee2012-05-08 01:45:38 +00002900 const ArchSpec &target_arch = m_target.GetArchitecture();
2901 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2902 {
2903 ArchSpec platform_arch;
2904 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2905 if (platform_sp)
2906 {
2907 m_target.SetPlatform (platform_sp);
2908 m_target.SetArchitecture(platform_arch);
2909 }
2910 }
2911 else
2912 {
2913 ProcessInstanceInfo process_info;
2914 platform_sp->GetProcessInfo (GetID(), process_info);
2915 const ArchSpec &process_arch = process_info.GetArchitecture();
2916 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2917 m_target.SetArchitecture (process_arch);
2918 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00002919 }
2920
2921 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002922 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00002923 DynamicLoader *dyld = GetDynamicLoader ();
2924 if (dyld)
2925 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00002926
Greg Clayton37f962e2011-08-22 02:49:39 +00002927 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002928 // Figure out which one is the executable, and set that in our target:
Jim Ingham93367902012-05-30 02:19:25 +00002929 ModuleList &target_modules = m_target.GetImages();
2930 Mutex::Locker modules_locker(target_modules.GetMutex());
2931 size_t num_modules = target_modules.GetSize();
2932 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00002933
Greg Clayton75c703d2011-02-16 04:46:07 +00002934 for (int i = 0; i < num_modules; i++)
2935 {
Jim Ingham93367902012-05-30 02:19:25 +00002936 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002937 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002938 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002939 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00002940 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00002941 break;
2942 }
2943 }
Jim Ingham93367902012-05-30 02:19:25 +00002944 if (new_executable_module_sp)
2945 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00002946}
2947
Chris Lattner24943d22010-06-08 16:52:24 +00002948Error
Jason Molendafac2e622012-09-29 04:02:01 +00002949Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00002950{
Greg Claytone71e2582011-02-04 01:58:07 +00002951 m_abi_sp.reset();
2952 m_process_input_reader.reset();
2953
2954 // Find the process and its architecture. Make sure it matches the architecture
2955 // of the current Target, and if not adjust it.
2956
Jason Molendafac2e622012-09-29 04:02:01 +00002957 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00002958 if (error.Success())
2959 {
Greg Claytona2f74232011-02-24 22:24:29 +00002960 if (GetID() != LLDB_INVALID_PROCESS_ID)
2961 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002962 EventSP event_sp;
2963 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2964
2965 if (state == eStateStopped || state == eStateCrashed)
2966 {
2967 // If we attached and actually have a process on the other end, then
2968 // this ended up being the equivalent of an attach.
2969 CompleteAttach ();
2970
2971 // This delays passing the stopped event to listeners till
2972 // CompleteAttach gets a chance to complete...
2973 HandlePrivateEvent (event_sp);
2974
2975 }
Greg Claytona2f74232011-02-24 22:24:29 +00002976 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002977
2978 if (PrivateStateThreadIsValid ())
2979 ResumePrivateStateThread ();
2980 else
2981 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002982 }
2983 return error;
2984}
2985
2986
2987Error
Jim Ingham027aaa72012-04-19 01:40:33 +00002988Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00002989{
Jim Inghame1a654b2012-09-06 19:24:17 +00002990 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00002991 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002992 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002993 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002994 StateAsCString(m_public_state.GetValue()),
2995 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002996
2997 Error error (WillResume());
2998 // Tell the process it is about to resume before the thread list
2999 if (error.Success())
3000 {
Johnny Chen9c11d472010-12-02 20:53:05 +00003001 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00003002 // can let all of our threads know that they are about to be
3003 // resumed. Threads will each be called with
3004 // Thread::WillResume(StateType) where StateType contains the state
3005 // that they are supposed to have when the process is resumed
3006 // (suspended/running/stepping). Threads should also check
3007 // their resume signal in lldb::Thread::GetResumeSignal()
3008 // to see if they are suppoed to start back up with a signal.
3009 if (m_thread_list.WillResume())
3010 {
Jim Ingham1831e782012-04-07 00:00:41 +00003011 // Last thing, do the PreResumeActions.
3012 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00003013 {
Jim Ingham1831e782012-04-07 00:00:41 +00003014 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
3015 }
3016 else
3017 {
3018 m_mod_id.BumpResumeID();
3019 error = DoResume();
3020 if (error.Success())
3021 {
3022 DidResume();
3023 m_thread_list.DidResume();
3024 if (log)
3025 log->Printf ("Process thinks the process has resumed.");
3026 }
Chris Lattner24943d22010-06-08 16:52:24 +00003027 }
3028 }
3029 else
3030 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003031 // Somebody wanted to run without running. So generate a continue & a stopped event,
3032 // and let the world handle them.
3033 if (log)
3034 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3035
3036 SetPrivateState(eStateRunning);
3037 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003038 }
3039 }
Jim Inghamac959662011-01-24 06:34:17 +00003040 else if (log)
3041 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003042 return error;
3043}
3044
3045Error
3046Process::Halt ()
3047{
Jim Ingham43892562012-06-06 00:29:30 +00003048 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3049 // we could just straightaway get another event. It just narrows the window...
3050 m_currently_handling_event.WaitForValueEqualTo(false);
3051
3052
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003053 // Pause our private state thread so we can ensure no one else eats
3054 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003055 Listener halt_listener ("lldb.process.halt_listener");
3056 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003057
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003058 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003059 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003060
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003061 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003062 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003063
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003064 bool caused_stop = false;
3065
3066 // Ask the process subclass to actually halt our process
3067 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003068 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003069 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003070 if (m_public_state.GetValue() == eStateAttaching)
3071 {
3072 SetExitStatus(SIGKILL, "Cancelled async attach.");
3073 Destroy ();
3074 }
3075 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003076 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003077 // If "caused_stop" is true, then DoHalt stopped the process. If
3078 // "caused_stop" is false, the process was already stopped.
3079 // If the DoHalt caused the process to stop, then we want to catch
3080 // this event and set the interrupted bool to true before we pass
3081 // this along so clients know that the process was interrupted by
3082 // a halt command.
3083 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003084 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003085 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003086 TimeValue timeout_time;
3087 timeout_time = TimeValue::Now();
3088 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003089 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3090 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003091
Jim Inghamf9f40c22011-02-08 05:20:59 +00003092 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003093 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003094 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003095 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003096 }
3097 else
3098 {
Greg Clayton20206082011-11-17 01:23:07 +00003099 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003100 {
3101 // We caused the process to interrupt itself, so mark this
3102 // as such in the stop event so clients can tell an interrupted
3103 // process from a natural stop
3104 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3105 }
3106 else
3107 {
3108 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3109 if (log)
3110 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3111 error.SetErrorString ("Did not get stopped event after halt.");
3112 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003113 }
3114 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003115 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003116 }
3117 }
Chris Lattner24943d22010-06-08 16:52:24 +00003118 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003119 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003120 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003121
3122 // Post any event we might have consumed. If all goes well, we will have
3123 // stopped the process, intercepted the event and set the interrupted
3124 // bool in the event. Post it to the private event queue and that will end up
3125 // correctly setting the state.
3126 if (event_sp)
3127 m_private_state_broadcaster.BroadcastEvent(event_sp);
3128
Chris Lattner24943d22010-06-08 16:52:24 +00003129 return error;
3130}
3131
3132Error
3133Process::Detach ()
3134{
3135 Error error (WillDetach());
3136
3137 if (error.Success())
3138 {
3139 DisableAllBreakpointSites();
3140 error = DoDetach();
3141 if (error.Success())
3142 {
3143 DidDetach();
3144 StopPrivateStateThread();
3145 }
3146 }
3147 return error;
3148}
3149
3150Error
3151Process::Destroy ()
3152{
3153 Error error (WillDestroy());
3154 if (error.Success())
3155 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003156 EventSP exit_event_sp;
Jim Inghamf4928de2012-05-23 15:46:31 +00003157 if (m_public_state.GetValue() == eStateRunning)
3158 {
Greg Clayton38ae5b92012-09-05 00:37:58 +00003159 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003160 if (log)
3161 log->Printf("Process::Destroy() About to halt.");
Jim Inghamf4928de2012-05-23 15:46:31 +00003162 error = Halt();
3163 if (error.Success())
3164 {
3165 // Consume the halt event.
Jim Inghamf4928de2012-05-23 15:46:31 +00003166 TimeValue timeout (TimeValue::Now());
Jim Ingham43892562012-06-06 00:29:30 +00003167 timeout.OffsetWithSeconds(1);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003168 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3169 if (state != eStateExited)
3170 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3171
Jim Inghamf4928de2012-05-23 15:46:31 +00003172 if (state != eStateStopped)
3173 {
Jim Inghamf4928de2012-05-23 15:46:31 +00003174 if (log)
3175 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Ingham43892562012-06-06 00:29:30 +00003176 // If we really couldn't stop the process then we should just error out here, but if the
3177 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3178 StateType private_state = m_private_state.GetValue();
3179 if (private_state != eStateStopped && private_state != eStateExited)
3180 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003181 // If we exited when we were waiting for a process to stop, then
3182 // forward the event here so we don't lose the event
Jim Ingham43892562012-06-06 00:29:30 +00003183 return error;
3184 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003185 }
3186 }
3187 else
3188 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003189 if (log)
3190 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3191 return error;
Jim Inghamf4928de2012-05-23 15:46:31 +00003192 }
3193 }
Jim Ingham43892562012-06-06 00:29:30 +00003194
3195 if (m_public_state.GetValue() != eStateRunning)
3196 {
3197 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3198 // kill it, we don't want it hitting a breakpoint...
3199 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3200 // we're not going to have much luck doing this now.
3201 m_thread_list.DiscardThreadPlans();
3202 DisableAllBreakpointSites();
3203 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003204
Chris Lattner24943d22010-06-08 16:52:24 +00003205 error = DoDestroy();
3206 if (error.Success())
3207 {
3208 DidDestroy();
3209 StopPrivateStateThread();
3210 }
Caroline Tice861efb32010-11-16 05:07:41 +00003211 m_stdio_communication.StopReadThread();
3212 m_stdio_communication.Disconnect();
3213 if (m_process_input_reader && m_process_input_reader->IsActive())
3214 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3215 if (m_process_input_reader)
3216 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003217
3218 // If we exited when we were waiting for a process to stop, then
3219 // forward the event here so we don't lose the event
3220 if (exit_event_sp)
3221 {
3222 // Directly broadcast our exited event because we shut down our
3223 // private state thread above
3224 BroadcastEvent(exit_event_sp);
3225 }
3226
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003227 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3228 // the last events through the event system, in which case we might strand the write lock. Unlock
3229 // it here so when we do to tear down the process we don't get an error destroying the lock.
3230 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003231 }
3232 return error;
3233}
3234
3235Error
3236Process::Signal (int signal)
3237{
3238 Error error (WillSignal());
3239 if (error.Success())
3240 {
3241 error = DoSignal(signal);
3242 if (error.Success())
3243 DidSignal();
3244 }
3245 return error;
3246}
3247
Greg Clayton395fc332011-02-15 21:59:32 +00003248lldb::ByteOrder
3249Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003250{
Greg Clayton395fc332011-02-15 21:59:32 +00003251 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003252}
3253
3254uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003255Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003256{
Greg Clayton395fc332011-02-15 21:59:32 +00003257 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003258}
3259
Greg Clayton395fc332011-02-15 21:59:32 +00003260
Chris Lattner24943d22010-06-08 16:52:24 +00003261bool
3262Process::ShouldBroadcastEvent (Event *event_ptr)
3263{
3264 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3265 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00003266 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003267
3268 switch (state)
3269 {
Greg Claytone71e2582011-02-04 01:58:07 +00003270 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003271 case eStateAttaching:
3272 case eStateLaunching:
3273 case eStateDetached:
3274 case eStateExited:
3275 case eStateUnloaded:
3276 // These events indicate changes in the state of the debugging session, always report them.
3277 return_value = true;
3278 break;
3279 case eStateInvalid:
3280 // We stopped for no apparent reason, don't report it.
3281 return_value = false;
3282 break;
3283 case eStateRunning:
3284 case eStateStepping:
3285 // If we've started the target running, we handle the cases where we
3286 // are already running and where there is a transition from stopped to
3287 // running differently.
3288 // running -> running: Automatically suppress extra running events
3289 // stopped -> running: Report except when there is one or more no votes
3290 // and no yes votes.
3291 SynchronouslyNotifyStateChanged (state);
3292 switch (m_public_state.GetValue())
3293 {
3294 case eStateRunning:
3295 case eStateStepping:
3296 // We always suppress multiple runnings with no PUBLIC stop in between.
3297 return_value = false;
3298 break;
3299 default:
3300 // TODO: make this work correctly. For now always report
3301 // run if we aren't running so we don't miss any runnning
3302 // events. If I run the lldb/test/thread/a.out file and
3303 // break at main.cpp:58, run and hit the breakpoints on
3304 // multiple threads, then somehow during the stepping over
3305 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003306
3307 // This is a transition from stop to run.
3308 switch (m_thread_list.ShouldReportRun (event_ptr))
3309 {
Greg Clayton4a379b12012-07-17 03:23:13 +00003310 default:
Chris Lattner24943d22010-06-08 16:52:24 +00003311 case eVoteYes:
3312 case eVoteNoOpinion:
3313 return_value = true;
3314 break;
3315 case eVoteNo:
3316 return_value = false;
3317 break;
3318 }
3319 break;
3320 }
3321 break;
3322 case eStateStopped:
3323 case eStateCrashed:
3324 case eStateSuspended:
3325 {
3326 // We've stopped. First see if we're going to restart the target.
3327 // If we are going to stop, then we always broadcast the event.
3328 // 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 +00003329 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003330
3331 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003332 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003333 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003334 if (log)
3335 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003336 return true;
3337 }
3338 else
3339 {
Chris Lattner24943d22010-06-08 16:52:24 +00003340
3341 if (m_thread_list.ShouldStop (event_ptr) == false)
3342 {
Jim Ingham8290bba2012-09-05 21:13:56 +00003343 // ShouldStop may have restarted the target already. If so, don't
3344 // resume it twice.
3345 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00003346 switch (m_thread_list.ShouldReportStop (event_ptr))
3347 {
3348 case eVoteYes:
3349 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003350 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003351 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003352 case eVoteNo:
3353 return_value = false;
3354 break;
3355 }
3356
3357 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003358 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham8290bba2012-09-05 21:13:56 +00003359 if (!was_restarted)
3360 PrivateResume ();
Chris Lattner24943d22010-06-08 16:52:24 +00003361 }
3362 else
3363 {
3364 return_value = true;
3365 SynchronouslyNotifyStateChanged (state);
3366 }
3367 }
3368 }
3369 }
3370
3371 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003372 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003373 return return_value;
3374}
3375
Chris Lattner24943d22010-06-08 16:52:24 +00003376
3377bool
Jim Ingham1831e782012-04-07 00:00:41 +00003378Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003379{
Greg Claytone005f2c2010-11-06 01:53:30 +00003380 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003381
Greg Claytonb72d0f02011-04-12 05:54:46 +00003382 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003383 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003384 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3385
Jim Ingham1831e782012-04-07 00:00:41 +00003386 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003387 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003388
3389 // Create a thread that watches our internal state and controls which
3390 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003391 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003392 if (already_running)
3393 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3394 else
3395 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003396
3397 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003398 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003399 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3400 if (success)
3401 {
3402 ResumePrivateStateThread();
3403 return true;
3404 }
3405 else
3406 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003407}
3408
3409void
3410Process::PausePrivateStateThread ()
3411{
3412 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3413}
3414
3415void
3416Process::ResumePrivateStateThread ()
3417{
3418 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3419}
3420
3421void
3422Process::StopPrivateStateThread ()
3423{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003424 if (PrivateStateThreadIsValid ())
3425 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003426 else
3427 {
3428 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3429 if (log)
3430 printf ("Went to stop the private state thread, but it was already invalid.");
3431 }
Chris Lattner24943d22010-06-08 16:52:24 +00003432}
3433
3434void
3435Process::ControlPrivateStateThread (uint32_t signal)
3436{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003437 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003438
3439 assert (signal == eBroadcastInternalStateControlStop ||
3440 signal == eBroadcastInternalStateControlPause ||
3441 signal == eBroadcastInternalStateControlResume);
3442
3443 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003444 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003445
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003446 // Signal the private state thread. First we should copy this is case the
3447 // thread starts exiting since the private state thread will NULL this out
3448 // when it exits
3449 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003450 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003451 {
3452 TimeValue timeout_time;
3453 bool timed_out;
3454
3455 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3456
3457 timeout_time = TimeValue::Now();
3458 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003459 if (log)
3460 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003461 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3462 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3463
3464 if (signal == eBroadcastInternalStateControlStop)
3465 {
3466 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003467 {
3468 Error error;
3469 Host::ThreadCancel (private_state_thread, &error);
3470 if (log)
3471 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3472 }
3473 else
3474 {
3475 if (log)
3476 log->Printf ("The control event killed the private state thread without having to cancel.");
3477 }
Chris Lattner24943d22010-06-08 16:52:24 +00003478
3479 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003480 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003481 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003482 }
3483 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003484 else
3485 {
3486 if (log)
3487 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3488 }
Chris Lattner24943d22010-06-08 16:52:24 +00003489}
3490
3491void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003492Process::SendAsyncInterrupt ()
3493{
3494 if (PrivateStateThreadIsValid())
3495 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3496 else
3497 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3498}
3499
3500void
Chris Lattner24943d22010-06-08 16:52:24 +00003501Process::HandlePrivateEvent (EventSP &event_sp)
3502{
Greg Claytone005f2c2010-11-06 01:53:30 +00003503 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003504 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003505
Greg Clayton68ca8232011-01-25 02:58:48 +00003506 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003507
3508 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003509 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003510 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003511 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003512 switch (action_result)
3513 {
3514 case NextEventAction::eEventActionSuccess:
3515 SetNextEventAction(NULL);
3516 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003517
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003518 case NextEventAction::eEventActionRetry:
3519 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003520
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003521 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003522 // Handle Exiting Here. If we already got an exited event,
3523 // we should just propagate it. Otherwise, swallow this event,
3524 // and set our state to exit so the next event will kill us.
3525 if (new_state != eStateExited)
3526 {
3527 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003528 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003529 SetNextEventAction(NULL);
3530 return;
3531 }
3532 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003533 break;
3534 }
3535 }
3536
Chris Lattner24943d22010-06-08 16:52:24 +00003537 // See if we should broadcast this state to external clients?
3538 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003539
3540 if (should_broadcast)
3541 {
3542 if (log)
3543 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003544 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003545 __FUNCTION__,
3546 GetID(),
3547 StateAsCString(new_state),
3548 StateAsCString (GetState ()),
3549 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003550 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003551 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003552 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003553 PushProcessInputReader ();
3554 else
3555 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003556
Chris Lattner24943d22010-06-08 16:52:24 +00003557 BroadcastEvent (event_sp);
3558 }
3559 else
3560 {
3561 if (log)
3562 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003563 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003564 __FUNCTION__,
3565 GetID(),
3566 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003567 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003568 }
3569 }
Jim Ingham43892562012-06-06 00:29:30 +00003570 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003571}
3572
3573void *
3574Process::PrivateStateThread (void *arg)
3575{
3576 Process *proc = static_cast<Process*> (arg);
3577 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003578 return result;
3579}
3580
3581void *
3582Process::RunPrivateStateThread ()
3583{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003584 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003585 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003586
Greg Claytone005f2c2010-11-06 01:53:30 +00003587 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003588 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003589 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003590
3591 bool exit_now = false;
3592 while (!exit_now)
3593 {
3594 EventSP event_sp;
3595 WaitForEventsPrivate (NULL, event_sp, control_only);
3596 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3597 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003598 if (log)
3599 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3600
Chris Lattner24943d22010-06-08 16:52:24 +00003601 switch (event_sp->GetType())
3602 {
3603 case eBroadcastInternalStateControlStop:
3604 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003605 break; // doing any internal state managment below
3606
3607 case eBroadcastInternalStateControlPause:
3608 control_only = true;
3609 break;
3610
3611 case eBroadcastInternalStateControlResume:
3612 control_only = false;
3613 break;
3614 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003615
Chris Lattner24943d22010-06-08 16:52:24 +00003616 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003617 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003618 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003619 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3620 {
3621 if (m_public_state.GetValue() == eStateAttaching)
3622 {
3623 if (log)
3624 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3625 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3626 }
3627 else
3628 {
3629 if (log)
3630 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3631 Halt();
3632 }
3633 continue;
3634 }
Chris Lattner24943d22010-06-08 16:52:24 +00003635
3636 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3637
3638 if (internal_state != eStateInvalid)
3639 {
3640 HandlePrivateEvent (event_sp);
3641 }
3642
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003643 if (internal_state == eStateInvalid ||
3644 internal_state == eStateExited ||
3645 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003646 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003647 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003648 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003649
Chris Lattner24943d22010-06-08 16:52:24 +00003650 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003651 }
Chris Lattner24943d22010-06-08 16:52:24 +00003652 }
3653
Caroline Tice926060e2010-10-29 21:48:37 +00003654 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003655 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003656 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003657
Greg Claytona4881d02011-01-22 07:12:45 +00003658 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3659 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003660 return NULL;
3661}
3662
Chris Lattner24943d22010-06-08 16:52:24 +00003663//------------------------------------------------------------------
3664// Process Event Data
3665//------------------------------------------------------------------
3666
3667Process::ProcessEventData::ProcessEventData () :
3668 EventData (),
3669 m_process_sp (),
3670 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003671 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003672 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003673 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003674{
3675}
3676
3677Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3678 EventData (),
3679 m_process_sp (process_sp),
3680 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003681 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003682 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003683 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003684{
3685}
3686
3687Process::ProcessEventData::~ProcessEventData()
3688{
3689}
3690
3691const ConstString &
3692Process::ProcessEventData::GetFlavorString ()
3693{
3694 static ConstString g_flavor ("Process::ProcessEventData");
3695 return g_flavor;
3696}
3697
3698const ConstString &
3699Process::ProcessEventData::GetFlavor () const
3700{
3701 return ProcessEventData::GetFlavorString ();
3702}
3703
Chris Lattner24943d22010-06-08 16:52:24 +00003704void
3705Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3706{
3707 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003708 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3709 // the public event queue, then other times when we're pretending that this is where we stopped at the
3710 // end of expression evaluation. m_update_state is used to distinguish these
3711 // three cases; it is 0 when we're just pulling it off for private handling,
3712 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003713
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003714 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003715 return;
3716
3717 m_process_sp->SetPublicState (m_state);
3718
3719 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3720 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003721 {
3722 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003723 uint32_t num_threads = curr_thread_list.GetSize();
3724 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003725
Jim Ingham21f37ad2011-08-09 02:12:22 +00003726 // The actions might change one of the thread's stop_info's opinions about whether we should
3727 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003728
3729 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3730 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3731 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3732 // 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
3733 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003734 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003735 for (idx = 0; idx < num_threads; ++idx)
3736 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3737
Jim Ingham21f37ad2011-08-09 02:12:22 +00003738 bool still_should_stop = true;
3739
Chris Lattner24943d22010-06-08 16:52:24 +00003740 for (idx = 0; idx < num_threads; ++idx)
3741 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003742 curr_thread_list = m_process_sp->GetThreadList();
3743 if (curr_thread_list.GetSize() != num_threads)
3744 {
3745 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003746 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003747 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 +00003748 break;
3749 }
3750
3751 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3752
3753 if (thread_sp->GetIndexID() != thread_index_array[idx])
3754 {
3755 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003756 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003757 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003758 idx,
3759 thread_index_array[idx],
3760 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003761 break;
3762 }
3763
Jim Ingham6297a3a2010-10-20 00:39:53 +00003764 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00003765 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00003766 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003767 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003768 // The stop action might restart the target. If it does, then we want to mark that in the
3769 // event so that whoever is receiving it will know to wait for the running event and reflect
3770 // that state appropriately.
3771 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003772
3773 // FIXME: we might have run.
3774 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003775 {
3776 SetRestarted (true);
3777 break;
3778 }
3779 else if (!stop_info_sp->ShouldStop(event_ptr))
3780 {
3781 still_should_stop = false;
3782 }
Chris Lattner24943d22010-06-08 16:52:24 +00003783 }
3784 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003785
Jim Ingham21f37ad2011-08-09 02:12:22 +00003786
3787 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003788 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003789 if (!still_should_stop)
3790 {
3791 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003792 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00003793 // Use the public resume method here, since this is just
3794 // extending a public resume.
Jim Ingham21f37ad2011-08-09 02:12:22 +00003795 m_process_sp->Resume();
3796 }
3797 else
3798 {
3799 // If we didn't restart, run the Stop Hooks here:
3800 // They might also restart the target, so watch for that.
3801 m_process_sp->GetTarget().RunStopHooks();
3802 if (m_process_sp->GetPrivateState() == eStateRunning)
3803 SetRestarted(true);
3804 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003805 }
3806
Chris Lattner24943d22010-06-08 16:52:24 +00003807 }
3808}
3809
3810void
3811Process::ProcessEventData::Dump (Stream *s) const
3812{
3813 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003814 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003815
Greg Claytonb72d0f02011-04-12 05:54:46 +00003816 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003817}
3818
3819const Process::ProcessEventData *
3820Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3821{
3822 if (event_ptr)
3823 {
3824 const EventData *event_data = event_ptr->GetData();
3825 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3826 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3827 }
3828 return NULL;
3829}
3830
3831ProcessSP
3832Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3833{
3834 ProcessSP process_sp;
3835 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3836 if (data)
3837 process_sp = data->GetProcessSP();
3838 return process_sp;
3839}
3840
3841StateType
3842Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3843{
3844 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3845 if (data == NULL)
3846 return eStateInvalid;
3847 else
3848 return data->GetState();
3849}
3850
3851bool
3852Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3853{
3854 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3855 if (data == NULL)
3856 return false;
3857 else
3858 return data->GetRestarted();
3859}
3860
3861void
3862Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3863{
3864 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3865 if (data != NULL)
3866 data->SetRestarted(new_value);
3867}
3868
3869bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003870Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3871{
3872 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3873 if (data == NULL)
3874 return false;
3875 else
3876 return data->GetInterrupted ();
3877}
3878
3879void
3880Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3881{
3882 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3883 if (data != NULL)
3884 data->SetInterrupted(new_value);
3885}
3886
3887bool
Chris Lattner24943d22010-06-08 16:52:24 +00003888Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3889{
3890 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3891 if (data)
3892 {
3893 data->SetUpdateStateOnRemoval();
3894 return true;
3895 }
3896 return false;
3897}
3898
Greg Clayton289afcb2012-02-18 05:35:26 +00003899lldb::TargetSP
3900Process::CalculateTarget ()
3901{
3902 return m_target.shared_from_this();
3903}
3904
Chris Lattner24943d22010-06-08 16:52:24 +00003905void
Greg Claytona830adb2010-10-04 01:05:56 +00003906Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003907{
Greg Clayton567e7f32011-09-22 04:58:26 +00003908 exe_ctx.SetTargetPtr (&m_target);
3909 exe_ctx.SetProcessPtr (this);
3910 exe_ctx.SetThreadPtr(NULL);
3911 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003912}
3913
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003914//uint32_t
3915//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3916//{
3917// return 0;
3918//}
3919//
3920//ArchSpec
3921//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3922//{
3923// return Host::GetArchSpecForExistingProcess (pid);
3924//}
3925//
3926//ArchSpec
3927//Process::GetArchSpecForExistingProcess (const char *process_name)
3928//{
3929// return Host::GetArchSpecForExistingProcess (process_name);
3930//}
3931//
Caroline Tice861efb32010-11-16 05:07:41 +00003932void
3933Process::AppendSTDOUT (const char * s, size_t len)
3934{
Greg Clayton20d338f2010-11-18 05:57:03 +00003935 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003936 m_stdout_data.append (s, len);
Greg Claytonb3781332010-12-05 19:16:56 +00003937 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003938}
3939
3940void
Greg Claytonbd06ff42011-11-13 04:45:22 +00003941Process::AppendSTDERR (const char * s, size_t len)
3942{
3943 Mutex::Locker locker (m_stdio_communication_mutex);
3944 m_stderr_data.append (s, len);
3945 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3946}
3947
3948//------------------------------------------------------------------
3949// Process STDIO
3950//------------------------------------------------------------------
3951
3952size_t
3953Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3954{
3955 Mutex::Locker locker(m_stdio_communication_mutex);
3956 size_t bytes_available = m_stdout_data.size();
3957 if (bytes_available > 0)
3958 {
3959 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3960 if (log)
Greg Clayton851e30e2012-09-18 18:04:04 +00003961 log->Printf ("Process::GetSTDOUT (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00003962 if (bytes_available > buf_size)
3963 {
3964 memcpy(buf, m_stdout_data.c_str(), buf_size);
3965 m_stdout_data.erase(0, buf_size);
3966 bytes_available = buf_size;
3967 }
3968 else
3969 {
3970 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3971 m_stdout_data.clear();
3972 }
3973 }
3974 return bytes_available;
3975}
3976
3977
3978size_t
3979Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3980{
3981 Mutex::Locker locker(m_stdio_communication_mutex);
3982 size_t bytes_available = m_stderr_data.size();
3983 if (bytes_available > 0)
3984 {
3985 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3986 if (log)
Greg Clayton851e30e2012-09-18 18:04:04 +00003987 log->Printf ("Process::GetSTDERR (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00003988 if (bytes_available > buf_size)
3989 {
3990 memcpy(buf, m_stderr_data.c_str(), buf_size);
3991 m_stderr_data.erase(0, buf_size);
3992 bytes_available = buf_size;
3993 }
3994 else
3995 {
3996 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3997 m_stderr_data.clear();
3998 }
3999 }
4000 return bytes_available;
4001}
4002
4003void
Caroline Tice861efb32010-11-16 05:07:41 +00004004Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
4005{
4006 Process *process = (Process *) baton;
4007 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
4008}
4009
4010size_t
4011Process::ProcessInputReaderCallback (void *baton,
4012 InputReader &reader,
4013 lldb::InputReaderAction notification,
4014 const char *bytes,
4015 size_t bytes_len)
4016{
4017 Process *process = (Process *) baton;
4018
4019 switch (notification)
4020 {
4021 case eInputReaderActivate:
4022 break;
4023
4024 case eInputReaderDeactivate:
4025 break;
4026
4027 case eInputReaderReactivate:
4028 break;
4029
Caroline Tice4a348082011-05-02 20:41:46 +00004030 case eInputReaderAsynchronousOutputWritten:
4031 break;
4032
Caroline Tice861efb32010-11-16 05:07:41 +00004033 case eInputReaderGotToken:
4034 {
4035 Error error;
4036 process->PutSTDIN (bytes, bytes_len, error);
4037 }
4038 break;
4039
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004040 case eInputReaderInterrupt:
4041 process->Halt ();
4042 break;
4043
4044 case eInputReaderEndOfFile:
4045 process->AppendSTDOUT ("^D", 2);
4046 break;
4047
Caroline Tice861efb32010-11-16 05:07:41 +00004048 case eInputReaderDone:
4049 break;
4050
4051 }
4052
4053 return bytes_len;
4054}
4055
4056void
4057Process::ResetProcessInputReader ()
4058{
4059 m_process_input_reader.reset();
4060}
4061
4062void
Greg Clayton464c6162011-11-17 22:14:31 +00004063Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004064{
4065 // First set up the Read Thread for reading/handling process I/O
4066
4067 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4068
4069 if (conn_ap.get())
4070 {
4071 m_stdio_communication.SetConnection (conn_ap.release());
4072 if (m_stdio_communication.IsConnected())
4073 {
4074 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4075 m_stdio_communication.StartReadThread();
4076
4077 // Now read thread is set up, set up input reader.
4078
4079 if (!m_process_input_reader.get())
4080 {
4081 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4082 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4083 this,
4084 eInputReaderGranularityByte,
4085 NULL,
4086 NULL,
4087 false));
4088
4089 if (err.Fail())
4090 m_process_input_reader.reset();
4091 }
4092 }
4093 }
4094}
4095
4096void
4097Process::PushProcessInputReader ()
4098{
4099 if (m_process_input_reader && !m_process_input_reader->IsActive())
4100 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4101}
4102
4103void
4104Process::PopProcessInputReader ()
4105{
4106 if (m_process_input_reader && m_process_input_reader->IsActive())
4107 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4108}
4109
Greg Claytond284b662011-02-18 01:44:25 +00004110// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004111void
Caroline Tice2a456812011-03-10 22:14:10 +00004112Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004113{
Greg Clayton73844aa2012-08-22 17:17:09 +00004114// static std::vector<OptionEnumValueElement> g_plugins;
4115//
4116// int i=0;
4117// const char *name;
4118// OptionEnumValueElement option_enum;
4119// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4120// {
4121// if (name)
4122// {
4123// option_enum.value = i;
4124// option_enum.string_value = name;
4125// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4126// g_plugins.push_back (option_enum);
4127// }
4128// ++i;
4129// }
4130// option_enum.value = 0;
4131// option_enum.string_value = NULL;
4132// option_enum.usage = NULL;
4133// g_plugins.push_back (option_enum);
4134//
4135// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4136// {
4137// if (::strcmp (name, "plugin") == 0)
4138// {
4139// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4140// break;
4141// }
4142// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004143//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004144 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004145}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004146
Greg Clayton990de7b2010-11-18 23:32:35 +00004147void
Caroline Tice2a456812011-03-10 22:14:10 +00004148Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004149{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004150 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004151}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004152
Greg Clayton427f2902010-12-14 02:59:59 +00004153ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004154Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004155 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004156 bool stop_others,
Jim Ingham47beabb2012-10-16 21:41:58 +00004157 bool run_others,
Jim Ingham360f53f2010-11-30 02:22:11 +00004158 bool discard_on_error,
Jim Ingham47beabb2012-10-16 21:41:58 +00004159 uint32_t timeout_usec,
Jim Ingham360f53f2010-11-30 02:22:11 +00004160 Stream &errors)
4161{
4162 ExecutionResults return_value = eExecutionSetupError;
4163
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004164 if (thread_plan_sp.get() == NULL)
4165 {
4166 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004167 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004168 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004169
4170 if (exe_ctx.GetProcessPtr() != this)
4171 {
4172 errors.Printf("RunThreadPlan called on wrong process.");
4173 return eExecutionSetupError;
4174 }
4175
4176 Thread *thread = exe_ctx.GetThreadPtr();
4177 if (thread == NULL)
4178 {
4179 errors.Printf("RunThreadPlan called with invalid thread.");
4180 return eExecutionSetupError;
4181 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004182
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004183 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4184 // For that to be true the plan can't be private - since private plans suppress themselves in the
4185 // GetCompletedPlan call.
4186
4187 bool orig_plan_private = thread_plan_sp->GetPrivate();
4188 thread_plan_sp->SetPrivate(false);
4189
Jim Inghamac959662011-01-24 06:34:17 +00004190 if (m_private_state.GetValue() != eStateStopped)
4191 {
4192 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004193 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004194 }
4195
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004196 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004197 const uint32_t thread_idx_id = thread->GetIndexID();
4198 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004199
4200 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4201 // so we should arrange to reset them as well.
4202
Greg Clayton567e7f32011-09-22 04:58:26 +00004203 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004204
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004205 uint32_t selected_tid;
4206 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004207 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004208 {
4209 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004210 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004211 }
4212 else
4213 {
4214 selected_tid = LLDB_INVALID_THREAD_ID;
4215 }
4216
Jim Ingham1831e782012-04-07 00:00:41 +00004217 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004218 lldb::StateType old_state;
4219 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004220
Jim Inghamd21d98b2012-04-10 01:21:57 +00004221 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004222 if (Host::GetCurrentThread() == m_private_state_thread)
4223 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004224 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4225 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004226 // 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 +00004227 // we are fielding public events here.
4228 if (log)
4229 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4230
4231
Jim Ingham1831e782012-04-07 00:00:41 +00004232 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004233
4234 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4235 // returning control here.
4236 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4237 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4238 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4239 // do just what we want.
4240 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4241 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4242 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4243 old_state = m_public_state.GetValue();
4244 m_public_state.SetValueNoLock(eStateStopped);
4245
4246 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004247 StartPrivateStateThread(true);
4248 }
4249
4250 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004251
Jim Ingham6ae318c2011-01-23 21:14:08 +00004252 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004253
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004254 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004255
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004256 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004257 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4258 // restored on exit to the function.
4259 //
4260 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4261 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004262
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004263 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004264
Jim Ingham360f53f2010-11-30 02:22:11 +00004265 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004266 {
4267 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004268 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4269 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4270 thread->GetIndexID(),
4271 thread->GetID(),
4272 s.GetData());
4273 }
4274
4275 bool got_event;
4276 lldb::EventSP event_sp;
4277 lldb::StateType stop_state = lldb::eStateInvalid;
4278
4279 TimeValue* timeout_ptr = NULL;
4280 TimeValue real_timeout;
4281
4282 bool first_timeout = true;
4283 bool do_resume = true;
Jim Ingham47beabb2012-10-16 21:41:58 +00004284 const uint64_t default_one_thread_timeout_usec = 250000;
4285 uint64_t computed_timeout = 0;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004286
4287 while (1)
4288 {
4289 // We usually want to resume the process if we get to the top of the loop.
4290 // The only exception is if we get two running events with no intervening
4291 // stop, which can happen, we will just wait for then next stop event.
4292
4293 if (do_resume)
4294 {
4295 // Do the initial resume and wait for the running event before going further.
4296
4297 Error resume_error = PrivateResume ();
4298 if (!resume_error.Success())
4299 {
4300 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4301 return_value = eExecutionSetupError;
4302 break;
4303 }
4304
4305 real_timeout = TimeValue::Now();
4306 real_timeout.OffsetWithMicroSeconds(500000);
4307 timeout_ptr = &real_timeout;
4308
4309 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4310 if (!got_event)
4311 {
4312 if (log)
4313 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4314
4315 errors.Printf("Didn't get any event after initial resume, exiting.");
4316 return_value = eExecutionSetupError;
4317 break;
4318 }
4319
4320 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4321 if (stop_state != eStateRunning)
4322 {
4323 if (log)
Jim Ingham47beabb2012-10-16 21:41:58 +00004324 log->Printf("Process::RunThreadPlan(): didn't get running event after "
4325 "initial resume, got %s instead.",
4326 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004327
Jim Ingham47beabb2012-10-16 21:41:58 +00004328 errors.Printf("Didn't get running event after initial resume, got %s instead.",
4329 StateAsCString(stop_state));
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004330 return_value = eExecutionSetupError;
4331 break;
4332 }
4333
4334 if (log)
4335 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4336 // We need to call the function synchronously, so spin waiting for it to return.
4337 // If we get interrupted while executing, we're going to lose our context, and
4338 // won't be able to gather the result at this point.
4339 // We set the timeout AFTER the resume, since the resume takes some time and we
4340 // don't want to charge that to the timeout.
4341
Jim Ingham47beabb2012-10-16 21:41:58 +00004342 if (first_timeout)
4343 {
4344 if (run_others)
4345 {
4346 // If we are running all threads then we take half the time to run all threads, bounded by
4347 // .25 sec.
4348 if (timeout_usec == 0)
4349 computed_timeout = default_one_thread_timeout_usec;
4350 else
4351 {
4352 computed_timeout = timeout_usec / 2;
4353 if (computed_timeout > default_one_thread_timeout_usec)
4354 {
4355 computed_timeout = default_one_thread_timeout_usec;
4356 }
4357 timeout_usec -= computed_timeout;
4358 }
4359 }
4360 else
4361 {
4362 computed_timeout = timeout_usec;
4363 }
4364 }
4365 else
4366 {
4367 computed_timeout = timeout_usec;
4368 }
4369
4370 if (computed_timeout != 0)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004371 {
Enrico Granata6cca9692012-07-16 23:10:35 +00004372 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004373 real_timeout = TimeValue::Now();
Jim Ingham47beabb2012-10-16 21:41:58 +00004374 real_timeout.OffsetWithMicroSeconds(computed_timeout);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004375
4376 timeout_ptr = &real_timeout;
4377 }
Enrico Granata6cca9692012-07-16 23:10:35 +00004378 else
4379 {
Jim Ingham47beabb2012-10-16 21:41:58 +00004380 timeout_ptr = NULL;
Enrico Granata6cca9692012-07-16 23:10:35 +00004381 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004382 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004383 else
4384 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004385 if (log)
4386 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4387 do_resume = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004388 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004389
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004390 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004391 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004392
Jim Inghamf9f40c22011-02-08 05:20:59 +00004393 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004394 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004395 if (timeout_ptr)
4396 {
4397 StreamString s;
4398 s.Printf ("about to wait - timeout is:\n ");
4399 timeout_ptr->Dump (&s, 120);
4400 s.Printf ("\nNow is:\n ");
4401 TimeValue::Now().Dump (&s, 120);
4402 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4403 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004404 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004405 {
4406 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4407 }
4408 }
4409
4410 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4411
4412 if (got_event)
4413 {
4414 if (event_sp.get())
4415 {
4416 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004417 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004418 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004419 Halt();
4420 keep_going = false;
4421 return_value = eExecutionInterrupted;
4422 errors.Printf ("Execution halted by user interrupt.");
4423 if (log)
4424 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4425 }
4426 else
4427 {
4428 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4429 if (log)
4430 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4431
4432 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004433 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004434 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004435 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004436 // Yay, we're done. Now make sure that our thread plan actually completed.
4437 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4438 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004439 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004440 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004441 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004442 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4443 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004444 }
4445 else
4446 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004447 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4448 StopReason stop_reason = eStopReasonInvalid;
4449 if (stop_info_sp)
4450 stop_reason = stop_info_sp->GetStopReason();
4451 if (stop_reason == eStopReasonPlanComplete)
4452 {
4453 if (log)
4454 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4455 // Now mark this plan as private so it doesn't get reported as the stop reason
4456 // after this point.
4457 if (thread_plan_sp)
4458 thread_plan_sp->SetPrivate (orig_plan_private);
4459 return_value = eExecutionCompleted;
4460 }
4461 else
4462 {
4463 if (log)
4464 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004465
Jim Ingham5d90ade2012-07-27 23:57:19 +00004466 return_value = eExecutionInterrupted;
4467 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004468 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004469 }
4470 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004471
Jim Ingham5d90ade2012-07-27 23:57:19 +00004472 case lldb::eStateCrashed:
4473 if (log)
4474 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4475 return_value = eExecutionInterrupted;
4476 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004477
Jim Ingham5d90ade2012-07-27 23:57:19 +00004478 case lldb::eStateRunning:
4479 do_resume = false;
4480 keep_going = true;
4481 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004482
Jim Ingham5d90ade2012-07-27 23:57:19 +00004483 default:
4484 if (log)
4485 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4486
4487 if (stop_state == eStateExited)
4488 event_to_broadcast_sp = event_sp;
4489
Sean Callanan96abc622012-08-08 17:35:10 +00004490 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00004491 return_value = eExecutionInterrupted;
4492 break;
4493 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004494 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004495
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004496 if (keep_going)
4497 continue;
4498 else
4499 break;
4500 }
4501 else
4502 {
4503 if (log)
4504 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4505 return_value = eExecutionInterrupted;
4506 break;
4507 }
4508 }
4509 else
4510 {
4511 // If we didn't get an event that means we've timed out...
4512 // We will interrupt the process here. Depending on what we were asked to do we will
4513 // either exit, or try with all threads running for the same timeout.
4514 // Not really sure what to do if Halt fails here...
4515
4516 if (log) {
Jim Ingham47beabb2012-10-16 21:41:58 +00004517 if (run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004518 {
4519 if (first_timeout)
Jim Ingham47beabb2012-10-16 21:41:58 +00004520 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %lld timed out, "
4521 "trying for %d usec with all threads enabled.",
4522 computed_timeout, timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004523 else
4524 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
Jim Ingham47beabb2012-10-16 21:41:58 +00004525 "and timeout: %d timed out, abandoning execution.",
4526 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004527 }
4528 else
4529 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
Jim Ingham47beabb2012-10-16 21:41:58 +00004530 "abandoning execution.",
4531 timeout_usec);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004532 }
4533
4534 Error halt_error = Halt();
4535 if (halt_error.Success())
4536 {
4537 if (log)
4538 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4539
4540 // If halt succeeds, it always produces a stopped event. Wait for that:
4541
4542 real_timeout = TimeValue::Now();
4543 real_timeout.OffsetWithMicroSeconds(500000);
4544
4545 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4546
4547 if (got_event)
4548 {
4549 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4550 if (log)
4551 {
4552 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4553 if (stop_state == lldb::eStateStopped
4554 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4555 log->PutCString (" Event was the Halt interruption event.");
4556 }
4557
4558 if (stop_state == lldb::eStateStopped)
4559 {
4560 // Between the time we initiated the Halt and the time we delivered it, the process could have
4561 // already finished its job. Check that here:
4562
4563 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4564 {
4565 if (log)
4566 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4567 "Exiting wait loop.");
4568 return_value = eExecutionCompleted;
4569 break;
4570 }
4571
Jim Ingham47beabb2012-10-16 21:41:58 +00004572 if (!run_others)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004573 {
4574 if (log)
4575 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4576 return_value = eExecutionInterrupted;
4577 break;
4578 }
4579
4580 if (first_timeout)
4581 {
4582 // Set all the other threads to run, and return to the top of the loop, which will continue;
4583 first_timeout = false;
4584 thread_plan_sp->SetStopOthers (false);
4585 if (log)
4586 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4587
4588 continue;
4589 }
4590 else
4591 {
4592 // Running all threads failed, so return Interrupted.
4593 if (log)
4594 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4595 return_value = eExecutionInterrupted;
4596 break;
4597 }
4598 }
4599 }
4600 else
4601 { if (log)
4602 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4603 "I'm getting out of here passing Interrupted.");
4604 return_value = eExecutionInterrupted;
4605 break;
4606 }
4607 }
4608 else
4609 {
4610 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4611 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4612 if (log)
4613 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.",
4614 halt_error.AsCString());
4615 real_timeout = TimeValue::Now();
4616 real_timeout.OffsetWithMicroSeconds(500000);
4617 timeout_ptr = &real_timeout;
4618 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4619 if (!got_event || event_sp.get() == NULL)
4620 {
4621 // This is not going anywhere, bag out.
4622 if (log)
4623 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4624 return_value = eExecutionInterrupted;
4625 break;
4626 }
4627 else
4628 {
4629 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4630 if (log)
4631 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4632 if (stop_state == lldb::eStateStopped)
4633 {
4634 // Between the time we initiated the Halt and the time we delivered it, the process could have
4635 // already finished its job. Check that here:
4636
4637 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4638 {
4639 if (log)
4640 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4641 "Exiting wait loop.");
4642 return_value = eExecutionCompleted;
4643 break;
4644 }
4645
4646 if (first_timeout)
4647 {
4648 // Set all the other threads to run, and return to the top of the loop, which will continue;
4649 first_timeout = false;
4650 thread_plan_sp->SetStopOthers (false);
4651 if (log)
4652 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4653
4654 continue;
4655 }
4656 else
4657 {
4658 // Running all threads failed, so return Interrupted.
4659 if (log)
4660 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4661 return_value = eExecutionInterrupted;
4662 break;
4663 }
4664 }
4665 else
4666 {
4667 if (log)
4668 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4669 " a stopped event, instead got %s.", StateAsCString(stop_state));
4670 return_value = eExecutionInterrupted;
4671 break;
4672 }
4673 }
4674 }
4675
4676 }
4677
4678 } // END WAIT LOOP
4679
4680 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4681 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4682 {
4683 StopPrivateStateThread();
4684 Error error;
4685 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00004686 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004687 {
4688 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4689 }
4690 m_public_state.SetValueNoLock(old_state);
4691
4692 }
4693
4694
4695 // Now do some processing on the results of the run:
4696 if (return_value == eExecutionInterrupted)
4697 {
4698 if (log)
4699 {
4700 StreamString s;
4701 if (event_sp)
4702 event_sp->Dump (&s);
4703 else
4704 {
4705 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4706 }
4707
4708 StreamString ts;
4709
4710 const char *event_explanation = NULL;
4711
4712 do
4713 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004714 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004715 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004716 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004717 break;
4718 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004719 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004720 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004721 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004722 break;
4723 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004724 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004725 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004726 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4727
4728 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004729 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004730 event_explanation = "<no event data>";
4731 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004732 }
4733
Jim Ingham5d90ade2012-07-27 23:57:19 +00004734 Process *process = event_data->GetProcessSP().get();
4735
4736 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004737 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004738 event_explanation = "<no process>";
4739 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004740 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004741
4742 ThreadList &thread_list = process->GetThreadList();
4743
4744 uint32_t num_threads = thread_list.GetSize();
4745 uint32_t thread_index;
4746
4747 ts.Printf("<%u threads> ", num_threads);
4748
4749 for (thread_index = 0;
4750 thread_index < num_threads;
4751 ++thread_index)
4752 {
4753 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4754
4755 if (!thread)
4756 {
4757 ts.Printf("<?> ");
4758 continue;
4759 }
4760
4761 ts.Printf("<0x%4.4llx ", thread->GetID());
4762 RegisterContext *register_context = thread->GetRegisterContext().get();
4763
4764 if (register_context)
4765 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4766 else
4767 ts.Printf("[ip unknown] ");
4768
4769 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4770 if (stop_info_sp)
4771 {
4772 const char *stop_desc = stop_info_sp->GetDescription();
4773 if (stop_desc)
4774 ts.PutCString (stop_desc);
4775 }
4776 ts.Printf(">");
4777 }
4778
4779 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004780 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004781 } while (0);
4782
Jim Ingham5d90ade2012-07-27 23:57:19 +00004783 if (event_explanation)
4784 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004785 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00004786 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4787 }
4788
4789 if (discard_on_error && thread_plan_sp)
4790 {
4791 if (log)
4792 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4793 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4794 thread_plan_sp->SetPrivate (orig_plan_private);
4795 }
4796 else
4797 {
4798 if (log)
4799 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004800 }
4801 }
4802 else if (return_value == eExecutionSetupError)
4803 {
4804 if (log)
4805 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004806
4807 if (discard_on_error && thread_plan_sp)
4808 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004809 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004810 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004811 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004812 }
4813 else
4814 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004815 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004816 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004817 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004818 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4819 return_value = eExecutionCompleted;
4820 }
4821 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4822 {
4823 if (log)
4824 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4825 return_value = eExecutionDiscarded;
4826 }
4827 else
4828 {
4829 if (log)
4830 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4831 if (discard_on_error && thread_plan_sp)
4832 {
4833 if (log)
4834 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4835 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4836 thread_plan_sp->SetPrivate (orig_plan_private);
4837 }
4838 }
4839 }
4840
4841 // Thread we ran the function in may have gone away because we ran the target
4842 // Check that it's still there, and if it is put it back in the context. Also restore the
4843 // frame in the context if it is still present.
4844 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4845 if (thread)
4846 {
4847 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4848 }
4849
4850 // Also restore the current process'es selected frame & thread, since this function calling may
4851 // be done behind the user's back.
4852
4853 if (selected_tid != LLDB_INVALID_THREAD_ID)
4854 {
4855 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4856 {
4857 // We were able to restore the selected thread, now restore the frame:
4858 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4859 if (old_frame_sp)
4860 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00004861 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004862 }
4863 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004864
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004865 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00004866
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004867 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004868 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004869 if (log)
4870 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4871 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00004872 }
4873
4874 return return_value;
4875}
4876
4877const char *
4878Process::ExecutionResultAsCString (ExecutionResults result)
4879{
4880 const char *result_name;
4881
4882 switch (result)
4883 {
Greg Claytonb3448432011-03-24 21:19:54 +00004884 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004885 result_name = "eExecutionCompleted";
4886 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004887 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00004888 result_name = "eExecutionDiscarded";
4889 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004890 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004891 result_name = "eExecutionInterrupted";
4892 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004893 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00004894 result_name = "eExecutionSetupError";
4895 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004896 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00004897 result_name = "eExecutionTimedOut";
4898 break;
4899 }
4900 return result_name;
4901}
4902
Greg Claytonabe0fed2011-04-18 08:33:37 +00004903void
4904Process::GetStatus (Stream &strm)
4905{
4906 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00004907 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00004908 {
4909 if (state == eStateExited)
4910 {
4911 int exit_status = GetExitStatus();
4912 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00004913 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00004914 GetID(),
4915 exit_status,
4916 exit_status,
4917 exit_description ? exit_description : "");
4918 }
4919 else
4920 {
4921 if (state == eStateConnected)
4922 strm.Printf ("Connected to remote target.\n");
4923 else
Greg Clayton444e35b2011-10-19 18:09:39 +00004924 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00004925 }
4926 }
4927 else
4928 {
Greg Clayton444e35b2011-10-19 18:09:39 +00004929 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004930 }
4931}
4932
4933size_t
4934Process::GetThreadStatus (Stream &strm,
4935 bool only_threads_with_stop_reason,
4936 uint32_t start_frame,
4937 uint32_t num_frames,
4938 uint32_t num_frames_with_source)
4939{
4940 size_t num_thread_infos_dumped = 0;
4941
Jim Inghamb9950592012-09-10 20:50:15 +00004942 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004943 const size_t num_threads = GetThreadList().GetSize();
4944 for (uint32_t i = 0; i < num_threads; i++)
4945 {
4946 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4947 if (thread)
4948 {
4949 if (only_threads_with_stop_reason)
4950 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00004951 StopInfoSP stop_info_sp = thread->GetStopInfo();
4952 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00004953 continue;
4954 }
4955 thread->GetStatus (strm,
4956 start_frame,
4957 num_frames,
4958 num_frames_with_source);
4959 ++num_thread_infos_dumped;
4960 }
4961 }
4962 return num_thread_infos_dumped;
4963}
4964
Greg Clayton76113302012-02-22 04:37:26 +00004965void
4966Process::AddInvalidMemoryRegion (const LoadRange &region)
4967{
4968 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4969}
4970
4971bool
4972Process::RemoveInvalidMemoryRange (const LoadRange &region)
4973{
4974 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4975}
4976
Jim Ingham1831e782012-04-07 00:00:41 +00004977void
4978Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4979{
4980 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4981}
4982
4983bool
4984Process::RunPreResumeActions ()
4985{
4986 bool result = true;
4987 while (!m_pre_resume_actions.empty())
4988 {
4989 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
4990 m_pre_resume_actions.pop_back();
4991 bool this_result = action.callback (action.baton);
4992 if (result == true) result = this_result;
4993 }
4994 return result;
4995}
4996
4997void
4998Process::ClearPreResumeActions ()
4999{
5000 m_pre_resume_actions.clear();
5001}
Greg Clayton76113302012-02-22 04:37:26 +00005002
Greg Claytoncf5927e2012-05-18 02:38:05 +00005003void
5004Process::Flush ()
5005{
5006 m_thread_list.Flush();
5007}