blob: 3b37796f8d1adfc44dd068ec224727c6b8ccd8d1 [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 Clayton36bc5ea2011-11-03 21:22:33 +0000305ProcessInfo::SetArguments (char const **argv,
306 bool first_arg_is_executable,
307 bool first_arg_is_executable_and_argument)
308{
309 m_arguments.SetArguments (argv);
310
311 // Is the first argument the executable?
312 if (first_arg_is_executable)
313 {
314 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
315 if (first_arg)
316 {
317 // Yes the first argument is an executable, set it as the executable
318 // in the launch options. Don't resolve the file path as the path
319 // could be a remote platform path
320 const bool resolve = false;
321 m_executable.SetFile(first_arg, resolve);
322
323 // If argument zero is an executable and shouldn't be included
324 // in the arguments, remove it from the front of the arguments
325 if (first_arg_is_executable_and_argument == false)
326 m_arguments.DeleteArgumentAtIndex (0);
327 }
328 }
329}
330void
331ProcessInfo::SetArguments (const Args& args,
332 bool first_arg_is_executable,
333 bool first_arg_is_executable_and_argument)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000334{
335 // Copy all arguments
336 m_arguments = args;
337
338 // Is the first argument the executable?
339 if (first_arg_is_executable)
340 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000341 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000342 if (first_arg)
343 {
344 // Yes the first argument is an executable, set it as the executable
345 // in the launch options. Don't resolve the file path as the path
346 // could be a remote platform path
347 const bool resolve = false;
348 m_executable.SetFile(first_arg, resolve);
349
350 // If argument zero is an executable and shouldn't be included
351 // in the arguments, remove it from the front of the arguments
352 if (first_arg_is_executable_and_argument == false)
353 m_arguments.DeleteArgumentAtIndex (0);
354 }
355 }
356}
357
Greg Claytonabb33022011-11-08 02:43:13 +0000358void
Greg Clayton464c6162011-11-17 22:14:31 +0000359ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000360{
361 // If notthing was specified, then check the process for any default
362 // settings that were set with "settings set"
363 if (m_file_actions.empty())
364 {
Greg Claytonabb33022011-11-08 02:43:13 +0000365 if (m_flags.Test(eLaunchFlagDisableSTDIO))
366 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000367 AppendSuppressFileAction (STDIN_FILENO , true, false);
368 AppendSuppressFileAction (STDOUT_FILENO, false, true);
369 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000370 }
371 else
372 {
373 // Check for any values that might have gotten set with any of:
374 // (lldb) settings set target.input-path
375 // (lldb) settings set target.output-path
376 // (lldb) settings set target.error-path
Greg Clayton73844aa2012-08-22 17:17:09 +0000377 FileSpec in_path;
378 FileSpec out_path;
379 FileSpec err_path;
Greg Claytonabb33022011-11-08 02:43:13 +0000380 if (target)
381 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000382 in_path = target->GetStandardInputPath();
383 out_path = target->GetStandardOutputPath();
384 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000385 }
386
Greg Clayton73844aa2012-08-22 17:17:09 +0000387 if (in_path || out_path || err_path)
388 {
389 char path[PATH_MAX];
390 if (in_path && in_path.GetPath(path, sizeof(path)))
391 AppendOpenFileAction(STDIN_FILENO, path, true, false);
392
393 if (out_path && out_path.GetPath(path, sizeof(path)))
394 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
395
396 if (err_path && err_path.GetPath(path, sizeof(path)))
397 AppendOpenFileAction(STDERR_FILENO, path, false, true);
398 }
399 else if (default_to_use_pty)
Greg Clayton464c6162011-11-17 22:14:31 +0000400 {
401 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000402 {
Greg Clayton73844aa2012-08-22 17:17:09 +0000403 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
404 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
405 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
406 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000407 }
408 }
Greg Claytonabb33022011-11-08 02:43:13 +0000409 }
410 }
411}
412
Greg Clayton527154d2011-11-15 03:53:30 +0000413
414bool
Greg Clayton97471182012-04-14 01:42:46 +0000415ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
416 bool localhost,
417 bool will_debug,
418 bool first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000419{
420 error.Clear();
421
422 if (GetFlags().Test (eLaunchFlagLaunchInShell))
423 {
424 const char *shell_executable = GetShell();
425 if (shell_executable)
426 {
427 char shell_resolved_path[PATH_MAX];
428
429 if (localhost)
430 {
431 FileSpec shell_filespec (shell_executable, true);
432
433 if (!shell_filespec.Exists())
434 {
435 // Resolve the path in case we just got "bash", "sh" or "tcsh"
436 if (!shell_filespec.ResolveExecutableLocation ())
437 {
438 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
439 return false;
440 }
441 }
442 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
443 shell_executable = shell_resolved_path;
444 }
445
446 Args shell_arguments;
447 std::string safe_arg;
448 shell_arguments.AppendArgument (shell_executable);
Greg Clayton527154d2011-11-15 03:53:30 +0000449 shell_arguments.AppendArgument ("-c");
Greg Clayton97471182012-04-14 01:42:46 +0000450
451 StreamString shell_command;
452 if (will_debug)
Greg Clayton527154d2011-11-15 03:53:30 +0000453 {
Greg Clayton97471182012-04-14 01:42:46 +0000454 shell_command.PutCString ("exec");
455 if (GetArchitecture().IsValid())
456 {
457 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
458 // Set the resume count to 2:
459 // 1 - stop in shell
460 // 2 - stop in /usr/bin/arch
461 // 3 - then we will stop in our program
462 SetResumeCount(2);
463 }
464 else
465 {
466 // Set the resume count to 1:
467 // 1 - stop in shell
468 // 2 - then we will stop in our program
469 SetResumeCount(1);
470 }
Greg Clayton527154d2011-11-15 03:53:30 +0000471 }
472
473 const char **argv = GetArguments().GetConstArgumentVector ();
474 if (argv)
475 {
Greg Clayton97471182012-04-14 01:42:46 +0000476 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000477 {
Greg Clayton97471182012-04-14 01:42:46 +0000478 // There should only be one argument that is the shell command itself to be used as is
479 if (argv[0] && !argv[1])
480 shell_command.Printf("%s", argv[0]);
481 else
482 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000483 }
Greg Clayton97471182012-04-14 01:42:46 +0000484 else
485 {
486 for (size_t i=0; argv[i] != NULL; ++i)
487 {
488 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
489 shell_command.Printf(" %s", arg);
490 }
491 }
492 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000493 }
Greg Clayton97471182012-04-14 01:42:46 +0000494 else
495 {
496 return false;
497 }
498
Greg Clayton527154d2011-11-15 03:53:30 +0000499 m_executable.SetFile(shell_executable, false);
500 m_arguments = shell_arguments;
501 return true;
502 }
503 else
504 {
505 error.SetErrorString ("invalid shell path");
506 }
507 }
508 else
509 {
510 error.SetErrorString ("not launching in shell");
511 }
512 return false;
513}
514
515
Greg Clayton24bc5d92011-03-30 18:16:51 +0000516bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000517ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
518{
519 if ((read || write) && fd >= 0 && path && path[0])
520 {
521 m_action = eFileActionOpen;
522 m_fd = fd;
523 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000524 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000525 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000526 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000527 else
Greg Clayton527154d2011-11-15 03:53:30 +0000528 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000529 m_path.assign (path);
530 return true;
531 }
532 else
533 {
534 Clear();
535 }
536 return false;
537}
538
539bool
540ProcessLaunchInfo::FileAction::Close (int fd)
541{
542 Clear();
543 if (fd >= 0)
544 {
545 m_action = eFileActionClose;
546 m_fd = fd;
547 }
548 return m_fd >= 0;
549}
550
551
552bool
553ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
554{
555 Clear();
556 if (fd >= 0 && dup_fd >= 0)
557 {
558 m_action = eFileActionDuplicate;
559 m_fd = fd;
560 m_arg = dup_fd;
561 }
562 return m_fd >= 0;
563}
564
565
566
567bool
568ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
569 const FileAction *info,
570 Log *log,
571 Error& error)
572{
573 if (info == NULL)
574 return false;
575
576 switch (info->m_action)
577 {
578 case eFileActionNone:
579 error.Clear();
580 break;
581
582 case eFileActionClose:
583 if (info->m_fd == -1)
584 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
585 else
586 {
587 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
588 eErrorTypePOSIX);
589 if (log && (error.Fail() || log))
590 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
591 file_actions, info->m_fd);
592 }
593 break;
594
595 case eFileActionDuplicate:
596 if (info->m_fd == -1)
597 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
598 else if (info->m_arg == -1)
599 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
600 else
601 {
602 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
603 eErrorTypePOSIX);
604 if (log && (error.Fail() || log))
605 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
606 file_actions, info->m_fd, info->m_arg);
607 }
608 break;
609
610 case eFileActionOpen:
611 if (info->m_fd == -1)
612 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
613 else
614 {
615 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000616
Greg Claytonb72d0f02011-04-12 05:54:46 +0000617 mode_t mode = 0;
618
Greg Clayton527154d2011-11-15 03:53:30 +0000619 if (oflag & O_CREAT)
620 mode = 0640;
621
Greg Claytonb72d0f02011-04-12 05:54:46 +0000622 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
623 info->m_fd,
624 info->m_path.c_str(),
625 oflag,
626 mode),
627 eErrorTypePOSIX);
628 if (error.Fail() || log)
629 error.PutToLog(log,
630 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
631 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
632 }
633 break;
634
635 default:
636 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
637 break;
638 }
639 return error.Success();
640}
641
642Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000643ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000644{
645 Error error;
646 char short_option = (char) m_getopt_table[option_idx].val;
647
648 switch (short_option)
649 {
650 case 's': // Stop at program entry point
651 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
652 break;
653
Greg Claytonb72d0f02011-04-12 05:54:46 +0000654 case 'i': // STDIN for read only
655 {
656 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000657 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000658 launch_info.AppendFileAction (action);
659 }
660 break;
661
662 case 'o': // Open STDOUT for write only
663 {
664 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000665 if (action.Open (STDOUT_FILENO, option_arg, false, true))
666 launch_info.AppendFileAction (action);
667 }
668 break;
669
670 case 'e': // STDERR for write only
671 {
672 ProcessLaunchInfo::FileAction action;
673 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000674 launch_info.AppendFileAction (action);
675 }
676 break;
677
Greg Clayton95ec1682012-03-06 04:01:04 +0000678
Greg Claytonb72d0f02011-04-12 05:54:46 +0000679 case 'p': // Process plug-in name
680 launch_info.SetProcessPluginName (option_arg);
681 break;
682
683 case 'n': // Disable STDIO
684 {
685 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000686 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000687 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000688 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000689 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000690 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000691 launch_info.AppendFileAction (action);
692 }
693 break;
694
695 case 'w':
696 launch_info.SetWorkingDirectory (option_arg);
697 break;
698
699 case 't': // Open process in new terminal window
700 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
701 break;
702
703 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000704 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
705 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000706 break;
707
708 case 'A':
709 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
710 break;
711
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000712 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000713 if (option_arg && option_arg[0])
714 launch_info.SetShell (option_arg);
715 else
716 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000717 break;
718
Greg Claytonb72d0f02011-04-12 05:54:46 +0000719 case 'v':
720 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
721 break;
722
723 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000724 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000725 break;
726
727 }
728 return error;
729}
730
731OptionDefinition
732ProcessLaunchCommandOptions::g_option_table[] =
733{
734{ 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."},
735{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
736{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
737{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
738{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
739{ 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 +0000740{ 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 +0000741
742{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
743{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
744{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
745
746{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
747
748{ 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."},
749
750{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
751};
752
753
754
755bool
756ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000757{
758 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
759 return true;
760 const char *match_name = m_match_info.GetName();
761 if (!match_name)
762 return true;
763
764 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
765}
766
767bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000768ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000769{
770 if (!NameMatches (proc_info.GetName()))
771 return false;
772
773 if (m_match_info.ProcessIDIsValid() &&
774 m_match_info.GetProcessID() != proc_info.GetProcessID())
775 return false;
776
777 if (m_match_info.ParentProcessIDIsValid() &&
778 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
779 return false;
780
Greg Claytonb72d0f02011-04-12 05:54:46 +0000781 if (m_match_info.UserIDIsValid () &&
782 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000783 return false;
784
Greg Claytonb72d0f02011-04-12 05:54:46 +0000785 if (m_match_info.GroupIDIsValid () &&
786 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000787 return false;
788
789 if (m_match_info.EffectiveUserIDIsValid () &&
790 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
791 return false;
792
793 if (m_match_info.EffectiveGroupIDIsValid () &&
794 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
795 return false;
796
797 if (m_match_info.GetArchitecture().IsValid() &&
798 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
799 return false;
800 return true;
801}
802
803bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000804ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000805{
806 if (m_name_match_type != eNameMatchIgnore)
807 return false;
808
809 if (m_match_info.ProcessIDIsValid())
810 return false;
811
812 if (m_match_info.ParentProcessIDIsValid())
813 return false;
814
Greg Claytonb72d0f02011-04-12 05:54:46 +0000815 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000816 return false;
817
Greg Claytonb72d0f02011-04-12 05:54:46 +0000818 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000819 return false;
820
821 if (m_match_info.EffectiveUserIDIsValid ())
822 return false;
823
824 if (m_match_info.EffectiveGroupIDIsValid ())
825 return false;
826
827 if (m_match_info.GetArchitecture().IsValid())
828 return false;
829
830 if (m_match_all_users)
831 return false;
832
833 return true;
834
835}
836
837void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000838ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000839{
840 m_match_info.Clear();
841 m_name_match_type = eNameMatchIgnore;
842 m_match_all_users = false;
843}
Greg Claytonfd119992011-01-07 06:08:19 +0000844
Greg Clayton46c9a352012-02-09 06:16:32 +0000845ProcessSP
846Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000847{
Greg Clayton46c9a352012-02-09 06:16:32 +0000848 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000849 ProcessCreateInstance create_callback = NULL;
850 if (plugin_name)
851 {
852 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
853 if (create_callback)
854 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000855 process_sp = create_callback(target, listener, crash_file_path);
856 if (process_sp)
857 {
858 if (!process_sp->CanDebug(target, true))
859 process_sp.reset();
860 }
Chris Lattner24943d22010-06-08 16:52:24 +0000861 }
862 }
863 else
864 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000865 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000866 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000867 process_sp = create_callback(target, listener, crash_file_path);
868 if (process_sp)
869 {
870 if (!process_sp->CanDebug(target, false))
871 process_sp.reset();
872 else
873 break;
874 }
Chris Lattner24943d22010-06-08 16:52:24 +0000875 }
876 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000877 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000878}
879
Jim Ingham5a15e692012-02-16 06:50:00 +0000880ConstString &
881Process::GetStaticBroadcasterClass ()
882{
883 static ConstString class_name ("lldb.process");
884 return class_name;
885}
Chris Lattner24943d22010-06-08 16:52:24 +0000886
887//----------------------------------------------------------------------
888// Process constructor
889//----------------------------------------------------------------------
890Process::Process(Target &target, Listener &listener) :
Greg Clayton73844aa2012-08-22 17:17:09 +0000891 ProcessProperties (false),
Chris Lattner24943d22010-06-08 16:52:24 +0000892 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000893 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner24943d22010-06-08 16:52:24 +0000894 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000895 m_public_state (eStateUnloaded),
896 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000897 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
898 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000899 m_private_state_listener ("lldb.process.internal_state_listener"),
900 m_private_state_control_wait(),
901 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000902 m_mod_id (),
Chris Lattner24943d22010-06-08 16:52:24 +0000903 m_thread_index_id (0),
904 m_exit_status (-1),
905 m_exit_string (),
906 m_thread_list (this),
907 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000908 m_image_tokens (),
909 m_listener (listener),
910 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000911 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000912 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000913 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000914 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000915 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000916 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000917 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000918 m_stderr_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000919 m_memory_cache (*this),
920 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +0000921 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000922 m_next_event_action_ap(),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000923 m_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +0000924 m_currently_handling_event(false),
Jim Inghamd0bdddf2012-08-22 21:34:33 +0000925 m_finalize_called(false),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000926 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +0000927{
Jim Ingham5a15e692012-02-16 06:50:00 +0000928 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +0000929
Greg Claytone005f2c2010-11-06 01:53:30 +0000930 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000931 if (log)
932 log->Printf ("%p Process::Process()", this);
933
Greg Clayton49ce6822010-10-31 03:01:06 +0000934 SetEventName (eBroadcastBitStateChanged, "state-changed");
935 SetEventName (eBroadcastBitInterrupt, "interrupt");
936 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
937 SetEventName (eBroadcastBitSTDERR, "stderr-available");
938
Chris Lattner24943d22010-06-08 16:52:24 +0000939 listener.StartListeningForEvents (this,
940 eBroadcastBitStateChanged |
941 eBroadcastBitInterrupt |
942 eBroadcastBitSTDOUT |
943 eBroadcastBitSTDERR);
944
945 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +0000946 eBroadcastBitStateChanged |
947 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +0000948
949 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
950 eBroadcastInternalStateControlStop |
951 eBroadcastInternalStateControlPause |
952 eBroadcastInternalStateControlResume);
953}
954
955//----------------------------------------------------------------------
956// Destructor
957//----------------------------------------------------------------------
958Process::~Process()
959{
Greg Claytone005f2c2010-11-06 01:53:30 +0000960 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000961 if (log)
962 log->Printf ("%p Process::~Process()", this);
963 StopPrivateStateThread();
964}
965
Greg Clayton73844aa2012-08-22 17:17:09 +0000966const ProcessPropertiesSP &
967Process::GetGlobalProperties()
968{
969 static ProcessPropertiesSP g_settings_sp;
970 if (!g_settings_sp)
971 g_settings_sp.reset (new ProcessProperties (true));
972 return g_settings_sp;
973}
974
Chris Lattner24943d22010-06-08 16:52:24 +0000975void
976Process::Finalize()
977{
Greg Claytonffa43a62011-11-17 04:46:02 +0000978 switch (GetPrivateState())
979 {
980 case eStateConnected:
981 case eStateAttaching:
982 case eStateLaunching:
983 case eStateStopped:
984 case eStateRunning:
985 case eStateStepping:
986 case eStateCrashed:
987 case eStateSuspended:
988 if (GetShouldDetach())
989 Detach();
990 else
991 Destroy();
992 break;
993
994 case eStateInvalid:
995 case eStateUnloaded:
996 case eStateDetached:
997 case eStateExited:
998 break;
999 }
1000
Greg Clayton2f57db02011-10-01 00:45:15 +00001001 // Clear our broadcaster before we proceed with destroying
1002 Broadcaster::Clear();
1003
Chris Lattner24943d22010-06-08 16:52:24 +00001004 // Do any cleanup needed prior to being destructed... Subclasses
1005 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +00001006
1007 // We need to destroy the loader before the derived Process class gets destroyed
1008 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +00001009 m_dynamic_checkers_ap.reset();
1010 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00001011 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +00001012 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +00001013 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +00001014 std::vector<Notifications> empty_notifications;
1015 m_notifications.swap(empty_notifications);
1016 m_image_tokens.clear();
1017 m_memory_cache.Clear();
1018 m_allocated_memory_cache.Clear();
1019 m_language_runtimes.clear();
1020 m_next_event_action_ap.reset();
Jim Inghamd0bdddf2012-08-22 21:34:33 +00001021 m_finalize_called = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001022}
1023
1024void
1025Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1026{
1027 m_notifications.push_back(callbacks);
1028 if (callbacks.initialize != NULL)
1029 callbacks.initialize (callbacks.baton, this);
1030}
1031
1032bool
1033Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1034{
1035 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1036 for (pos = m_notifications.begin(); pos != end; ++pos)
1037 {
1038 if (pos->baton == callbacks.baton &&
1039 pos->initialize == callbacks.initialize &&
1040 pos->process_state_changed == callbacks.process_state_changed)
1041 {
1042 m_notifications.erase(pos);
1043 return true;
1044 }
1045 }
1046 return false;
1047}
1048
1049void
1050Process::SynchronouslyNotifyStateChanged (StateType state)
1051{
1052 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1053 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1054 {
1055 if (notification_pos->process_state_changed)
1056 notification_pos->process_state_changed (notification_pos->baton, this, state);
1057 }
1058}
1059
1060// FIXME: We need to do some work on events before the general Listener sees them.
1061// For instance if we are continuing from a breakpoint, we need to ensure that we do
1062// the little "insert real insn, step & stop" trick. But we can't do that when the
1063// event is delivered by the broadcaster - since that is done on the thread that is
1064// waiting for new events, so if we needed more than one event for our handling, we would
1065// stall. So instead we do it when we fetch the event off of the queue.
1066//
1067
1068StateType
1069Process::GetNextEvent (EventSP &event_sp)
1070{
1071 StateType state = eStateInvalid;
1072
1073 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1074 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1075
1076 return state;
1077}
1078
1079
1080StateType
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001081Process::WaitForProcessToStop (const TimeValue *timeout, lldb::EventSP *event_sp_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +00001082{
Jim Ingham21f37ad2011-08-09 02:12:22 +00001083 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1084 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1085 // on the event.
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001086 if (event_sp_ptr)
1087 event_sp_ptr->reset();
Jim Ingham21f37ad2011-08-09 02:12:22 +00001088 StateType state = GetState();
1089 // If we are exited or detached, we won't ever get back to any
1090 // other valid state...
1091 if (state == eStateDetached || state == eStateExited)
1092 return state;
1093
1094 while (state != eStateInvalid)
1095 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001096 EventSP event_sp;
Jim Ingham21f37ad2011-08-09 02:12:22 +00001097 state = WaitForStateChangedEvents (timeout, event_sp);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00001098 if (event_sp_ptr && event_sp)
1099 *event_sp_ptr = event_sp;
1100
Jim Ingham21f37ad2011-08-09 02:12:22 +00001101 switch (state)
1102 {
1103 case eStateCrashed:
1104 case eStateDetached:
1105 case eStateExited:
1106 case eStateUnloaded:
1107 return state;
1108 case eStateStopped:
1109 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1110 continue;
1111 else
1112 return state;
1113 default:
1114 continue;
1115 }
1116 }
1117 return state;
Chris Lattner24943d22010-06-08 16:52:24 +00001118}
1119
1120
1121StateType
1122Process::WaitForState
1123(
1124 const TimeValue *timeout,
1125 const StateType *match_states, const uint32_t num_match_states
1126)
1127{
1128 EventSP event_sp;
1129 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001130 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001131 while (state != eStateInvalid)
1132 {
Greg Claytond8c62532010-10-07 04:19:01 +00001133 // If we are exited or detached, we won't ever get back to any
1134 // other valid state...
1135 if (state == eStateDetached || state == eStateExited)
1136 return state;
1137
Chris Lattner24943d22010-06-08 16:52:24 +00001138 state = WaitForStateChangedEvents (timeout, event_sp);
1139
1140 for (i=0; i<num_match_states; ++i)
1141 {
1142 if (match_states[i] == state)
1143 return state;
1144 }
1145 }
1146 return state;
1147}
1148
Jim Ingham63e24d72010-10-11 23:53:14 +00001149bool
1150Process::HijackProcessEvents (Listener *listener)
1151{
1152 if (listener != NULL)
1153 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001154 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001155 }
1156 else
1157 return false;
1158}
1159
1160void
1161Process::RestoreProcessEvents ()
1162{
1163 RestoreBroadcaster();
1164}
1165
Jim Inghamf9f40c22011-02-08 05:20:59 +00001166bool
1167Process::HijackPrivateProcessEvents (Listener *listener)
1168{
1169 if (listener != NULL)
1170 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001171 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001172 }
1173 else
1174 return false;
1175}
1176
1177void
1178Process::RestorePrivateProcessEvents ()
1179{
1180 m_private_state_broadcaster.RestoreBroadcaster();
1181}
1182
Chris Lattner24943d22010-06-08 16:52:24 +00001183StateType
1184Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1185{
Greg Claytone005f2c2010-11-06 01:53:30 +00001186 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001187
1188 if (log)
1189 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1190
1191 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001192 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1193 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001194 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001195 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001196 {
1197 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1198 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1199 else if (log)
1200 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1201 }
Chris Lattner24943d22010-06-08 16:52:24 +00001202
1203 if (log)
1204 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1205 __FUNCTION__,
1206 timeout,
1207 StateAsCString(state));
1208 return state;
1209}
1210
1211Event *
1212Process::PeekAtStateChangedEvents ()
1213{
Greg Claytone005f2c2010-11-06 01:53:30 +00001214 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001215
1216 if (log)
1217 log->Printf ("Process::%s...", __FUNCTION__);
1218
1219 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001220 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1221 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001222 if (log)
1223 {
1224 if (event_ptr)
1225 {
1226 log->Printf ("Process::%s (event_ptr) => %s",
1227 __FUNCTION__,
1228 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1229 }
1230 else
1231 {
1232 log->Printf ("Process::%s no events found",
1233 __FUNCTION__);
1234 }
1235 }
1236 return event_ptr;
1237}
1238
1239StateType
1240Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1241{
Greg Claytone005f2c2010-11-06 01:53:30 +00001242 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001243
1244 if (log)
1245 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1246
1247 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001248 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1249 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001250 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001251 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001252 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1253 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001254
1255 // This is a bit of a hack, but when we wait here we could very well return
1256 // to the command-line, and that could disable the log, which would render the
1257 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001258 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001259 {
1260 if (state == eStateInvalid)
1261 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1262 else
1263 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1264 }
Chris Lattner24943d22010-06-08 16:52:24 +00001265 return state;
1266}
1267
1268bool
1269Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1270{
Greg Claytone005f2c2010-11-06 01:53:30 +00001271 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001272
1273 if (log)
1274 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1275
1276 if (control_only)
1277 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1278 else
1279 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1280}
1281
1282bool
1283Process::IsRunning () const
1284{
1285 return StateIsRunningState (m_public_state.GetValue());
1286}
1287
1288int
1289Process::GetExitStatus ()
1290{
1291 if (m_public_state.GetValue() == eStateExited)
1292 return m_exit_status;
1293 return -1;
1294}
1295
Greg Clayton638351a2010-12-04 00:10:17 +00001296
Chris Lattner24943d22010-06-08 16:52:24 +00001297const char *
1298Process::GetExitDescription ()
1299{
1300 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1301 return m_exit_string.c_str();
1302 return NULL;
1303}
1304
Greg Clayton72e1c782011-01-22 23:43:18 +00001305bool
Chris Lattner24943d22010-06-08 16:52:24 +00001306Process::SetExitStatus (int status, const char *cstr)
1307{
Greg Clayton68ca8232011-01-25 02:58:48 +00001308 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1309 if (log)
1310 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1311 status, status,
1312 cstr ? "\"" : "",
1313 cstr ? cstr : "NULL",
1314 cstr ? "\"" : "");
1315
Greg Clayton72e1c782011-01-22 23:43:18 +00001316 // We were already in the exited state
1317 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001318 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001319 if (log)
1320 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001321 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001322 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001323
1324 m_exit_status = status;
1325 if (cstr)
1326 m_exit_string = cstr;
1327 else
1328 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001329
Greg Clayton72e1c782011-01-22 23:43:18 +00001330 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001331
Greg Clayton72e1c782011-01-22 23:43:18 +00001332 SetPrivateState (eStateExited);
1333 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001334}
1335
1336// This static callback can be used to watch for local child processes on
1337// the current host. The the child process exits, the process will be
1338// found in the global target list (we want to be completely sure that the
1339// lldb_private::Process doesn't go away before we can deliver the signal.
1340bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001341Process::SetProcessExitStatus (void *callback_baton,
1342 lldb::pid_t pid,
1343 bool exited,
1344 int signo, // Zero for no signal
1345 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001346)
1347{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001348 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1349 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00001350 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001351 callback_baton,
1352 pid,
1353 exited,
1354 signo,
1355 exit_status);
1356
1357 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001358 {
Greg Clayton63094e02010-06-23 01:19:29 +00001359 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001360 if (target_sp)
1361 {
1362 ProcessSP process_sp (target_sp->GetProcessSP());
1363 if (process_sp)
1364 {
1365 const char *signal_cstr = NULL;
1366 if (signo)
1367 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1368
1369 process_sp->SetExitStatus (exit_status, signal_cstr);
1370 }
1371 }
1372 return true;
1373 }
1374 return false;
1375}
1376
1377
Greg Clayton37f962e2011-08-22 02:49:39 +00001378void
1379Process::UpdateThreadListIfNeeded ()
1380{
1381 const uint32_t stop_id = GetStopID();
1382 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1383 {
Greg Clayton20206082011-11-17 01:23:07 +00001384 const StateType state = GetPrivateState();
1385 if (StateIsStoppedState (state, true))
1386 {
1387 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001388 // m_thread_list does have its own mutex, but we need to
1389 // hold onto the mutex between the call to UpdateThreadList(...)
1390 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001391 ThreadList new_thread_list(this);
1392 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001393 // thread list, but only update if "true" is returned
1394 if (UpdateThreadList (m_thread_list, new_thread_list))
1395 {
1396 OperatingSystem *os = GetOperatingSystem ();
1397 if (os)
1398 os->UpdateThreadList (m_thread_list, new_thread_list);
1399 m_thread_list.Update (new_thread_list);
1400 m_thread_list.SetStopID (stop_id);
1401 }
Greg Clayton20206082011-11-17 01:23:07 +00001402 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001403 }
1404}
1405
Chris Lattner24943d22010-06-08 16:52:24 +00001406uint32_t
1407Process::GetNextThreadIndexID ()
1408{
1409 return ++m_thread_index_id;
1410}
1411
1412StateType
1413Process::GetState()
1414{
1415 // If any other threads access this we will need a mutex for it
1416 return m_public_state.GetValue ();
1417}
1418
1419void
1420Process::SetPublicState (StateType new_state)
1421{
Greg Clayton68ca8232011-01-25 02:58:48 +00001422 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001423 if (log)
1424 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001425 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001426 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001427
1428 // On the transition from Run to Stopped, we unlock the writer end of the
1429 // run lock. The lock gets locked in Resume, which is the public API
1430 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001431 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1432 {
Sean Callanana3772862012-06-02 01:16:20 +00001433 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001434 {
Sean Callanana3772862012-06-02 01:16:20 +00001435 if (log)
1436 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1437 m_run_lock.WriteUnlock();
1438 }
1439 else
1440 {
1441 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1442 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1443 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001444 {
Sean Callanana3772862012-06-02 01:16:20 +00001445 if (new_state_is_stopped)
1446 {
1447 if (log)
1448 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1449 m_run_lock.WriteUnlock();
1450 }
Greg Claytona894fe72012-04-05 16:12:35 +00001451 }
Greg Claytona894fe72012-04-05 16:12:35 +00001452 }
1453 }
Chris Lattner24943d22010-06-08 16:52:24 +00001454}
1455
Jim Ingham027aaa72012-04-19 01:40:33 +00001456Error
1457Process::Resume ()
1458{
1459 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1460 if (log)
1461 log->Printf("Process::Resume -- locking run lock");
1462 if (!m_run_lock.WriteTryLock())
1463 {
1464 Error error("Resume request failed - process still running.");
1465 if (log)
1466 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1467 return error;
1468 }
1469 return PrivateResume();
1470}
1471
Chris Lattner24943d22010-06-08 16:52:24 +00001472StateType
1473Process::GetPrivateState ()
1474{
1475 return m_private_state.GetValue();
1476}
1477
1478void
1479Process::SetPrivateState (StateType new_state)
1480{
Greg Clayton68ca8232011-01-25 02:58:48 +00001481 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001482 bool state_changed = false;
1483
1484 if (log)
1485 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1486
1487 Mutex::Locker locker(m_private_state.GetMutex());
1488
1489 const StateType old_state = m_private_state.GetValueNoLock ();
1490 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001491 // This code is left commented out in case we ever need to control
1492 // the private process state with another run lock. Right now it doesn't
1493 // seem like we need to do this, but if we ever do, we can uncomment and
1494 // use this code.
1495// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1496// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1497// if (old_state_is_stopped != new_state_is_stopped)
1498// {
1499// if (new_state_is_stopped)
1500// m_private_run_lock.WriteUnlock();
1501// else
1502// m_private_run_lock.WriteLock();
1503// }
1504
Chris Lattner24943d22010-06-08 16:52:24 +00001505 if (state_changed)
1506 {
1507 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001508 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001509 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001510 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001511 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001512 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001513 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001514 }
1515 // Use our target to get a shared pointer to ourselves...
1516 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1517 }
1518 else
1519 {
1520 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001521 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001522 }
1523}
1524
Jim Ingham0296fe72011-11-08 03:00:11 +00001525void
1526Process::SetRunningUserExpression (bool on)
1527{
1528 m_mod_id.SetRunningUserExpression (on);
1529}
1530
Chris Lattner24943d22010-06-08 16:52:24 +00001531addr_t
1532Process::GetImageInfoAddress()
1533{
1534 return LLDB_INVALID_ADDRESS;
1535}
1536
Greg Clayton0baa3942010-11-04 01:54:29 +00001537//----------------------------------------------------------------------
1538// LoadImage
1539//
1540// This function provides a default implementation that works for most
1541// unix variants. Any Process subclasses that need to do shared library
1542// loading differently should override LoadImage and UnloadImage and
1543// do what is needed.
1544//----------------------------------------------------------------------
1545uint32_t
1546Process::LoadImage (const FileSpec &image_spec, Error &error)
1547{
Greg Clayton77d40712012-04-18 00:05:19 +00001548 char path[PATH_MAX];
1549 image_spec.GetPath(path, sizeof(path));
1550
Greg Clayton0baa3942010-11-04 01:54:29 +00001551 DynamicLoader *loader = GetDynamicLoader();
1552 if (loader)
1553 {
1554 error = loader->CanLoadImage();
1555 if (error.Fail())
1556 return LLDB_INVALID_IMAGE_TOKEN;
1557 }
1558
1559 if (error.Success())
1560 {
1561 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001562
1563 if (thread_sp)
1564 {
1565 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1566
1567 if (frame_sp)
1568 {
1569 ExecutionContext exe_ctx;
1570 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001571 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001572 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001573 expr.Printf("dlopen (\"%s\", 2)", path);
1574 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001575 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001576 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 +00001577 error = result_valobj_sp->GetError();
1578 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001579 {
1580 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001581 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001582 {
1583 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1584 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1585 {
1586 uint32_t image_token = m_image_tokens.size();
1587 m_image_tokens.push_back (image_ptr);
1588 return image_token;
1589 }
1590 }
1591 }
1592 }
1593 }
1594 }
Greg Clayton77d40712012-04-18 00:05:19 +00001595 if (!error.AsCString())
1596 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001597 return LLDB_INVALID_IMAGE_TOKEN;
1598}
1599
1600//----------------------------------------------------------------------
1601// UnloadImage
1602//
1603// This function provides a default implementation that works for most
1604// unix variants. Any Process subclasses that need to do shared library
1605// loading differently should override LoadImage and UnloadImage and
1606// do what is needed.
1607//----------------------------------------------------------------------
1608Error
1609Process::UnloadImage (uint32_t image_token)
1610{
1611 Error error;
1612 if (image_token < m_image_tokens.size())
1613 {
1614 const addr_t image_addr = m_image_tokens[image_token];
1615 if (image_addr == LLDB_INVALID_ADDRESS)
1616 {
1617 error.SetErrorString("image already unloaded");
1618 }
1619 else
1620 {
1621 DynamicLoader *loader = GetDynamicLoader();
1622 if (loader)
1623 error = loader->CanLoadImage();
1624
1625 if (error.Success())
1626 {
1627 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001628
1629 if (thread_sp)
1630 {
1631 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1632
1633 if (frame_sp)
1634 {
1635 ExecutionContext exe_ctx;
1636 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001637 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001638 StreamString expr;
1639 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1640 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001641 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001642 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 +00001643 if (result_valobj_sp->GetError().Success())
1644 {
1645 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001646 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001647 {
1648 if (scalar.UInt(1))
1649 {
1650 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1651 }
1652 else
1653 {
1654 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1655 }
1656 }
1657 }
1658 else
1659 {
1660 error = result_valobj_sp->GetError();
1661 }
1662 }
1663 }
1664 }
1665 }
1666 }
1667 else
1668 {
1669 error.SetErrorString("invalid image token");
1670 }
1671 return error;
1672}
1673
Greg Clayton75906e42011-05-11 18:39:18 +00001674const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001675Process::GetABI()
1676{
Greg Clayton75906e42011-05-11 18:39:18 +00001677 if (!m_abi_sp)
1678 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1679 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001680}
1681
Jim Ingham642036f2010-09-23 02:01:19 +00001682LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001683Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001684{
1685 LanguageRuntimeCollection::iterator pos;
1686 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001687 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001688 {
Jim Inghame3117662012-03-10 00:22:19 +00001689 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001690
Jim Inghame3117662012-03-10 00:22:19 +00001691 m_language_runtimes[language] = runtime_sp;
1692 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001693 }
1694 else
1695 return (*pos).second.get();
1696}
1697
1698CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001699Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001700{
Jim Inghame3117662012-03-10 00:22:19 +00001701 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001702 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1703 return static_cast<CPPLanguageRuntime *> (runtime);
1704 return NULL;
1705}
1706
1707ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001708Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001709{
Jim Inghame3117662012-03-10 00:22:19 +00001710 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001711 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1712 return static_cast<ObjCLanguageRuntime *> (runtime);
1713 return NULL;
1714}
1715
Enrico Granata6b1763b2012-05-21 16:51:35 +00001716bool
1717Process::IsPossibleDynamicValue (ValueObject& in_value)
1718{
1719 if (in_value.IsDynamic())
1720 return false;
1721 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1722
1723 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1724 {
1725 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1726 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1727 }
1728
1729 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1730 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1731 return true;
1732
1733 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1734 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1735}
1736
Chris Lattner24943d22010-06-08 16:52:24 +00001737BreakpointSiteList &
1738Process::GetBreakpointSiteList()
1739{
1740 return m_breakpoint_site_list;
1741}
1742
1743const BreakpointSiteList &
1744Process::GetBreakpointSiteList() const
1745{
1746 return m_breakpoint_site_list;
1747}
1748
1749
1750void
1751Process::DisableAllBreakpointSites ()
1752{
1753 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001754 size_t num_sites = m_breakpoint_site_list.GetSize();
1755 for (size_t i = 0; i < num_sites; i++)
1756 {
1757 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1758 }
Chris Lattner24943d22010-06-08 16:52:24 +00001759}
1760
1761Error
1762Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1763{
1764 Error error (DisableBreakpointSiteByID (break_id));
1765
1766 if (error.Success())
1767 m_breakpoint_site_list.Remove(break_id);
1768
1769 return error;
1770}
1771
1772Error
1773Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1774{
1775 Error error;
1776 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1777 if (bp_site_sp)
1778 {
1779 if (bp_site_sp->IsEnabled())
1780 error = DisableBreakpoint (bp_site_sp.get());
1781 }
1782 else
1783 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001784 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001785 }
1786
1787 return error;
1788}
1789
1790Error
1791Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1792{
1793 Error error;
1794 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1795 if (bp_site_sp)
1796 {
1797 if (!bp_site_sp->IsEnabled())
1798 error = EnableBreakpoint (bp_site_sp.get());
1799 }
1800 else
1801 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001802 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001803 }
1804 return error;
1805}
1806
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001807lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001808Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001809{
Greg Clayton265ab332011-05-19 18:17:41 +00001810 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001811 if (load_addr != LLDB_INVALID_ADDRESS)
1812 {
1813 BreakpointSiteSP bp_site_sp;
1814
1815 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1816 // create a new breakpoint site and add it.
1817
1818 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1819
1820 if (bp_site_sp)
1821 {
1822 bp_site_sp->AddOwner (owner);
1823 owner->SetBreakpointSite (bp_site_sp);
1824 return bp_site_sp->GetID();
1825 }
1826 else
1827 {
1828 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1829 if (bp_site_sp)
1830 {
1831 if (EnableBreakpoint (bp_site_sp.get()).Success())
1832 {
1833 owner->SetBreakpointSite (bp_site_sp);
1834 return m_breakpoint_site_list.Add (bp_site_sp);
1835 }
1836 }
1837 }
1838 }
1839 // We failed to enable the breakpoint
1840 return LLDB_INVALID_BREAK_ID;
1841
1842}
1843
1844void
1845Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1846{
1847 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1848 if (num_owners == 0)
1849 {
1850 DisableBreakpoint(bp_site_sp.get());
1851 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1852 }
1853}
1854
1855
1856size_t
1857Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1858{
1859 size_t bytes_removed = 0;
1860 addr_t intersect_addr;
1861 size_t intersect_size;
1862 size_t opcode_offset;
1863 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001864 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001865 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001866
Jim Ingham82820f92011-06-29 19:42:28 +00001867 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001868 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001869 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001870 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001871 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001872 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001873 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001874 {
1875 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1876 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001877 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001878 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001879 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001880 }
Chris Lattner24943d22010-06-08 16:52:24 +00001881 }
1882 }
1883 }
1884 return bytes_removed;
1885}
1886
1887
Greg Claytonb1888f22011-03-19 01:12:21 +00001888
1889size_t
1890Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1891{
1892 PlatformSP platform_sp (m_target.GetPlatform());
1893 if (platform_sp)
1894 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1895 return 0;
1896}
1897
Chris Lattner24943d22010-06-08 16:52:24 +00001898Error
1899Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1900{
1901 Error error;
1902 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001903 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001904 const addr_t bp_addr = bp_site->GetLoadAddress();
1905 if (log)
1906 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1907 if (bp_site->IsEnabled())
1908 {
1909 if (log)
1910 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1911 return error;
1912 }
1913
1914 if (bp_addr == LLDB_INVALID_ADDRESS)
1915 {
1916 error.SetErrorString("BreakpointSite contains an invalid load address.");
1917 return error;
1918 }
1919 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1920 // trap for the breakpoint site
1921 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1922
1923 if (bp_opcode_size == 0)
1924 {
Greg Clayton9c236732011-10-26 00:56:27 +00001925 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001926 }
1927 else
1928 {
1929 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1930
1931 if (bp_opcode_bytes == NULL)
1932 {
1933 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1934 return error;
1935 }
1936
1937 // Save the original opcode by reading it
1938 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1939 {
1940 // Write a software breakpoint in place of the original opcode
1941 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1942 {
1943 uint8_t verify_bp_opcode_bytes[64];
1944 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1945 {
1946 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1947 {
1948 bp_site->SetEnabled(true);
1949 bp_site->SetType (BreakpointSite::eSoftware);
1950 if (log)
1951 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1952 bp_site->GetID(),
1953 (uint64_t)bp_addr);
1954 }
1955 else
Greg Clayton9c236732011-10-26 00:56:27 +00001956 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00001957 }
1958 else
1959 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1960 }
1961 else
1962 error.SetErrorString("Unable to write breakpoint trap to memory.");
1963 }
1964 else
1965 error.SetErrorString("Unable to read memory at breakpoint address.");
1966 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001967 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001968 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1969 bp_site->GetID(),
1970 (uint64_t)bp_addr,
1971 error.AsCString());
1972 return error;
1973}
1974
1975Error
1976Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1977{
1978 Error error;
1979 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001980 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001981 addr_t bp_addr = bp_site->GetLoadAddress();
1982 lldb::user_id_t breakID = bp_site->GetID();
1983 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001984 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001985
1986 if (bp_site->IsHardware())
1987 {
1988 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1989 }
1990 else if (bp_site->IsEnabled())
1991 {
1992 const size_t break_op_size = bp_site->GetByteSize();
1993 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1994 if (break_op_size > 0)
1995 {
1996 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001997 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001998 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001999 bool break_op_found = false;
2000
2001 // Read the breakpoint opcode
2002 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
2003 {
2004 bool verify = false;
2005 // Make sure we have the a breakpoint opcode exists at this address
2006 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2007 {
2008 break_op_found = true;
2009 // We found a valid breakpoint opcode at this address, now restore
2010 // the saved opcode.
2011 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2012 {
2013 verify = true;
2014 }
2015 else
2016 error.SetErrorString("Memory write failed when restoring original opcode.");
2017 }
2018 else
2019 {
2020 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2021 // Set verify to true and so we can check if the original opcode has already been restored
2022 verify = true;
2023 }
2024
2025 if (verify)
2026 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00002027 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00002028 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00002029 // Verify that our original opcode made it back to the inferior
2030 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2031 {
2032 // compare the memory we just read with the original opcode
2033 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2034 {
2035 // SUCCESS
2036 bp_site->SetEnabled(false);
2037 if (log)
2038 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2039 return error;
2040 }
2041 else
2042 {
2043 if (break_op_found)
2044 error.SetErrorString("Failed to restore original opcode.");
2045 }
2046 }
2047 else
2048 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2049 }
2050 }
2051 else
2052 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2053 }
2054 }
2055 else
2056 {
2057 if (log)
2058 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2059 return error;
2060 }
2061
2062 if (log)
2063 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2064 bp_site->GetID(),
2065 (uint64_t)bp_addr,
2066 error.AsCString());
2067 return error;
2068
2069}
2070
Greg Claytonfd119992011-01-07 06:08:19 +00002071// Uncomment to verify memory caching works after making changes to caching code
2072//#define VERIFY_MEMORY_READS
2073
Sean Callananf90b5f32012-06-07 22:26:42 +00002074size_t
2075Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2076{
2077 if (!GetDisableMemoryCache())
2078 {
Greg Claytonfd119992011-01-07 06:08:19 +00002079#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00002080 // Memory caching is enabled, with debug verification
2081
2082 if (buf && size)
2083 {
2084 // Uncomment the line below to make sure memory caching is working.
2085 // I ran this through the test suite and got no assertions, so I am
2086 // pretty confident this is working well. If any changes are made to
2087 // memory caching, uncomment the line below and test your changes!
2088
2089 // Verify all memory reads by using the cache first, then redundantly
2090 // reading the same memory from the inferior and comparing to make sure
2091 // everything is exactly the same.
2092 std::string verify_buf (size, '\0');
2093 assert (verify_buf.size() == size);
2094 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2095 Error verify_error;
2096 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2097 assert (cache_bytes_read == verify_bytes_read);
2098 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2099 assert (verify_error.Success() == error.Success());
2100 return cache_bytes_read;
2101 }
2102 return 0;
2103#else // !defined(VERIFY_MEMORY_READS)
2104 // Memory caching is enabled, without debug verification
2105
2106 return m_memory_cache.Read (addr, buf, size, error);
2107#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00002108 }
Sean Callananf90b5f32012-06-07 22:26:42 +00002109 else
2110 {
2111 // Memory caching is disabled
2112
2113 return ReadMemoryFromInferior (addr, buf, size, error);
2114 }
Greg Claytonfd119992011-01-07 06:08:19 +00002115}
Greg Claytonfd119992011-01-07 06:08:19 +00002116
Greg Claytondd29b972012-05-18 23:20:01 +00002117size_t
2118Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2119{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002120 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002121 out_str.clear();
2122 addr_t curr_addr = addr;
2123 while (1)
2124 {
2125 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2126 if (length == 0)
2127 break;
2128 out_str.append(buf, length);
2129 // If we got "length - 1" bytes, we didn't get the whole C string, we
2130 // need to read some more characters
2131 if (length == sizeof(buf) - 1)
2132 curr_addr += length;
2133 else
2134 break;
2135 }
2136 return out_str.size();
2137}
2138
Greg Claytonfd119992011-01-07 06:08:19 +00002139
2140size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002141Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002142{
2143 size_t total_cstr_len = 0;
2144 if (dst && dst_max_len)
2145 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002146 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002147 // NULL out everything just to be safe
2148 memset (dst, 0, dst_max_len);
2149 Error error;
2150 addr_t curr_addr = addr;
2151 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2152 size_t bytes_left = dst_max_len - 1;
2153 char *curr_dst = dst;
2154
2155 while (bytes_left > 0)
2156 {
2157 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2158 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2159 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2160
2161 if (bytes_read == 0)
2162 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002163 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002164 dst[total_cstr_len] = '\0';
2165 break;
2166 }
2167 const size_t len = strlen(curr_dst);
2168
2169 total_cstr_len += len;
2170
2171 if (len < bytes_to_read)
2172 break;
2173
2174 curr_dst += bytes_read;
2175 curr_addr += bytes_read;
2176 bytes_left -= bytes_read;
2177 }
2178 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002179 else
2180 {
2181 if (dst == NULL)
2182 result_error.SetErrorString("invalid arguments");
2183 else
2184 result_error.Clear();
2185 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002186 return total_cstr_len;
2187}
2188
2189size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002190Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2191{
Chris Lattner24943d22010-06-08 16:52:24 +00002192 if (buf == NULL || size == 0)
2193 return 0;
2194
2195 size_t bytes_read = 0;
2196 uint8_t *bytes = (uint8_t *)buf;
2197
2198 while (bytes_read < size)
2199 {
2200 const size_t curr_size = size - bytes_read;
2201 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2202 bytes + bytes_read,
2203 curr_size,
2204 error);
2205 bytes_read += curr_bytes_read;
2206 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2207 break;
2208 }
2209
2210 // Replace any software breakpoint opcodes that fall into this range back
2211 // into "buf" before we return
2212 if (bytes_read > 0)
2213 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2214 return bytes_read;
2215}
2216
Greg Claytonf72fdee2010-12-16 20:01:20 +00002217uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002218Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002219{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002220 Scalar scalar;
2221 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2222 return scalar.ULongLong(fail_value);
2223 return fail_value;
2224}
2225
2226addr_t
2227Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2228{
2229 Scalar scalar;
2230 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2231 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2232 return LLDB_INVALID_ADDRESS;
2233}
2234
2235
2236bool
2237Process::WritePointerToMemory (lldb::addr_t vm_addr,
2238 lldb::addr_t ptr_value,
2239 Error &error)
2240{
2241 Scalar scalar;
2242 const uint32_t addr_byte_size = GetAddressByteSize();
2243 if (addr_byte_size <= 4)
2244 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002245 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002246 scalar = ptr_value;
2247 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002248}
2249
Chris Lattner24943d22010-06-08 16:52:24 +00002250size_t
2251Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2252{
2253 size_t bytes_written = 0;
2254 const uint8_t *bytes = (const uint8_t *)buf;
2255
2256 while (bytes_written < size)
2257 {
2258 const size_t curr_size = size - bytes_written;
2259 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2260 bytes + bytes_written,
2261 curr_size,
2262 error);
2263 bytes_written += curr_bytes_written;
2264 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2265 break;
2266 }
2267 return bytes_written;
2268}
2269
2270size_t
2271Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2272{
Greg Claytonfd119992011-01-07 06:08:19 +00002273#if defined (ENABLE_MEMORY_CACHING)
2274 m_memory_cache.Flush (addr, size);
2275#endif
2276
Chris Lattner24943d22010-06-08 16:52:24 +00002277 if (buf == NULL || size == 0)
2278 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002279
Jim Ingham21f37ad2011-08-09 02:12:22 +00002280 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002281
Chris Lattner24943d22010-06-08 16:52:24 +00002282 // We need to write any data that would go where any current software traps
2283 // (enabled software breakpoints) any software traps (breakpoints) that we
2284 // may have placed in our tasks memory.
2285
2286 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2287 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2288
2289 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002290 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002291
2292 BreakpointSiteList::collection::const_iterator pos;
2293 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002294 addr_t intersect_addr = 0;
2295 size_t intersect_size = 0;
2296 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002297 const uint8_t *ubuf = (const uint8_t *)buf;
2298
2299 for (pos = iter; pos != end; ++pos)
2300 {
2301 BreakpointSiteSP bp;
2302 bp = pos->second;
2303
2304 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2305 assert(addr <= intersect_addr && intersect_addr < addr + size);
2306 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2307 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2308
2309 // Check for bytes before this breakpoint
2310 const addr_t curr_addr = addr + bytes_written;
2311 if (intersect_addr > curr_addr)
2312 {
2313 // There are some bytes before this breakpoint that we need to
2314 // just write to memory
2315 size_t curr_size = intersect_addr - curr_addr;
2316 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2317 ubuf + bytes_written,
2318 curr_size,
2319 error);
2320 bytes_written += curr_bytes_written;
2321 if (curr_bytes_written != curr_size)
2322 {
2323 // We weren't able to write all of the requested bytes, we
2324 // are done looping and will return the number of bytes that
2325 // we have written so far.
2326 break;
2327 }
2328 }
2329
2330 // Now write any bytes that would cover up any software breakpoints
2331 // directly into the breakpoint opcode buffer
2332 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2333 bytes_written += intersect_size;
2334 }
2335
2336 // Write any remaining bytes after the last breakpoint if we have any left
2337 if (bytes_written < size)
2338 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2339 ubuf + bytes_written,
2340 size - bytes_written,
2341 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002342
Chris Lattner24943d22010-06-08 16:52:24 +00002343 return bytes_written;
2344}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002345
2346size_t
2347Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2348{
2349 if (byte_size == UINT32_MAX)
2350 byte_size = scalar.GetByteSize();
2351 if (byte_size > 0)
2352 {
2353 uint8_t buf[32];
2354 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2355 if (mem_size > 0)
2356 return WriteMemory(addr, buf, mem_size, error);
2357 else
2358 error.SetErrorString ("failed to get scalar as memory data");
2359 }
2360 else
2361 {
2362 error.SetErrorString ("invalid scalar value");
2363 }
2364 return 0;
2365}
2366
2367size_t
2368Process::ReadScalarIntegerFromMemory (addr_t addr,
2369 uint32_t byte_size,
2370 bool is_signed,
2371 Scalar &scalar,
2372 Error &error)
2373{
2374 uint64_t uval;
2375
2376 if (byte_size <= sizeof(uval))
2377 {
2378 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2379 if (bytes_read == byte_size)
2380 {
2381 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2382 uint32_t offset = 0;
2383 if (byte_size <= 4)
2384 scalar = data.GetMaxU32 (&offset, byte_size);
2385 else
2386 scalar = data.GetMaxU64 (&offset, byte_size);
2387
2388 if (is_signed)
2389 scalar.SignExtend(byte_size * 8);
2390 return bytes_read;
2391 }
2392 }
2393 else
2394 {
2395 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2396 }
2397 return 0;
2398}
2399
Greg Clayton613b8732011-05-17 03:37:42 +00002400#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002401addr_t
2402Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2403{
Jim Inghame6bd1422011-06-20 17:32:44 +00002404 if (GetPrivateState() != eStateStopped)
2405 return LLDB_INVALID_ADDRESS;
2406
Greg Clayton613b8732011-05-17 03:37:42 +00002407#if defined (USE_ALLOCATE_MEMORY_CACHE)
2408 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2409#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002410 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2411 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2412 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002413 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 +00002414 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002415 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002416 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002417 m_mod_id.GetStopID(),
2418 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002419 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002420#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002421}
2422
Sean Callanan6cf6c472011-09-20 23:01:51 +00002423bool
2424Process::CanJIT ()
2425{
Sean Callanan04200f62012-02-14 22:50:38 +00002426 if (m_can_jit == eCanJITDontKnow)
2427 {
2428 Error err;
2429
2430 uint64_t allocated_memory = AllocateMemory(8,
2431 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2432 err);
2433
2434 if (err.Success())
2435 m_can_jit = eCanJITYes;
2436 else
2437 m_can_jit = eCanJITNo;
2438
2439 DeallocateMemory (allocated_memory);
2440 }
2441
Sean Callanan6cf6c472011-09-20 23:01:51 +00002442 return m_can_jit == eCanJITYes;
2443}
2444
2445void
2446Process::SetCanJIT (bool can_jit)
2447{
2448 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2449}
2450
Chris Lattner24943d22010-06-08 16:52:24 +00002451Error
2452Process::DeallocateMemory (addr_t ptr)
2453{
Greg Clayton613b8732011-05-17 03:37:42 +00002454 Error error;
2455#if defined (USE_ALLOCATE_MEMORY_CACHE)
2456 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2457 {
2458 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2459 }
2460#else
2461 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002462
2463 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2464 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002465 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 +00002466 ptr,
2467 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002468 m_mod_id.GetStopID(),
2469 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002470#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002471 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002472}
2473
Greg Claytonb5a8f142012-02-05 02:38:54 +00002474ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002475Process::ReadModuleFromMemory (const FileSpec& file_spec,
2476 lldb::addr_t header_addr,
2477 bool add_image_to_target,
2478 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002479{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002480 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002481 if (module_sp)
2482 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002483 Error error;
2484 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2485 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002486 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002487 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002488 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002489 m_target.GetImages().Append(module_sp);
2490 if (load_sections_in_target)
2491 {
2492 bool changed = false;
2493 module_sp->SetLoadAddress (m_target, 0, changed);
2494 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002495 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002496 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002497 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002498 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002499 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002500}
Chris Lattner24943d22010-06-08 16:52:24 +00002501
2502Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002503Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002504{
2505 Error error;
2506 error.SetErrorString("watchpoints are not supported");
2507 return error;
2508}
2509
2510Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002511Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002512{
2513 Error error;
2514 error.SetErrorString("watchpoints are not supported");
2515 return error;
2516}
2517
2518StateType
2519Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2520{
2521 StateType state;
2522 // Now wait for the process to launch and return control to us, and then
2523 // call DidLaunch:
2524 while (1)
2525 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002526 event_sp.reset();
2527 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2528
Greg Clayton20206082011-11-17 01:23:07 +00002529 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002530 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002531
2532 // If state is invalid, then we timed out
2533 if (state == eStateInvalid)
2534 break;
2535
2536 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002537 HandlePrivateEvent (event_sp);
2538 }
2539 return state;
2540}
2541
2542Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002543Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002544{
2545 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002546 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002547 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002548 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002549 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002550
Greg Clayton5beb99d2011-08-11 02:48:45 +00002551 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002552 if (exe_module)
2553 {
Greg Clayton180546b2011-04-30 01:09:13 +00002554 char local_exec_file_path[PATH_MAX];
2555 char platform_exec_file_path[PATH_MAX];
2556 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2557 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002558 if (exe_module->GetFileSpec().Exists())
2559 {
Greg Claytona2f74232011-02-24 22:24:29 +00002560 if (PrivateStateThreadIsValid ())
2561 PausePrivateStateThread ();
2562
Chris Lattner24943d22010-06-08 16:52:24 +00002563 error = WillLaunch (exe_module);
2564 if (error.Success())
2565 {
Greg Claytond8c62532010-10-07 04:19:01 +00002566 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002567 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002568
Greg Clayton777c6b72012-09-04 20:29:05 +00002569 if (m_run_lock.WriteTryLock())
2570 {
2571 // Now launch using these arguments.
2572 error = DoLaunch (exe_module, launch_info);
2573 }
2574 else
2575 {
2576 // This shouldn't happen
2577 error.SetErrorString("failed to acquire process run lock");
2578 }
Chris Lattner24943d22010-06-08 16:52:24 +00002579
2580 if (error.Fail())
2581 {
2582 if (GetID() != LLDB_INVALID_PROCESS_ID)
2583 {
2584 SetID (LLDB_INVALID_PROCESS_ID);
2585 const char *error_string = error.AsCString();
2586 if (error_string == NULL)
2587 error_string = "launch failed";
2588 SetExitStatus (-1, error_string);
2589 }
2590 }
2591 else
2592 {
2593 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002594 TimeValue timeout_time;
2595 timeout_time = TimeValue::Now();
2596 timeout_time.OffsetWithSeconds(10);
2597 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002598
Greg Clayton49859592011-06-22 01:42:17 +00002599 if (state == eStateInvalid || event_sp.get() == NULL)
2600 {
2601 // We were able to launch the process, but we failed to
2602 // catch the initial stop.
2603 SetExitStatus (0, "failed to catch stop after launch");
2604 Destroy();
2605 }
2606 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002607 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002608
Chris Lattner24943d22010-06-08 16:52:24 +00002609 DidLaunch ();
2610
Greg Clayton9ce95382012-02-13 23:10:39 +00002611 DynamicLoader *dyld = GetDynamicLoader ();
2612 if (dyld)
2613 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002614
Greg Clayton37f962e2011-08-22 02:49:39 +00002615 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002616 // This delays passing the stopped event to listeners till DidLaunch gets
2617 // a chance to complete...
2618 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002619
2620 if (PrivateStateThreadIsValid ())
2621 ResumePrivateStateThread ();
2622 else
2623 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002624 }
2625 else if (state == eStateExited)
2626 {
2627 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2628 // not likely to work, and return an invalid pid.
2629 HandlePrivateEvent (event_sp);
2630 }
2631 }
2632 }
2633 }
2634 else
2635 {
Greg Clayton9c236732011-10-26 00:56:27 +00002636 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002637 }
2638 }
2639 return error;
2640}
2641
Greg Clayton46c9a352012-02-09 06:16:32 +00002642
2643Error
2644Process::LoadCore ()
2645{
2646 Error error = DoLoadCore();
2647 if (error.Success())
2648 {
2649 if (PrivateStateThreadIsValid ())
2650 ResumePrivateStateThread ();
2651 else
2652 StartPrivateStateThread ();
2653
Greg Clayton9ce95382012-02-13 23:10:39 +00002654 DynamicLoader *dyld = GetDynamicLoader ();
2655 if (dyld)
2656 dyld->DidAttach();
2657
2658 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002659 // We successfully loaded a core file, now pretend we stopped so we can
2660 // show all of the threads in the core file and explore the crashed
2661 // state.
2662 SetPrivateState (eStateStopped);
2663
2664 }
2665 return error;
2666}
2667
Greg Clayton9ce95382012-02-13 23:10:39 +00002668DynamicLoader *
2669Process::GetDynamicLoader ()
2670{
2671 if (m_dyld_ap.get() == NULL)
2672 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2673 return m_dyld_ap.get();
2674}
Greg Clayton46c9a352012-02-09 06:16:32 +00002675
2676
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002677Process::NextEventAction::EventActionResult
2678Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002679{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002680 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2681 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002682 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002683 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002684 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002685 return eEventActionRetry;
2686
2687 case eStateStopped:
2688 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002689 {
2690 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002691 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002692 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2693 if (m_exec_count > 0)
2694 {
2695 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002696 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002697 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002698 return eEventActionRetry;
2699 }
2700 else
2701 {
2702 m_process->CompleteAttach ();
2703 return eEventActionSuccess;
2704 }
2705 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002706 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002707
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002708 default:
2709 case eStateExited:
2710 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002711 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002712 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002713
2714 m_exit_string.assign ("No valid Process");
2715 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002716}
Chris Lattner24943d22010-06-08 16:52:24 +00002717
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002718Process::NextEventAction::EventActionResult
2719Process::AttachCompletionHandler::HandleBeingInterrupted()
2720{
2721 return eEventActionSuccess;
2722}
2723
2724const char *
2725Process::AttachCompletionHandler::GetExitString ()
2726{
2727 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002728}
2729
2730Error
Greg Clayton527154d2011-11-15 03:53:30 +00002731Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002732{
Chris Lattner24943d22010-06-08 16:52:24 +00002733 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002734 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002735 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002736 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002737
Greg Clayton527154d2011-11-15 03:53:30 +00002738 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002739 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002740 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002741 {
Greg Clayton527154d2011-11-15 03:53:30 +00002742 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002743
Greg Clayton527154d2011-11-15 03:53:30 +00002744 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002745 {
Greg Clayton527154d2011-11-15 03:53:30 +00002746 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2747
2748 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002749 {
Greg Clayton527154d2011-11-15 03:53:30 +00002750 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2751 if (error.Success())
2752 {
Greg Claytond34a3b22012-10-12 16:10:12 +00002753 if (m_run_lock.WriteTryLock())
2754 {
2755 m_should_detach = true;
2756 SetPublicState (eStateAttaching);
2757 // Now attach using these arguments.
2758 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
2759 }
2760 else
2761 {
2762 // This shouldn't happen
2763 error.SetErrorString("failed to acquire process run lock");
2764 }
Greg Claytonffa43a62011-11-17 04:46:02 +00002765
Greg Clayton527154d2011-11-15 03:53:30 +00002766 if (error.Fail())
2767 {
2768 if (GetID() != LLDB_INVALID_PROCESS_ID)
2769 {
2770 SetID (LLDB_INVALID_PROCESS_ID);
2771 if (error.AsCString() == NULL)
2772 error.SetErrorString("attach failed");
2773
2774 SetExitStatus(-1, error.AsCString());
2775 }
2776 }
2777 else
2778 {
2779 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2780 StartPrivateStateThread();
2781 }
2782 return error;
2783 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002784 }
Greg Clayton527154d2011-11-15 03:53:30 +00002785 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002786 {
Greg Clayton527154d2011-11-15 03:53:30 +00002787 ProcessInstanceInfoList process_infos;
2788 PlatformSP platform_sp (m_target.GetPlatform ());
2789
2790 if (platform_sp)
2791 {
2792 ProcessInstanceInfoMatch match_info;
2793 match_info.GetProcessInfo() = attach_info;
2794 match_info.SetNameMatchType (eNameMatchEquals);
2795 platform_sp->FindProcesses (match_info, process_infos);
2796 const uint32_t num_matches = process_infos.GetSize();
2797 if (num_matches == 1)
2798 {
2799 attach_pid = process_infos.GetProcessIDAtIndex(0);
2800 // Fall through and attach using the above process ID
2801 }
2802 else
2803 {
2804 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2805 if (num_matches > 1)
2806 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2807 else
2808 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2809 }
2810 }
2811 else
2812 {
2813 error.SetErrorString ("invalid platform, can't find processes by name");
2814 return error;
2815 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002816 }
Chris Lattner24943d22010-06-08 16:52:24 +00002817 }
2818 else
Greg Clayton527154d2011-11-15 03:53:30 +00002819 {
2820 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002821 }
2822 }
Greg Clayton527154d2011-11-15 03:53:30 +00002823
2824 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002825 {
Greg Clayton527154d2011-11-15 03:53:30 +00002826 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002827 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002828 {
Greg Clayton527154d2011-11-15 03:53:30 +00002829
Greg Claytond34a3b22012-10-12 16:10:12 +00002830 if (m_run_lock.WriteTryLock())
2831 {
2832 // Now attach using these arguments.
2833 m_should_detach = true;
2834 SetPublicState (eStateAttaching);
2835 error = DoAttachToProcessWithID (attach_pid, attach_info);
2836 }
2837 else
2838 {
2839 // This shouldn't happen
2840 error.SetErrorString("failed to acquire process run lock");
2841 }
2842
Greg Clayton527154d2011-11-15 03:53:30 +00002843 if (error.Success())
2844 {
2845
2846 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2847 StartPrivateStateThread();
2848 }
2849 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002850 {
2851 if (GetID() != LLDB_INVALID_PROCESS_ID)
2852 {
2853 SetID (LLDB_INVALID_PROCESS_ID);
2854 const char *error_string = error.AsCString();
2855 if (error_string == NULL)
2856 error_string = "attach failed";
2857
2858 SetExitStatus(-1, error_string);
2859 }
2860 }
Chris Lattner24943d22010-06-08 16:52:24 +00002861 }
2862 }
2863 return error;
2864}
2865
Greg Clayton75c703d2011-02-16 04:46:07 +00002866void
2867Process::CompleteAttach ()
2868{
2869 // Let the process subclass figure out at much as it can about the process
2870 // before we go looking for a dynamic loader plug-in.
2871 DidAttach();
2872
Jim Ingham0d7f7772011-09-15 01:10:17 +00002873 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2874 // the same as the one we've already set, switch architectures.
2875 PlatformSP platform_sp (m_target.GetPlatform ());
2876 assert (platform_sp.get());
2877 if (platform_sp)
2878 {
Greg Claytonb170aee2012-05-08 01:45:38 +00002879 const ArchSpec &target_arch = m_target.GetArchitecture();
2880 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2881 {
2882 ArchSpec platform_arch;
2883 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2884 if (platform_sp)
2885 {
2886 m_target.SetPlatform (platform_sp);
2887 m_target.SetArchitecture(platform_arch);
2888 }
2889 }
2890 else
2891 {
2892 ProcessInstanceInfo process_info;
2893 platform_sp->GetProcessInfo (GetID(), process_info);
2894 const ArchSpec &process_arch = process_info.GetArchitecture();
2895 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2896 m_target.SetArchitecture (process_arch);
2897 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00002898 }
2899
2900 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002901 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00002902 DynamicLoader *dyld = GetDynamicLoader ();
2903 if (dyld)
2904 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00002905
Greg Clayton37f962e2011-08-22 02:49:39 +00002906 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002907 // Figure out which one is the executable, and set that in our target:
Jim Ingham93367902012-05-30 02:19:25 +00002908 ModuleList &target_modules = m_target.GetImages();
2909 Mutex::Locker modules_locker(target_modules.GetMutex());
2910 size_t num_modules = target_modules.GetSize();
2911 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00002912
Greg Clayton75c703d2011-02-16 04:46:07 +00002913 for (int i = 0; i < num_modules; i++)
2914 {
Jim Ingham93367902012-05-30 02:19:25 +00002915 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002916 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002917 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002918 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00002919 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00002920 break;
2921 }
2922 }
Jim Ingham93367902012-05-30 02:19:25 +00002923 if (new_executable_module_sp)
2924 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00002925}
2926
Chris Lattner24943d22010-06-08 16:52:24 +00002927Error
Jason Molendafac2e622012-09-29 04:02:01 +00002928Process::ConnectRemote (Stream *strm, const char *remote_url)
Greg Claytone71e2582011-02-04 01:58:07 +00002929{
Greg Claytone71e2582011-02-04 01:58:07 +00002930 m_abi_sp.reset();
2931 m_process_input_reader.reset();
2932
2933 // Find the process and its architecture. Make sure it matches the architecture
2934 // of the current Target, and if not adjust it.
2935
Jason Molendafac2e622012-09-29 04:02:01 +00002936 Error error (DoConnectRemote (strm, remote_url));
Greg Claytone71e2582011-02-04 01:58:07 +00002937 if (error.Success())
2938 {
Greg Claytona2f74232011-02-24 22:24:29 +00002939 if (GetID() != LLDB_INVALID_PROCESS_ID)
2940 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002941 EventSP event_sp;
2942 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2943
2944 if (state == eStateStopped || state == eStateCrashed)
2945 {
2946 // If we attached and actually have a process on the other end, then
2947 // this ended up being the equivalent of an attach.
2948 CompleteAttach ();
2949
2950 // This delays passing the stopped event to listeners till
2951 // CompleteAttach gets a chance to complete...
2952 HandlePrivateEvent (event_sp);
2953
2954 }
Greg Claytona2f74232011-02-24 22:24:29 +00002955 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002956
2957 if (PrivateStateThreadIsValid ())
2958 ResumePrivateStateThread ();
2959 else
2960 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002961 }
2962 return error;
2963}
2964
2965
2966Error
Jim Ingham027aaa72012-04-19 01:40:33 +00002967Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00002968{
Jim Inghame1a654b2012-09-06 19:24:17 +00002969 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner24943d22010-06-08 16:52:24 +00002970 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002971 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002972 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002973 StateAsCString(m_public_state.GetValue()),
2974 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002975
2976 Error error (WillResume());
2977 // Tell the process it is about to resume before the thread list
2978 if (error.Success())
2979 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002980 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002981 // can let all of our threads know that they are about to be
2982 // resumed. Threads will each be called with
2983 // Thread::WillResume(StateType) where StateType contains the state
2984 // that they are supposed to have when the process is resumed
2985 // (suspended/running/stepping). Threads should also check
2986 // their resume signal in lldb::Thread::GetResumeSignal()
2987 // to see if they are suppoed to start back up with a signal.
2988 if (m_thread_list.WillResume())
2989 {
Jim Ingham1831e782012-04-07 00:00:41 +00002990 // Last thing, do the PreResumeActions.
2991 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00002992 {
Jim Ingham1831e782012-04-07 00:00:41 +00002993 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
2994 }
2995 else
2996 {
2997 m_mod_id.BumpResumeID();
2998 error = DoResume();
2999 if (error.Success())
3000 {
3001 DidResume();
3002 m_thread_list.DidResume();
3003 if (log)
3004 log->Printf ("Process thinks the process has resumed.");
3005 }
Chris Lattner24943d22010-06-08 16:52:24 +00003006 }
3007 }
3008 else
3009 {
Jim Ingham0c8fa2d2012-09-01 01:02:41 +00003010 // Somebody wanted to run without running. So generate a continue & a stopped event,
3011 // and let the world handle them.
3012 if (log)
3013 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
3014
3015 SetPrivateState(eStateRunning);
3016 SetPrivateState(eStateStopped);
Chris Lattner24943d22010-06-08 16:52:24 +00003017 }
3018 }
Jim Inghamac959662011-01-24 06:34:17 +00003019 else if (log)
3020 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00003021 return error;
3022}
3023
3024Error
3025Process::Halt ()
3026{
Jim Ingham43892562012-06-06 00:29:30 +00003027 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3028 // we could just straightaway get another event. It just narrows the window...
3029 m_currently_handling_event.WaitForValueEqualTo(false);
3030
3031
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003032 // Pause our private state thread so we can ensure no one else eats
3033 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00003034 Listener halt_listener ("lldb.process.halt_listener");
3035 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00003036
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003037 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003038 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003039
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003040 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003041 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003042
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003043 bool caused_stop = false;
3044
3045 // Ask the process subclass to actually halt our process
3046 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00003047 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00003048 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00003049 if (m_public_state.GetValue() == eStateAttaching)
3050 {
3051 SetExitStatus(SIGKILL, "Cancelled async attach.");
3052 Destroy ();
3053 }
3054 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00003055 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003056 // If "caused_stop" is true, then DoHalt stopped the process. If
3057 // "caused_stop" is false, the process was already stopped.
3058 // If the DoHalt caused the process to stop, then we want to catch
3059 // this event and set the interrupted bool to true before we pass
3060 // this along so clients know that the process was interrupted by
3061 // a halt command.
3062 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00003063 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003064 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003065 TimeValue timeout_time;
3066 timeout_time = TimeValue::Now();
3067 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003068 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3069 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003070
Jim Inghamf9f40c22011-02-08 05:20:59 +00003071 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00003072 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003073 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003074 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00003075 }
3076 else
3077 {
Greg Clayton20206082011-11-17 01:23:07 +00003078 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003079 {
3080 // We caused the process to interrupt itself, so mark this
3081 // as such in the stop event so clients can tell an interrupted
3082 // process from a natural stop
3083 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3084 }
3085 else
3086 {
3087 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3088 if (log)
3089 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3090 error.SetErrorString ("Did not get stopped event after halt.");
3091 }
Greg Clayton20d338f2010-11-18 05:57:03 +00003092 }
3093 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003094 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003095 }
3096 }
Chris Lattner24943d22010-06-08 16:52:24 +00003097 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003098 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003099 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003100
3101 // Post any event we might have consumed. If all goes well, we will have
3102 // stopped the process, intercepted the event and set the interrupted
3103 // bool in the event. Post it to the private event queue and that will end up
3104 // correctly setting the state.
3105 if (event_sp)
3106 m_private_state_broadcaster.BroadcastEvent(event_sp);
3107
Chris Lattner24943d22010-06-08 16:52:24 +00003108 return error;
3109}
3110
3111Error
3112Process::Detach ()
3113{
3114 Error error (WillDetach());
3115
3116 if (error.Success())
3117 {
3118 DisableAllBreakpointSites();
3119 error = DoDetach();
3120 if (error.Success())
3121 {
3122 DidDetach();
3123 StopPrivateStateThread();
3124 }
3125 }
3126 return error;
3127}
3128
3129Error
3130Process::Destroy ()
3131{
3132 Error error (WillDestroy());
3133 if (error.Success())
3134 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003135 EventSP exit_event_sp;
Jim Inghamf4928de2012-05-23 15:46:31 +00003136 if (m_public_state.GetValue() == eStateRunning)
3137 {
Greg Clayton38ae5b92012-09-05 00:37:58 +00003138 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003139 if (log)
3140 log->Printf("Process::Destroy() About to halt.");
Jim Inghamf4928de2012-05-23 15:46:31 +00003141 error = Halt();
3142 if (error.Success())
3143 {
3144 // Consume the halt event.
Jim Inghamf4928de2012-05-23 15:46:31 +00003145 TimeValue timeout (TimeValue::Now());
Jim Ingham43892562012-06-06 00:29:30 +00003146 timeout.OffsetWithSeconds(1);
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003147 StateType state = WaitForProcessToStop (&timeout, &exit_event_sp);
3148 if (state != eStateExited)
3149 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3150
Jim Inghamf4928de2012-05-23 15:46:31 +00003151 if (state != eStateStopped)
3152 {
Jim Inghamf4928de2012-05-23 15:46:31 +00003153 if (log)
3154 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Ingham43892562012-06-06 00:29:30 +00003155 // If we really couldn't stop the process then we should just error out here, but if the
3156 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3157 StateType private_state = m_private_state.GetValue();
3158 if (private_state != eStateStopped && private_state != eStateExited)
3159 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003160 // If we exited when we were waiting for a process to stop, then
3161 // forward the event here so we don't lose the event
Jim Ingham43892562012-06-06 00:29:30 +00003162 return error;
3163 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003164 }
3165 }
3166 else
3167 {
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003168 if (log)
3169 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3170 return error;
Jim Inghamf4928de2012-05-23 15:46:31 +00003171 }
3172 }
Jim Ingham43892562012-06-06 00:29:30 +00003173
3174 if (m_public_state.GetValue() != eStateRunning)
3175 {
3176 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3177 // kill it, we don't want it hitting a breakpoint...
3178 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3179 // we're not going to have much luck doing this now.
3180 m_thread_list.DiscardThreadPlans();
3181 DisableAllBreakpointSites();
3182 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003183
Chris Lattner24943d22010-06-08 16:52:24 +00003184 error = DoDestroy();
3185 if (error.Success())
3186 {
3187 DidDestroy();
3188 StopPrivateStateThread();
3189 }
Caroline Tice861efb32010-11-16 05:07:41 +00003190 m_stdio_communication.StopReadThread();
3191 m_stdio_communication.Disconnect();
3192 if (m_process_input_reader && m_process_input_reader->IsActive())
3193 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3194 if (m_process_input_reader)
3195 m_process_input_reader.reset();
Greg Claytonbb1af9c2012-09-11 02:33:37 +00003196
3197 // If we exited when we were waiting for a process to stop, then
3198 // forward the event here so we don't lose the event
3199 if (exit_event_sp)
3200 {
3201 // Directly broadcast our exited event because we shut down our
3202 // private state thread above
3203 BroadcastEvent(exit_event_sp);
3204 }
3205
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003206 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3207 // the last events through the event system, in which case we might strand the write lock. Unlock
3208 // it here so when we do to tear down the process we don't get an error destroying the lock.
3209 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003210 }
3211 return error;
3212}
3213
3214Error
3215Process::Signal (int signal)
3216{
3217 Error error (WillSignal());
3218 if (error.Success())
3219 {
3220 error = DoSignal(signal);
3221 if (error.Success())
3222 DidSignal();
3223 }
3224 return error;
3225}
3226
Greg Clayton395fc332011-02-15 21:59:32 +00003227lldb::ByteOrder
3228Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003229{
Greg Clayton395fc332011-02-15 21:59:32 +00003230 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003231}
3232
3233uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003234Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003235{
Greg Clayton395fc332011-02-15 21:59:32 +00003236 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003237}
3238
Greg Clayton395fc332011-02-15 21:59:32 +00003239
Chris Lattner24943d22010-06-08 16:52:24 +00003240bool
3241Process::ShouldBroadcastEvent (Event *event_ptr)
3242{
3243 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3244 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00003245 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003246
3247 switch (state)
3248 {
Greg Claytone71e2582011-02-04 01:58:07 +00003249 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003250 case eStateAttaching:
3251 case eStateLaunching:
3252 case eStateDetached:
3253 case eStateExited:
3254 case eStateUnloaded:
3255 // These events indicate changes in the state of the debugging session, always report them.
3256 return_value = true;
3257 break;
3258 case eStateInvalid:
3259 // We stopped for no apparent reason, don't report it.
3260 return_value = false;
3261 break;
3262 case eStateRunning:
3263 case eStateStepping:
3264 // If we've started the target running, we handle the cases where we
3265 // are already running and where there is a transition from stopped to
3266 // running differently.
3267 // running -> running: Automatically suppress extra running events
3268 // stopped -> running: Report except when there is one or more no votes
3269 // and no yes votes.
3270 SynchronouslyNotifyStateChanged (state);
3271 switch (m_public_state.GetValue())
3272 {
3273 case eStateRunning:
3274 case eStateStepping:
3275 // We always suppress multiple runnings with no PUBLIC stop in between.
3276 return_value = false;
3277 break;
3278 default:
3279 // TODO: make this work correctly. For now always report
3280 // run if we aren't running so we don't miss any runnning
3281 // events. If I run the lldb/test/thread/a.out file and
3282 // break at main.cpp:58, run and hit the breakpoints on
3283 // multiple threads, then somehow during the stepping over
3284 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003285
3286 // This is a transition from stop to run.
3287 switch (m_thread_list.ShouldReportRun (event_ptr))
3288 {
Greg Clayton4a379b12012-07-17 03:23:13 +00003289 default:
Chris Lattner24943d22010-06-08 16:52:24 +00003290 case eVoteYes:
3291 case eVoteNoOpinion:
3292 return_value = true;
3293 break;
3294 case eVoteNo:
3295 return_value = false;
3296 break;
3297 }
3298 break;
3299 }
3300 break;
3301 case eStateStopped:
3302 case eStateCrashed:
3303 case eStateSuspended:
3304 {
3305 // We've stopped. First see if we're going to restart the target.
3306 // If we are going to stop, then we always broadcast the event.
3307 // 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 +00003308 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003309
3310 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003311 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003312 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003313 if (log)
3314 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003315 return true;
3316 }
3317 else
3318 {
Chris Lattner24943d22010-06-08 16:52:24 +00003319
3320 if (m_thread_list.ShouldStop (event_ptr) == false)
3321 {
Jim Ingham8290bba2012-09-05 21:13:56 +00003322 // ShouldStop may have restarted the target already. If so, don't
3323 // resume it twice.
3324 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00003325 switch (m_thread_list.ShouldReportStop (event_ptr))
3326 {
3327 case eVoteYes:
3328 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003329 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003330 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003331 case eVoteNo:
3332 return_value = false;
3333 break;
3334 }
3335
3336 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003337 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham8290bba2012-09-05 21:13:56 +00003338 if (!was_restarted)
3339 PrivateResume ();
Chris Lattner24943d22010-06-08 16:52:24 +00003340 }
3341 else
3342 {
3343 return_value = true;
3344 SynchronouslyNotifyStateChanged (state);
3345 }
3346 }
3347 }
3348 }
3349
3350 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003351 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003352 return return_value;
3353}
3354
Chris Lattner24943d22010-06-08 16:52:24 +00003355
3356bool
Jim Ingham1831e782012-04-07 00:00:41 +00003357Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003358{
Greg Claytone005f2c2010-11-06 01:53:30 +00003359 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003360
Greg Claytonb72d0f02011-04-12 05:54:46 +00003361 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003362 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003363 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3364
Jim Ingham1831e782012-04-07 00:00:41 +00003365 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003366 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003367
3368 // Create a thread that watches our internal state and controls which
3369 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003370 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003371 if (already_running)
3372 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3373 else
3374 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003375
3376 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003377 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003378 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3379 if (success)
3380 {
3381 ResumePrivateStateThread();
3382 return true;
3383 }
3384 else
3385 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003386}
3387
3388void
3389Process::PausePrivateStateThread ()
3390{
3391 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3392}
3393
3394void
3395Process::ResumePrivateStateThread ()
3396{
3397 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3398}
3399
3400void
3401Process::StopPrivateStateThread ()
3402{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003403 if (PrivateStateThreadIsValid ())
3404 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003405 else
3406 {
3407 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3408 if (log)
3409 printf ("Went to stop the private state thread, but it was already invalid.");
3410 }
Chris Lattner24943d22010-06-08 16:52:24 +00003411}
3412
3413void
3414Process::ControlPrivateStateThread (uint32_t signal)
3415{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003416 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003417
3418 assert (signal == eBroadcastInternalStateControlStop ||
3419 signal == eBroadcastInternalStateControlPause ||
3420 signal == eBroadcastInternalStateControlResume);
3421
3422 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003423 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003424
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003425 // Signal the private state thread. First we should copy this is case the
3426 // thread starts exiting since the private state thread will NULL this out
3427 // when it exits
3428 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003429 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003430 {
3431 TimeValue timeout_time;
3432 bool timed_out;
3433
3434 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3435
3436 timeout_time = TimeValue::Now();
3437 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003438 if (log)
3439 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003440 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3441 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3442
3443 if (signal == eBroadcastInternalStateControlStop)
3444 {
3445 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003446 {
3447 Error error;
3448 Host::ThreadCancel (private_state_thread, &error);
3449 if (log)
3450 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3451 }
3452 else
3453 {
3454 if (log)
3455 log->Printf ("The control event killed the private state thread without having to cancel.");
3456 }
Chris Lattner24943d22010-06-08 16:52:24 +00003457
3458 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003459 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003460 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003461 }
3462 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003463 else
3464 {
3465 if (log)
3466 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3467 }
Chris Lattner24943d22010-06-08 16:52:24 +00003468}
3469
3470void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003471Process::SendAsyncInterrupt ()
3472{
3473 if (PrivateStateThreadIsValid())
3474 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3475 else
3476 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3477}
3478
3479void
Chris Lattner24943d22010-06-08 16:52:24 +00003480Process::HandlePrivateEvent (EventSP &event_sp)
3481{
Greg Claytone005f2c2010-11-06 01:53:30 +00003482 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003483 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003484
Greg Clayton68ca8232011-01-25 02:58:48 +00003485 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003486
3487 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003488 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003489 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003490 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003491 switch (action_result)
3492 {
3493 case NextEventAction::eEventActionSuccess:
3494 SetNextEventAction(NULL);
3495 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003496
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003497 case NextEventAction::eEventActionRetry:
3498 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003499
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003500 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003501 // Handle Exiting Here. If we already got an exited event,
3502 // we should just propagate it. Otherwise, swallow this event,
3503 // and set our state to exit so the next event will kill us.
3504 if (new_state != eStateExited)
3505 {
3506 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003507 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003508 SetNextEventAction(NULL);
3509 return;
3510 }
3511 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003512 break;
3513 }
3514 }
3515
Chris Lattner24943d22010-06-08 16:52:24 +00003516 // See if we should broadcast this state to external clients?
3517 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003518
3519 if (should_broadcast)
3520 {
3521 if (log)
3522 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003523 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003524 __FUNCTION__,
3525 GetID(),
3526 StateAsCString(new_state),
3527 StateAsCString (GetState ()),
3528 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003529 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003530 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003531 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003532 PushProcessInputReader ();
3533 else
3534 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003535
Chris Lattner24943d22010-06-08 16:52:24 +00003536 BroadcastEvent (event_sp);
3537 }
3538 else
3539 {
3540 if (log)
3541 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003542 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003543 __FUNCTION__,
3544 GetID(),
3545 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003546 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003547 }
3548 }
Jim Ingham43892562012-06-06 00:29:30 +00003549 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003550}
3551
3552void *
3553Process::PrivateStateThread (void *arg)
3554{
3555 Process *proc = static_cast<Process*> (arg);
3556 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003557 return result;
3558}
3559
3560void *
3561Process::RunPrivateStateThread ()
3562{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003563 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003564 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003565
Greg Claytone005f2c2010-11-06 01:53:30 +00003566 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003567 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003568 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003569
3570 bool exit_now = false;
3571 while (!exit_now)
3572 {
3573 EventSP event_sp;
3574 WaitForEventsPrivate (NULL, event_sp, control_only);
3575 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3576 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003577 if (log)
3578 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3579
Chris Lattner24943d22010-06-08 16:52:24 +00003580 switch (event_sp->GetType())
3581 {
3582 case eBroadcastInternalStateControlStop:
3583 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003584 break; // doing any internal state managment below
3585
3586 case eBroadcastInternalStateControlPause:
3587 control_only = true;
3588 break;
3589
3590 case eBroadcastInternalStateControlResume:
3591 control_only = false;
3592 break;
3593 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003594
Chris Lattner24943d22010-06-08 16:52:24 +00003595 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003596 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003597 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003598 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3599 {
3600 if (m_public_state.GetValue() == eStateAttaching)
3601 {
3602 if (log)
3603 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3604 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3605 }
3606 else
3607 {
3608 if (log)
3609 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3610 Halt();
3611 }
3612 continue;
3613 }
Chris Lattner24943d22010-06-08 16:52:24 +00003614
3615 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3616
3617 if (internal_state != eStateInvalid)
3618 {
3619 HandlePrivateEvent (event_sp);
3620 }
3621
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003622 if (internal_state == eStateInvalid ||
3623 internal_state == eStateExited ||
3624 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003625 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003626 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003627 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 +00003628
Chris Lattner24943d22010-06-08 16:52:24 +00003629 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003630 }
Chris Lattner24943d22010-06-08 16:52:24 +00003631 }
3632
Caroline Tice926060e2010-10-29 21:48:37 +00003633 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003634 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003635 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003636
Greg Claytona4881d02011-01-22 07:12:45 +00003637 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3638 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003639 return NULL;
3640}
3641
Chris Lattner24943d22010-06-08 16:52:24 +00003642//------------------------------------------------------------------
3643// Process Event Data
3644//------------------------------------------------------------------
3645
3646Process::ProcessEventData::ProcessEventData () :
3647 EventData (),
3648 m_process_sp (),
3649 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003650 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003651 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003652 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003653{
3654}
3655
3656Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3657 EventData (),
3658 m_process_sp (process_sp),
3659 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003660 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003661 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003662 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003663{
3664}
3665
3666Process::ProcessEventData::~ProcessEventData()
3667{
3668}
3669
3670const ConstString &
3671Process::ProcessEventData::GetFlavorString ()
3672{
3673 static ConstString g_flavor ("Process::ProcessEventData");
3674 return g_flavor;
3675}
3676
3677const ConstString &
3678Process::ProcessEventData::GetFlavor () const
3679{
3680 return ProcessEventData::GetFlavorString ();
3681}
3682
Chris Lattner24943d22010-06-08 16:52:24 +00003683void
3684Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3685{
3686 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003687 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3688 // the public event queue, then other times when we're pretending that this is where we stopped at the
3689 // end of expression evaluation. m_update_state is used to distinguish these
3690 // three cases; it is 0 when we're just pulling it off for private handling,
3691 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003692
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003693 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003694 return;
3695
3696 m_process_sp->SetPublicState (m_state);
3697
3698 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3699 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003700 {
3701 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003702 uint32_t num_threads = curr_thread_list.GetSize();
3703 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003704
Jim Ingham21f37ad2011-08-09 02:12:22 +00003705 // The actions might change one of the thread's stop_info's opinions about whether we should
3706 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003707
3708 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3709 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3710 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3711 // 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
3712 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003713 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003714 for (idx = 0; idx < num_threads; ++idx)
3715 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3716
Jim Ingham21f37ad2011-08-09 02:12:22 +00003717 bool still_should_stop = true;
3718
Chris Lattner24943d22010-06-08 16:52:24 +00003719 for (idx = 0; idx < num_threads; ++idx)
3720 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003721 curr_thread_list = m_process_sp->GetThreadList();
3722 if (curr_thread_list.GetSize() != num_threads)
3723 {
3724 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003725 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003726 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 +00003727 break;
3728 }
3729
3730 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3731
3732 if (thread_sp->GetIndexID() != thread_index_array[idx])
3733 {
3734 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003735 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003736 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003737 idx,
3738 thread_index_array[idx],
3739 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003740 break;
3741 }
3742
Jim Ingham6297a3a2010-10-20 00:39:53 +00003743 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
Jim Ingham6bc24c12012-10-16 00:09:33 +00003744 if (stop_info_sp && stop_info_sp->IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00003745 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003746 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003747 // The stop action might restart the target. If it does, then we want to mark that in the
3748 // event so that whoever is receiving it will know to wait for the running event and reflect
3749 // that state appropriately.
3750 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003751
3752 // FIXME: we might have run.
3753 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003754 {
3755 SetRestarted (true);
3756 break;
3757 }
3758 else if (!stop_info_sp->ShouldStop(event_ptr))
3759 {
3760 still_should_stop = false;
3761 }
Chris Lattner24943d22010-06-08 16:52:24 +00003762 }
3763 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003764
Jim Ingham21f37ad2011-08-09 02:12:22 +00003765
3766 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003767 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003768 if (!still_should_stop)
3769 {
3770 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003771 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00003772 // Use the public resume method here, since this is just
3773 // extending a public resume.
Jim Ingham21f37ad2011-08-09 02:12:22 +00003774 m_process_sp->Resume();
3775 }
3776 else
3777 {
3778 // If we didn't restart, run the Stop Hooks here:
3779 // They might also restart the target, so watch for that.
3780 m_process_sp->GetTarget().RunStopHooks();
3781 if (m_process_sp->GetPrivateState() == eStateRunning)
3782 SetRestarted(true);
3783 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003784 }
3785
Chris Lattner24943d22010-06-08 16:52:24 +00003786 }
3787}
3788
3789void
3790Process::ProcessEventData::Dump (Stream *s) const
3791{
3792 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003793 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003794
Greg Claytonb72d0f02011-04-12 05:54:46 +00003795 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003796}
3797
3798const Process::ProcessEventData *
3799Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3800{
3801 if (event_ptr)
3802 {
3803 const EventData *event_data = event_ptr->GetData();
3804 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3805 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3806 }
3807 return NULL;
3808}
3809
3810ProcessSP
3811Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3812{
3813 ProcessSP process_sp;
3814 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3815 if (data)
3816 process_sp = data->GetProcessSP();
3817 return process_sp;
3818}
3819
3820StateType
3821Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3822{
3823 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3824 if (data == NULL)
3825 return eStateInvalid;
3826 else
3827 return data->GetState();
3828}
3829
3830bool
3831Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3832{
3833 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3834 if (data == NULL)
3835 return false;
3836 else
3837 return data->GetRestarted();
3838}
3839
3840void
3841Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3842{
3843 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3844 if (data != NULL)
3845 data->SetRestarted(new_value);
3846}
3847
3848bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003849Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3850{
3851 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3852 if (data == NULL)
3853 return false;
3854 else
3855 return data->GetInterrupted ();
3856}
3857
3858void
3859Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3860{
3861 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3862 if (data != NULL)
3863 data->SetInterrupted(new_value);
3864}
3865
3866bool
Chris Lattner24943d22010-06-08 16:52:24 +00003867Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3868{
3869 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3870 if (data)
3871 {
3872 data->SetUpdateStateOnRemoval();
3873 return true;
3874 }
3875 return false;
3876}
3877
Greg Clayton289afcb2012-02-18 05:35:26 +00003878lldb::TargetSP
3879Process::CalculateTarget ()
3880{
3881 return m_target.shared_from_this();
3882}
3883
Chris Lattner24943d22010-06-08 16:52:24 +00003884void
Greg Claytona830adb2010-10-04 01:05:56 +00003885Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003886{
Greg Clayton567e7f32011-09-22 04:58:26 +00003887 exe_ctx.SetTargetPtr (&m_target);
3888 exe_ctx.SetProcessPtr (this);
3889 exe_ctx.SetThreadPtr(NULL);
3890 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003891}
3892
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003893//uint32_t
3894//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3895//{
3896// return 0;
3897//}
3898//
3899//ArchSpec
3900//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3901//{
3902// return Host::GetArchSpecForExistingProcess (pid);
3903//}
3904//
3905//ArchSpec
3906//Process::GetArchSpecForExistingProcess (const char *process_name)
3907//{
3908// return Host::GetArchSpecForExistingProcess (process_name);
3909//}
3910//
Caroline Tice861efb32010-11-16 05:07:41 +00003911void
3912Process::AppendSTDOUT (const char * s, size_t len)
3913{
Greg Clayton20d338f2010-11-18 05:57:03 +00003914 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003915 m_stdout_data.append (s, len);
Greg Claytonb3781332010-12-05 19:16:56 +00003916 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003917}
3918
3919void
Greg Claytonbd06ff42011-11-13 04:45:22 +00003920Process::AppendSTDERR (const char * s, size_t len)
3921{
3922 Mutex::Locker locker (m_stdio_communication_mutex);
3923 m_stderr_data.append (s, len);
3924 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3925}
3926
3927//------------------------------------------------------------------
3928// Process STDIO
3929//------------------------------------------------------------------
3930
3931size_t
3932Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3933{
3934 Mutex::Locker locker(m_stdio_communication_mutex);
3935 size_t bytes_available = m_stdout_data.size();
3936 if (bytes_available > 0)
3937 {
3938 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3939 if (log)
Greg Clayton851e30e2012-09-18 18:04:04 +00003940 log->Printf ("Process::GetSTDOUT (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00003941 if (bytes_available > buf_size)
3942 {
3943 memcpy(buf, m_stdout_data.c_str(), buf_size);
3944 m_stdout_data.erase(0, buf_size);
3945 bytes_available = buf_size;
3946 }
3947 else
3948 {
3949 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3950 m_stdout_data.clear();
3951 }
3952 }
3953 return bytes_available;
3954}
3955
3956
3957size_t
3958Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3959{
3960 Mutex::Locker locker(m_stdio_communication_mutex);
3961 size_t bytes_available = m_stderr_data.size();
3962 if (bytes_available > 0)
3963 {
3964 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3965 if (log)
Greg Clayton851e30e2012-09-18 18:04:04 +00003966 log->Printf ("Process::GetSTDERR (buf = %p, size = %llu)", buf, (uint64_t)buf_size);
Greg Claytonbd06ff42011-11-13 04:45:22 +00003967 if (bytes_available > buf_size)
3968 {
3969 memcpy(buf, m_stderr_data.c_str(), buf_size);
3970 m_stderr_data.erase(0, buf_size);
3971 bytes_available = buf_size;
3972 }
3973 else
3974 {
3975 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3976 m_stderr_data.clear();
3977 }
3978 }
3979 return bytes_available;
3980}
3981
3982void
Caroline Tice861efb32010-11-16 05:07:41 +00003983Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3984{
3985 Process *process = (Process *) baton;
3986 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3987}
3988
3989size_t
3990Process::ProcessInputReaderCallback (void *baton,
3991 InputReader &reader,
3992 lldb::InputReaderAction notification,
3993 const char *bytes,
3994 size_t bytes_len)
3995{
3996 Process *process = (Process *) baton;
3997
3998 switch (notification)
3999 {
4000 case eInputReaderActivate:
4001 break;
4002
4003 case eInputReaderDeactivate:
4004 break;
4005
4006 case eInputReaderReactivate:
4007 break;
4008
Caroline Tice4a348082011-05-02 20:41:46 +00004009 case eInputReaderAsynchronousOutputWritten:
4010 break;
4011
Caroline Tice861efb32010-11-16 05:07:41 +00004012 case eInputReaderGotToken:
4013 {
4014 Error error;
4015 process->PutSTDIN (bytes, bytes_len, error);
4016 }
4017 break;
4018
Caroline Ticec4f55fe2010-11-19 20:47:54 +00004019 case eInputReaderInterrupt:
4020 process->Halt ();
4021 break;
4022
4023 case eInputReaderEndOfFile:
4024 process->AppendSTDOUT ("^D", 2);
4025 break;
4026
Caroline Tice861efb32010-11-16 05:07:41 +00004027 case eInputReaderDone:
4028 break;
4029
4030 }
4031
4032 return bytes_len;
4033}
4034
4035void
4036Process::ResetProcessInputReader ()
4037{
4038 m_process_input_reader.reset();
4039}
4040
4041void
Greg Clayton464c6162011-11-17 22:14:31 +00004042Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00004043{
4044 // First set up the Read Thread for reading/handling process I/O
4045
4046 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4047
4048 if (conn_ap.get())
4049 {
4050 m_stdio_communication.SetConnection (conn_ap.release());
4051 if (m_stdio_communication.IsConnected())
4052 {
4053 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4054 m_stdio_communication.StartReadThread();
4055
4056 // Now read thread is set up, set up input reader.
4057
4058 if (!m_process_input_reader.get())
4059 {
4060 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4061 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4062 this,
4063 eInputReaderGranularityByte,
4064 NULL,
4065 NULL,
4066 false));
4067
4068 if (err.Fail())
4069 m_process_input_reader.reset();
4070 }
4071 }
4072 }
4073}
4074
4075void
4076Process::PushProcessInputReader ()
4077{
4078 if (m_process_input_reader && !m_process_input_reader->IsActive())
4079 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4080}
4081
4082void
4083Process::PopProcessInputReader ()
4084{
4085 if (m_process_input_reader && m_process_input_reader->IsActive())
4086 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4087}
4088
Greg Claytond284b662011-02-18 01:44:25 +00004089// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00004090void
Caroline Tice2a456812011-03-10 22:14:10 +00004091Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004092{
Greg Clayton73844aa2012-08-22 17:17:09 +00004093// static std::vector<OptionEnumValueElement> g_plugins;
4094//
4095// int i=0;
4096// const char *name;
4097// OptionEnumValueElement option_enum;
4098// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4099// {
4100// if (name)
4101// {
4102// option_enum.value = i;
4103// option_enum.string_value = name;
4104// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4105// g_plugins.push_back (option_enum);
4106// }
4107// ++i;
4108// }
4109// option_enum.value = 0;
4110// option_enum.string_value = NULL;
4111// option_enum.usage = NULL;
4112// g_plugins.push_back (option_enum);
4113//
4114// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4115// {
4116// if (::strcmp (name, "plugin") == 0)
4117// {
4118// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4119// break;
4120// }
4121// }
Greg Clayton73844aa2012-08-22 17:17:09 +00004122//
Greg Claytonc6e82e42012-08-22 18:39:03 +00004123 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004124}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004125
Greg Clayton990de7b2010-11-18 23:32:35 +00004126void
Caroline Tice2a456812011-03-10 22:14:10 +00004127Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00004128{
Greg Claytonc6e82e42012-08-22 18:39:03 +00004129 Thread::SettingsTerminate ();
Greg Clayton990de7b2010-11-18 23:32:35 +00004130}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004131
Greg Clayton427f2902010-12-14 02:59:59 +00004132ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004133Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004134 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004135 bool stop_others,
4136 bool try_all_threads,
4137 bool discard_on_error,
4138 uint32_t single_thread_timeout_usec,
4139 Stream &errors)
4140{
4141 ExecutionResults return_value = eExecutionSetupError;
4142
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004143 if (thread_plan_sp.get() == NULL)
4144 {
4145 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004146 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004147 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004148
4149 if (exe_ctx.GetProcessPtr() != this)
4150 {
4151 errors.Printf("RunThreadPlan called on wrong process.");
4152 return eExecutionSetupError;
4153 }
4154
4155 Thread *thread = exe_ctx.GetThreadPtr();
4156 if (thread == NULL)
4157 {
4158 errors.Printf("RunThreadPlan called with invalid thread.");
4159 return eExecutionSetupError;
4160 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004161
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004162 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4163 // For that to be true the plan can't be private - since private plans suppress themselves in the
4164 // GetCompletedPlan call.
4165
4166 bool orig_plan_private = thread_plan_sp->GetPrivate();
4167 thread_plan_sp->SetPrivate(false);
4168
Jim Inghamac959662011-01-24 06:34:17 +00004169 if (m_private_state.GetValue() != eStateStopped)
4170 {
4171 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004172 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004173 }
4174
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004175 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004176 const uint32_t thread_idx_id = thread->GetIndexID();
4177 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004178
4179 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4180 // so we should arrange to reset them as well.
4181
Greg Clayton567e7f32011-09-22 04:58:26 +00004182 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004183
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004184 uint32_t selected_tid;
4185 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004186 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004187 {
4188 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004189 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004190 }
4191 else
4192 {
4193 selected_tid = LLDB_INVALID_THREAD_ID;
4194 }
4195
Jim Ingham1831e782012-04-07 00:00:41 +00004196 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004197 lldb::StateType old_state;
4198 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004199
Jim Inghamd21d98b2012-04-10 01:21:57 +00004200 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004201 if (Host::GetCurrentThread() == m_private_state_thread)
4202 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004203 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4204 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004205 // 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 +00004206 // we are fielding public events here.
4207 if (log)
4208 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4209
4210
Jim Ingham1831e782012-04-07 00:00:41 +00004211 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004212
4213 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4214 // returning control here.
4215 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4216 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4217 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4218 // do just what we want.
4219 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4220 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4221 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4222 old_state = m_public_state.GetValue();
4223 m_public_state.SetValueNoLock(eStateStopped);
4224
4225 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004226 StartPrivateStateThread(true);
4227 }
4228
4229 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004230
Jim Ingham6ae318c2011-01-23 21:14:08 +00004231 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004232
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004233 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004234
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004235 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004236 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4237 // restored on exit to the function.
4238 //
4239 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4240 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004241
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004242 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004243
Jim Ingham360f53f2010-11-30 02:22:11 +00004244 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004245 {
4246 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004247 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4248 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4249 thread->GetIndexID(),
4250 thread->GetID(),
4251 s.GetData());
4252 }
4253
4254 bool got_event;
4255 lldb::EventSP event_sp;
4256 lldb::StateType stop_state = lldb::eStateInvalid;
4257
4258 TimeValue* timeout_ptr = NULL;
4259 TimeValue real_timeout;
4260
4261 bool first_timeout = true;
4262 bool do_resume = true;
4263
4264 while (1)
4265 {
4266 // We usually want to resume the process if we get to the top of the loop.
4267 // The only exception is if we get two running events with no intervening
4268 // stop, which can happen, we will just wait for then next stop event.
4269
4270 if (do_resume)
4271 {
4272 // Do the initial resume and wait for the running event before going further.
4273
4274 Error resume_error = PrivateResume ();
4275 if (!resume_error.Success())
4276 {
4277 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4278 return_value = eExecutionSetupError;
4279 break;
4280 }
4281
4282 real_timeout = TimeValue::Now();
4283 real_timeout.OffsetWithMicroSeconds(500000);
4284 timeout_ptr = &real_timeout;
4285
4286 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4287 if (!got_event)
4288 {
4289 if (log)
4290 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4291
4292 errors.Printf("Didn't get any event after initial resume, exiting.");
4293 return_value = eExecutionSetupError;
4294 break;
4295 }
4296
4297 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4298 if (stop_state != eStateRunning)
4299 {
4300 if (log)
4301 log->Printf("Process::RunThreadPlan(): didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
4302
4303 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
4304 return_value = eExecutionSetupError;
4305 break;
4306 }
4307
4308 if (log)
4309 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4310 // We need to call the function synchronously, so spin waiting for it to return.
4311 // If we get interrupted while executing, we're going to lose our context, and
4312 // won't be able to gather the result at this point.
4313 // We set the timeout AFTER the resume, since the resume takes some time and we
4314 // don't want to charge that to the timeout.
4315
4316 if (single_thread_timeout_usec != 0)
4317 {
Enrico Granata6cca9692012-07-16 23:10:35 +00004318 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004319 real_timeout = TimeValue::Now();
4320 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
4321
4322 timeout_ptr = &real_timeout;
4323 }
Enrico Granata6cca9692012-07-16 23:10:35 +00004324 else if (first_timeout)
4325 {
4326 // if we are willing to wait "forever" we still need to have an initial timeout
4327 // this timeout is going to induce all threads to run when hit. we do this so that
4328 // we can avoid ending locked up because of multithreaded contention issues
4329 real_timeout = TimeValue::Now();
4330 real_timeout.OffsetWithNanoSeconds(500000000UL);
4331 timeout_ptr = &real_timeout;
4332 }
4333 else
4334 {
4335 timeout_ptr = NULL; // if we are in a no-timeout scenario, then we only need a fake timeout the first time through
4336 // at this point in the code, all threads will be running so we are willing to wait forever, and do not
4337 // need a timeout
4338 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004339 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004340 else
4341 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004342 if (log)
4343 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4344 do_resume = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004345 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004346
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004347 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004348 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004349
Jim Inghamf9f40c22011-02-08 05:20:59 +00004350 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004351 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004352 if (timeout_ptr)
4353 {
4354 StreamString s;
4355 s.Printf ("about to wait - timeout is:\n ");
4356 timeout_ptr->Dump (&s, 120);
4357 s.Printf ("\nNow is:\n ");
4358 TimeValue::Now().Dump (&s, 120);
4359 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4360 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004361 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004362 {
4363 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4364 }
4365 }
4366
4367 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4368
4369 if (got_event)
4370 {
4371 if (event_sp.get())
4372 {
4373 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004374 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004375 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004376 Halt();
4377 keep_going = false;
4378 return_value = eExecutionInterrupted;
4379 errors.Printf ("Execution halted by user interrupt.");
4380 if (log)
4381 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4382 }
4383 else
4384 {
4385 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4386 if (log)
4387 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4388
4389 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004390 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004391 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004392 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004393 // Yay, we're done. Now make sure that our thread plan actually completed.
4394 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4395 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004396 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004397 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004398 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004399 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4400 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004401 }
4402 else
4403 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004404 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4405 StopReason stop_reason = eStopReasonInvalid;
4406 if (stop_info_sp)
4407 stop_reason = stop_info_sp->GetStopReason();
4408 if (stop_reason == eStopReasonPlanComplete)
4409 {
4410 if (log)
4411 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4412 // Now mark this plan as private so it doesn't get reported as the stop reason
4413 // after this point.
4414 if (thread_plan_sp)
4415 thread_plan_sp->SetPrivate (orig_plan_private);
4416 return_value = eExecutionCompleted;
4417 }
4418 else
4419 {
4420 if (log)
4421 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004422
Jim Ingham5d90ade2012-07-27 23:57:19 +00004423 return_value = eExecutionInterrupted;
4424 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004425 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004426 }
4427 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004428
Jim Ingham5d90ade2012-07-27 23:57:19 +00004429 case lldb::eStateCrashed:
4430 if (log)
4431 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4432 return_value = eExecutionInterrupted;
4433 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004434
Jim Ingham5d90ade2012-07-27 23:57:19 +00004435 case lldb::eStateRunning:
4436 do_resume = false;
4437 keep_going = true;
4438 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004439
Jim Ingham5d90ade2012-07-27 23:57:19 +00004440 default:
4441 if (log)
4442 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4443
4444 if (stop_state == eStateExited)
4445 event_to_broadcast_sp = event_sp;
4446
Sean Callanan96abc622012-08-08 17:35:10 +00004447 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Ingham5d90ade2012-07-27 23:57:19 +00004448 return_value = eExecutionInterrupted;
4449 break;
4450 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004451 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004452
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004453 if (keep_going)
4454 continue;
4455 else
4456 break;
4457 }
4458 else
4459 {
4460 if (log)
4461 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4462 return_value = eExecutionInterrupted;
4463 break;
4464 }
4465 }
4466 else
4467 {
4468 // If we didn't get an event that means we've timed out...
4469 // We will interrupt the process here. Depending on what we were asked to do we will
4470 // either exit, or try with all threads running for the same timeout.
4471 // Not really sure what to do if Halt fails here...
4472
4473 if (log) {
4474 if (try_all_threads)
4475 {
4476 if (first_timeout)
4477 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4478 "trying with all threads enabled.",
4479 single_thread_timeout_usec);
4480 else
4481 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4482 "and timeout: %d timed out.",
4483 single_thread_timeout_usec);
4484 }
4485 else
4486 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4487 "halt and abandoning execution.",
4488 single_thread_timeout_usec);
4489 }
4490
4491 Error halt_error = Halt();
4492 if (halt_error.Success())
4493 {
4494 if (log)
4495 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4496
4497 // If halt succeeds, it always produces a stopped event. Wait for that:
4498
4499 real_timeout = TimeValue::Now();
4500 real_timeout.OffsetWithMicroSeconds(500000);
4501
4502 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4503
4504 if (got_event)
4505 {
4506 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4507 if (log)
4508 {
4509 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4510 if (stop_state == lldb::eStateStopped
4511 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4512 log->PutCString (" Event was the Halt interruption event.");
4513 }
4514
4515 if (stop_state == lldb::eStateStopped)
4516 {
4517 // Between the time we initiated the Halt and the time we delivered it, the process could have
4518 // already finished its job. Check that here:
4519
4520 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4521 {
4522 if (log)
4523 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4524 "Exiting wait loop.");
4525 return_value = eExecutionCompleted;
4526 break;
4527 }
4528
4529 if (!try_all_threads)
4530 {
4531 if (log)
4532 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4533 return_value = eExecutionInterrupted;
4534 break;
4535 }
4536
4537 if (first_timeout)
4538 {
4539 // Set all the other threads to run, and return to the top of the loop, which will continue;
4540 first_timeout = false;
4541 thread_plan_sp->SetStopOthers (false);
4542 if (log)
4543 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4544
4545 continue;
4546 }
4547 else
4548 {
4549 // Running all threads failed, so return Interrupted.
4550 if (log)
4551 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4552 return_value = eExecutionInterrupted;
4553 break;
4554 }
4555 }
4556 }
4557 else
4558 { if (log)
4559 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4560 "I'm getting out of here passing Interrupted.");
4561 return_value = eExecutionInterrupted;
4562 break;
4563 }
4564 }
4565 else
4566 {
4567 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4568 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4569 if (log)
4570 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.",
4571 halt_error.AsCString());
4572 real_timeout = TimeValue::Now();
4573 real_timeout.OffsetWithMicroSeconds(500000);
4574 timeout_ptr = &real_timeout;
4575 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4576 if (!got_event || event_sp.get() == NULL)
4577 {
4578 // This is not going anywhere, bag out.
4579 if (log)
4580 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4581 return_value = eExecutionInterrupted;
4582 break;
4583 }
4584 else
4585 {
4586 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4587 if (log)
4588 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4589 if (stop_state == lldb::eStateStopped)
4590 {
4591 // Between the time we initiated the Halt and the time we delivered it, the process could have
4592 // already finished its job. Check that here:
4593
4594 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4595 {
4596 if (log)
4597 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4598 "Exiting wait loop.");
4599 return_value = eExecutionCompleted;
4600 break;
4601 }
4602
4603 if (first_timeout)
4604 {
4605 // Set all the other threads to run, and return to the top of the loop, which will continue;
4606 first_timeout = false;
4607 thread_plan_sp->SetStopOthers (false);
4608 if (log)
4609 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4610
4611 continue;
4612 }
4613 else
4614 {
4615 // Running all threads failed, so return Interrupted.
4616 if (log)
4617 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4618 return_value = eExecutionInterrupted;
4619 break;
4620 }
4621 }
4622 else
4623 {
4624 if (log)
4625 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4626 " a stopped event, instead got %s.", StateAsCString(stop_state));
4627 return_value = eExecutionInterrupted;
4628 break;
4629 }
4630 }
4631 }
4632
4633 }
4634
4635 } // END WAIT LOOP
4636
4637 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4638 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4639 {
4640 StopPrivateStateThread();
4641 Error error;
4642 m_private_state_thread = backup_private_state_thread;
Sean Callananb386d822012-08-09 00:50:26 +00004643 if (stopper_base_plan_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004644 {
4645 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4646 }
4647 m_public_state.SetValueNoLock(old_state);
4648
4649 }
4650
4651
4652 // Now do some processing on the results of the run:
4653 if (return_value == eExecutionInterrupted)
4654 {
4655 if (log)
4656 {
4657 StreamString s;
4658 if (event_sp)
4659 event_sp->Dump (&s);
4660 else
4661 {
4662 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4663 }
4664
4665 StreamString ts;
4666
4667 const char *event_explanation = NULL;
4668
4669 do
4670 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004671 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004672 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004673 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004674 break;
4675 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004676 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004677 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004678 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004679 break;
4680 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004681 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004682 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004683 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4684
4685 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004686 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004687 event_explanation = "<no event data>";
4688 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004689 }
4690
Jim Ingham5d90ade2012-07-27 23:57:19 +00004691 Process *process = event_data->GetProcessSP().get();
4692
4693 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004694 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004695 event_explanation = "<no process>";
4696 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004697 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004698
4699 ThreadList &thread_list = process->GetThreadList();
4700
4701 uint32_t num_threads = thread_list.GetSize();
4702 uint32_t thread_index;
4703
4704 ts.Printf("<%u threads> ", num_threads);
4705
4706 for (thread_index = 0;
4707 thread_index < num_threads;
4708 ++thread_index)
4709 {
4710 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4711
4712 if (!thread)
4713 {
4714 ts.Printf("<?> ");
4715 continue;
4716 }
4717
4718 ts.Printf("<0x%4.4llx ", thread->GetID());
4719 RegisterContext *register_context = thread->GetRegisterContext().get();
4720
4721 if (register_context)
4722 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4723 else
4724 ts.Printf("[ip unknown] ");
4725
4726 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4727 if (stop_info_sp)
4728 {
4729 const char *stop_desc = stop_info_sp->GetDescription();
4730 if (stop_desc)
4731 ts.PutCString (stop_desc);
4732 }
4733 ts.Printf(">");
4734 }
4735
4736 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004737 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004738 } while (0);
4739
Jim Ingham5d90ade2012-07-27 23:57:19 +00004740 if (event_explanation)
4741 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004742 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00004743 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4744 }
4745
4746 if (discard_on_error && thread_plan_sp)
4747 {
4748 if (log)
4749 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4750 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4751 thread_plan_sp->SetPrivate (orig_plan_private);
4752 }
4753 else
4754 {
4755 if (log)
4756 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004757 }
4758 }
4759 else if (return_value == eExecutionSetupError)
4760 {
4761 if (log)
4762 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004763
4764 if (discard_on_error && thread_plan_sp)
4765 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004766 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004767 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004768 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004769 }
4770 else
4771 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004772 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004773 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004774 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004775 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4776 return_value = eExecutionCompleted;
4777 }
4778 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4779 {
4780 if (log)
4781 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4782 return_value = eExecutionDiscarded;
4783 }
4784 else
4785 {
4786 if (log)
4787 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4788 if (discard_on_error && thread_plan_sp)
4789 {
4790 if (log)
4791 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4792 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4793 thread_plan_sp->SetPrivate (orig_plan_private);
4794 }
4795 }
4796 }
4797
4798 // Thread we ran the function in may have gone away because we ran the target
4799 // Check that it's still there, and if it is put it back in the context. Also restore the
4800 // frame in the context if it is still present.
4801 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4802 if (thread)
4803 {
4804 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4805 }
4806
4807 // Also restore the current process'es selected frame & thread, since this function calling may
4808 // be done behind the user's back.
4809
4810 if (selected_tid != LLDB_INVALID_THREAD_ID)
4811 {
4812 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4813 {
4814 // We were able to restore the selected thread, now restore the frame:
4815 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4816 if (old_frame_sp)
4817 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00004818 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004819 }
4820 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004821
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004822 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00004823
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004824 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004825 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004826 if (log)
4827 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4828 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00004829 }
4830
4831 return return_value;
4832}
4833
4834const char *
4835Process::ExecutionResultAsCString (ExecutionResults result)
4836{
4837 const char *result_name;
4838
4839 switch (result)
4840 {
Greg Claytonb3448432011-03-24 21:19:54 +00004841 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004842 result_name = "eExecutionCompleted";
4843 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004844 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00004845 result_name = "eExecutionDiscarded";
4846 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004847 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004848 result_name = "eExecutionInterrupted";
4849 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004850 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00004851 result_name = "eExecutionSetupError";
4852 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004853 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00004854 result_name = "eExecutionTimedOut";
4855 break;
4856 }
4857 return result_name;
4858}
4859
Greg Claytonabe0fed2011-04-18 08:33:37 +00004860void
4861Process::GetStatus (Stream &strm)
4862{
4863 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00004864 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00004865 {
4866 if (state == eStateExited)
4867 {
4868 int exit_status = GetExitStatus();
4869 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00004870 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00004871 GetID(),
4872 exit_status,
4873 exit_status,
4874 exit_description ? exit_description : "");
4875 }
4876 else
4877 {
4878 if (state == eStateConnected)
4879 strm.Printf ("Connected to remote target.\n");
4880 else
Greg Clayton444e35b2011-10-19 18:09:39 +00004881 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00004882 }
4883 }
4884 else
4885 {
Greg Clayton444e35b2011-10-19 18:09:39 +00004886 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004887 }
4888}
4889
4890size_t
4891Process::GetThreadStatus (Stream &strm,
4892 bool only_threads_with_stop_reason,
4893 uint32_t start_frame,
4894 uint32_t num_frames,
4895 uint32_t num_frames_with_source)
4896{
4897 size_t num_thread_infos_dumped = 0;
4898
Jim Inghamb9950592012-09-10 20:50:15 +00004899 Mutex::Locker locker (GetThreadList().GetMutex());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004900 const size_t num_threads = GetThreadList().GetSize();
4901 for (uint32_t i = 0; i < num_threads; i++)
4902 {
4903 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4904 if (thread)
4905 {
4906 if (only_threads_with_stop_reason)
4907 {
Jim Ingham6bc24c12012-10-16 00:09:33 +00004908 StopInfoSP stop_info_sp = thread->GetStopInfo();
4909 if (stop_info_sp.get() == NULL || !stop_info_sp->IsValid())
Greg Claytonabe0fed2011-04-18 08:33:37 +00004910 continue;
4911 }
4912 thread->GetStatus (strm,
4913 start_frame,
4914 num_frames,
4915 num_frames_with_source);
4916 ++num_thread_infos_dumped;
4917 }
4918 }
4919 return num_thread_infos_dumped;
4920}
4921
Greg Clayton76113302012-02-22 04:37:26 +00004922void
4923Process::AddInvalidMemoryRegion (const LoadRange &region)
4924{
4925 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4926}
4927
4928bool
4929Process::RemoveInvalidMemoryRange (const LoadRange &region)
4930{
4931 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4932}
4933
Jim Ingham1831e782012-04-07 00:00:41 +00004934void
4935Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4936{
4937 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4938}
4939
4940bool
4941Process::RunPreResumeActions ()
4942{
4943 bool result = true;
4944 while (!m_pre_resume_actions.empty())
4945 {
4946 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
4947 m_pre_resume_actions.pop_back();
4948 bool this_result = action.callback (action.baton);
4949 if (result == true) result = this_result;
4950 }
4951 return result;
4952}
4953
4954void
4955Process::ClearPreResumeActions ()
4956{
4957 m_pre_resume_actions.clear();
4958}
Greg Clayton76113302012-02-22 04:37:26 +00004959
Greg Claytoncf5927e2012-05-18 02:38:05 +00004960void
4961Process::Flush ()
4962{
4963 m_thread_list.Flush();
4964}