blob: 918f98c369cff2e8be30dfcb8ef36d9c2a31220d [file] [log] [blame]
Chris Lattner30fdc8d2010-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 Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
Greg Clayton1f746072012-08-29 21:13:06 +000021#include "lldb/Core/Module.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
23#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000024#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000025#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Host/Host.h"
27#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000028#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000029#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000030#include "lldb/Target/LanguageRuntime.h"
31#include "lldb/Target/CPPLanguageRuntime.h"
32#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000033#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000035#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-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 Ingham076b3042012-04-10 01:21:57 +000040#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041
42using namespace lldb;
43using namespace lldb_private;
44
Greg Clayton67cc0632012-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 Clayton32e0a752011-03-30 18:16:51 +0000148void
Greg Clayton8b82f082011-04-12 05:54:46 +0000149ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000150{
151 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000152 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +0000153 s.Printf (" pid = %llu\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000154
155 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +0000156 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000165 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000166 if (argc > 0)
167 {
168 for (uint32_t i=0; i<argc; i++)
169 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000170 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000171 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000172 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000173 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000174 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000175 }
176 }
Greg Clayton8b82f082011-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 Clayton95bf0fd2011-04-01 00:29:43 +0000191 if (m_arch.IsValid())
192 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
193
Greg Clayton8b82f082011-04-12 05:54:46 +0000194 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000195 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000196 cstr = platform->GetUserName (m_uid);
197 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000198 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000199 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000200 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000201 cstr = platform->GetGroupName (m_gid);
202 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000203 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000204 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000205 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000206 cstr = platform->GetUserName (m_euid);
207 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000208 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000209 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000210 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000211 cstr = platform->GetGroupName (m_egid);
212 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000213 }
214}
215
216void
Greg Clayton8b82f082011-04-12 05:54:46 +0000217ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000218{
Greg Clayton8b82f082011-04-12 05:54:46 +0000219 const char *label;
220 if (show_args || verbose)
221 label = "ARGUMENTS";
222 else
223 label = "NAME";
224
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000225 if (verbose)
226 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000227 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000228 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
229 }
230 else
231 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000232 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000233 s.PutCString ("====== ====== ========== ======= ============================\n");
234 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000235}
236
237void
Greg Clayton8b82f082011-04-12 05:54:46 +0000238ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000239{
240 if (m_pid != LLDB_INVALID_PROCESS_ID)
241 {
242 const char *cstr;
Greg Clayton61e7a582011-12-01 23:28:38 +0000243 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000244
Greg Clayton32e0a752011-03-30 18:16:51 +0000245
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000246 if (verbose)
247 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000248 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000252 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000253
Greg Clayton8b82f082011-04-12 05:54:46 +0000254 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000258 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000259
Greg Clayton8b82f082011-04-12 05:54:46 +0000260 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000264 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000265
Greg Clayton8b82f082011-04-12 05:54:46 +0000266 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000270 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000271 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
272 }
273 else
274 {
Jason Molendafd54b362011-09-20 21:44:10 +0000275 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000276 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000277 (int)m_arch.GetTriple().getArchName().size(),
278 m_arch.GetTriple().getArchName().data());
279 }
280
Greg Clayton8b82f082011-04-12 05:54:46 +0000281 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000282 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000283 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000290 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000291 }
292 }
293 }
294 else
295 {
296 s.PutCString (GetName());
297 }
298
299 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000300 }
301}
302
Greg Clayton8b82f082011-04-12 05:54:46 +0000303
304void
Greg Clayton982c9762011-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 Clayton8b82f082011-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 Clayton982c9762011-11-03 21:22:33 +0000341 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-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 Clayton1d885962011-11-08 02:43:13 +0000358void
Greg Claytonee95ed52011-11-17 22:14:31 +0000359ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-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 Clayton1d885962011-11-08 02:43:13 +0000365 if (m_flags.Test(eLaunchFlagDisableSTDIO))
366 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000367 AppendSuppressFileAction (STDIN_FILENO , true, false);
368 AppendSuppressFileAction (STDOUT_FILENO, false, true);
369 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-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 Clayton67cc0632012-08-22 17:17:09 +0000377 FileSpec in_path;
378 FileSpec out_path;
379 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000380 if (target)
381 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000382 in_path = target->GetStandardInputPath();
383 out_path = target->GetStandardOutputPath();
384 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000385 }
386
Greg Clayton67cc0632012-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 Claytonee95ed52011-11-17 22:14:31 +0000400 {
401 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000402 {
Greg Clayton67cc0632012-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 Clayton1d885962011-11-08 02:43:13 +0000407 }
408 }
Greg Clayton1d885962011-11-08 02:43:13 +0000409 }
410 }
411}
412
Greg Clayton144f3a92011-11-15 03:53:30 +0000413
414bool
Greg Claytond1cf11a2012-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 Clayton144f3a92011-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 Clayton144f3a92011-11-15 03:53:30 +0000449 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000450
451 StreamString shell_command;
452 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000453 {
Greg Claytond1cf11a2012-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 Clayton144f3a92011-11-15 03:53:30 +0000471 }
472
473 const char **argv = GetArguments().GetConstArgumentVector ();
474 if (argv)
475 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000476 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000477 {
Greg Claytond1cf11a2012-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 Clayton144f3a92011-11-15 03:53:30 +0000483 }
Greg Claytond1cf11a2012-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 Clayton144f3a92011-11-15 03:53:30 +0000493 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000494 else
495 {
496 return false;
497 }
498
Greg Clayton144f3a92011-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 Clayton32e0a752011-03-30 18:16:51 +0000516bool
Greg Clayton8b82f082011-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 Clayton144f3a92011-11-15 03:53:30 +0000524 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000525 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000526 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000527 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000528 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-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 Clayton144f3a92011-11-15 03:53:30 +0000616
Greg Clayton8b82f082011-04-12 05:54:46 +0000617 mode_t mode = 0;
618
Greg Clayton144f3a92011-11-15 03:53:30 +0000619 if (oflag & O_CREAT)
620 mode = 0640;
621
Greg Clayton8b82f082011-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 Claytonf6b8b582011-04-13 00:18:08 +0000643ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-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 Clayton8b82f082011-04-12 05:54:46 +0000654 case 'i': // STDIN for read only
655 {
656 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000657 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-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 Clayton9845a8d2012-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 Clayton8b82f082011-04-12 05:54:46 +0000674 launch_info.AppendFileAction (action);
675 }
676 break;
677
Greg Clayton9845a8d2012-03-06 04:01:04 +0000678
Greg Clayton8b82f082011-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 Clayton9845a8d2012-03-06 04:01:04 +0000686 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000687 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000688 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000689 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000690 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-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 Clayton70512312012-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 Clayton8b82f082011-04-12 05:54:46 +0000706 break;
707
708 case 'A':
709 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
710 break;
711
Greg Clayton982c9762011-11-03 21:22:33 +0000712 case 'c':
Greg Clayton144f3a92011-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 Clayton982c9762011-11-03 21:22:33 +0000717 break;
718
Greg Clayton8b82f082011-04-12 05:54:46 +0000719 case 'v':
720 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
721 break;
722
723 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000724 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-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 Clayton144f3a92011-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 Clayton8b82f082011-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 Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000768ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000781 if (m_match_info.UserIDIsValid () &&
782 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000783 return false;
784
Greg Clayton8b82f082011-04-12 05:54:46 +0000785 if (m_match_info.GroupIDIsValid () &&
786 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000804ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000815 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000816 return false;
817
Greg Clayton8b82f082011-04-12 05:54:46 +0000818 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000838ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-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 Clayton58be07b2011-01-07 06:08:19 +0000844
Greg Claytonc3776bf2012-02-09 06:16:32 +0000845ProcessSP
846Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000847{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000848 ProcessSP process_sp;
Chris Lattner30fdc8d2010-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 Claytonc3776bf2012-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 Lattner30fdc8d2010-06-08 16:52:24 +0000861 }
862 }
863 else
864 {
Greg Claytonc982c762010-07-09 20:39:50 +0000865 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000866 {
Greg Claytonc3776bf2012-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 Lattner30fdc8d2010-06-08 16:52:24 +0000875 }
876 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000877 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878}
879
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000880ConstString &
881Process::GetStaticBroadcasterClass ()
882{
883 static ConstString class_name ("lldb.process");
884 return class_name;
885}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000886
887//----------------------------------------------------------------------
888// Process constructor
889//----------------------------------------------------------------------
890Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000891 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000892 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000893 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000894 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000895 m_public_state (eStateUnloaded),
896 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-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 Lattner30fdc8d2010-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 Ingham4b536182011-08-09 02:12:22 +0000902 m_mod_id (),
Chris Lattner30fdc8d2010-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 Clayton3af9ea52010-11-18 05:57:03 +0000908 m_image_tokens (),
909 m_listener (listener),
910 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000911 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000912 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000913 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000914 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000915 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000916 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000917 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000918 m_stderr_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000919 m_memory_cache (*this),
920 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000921 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000922 m_next_event_action_ap(),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000923 m_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000924 m_currently_handling_event(false),
Jim Ingham4fc6cb92012-08-22 21:34:33 +0000925 m_finalize_called(false),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000926 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000927{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000928 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000929
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000930 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000931 if (log)
932 log->Printf ("%p Process::Process()", this);
933
Greg Claytoncfd1ace2010-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 Lattner30fdc8d2010-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 Inghamcfc09352012-07-27 23:57:19 +0000946 eBroadcastBitStateChanged |
947 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-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 Clayton2d4edfb2010-11-06 01:53:30 +0000960 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000961 if (log)
962 log->Printf ("%p Process::~Process()", this);
963 StopPrivateStateThread();
964}
965
Greg Clayton67cc0632012-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 Lattner30fdc8d2010-06-08 16:52:24 +0000975void
976Process::Finalize()
977{
Greg Claytone24c4ac2011-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 Clayton1ed54f52011-10-01 00:45:15 +00001001 // Clear our broadcaster before we proceed with destroying
1002 Broadcaster::Clear();
1003
Chris Lattner30fdc8d2010-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 Inghamd0a3e122011-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 Clayton894f82f2012-01-20 23:08:34 +00001009 m_dynamic_checkers_ap.reset();
1010 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001011 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001012 m_dyld_ap.reset();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001013 m_thread_list.Destroy();
Greg Clayton894f82f2012-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 Ingham4fc6cb92012-08-22 21:34:33 +00001021 m_finalize_called = true;
Chris Lattner30fdc8d2010-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
1081Process::WaitForProcessToStop (const TimeValue *timeout)
1082{
Jim Ingham4b536182011-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.
1086 EventSP event_sp;
1087 StateType state = GetState();
1088 // If we are exited or detached, we won't ever get back to any
1089 // other valid state...
1090 if (state == eStateDetached || state == eStateExited)
1091 return state;
1092
1093 while (state != eStateInvalid)
1094 {
1095 state = WaitForStateChangedEvents (timeout, event_sp);
1096 switch (state)
1097 {
1098 case eStateCrashed:
1099 case eStateDetached:
1100 case eStateExited:
1101 case eStateUnloaded:
1102 return state;
1103 case eStateStopped:
1104 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1105 continue;
1106 else
1107 return state;
1108 default:
1109 continue;
1110 }
1111 }
1112 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113}
1114
1115
1116StateType
1117Process::WaitForState
1118(
1119 const TimeValue *timeout,
1120 const StateType *match_states, const uint32_t num_match_states
1121)
1122{
1123 EventSP event_sp;
1124 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001125 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001126 while (state != eStateInvalid)
1127 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001128 // If we are exited or detached, we won't ever get back to any
1129 // other valid state...
1130 if (state == eStateDetached || state == eStateExited)
1131 return state;
1132
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001133 state = WaitForStateChangedEvents (timeout, event_sp);
1134
1135 for (i=0; i<num_match_states; ++i)
1136 {
1137 if (match_states[i] == state)
1138 return state;
1139 }
1140 }
1141 return state;
1142}
1143
Jim Ingham30f9b212010-10-11 23:53:14 +00001144bool
1145Process::HijackProcessEvents (Listener *listener)
1146{
1147 if (listener != NULL)
1148 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001149 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001150 }
1151 else
1152 return false;
1153}
1154
1155void
1156Process::RestoreProcessEvents ()
1157{
1158 RestoreBroadcaster();
1159}
1160
Jim Ingham0f16e732011-02-08 05:20:59 +00001161bool
1162Process::HijackPrivateProcessEvents (Listener *listener)
1163{
1164 if (listener != NULL)
1165 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001166 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001167 }
1168 else
1169 return false;
1170}
1171
1172void
1173Process::RestorePrivateProcessEvents ()
1174{
1175 m_private_state_broadcaster.RestoreBroadcaster();
1176}
1177
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001178StateType
1179Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1180{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001181 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001182
1183 if (log)
1184 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1185
1186 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001187 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1188 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001189 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001190 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001191 {
1192 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1193 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1194 else if (log)
1195 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1196 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197
1198 if (log)
1199 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1200 __FUNCTION__,
1201 timeout,
1202 StateAsCString(state));
1203 return state;
1204}
1205
1206Event *
1207Process::PeekAtStateChangedEvents ()
1208{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001209 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001210
1211 if (log)
1212 log->Printf ("Process::%s...", __FUNCTION__);
1213
1214 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001215 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1216 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001217 if (log)
1218 {
1219 if (event_ptr)
1220 {
1221 log->Printf ("Process::%s (event_ptr) => %s",
1222 __FUNCTION__,
1223 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1224 }
1225 else
1226 {
1227 log->Printf ("Process::%s no events found",
1228 __FUNCTION__);
1229 }
1230 }
1231 return event_ptr;
1232}
1233
1234StateType
1235Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1236{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001237 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001238
1239 if (log)
1240 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1241
1242 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001243 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1244 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001245 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001246 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001247 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1248 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001249
1250 // This is a bit of a hack, but when we wait here we could very well return
1251 // to the command-line, and that could disable the log, which would render the
1252 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001253 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001254 {
1255 if (state == eStateInvalid)
1256 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1257 else
1258 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1259 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001260 return state;
1261}
1262
1263bool
1264Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1265{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001266 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001267
1268 if (log)
1269 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1270
1271 if (control_only)
1272 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1273 else
1274 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1275}
1276
1277bool
1278Process::IsRunning () const
1279{
1280 return StateIsRunningState (m_public_state.GetValue());
1281}
1282
1283int
1284Process::GetExitStatus ()
1285{
1286 if (m_public_state.GetValue() == eStateExited)
1287 return m_exit_status;
1288 return -1;
1289}
1290
Greg Clayton85851dd2010-12-04 00:10:17 +00001291
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001292const char *
1293Process::GetExitDescription ()
1294{
1295 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1296 return m_exit_string.c_str();
1297 return NULL;
1298}
1299
Greg Clayton6779606a2011-01-22 23:43:18 +00001300bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001301Process::SetExitStatus (int status, const char *cstr)
1302{
Greg Clayton414f5d32011-01-25 02:58:48 +00001303 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1304 if (log)
1305 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1306 status, status,
1307 cstr ? "\"" : "",
1308 cstr ? cstr : "NULL",
1309 cstr ? "\"" : "");
1310
Greg Clayton6779606a2011-01-22 23:43:18 +00001311 // We were already in the exited state
1312 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001313 {
Greg Clayton385d6032011-01-26 23:47:29 +00001314 if (log)
1315 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001316 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001317 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001318
1319 m_exit_status = status;
1320 if (cstr)
1321 m_exit_string = cstr;
1322 else
1323 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001324
Greg Clayton6779606a2011-01-22 23:43:18 +00001325 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001326
Greg Clayton6779606a2011-01-22 23:43:18 +00001327 SetPrivateState (eStateExited);
1328 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001329}
1330
1331// This static callback can be used to watch for local child processes on
1332// the current host. The the child process exits, the process will be
1333// found in the global target list (we want to be completely sure that the
1334// lldb_private::Process doesn't go away before we can deliver the signal.
1335bool
Greg Claytone4e45922011-11-16 05:37:56 +00001336Process::SetProcessExitStatus (void *callback_baton,
1337 lldb::pid_t pid,
1338 bool exited,
1339 int signo, // Zero for no signal
1340 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001341)
1342{
Greg Claytone4e45922011-11-16 05:37:56 +00001343 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1344 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00001345 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001346 callback_baton,
1347 pid,
1348 exited,
1349 signo,
1350 exit_status);
1351
1352 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001353 {
Greg Clayton66111032010-06-23 01:19:29 +00001354 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355 if (target_sp)
1356 {
1357 ProcessSP process_sp (target_sp->GetProcessSP());
1358 if (process_sp)
1359 {
1360 const char *signal_cstr = NULL;
1361 if (signo)
1362 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1363
1364 process_sp->SetExitStatus (exit_status, signal_cstr);
1365 }
1366 }
1367 return true;
1368 }
1369 return false;
1370}
1371
1372
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001373void
1374Process::UpdateThreadListIfNeeded ()
1375{
1376 const uint32_t stop_id = GetStopID();
1377 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1378 {
Greg Clayton2637f822011-11-17 01:23:07 +00001379 const StateType state = GetPrivateState();
1380 if (StateIsStoppedState (state, true))
1381 {
1382 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001383 // m_thread_list does have its own mutex, but we need to
1384 // hold onto the mutex between the call to UpdateThreadList(...)
1385 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton2637f822011-11-17 01:23:07 +00001386 ThreadList new_thread_list(this);
1387 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001388 // thread list, but only update if "true" is returned
1389 if (UpdateThreadList (m_thread_list, new_thread_list))
1390 {
1391 OperatingSystem *os = GetOperatingSystem ();
1392 if (os)
1393 os->UpdateThreadList (m_thread_list, new_thread_list);
1394 m_thread_list.Update (new_thread_list);
1395 m_thread_list.SetStopID (stop_id);
1396 }
Greg Clayton2637f822011-11-17 01:23:07 +00001397 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001398 }
1399}
1400
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001401uint32_t
1402Process::GetNextThreadIndexID ()
1403{
1404 return ++m_thread_index_id;
1405}
1406
1407StateType
1408Process::GetState()
1409{
1410 // If any other threads access this we will need a mutex for it
1411 return m_public_state.GetValue ();
1412}
1413
1414void
1415Process::SetPublicState (StateType new_state)
1416{
Greg Clayton414f5d32011-01-25 02:58:48 +00001417 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001418 if (log)
1419 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001420 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001421 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001422
1423 // On the transition from Run to Stopped, we unlock the writer end of the
1424 // run lock. The lock gets locked in Resume, which is the public API
1425 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001426 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1427 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001428 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001429 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001430 if (log)
1431 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1432 m_run_lock.WriteUnlock();
1433 }
1434 else
1435 {
1436 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1437 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1438 if (old_state_is_stopped != new_state_is_stopped)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001439 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001440 if (new_state_is_stopped)
1441 {
1442 if (log)
1443 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1444 m_run_lock.WriteUnlock();
1445 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001446 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001447 }
1448 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001449}
1450
Jim Ingham3b8285d2012-04-19 01:40:33 +00001451Error
1452Process::Resume ()
1453{
1454 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1455 if (log)
1456 log->Printf("Process::Resume -- locking run lock");
1457 if (!m_run_lock.WriteTryLock())
1458 {
1459 Error error("Resume request failed - process still running.");
1460 if (log)
1461 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1462 return error;
1463 }
1464 return PrivateResume();
1465}
1466
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001467StateType
1468Process::GetPrivateState ()
1469{
1470 return m_private_state.GetValue();
1471}
1472
1473void
1474Process::SetPrivateState (StateType new_state)
1475{
Greg Clayton414f5d32011-01-25 02:58:48 +00001476 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001477 bool state_changed = false;
1478
1479 if (log)
1480 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1481
1482 Mutex::Locker locker(m_private_state.GetMutex());
1483
1484 const StateType old_state = m_private_state.GetValueNoLock ();
1485 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001486 // This code is left commented out in case we ever need to control
1487 // the private process state with another run lock. Right now it doesn't
1488 // seem like we need to do this, but if we ever do, we can uncomment and
1489 // use this code.
1490// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1491// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1492// if (old_state_is_stopped != new_state_is_stopped)
1493// {
1494// if (new_state_is_stopped)
1495// m_private_run_lock.WriteUnlock();
1496// else
1497// m_private_run_lock.WriteLock();
1498// }
1499
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001500 if (state_changed)
1501 {
1502 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001503 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504 {
Jim Ingham4b536182011-08-09 02:12:22 +00001505 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001506 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001507 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001508 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001509 }
1510 // Use our target to get a shared pointer to ourselves...
1511 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1512 }
1513 else
1514 {
1515 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001516 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001517 }
1518}
1519
Jim Ingham0faa43f2011-11-08 03:00:11 +00001520void
1521Process::SetRunningUserExpression (bool on)
1522{
1523 m_mod_id.SetRunningUserExpression (on);
1524}
1525
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001526addr_t
1527Process::GetImageInfoAddress()
1528{
1529 return LLDB_INVALID_ADDRESS;
1530}
1531
Greg Clayton8f343b02010-11-04 01:54:29 +00001532//----------------------------------------------------------------------
1533// LoadImage
1534//
1535// This function provides a default implementation that works for most
1536// unix variants. Any Process subclasses that need to do shared library
1537// loading differently should override LoadImage and UnloadImage and
1538// do what is needed.
1539//----------------------------------------------------------------------
1540uint32_t
1541Process::LoadImage (const FileSpec &image_spec, Error &error)
1542{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001543 char path[PATH_MAX];
1544 image_spec.GetPath(path, sizeof(path));
1545
Greg Clayton8f343b02010-11-04 01:54:29 +00001546 DynamicLoader *loader = GetDynamicLoader();
1547 if (loader)
1548 {
1549 error = loader->CanLoadImage();
1550 if (error.Fail())
1551 return LLDB_INVALID_IMAGE_TOKEN;
1552 }
1553
1554 if (error.Success())
1555 {
1556 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001557
1558 if (thread_sp)
1559 {
1560 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1561
1562 if (frame_sp)
1563 {
1564 ExecutionContext exe_ctx;
1565 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001566 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001567 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001568 expr.Printf("dlopen (\"%s\", 2)", path);
1569 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001570 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001571 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chene92aa432011-09-09 00:01:43 +00001572 error = result_valobj_sp->GetError();
1573 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001574 {
1575 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001576 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001577 {
1578 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1579 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1580 {
1581 uint32_t image_token = m_image_tokens.size();
1582 m_image_tokens.push_back (image_ptr);
1583 return image_token;
1584 }
1585 }
1586 }
1587 }
1588 }
1589 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001590 if (!error.AsCString())
1591 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001592 return LLDB_INVALID_IMAGE_TOKEN;
1593}
1594
1595//----------------------------------------------------------------------
1596// UnloadImage
1597//
1598// This function provides a default implementation that works for most
1599// unix variants. Any Process subclasses that need to do shared library
1600// loading differently should override LoadImage and UnloadImage and
1601// do what is needed.
1602//----------------------------------------------------------------------
1603Error
1604Process::UnloadImage (uint32_t image_token)
1605{
1606 Error error;
1607 if (image_token < m_image_tokens.size())
1608 {
1609 const addr_t image_addr = m_image_tokens[image_token];
1610 if (image_addr == LLDB_INVALID_ADDRESS)
1611 {
1612 error.SetErrorString("image already unloaded");
1613 }
1614 else
1615 {
1616 DynamicLoader *loader = GetDynamicLoader();
1617 if (loader)
1618 error = loader->CanLoadImage();
1619
1620 if (error.Success())
1621 {
1622 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001623
1624 if (thread_sp)
1625 {
1626 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1627
1628 if (frame_sp)
1629 {
1630 ExecutionContext exe_ctx;
1631 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001632 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001633 StreamString expr;
1634 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1635 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001636 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001637 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +00001638 if (result_valobj_sp->GetError().Success())
1639 {
1640 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001641 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001642 {
1643 if (scalar.UInt(1))
1644 {
1645 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1646 }
1647 else
1648 {
1649 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1650 }
1651 }
1652 }
1653 else
1654 {
1655 error = result_valobj_sp->GetError();
1656 }
1657 }
1658 }
1659 }
1660 }
1661 }
1662 else
1663 {
1664 error.SetErrorString("invalid image token");
1665 }
1666 return error;
1667}
1668
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001669const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001670Process::GetABI()
1671{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001672 if (!m_abi_sp)
1673 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1674 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001675}
1676
Jim Ingham22777012010-09-23 02:01:19 +00001677LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001678Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001679{
1680 LanguageRuntimeCollection::iterator pos;
1681 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001682 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001683 {
Jim Inghamab175242012-03-10 00:22:19 +00001684 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001685
Jim Inghamab175242012-03-10 00:22:19 +00001686 m_language_runtimes[language] = runtime_sp;
1687 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001688 }
1689 else
1690 return (*pos).second.get();
1691}
1692
1693CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001694Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001695{
Jim Inghamab175242012-03-10 00:22:19 +00001696 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001697 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1698 return static_cast<CPPLanguageRuntime *> (runtime);
1699 return NULL;
1700}
1701
1702ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001703Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001704{
Jim Inghamab175242012-03-10 00:22:19 +00001705 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001706 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1707 return static_cast<ObjCLanguageRuntime *> (runtime);
1708 return NULL;
1709}
1710
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001711bool
1712Process::IsPossibleDynamicValue (ValueObject& in_value)
1713{
1714 if (in_value.IsDynamic())
1715 return false;
1716 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1717
1718 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1719 {
1720 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1721 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1722 }
1723
1724 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1725 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1726 return true;
1727
1728 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1729 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1730}
1731
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001732BreakpointSiteList &
1733Process::GetBreakpointSiteList()
1734{
1735 return m_breakpoint_site_list;
1736}
1737
1738const BreakpointSiteList &
1739Process::GetBreakpointSiteList() const
1740{
1741 return m_breakpoint_site_list;
1742}
1743
1744
1745void
1746Process::DisableAllBreakpointSites ()
1747{
1748 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham43c555d2012-07-04 00:35:43 +00001749 size_t num_sites = m_breakpoint_site_list.GetSize();
1750 for (size_t i = 0; i < num_sites; i++)
1751 {
1752 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1753 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001754}
1755
1756Error
1757Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1758{
1759 Error error (DisableBreakpointSiteByID (break_id));
1760
1761 if (error.Success())
1762 m_breakpoint_site_list.Remove(break_id);
1763
1764 return error;
1765}
1766
1767Error
1768Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1769{
1770 Error error;
1771 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1772 if (bp_site_sp)
1773 {
1774 if (bp_site_sp->IsEnabled())
1775 error = DisableBreakpoint (bp_site_sp.get());
1776 }
1777 else
1778 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001779 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001780 }
1781
1782 return error;
1783}
1784
1785Error
1786Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1787{
1788 Error error;
1789 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1790 if (bp_site_sp)
1791 {
1792 if (!bp_site_sp->IsEnabled())
1793 error = EnableBreakpoint (bp_site_sp.get());
1794 }
1795 else
1796 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001797 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001798 }
1799 return error;
1800}
1801
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001802lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001803Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001804{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001805 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001806 if (load_addr != LLDB_INVALID_ADDRESS)
1807 {
1808 BreakpointSiteSP bp_site_sp;
1809
1810 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1811 // create a new breakpoint site and add it.
1812
1813 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1814
1815 if (bp_site_sp)
1816 {
1817 bp_site_sp->AddOwner (owner);
1818 owner->SetBreakpointSite (bp_site_sp);
1819 return bp_site_sp->GetID();
1820 }
1821 else
1822 {
1823 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1824 if (bp_site_sp)
1825 {
1826 if (EnableBreakpoint (bp_site_sp.get()).Success())
1827 {
1828 owner->SetBreakpointSite (bp_site_sp);
1829 return m_breakpoint_site_list.Add (bp_site_sp);
1830 }
1831 }
1832 }
1833 }
1834 // We failed to enable the breakpoint
1835 return LLDB_INVALID_BREAK_ID;
1836
1837}
1838
1839void
1840Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1841{
1842 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1843 if (num_owners == 0)
1844 {
1845 DisableBreakpoint(bp_site_sp.get());
1846 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1847 }
1848}
1849
1850
1851size_t
1852Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1853{
1854 size_t bytes_removed = 0;
1855 addr_t intersect_addr;
1856 size_t intersect_size;
1857 size_t opcode_offset;
1858 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001859 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001860 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001861
Jim Ingham20c77192011-06-29 19:42:28 +00001862 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001863 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001864 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001866 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001867 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001868 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001869 {
1870 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1871 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001872 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001873 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001874 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001875 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001876 }
1877 }
1878 }
1879 return bytes_removed;
1880}
1881
1882
Greg Claytonded470d2011-03-19 01:12:21 +00001883
1884size_t
1885Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1886{
1887 PlatformSP platform_sp (m_target.GetPlatform());
1888 if (platform_sp)
1889 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1890 return 0;
1891}
1892
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001893Error
1894Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1895{
1896 Error error;
1897 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001898 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001899 const addr_t bp_addr = bp_site->GetLoadAddress();
1900 if (log)
1901 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1902 if (bp_site->IsEnabled())
1903 {
1904 if (log)
1905 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1906 return error;
1907 }
1908
1909 if (bp_addr == LLDB_INVALID_ADDRESS)
1910 {
1911 error.SetErrorString("BreakpointSite contains an invalid load address.");
1912 return error;
1913 }
1914 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1915 // trap for the breakpoint site
1916 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1917
1918 if (bp_opcode_size == 0)
1919 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001920 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001921 }
1922 else
1923 {
1924 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1925
1926 if (bp_opcode_bytes == NULL)
1927 {
1928 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1929 return error;
1930 }
1931
1932 // Save the original opcode by reading it
1933 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1934 {
1935 // Write a software breakpoint in place of the original opcode
1936 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1937 {
1938 uint8_t verify_bp_opcode_bytes[64];
1939 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1940 {
1941 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1942 {
1943 bp_site->SetEnabled(true);
1944 bp_site->SetType (BreakpointSite::eSoftware);
1945 if (log)
1946 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1947 bp_site->GetID(),
1948 (uint64_t)bp_addr);
1949 }
1950 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001951 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001952 }
1953 else
1954 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1955 }
1956 else
1957 error.SetErrorString("Unable to write breakpoint trap to memory.");
1958 }
1959 else
1960 error.SetErrorString("Unable to read memory at breakpoint address.");
1961 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001962 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001963 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1964 bp_site->GetID(),
1965 (uint64_t)bp_addr,
1966 error.AsCString());
1967 return error;
1968}
1969
1970Error
1971Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1972{
1973 Error error;
1974 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001975 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001976 addr_t bp_addr = bp_site->GetLoadAddress();
1977 lldb::user_id_t breakID = bp_site->GetID();
1978 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001979 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001980
1981 if (bp_site->IsHardware())
1982 {
1983 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1984 }
1985 else if (bp_site->IsEnabled())
1986 {
1987 const size_t break_op_size = bp_site->GetByteSize();
1988 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1989 if (break_op_size > 0)
1990 {
1991 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001992 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001993 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001994 bool break_op_found = false;
1995
1996 // Read the breakpoint opcode
1997 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1998 {
1999 bool verify = false;
2000 // Make sure we have the a breakpoint opcode exists at this address
2001 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
2002 {
2003 break_op_found = true;
2004 // We found a valid breakpoint opcode at this address, now restore
2005 // the saved opcode.
2006 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2007 {
2008 verify = true;
2009 }
2010 else
2011 error.SetErrorString("Memory write failed when restoring original opcode.");
2012 }
2013 else
2014 {
2015 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2016 // Set verify to true and so we can check if the original opcode has already been restored
2017 verify = true;
2018 }
2019
2020 if (verify)
2021 {
Greg Claytonc982c762010-07-09 20:39:50 +00002022 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002023 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002024 // Verify that our original opcode made it back to the inferior
2025 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2026 {
2027 // compare the memory we just read with the original opcode
2028 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2029 {
2030 // SUCCESS
2031 bp_site->SetEnabled(false);
2032 if (log)
2033 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2034 return error;
2035 }
2036 else
2037 {
2038 if (break_op_found)
2039 error.SetErrorString("Failed to restore original opcode.");
2040 }
2041 }
2042 else
2043 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2044 }
2045 }
2046 else
2047 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2048 }
2049 }
2050 else
2051 {
2052 if (log)
2053 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2054 return error;
2055 }
2056
2057 if (log)
2058 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2059 bp_site->GetID(),
2060 (uint64_t)bp_addr,
2061 error.AsCString());
2062 return error;
2063
2064}
2065
Greg Clayton58be07b2011-01-07 06:08:19 +00002066// Uncomment to verify memory caching works after making changes to caching code
2067//#define VERIFY_MEMORY_READS
2068
Sean Callanan64c0cf22012-06-07 22:26:42 +00002069size_t
2070Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2071{
2072 if (!GetDisableMemoryCache())
2073 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002074#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002075 // Memory caching is enabled, with debug verification
2076
2077 if (buf && size)
2078 {
2079 // Uncomment the line below to make sure memory caching is working.
2080 // I ran this through the test suite and got no assertions, so I am
2081 // pretty confident this is working well. If any changes are made to
2082 // memory caching, uncomment the line below and test your changes!
2083
2084 // Verify all memory reads by using the cache first, then redundantly
2085 // reading the same memory from the inferior and comparing to make sure
2086 // everything is exactly the same.
2087 std::string verify_buf (size, '\0');
2088 assert (verify_buf.size() == size);
2089 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2090 Error verify_error;
2091 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2092 assert (cache_bytes_read == verify_bytes_read);
2093 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2094 assert (verify_error.Success() == error.Success());
2095 return cache_bytes_read;
2096 }
2097 return 0;
2098#else // !defined(VERIFY_MEMORY_READS)
2099 // Memory caching is enabled, without debug verification
2100
2101 return m_memory_cache.Read (addr, buf, size, error);
2102#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002103 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002104 else
2105 {
2106 // Memory caching is disabled
2107
2108 return ReadMemoryFromInferior (addr, buf, size, error);
2109 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002110}
Greg Clayton58be07b2011-01-07 06:08:19 +00002111
Greg Clayton4c82d422012-05-18 23:20:01 +00002112size_t
2113Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2114{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002115 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002116 out_str.clear();
2117 addr_t curr_addr = addr;
2118 while (1)
2119 {
2120 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2121 if (length == 0)
2122 break;
2123 out_str.append(buf, length);
2124 // If we got "length - 1" bytes, we didn't get the whole C string, we
2125 // need to read some more characters
2126 if (length == sizeof(buf) - 1)
2127 curr_addr += length;
2128 else
2129 break;
2130 }
2131 return out_str.size();
2132}
2133
Greg Clayton58be07b2011-01-07 06:08:19 +00002134
2135size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002136Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002137{
2138 size_t total_cstr_len = 0;
2139 if (dst && dst_max_len)
2140 {
Greg Claytone91b7952011-12-15 03:14:23 +00002141 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002142 // NULL out everything just to be safe
2143 memset (dst, 0, dst_max_len);
2144 Error error;
2145 addr_t curr_addr = addr;
2146 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2147 size_t bytes_left = dst_max_len - 1;
2148 char *curr_dst = dst;
2149
2150 while (bytes_left > 0)
2151 {
2152 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2153 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2154 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2155
2156 if (bytes_read == 0)
2157 {
Greg Claytone91b7952011-12-15 03:14:23 +00002158 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002159 dst[total_cstr_len] = '\0';
2160 break;
2161 }
2162 const size_t len = strlen(curr_dst);
2163
2164 total_cstr_len += len;
2165
2166 if (len < bytes_to_read)
2167 break;
2168
2169 curr_dst += bytes_read;
2170 curr_addr += bytes_read;
2171 bytes_left -= bytes_read;
2172 }
2173 }
Greg Claytone91b7952011-12-15 03:14:23 +00002174 else
2175 {
2176 if (dst == NULL)
2177 result_error.SetErrorString("invalid arguments");
2178 else
2179 result_error.Clear();
2180 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002181 return total_cstr_len;
2182}
2183
2184size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002185Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2186{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002187 if (buf == NULL || size == 0)
2188 return 0;
2189
2190 size_t bytes_read = 0;
2191 uint8_t *bytes = (uint8_t *)buf;
2192
2193 while (bytes_read < size)
2194 {
2195 const size_t curr_size = size - bytes_read;
2196 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2197 bytes + bytes_read,
2198 curr_size,
2199 error);
2200 bytes_read += curr_bytes_read;
2201 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2202 break;
2203 }
2204
2205 // Replace any software breakpoint opcodes that fall into this range back
2206 // into "buf" before we return
2207 if (bytes_read > 0)
2208 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2209 return bytes_read;
2210}
2211
Greg Clayton58a4c462010-12-16 20:01:20 +00002212uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002213Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002214{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002215 Scalar scalar;
2216 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2217 return scalar.ULongLong(fail_value);
2218 return fail_value;
2219}
2220
2221addr_t
2222Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2223{
2224 Scalar scalar;
2225 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2226 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2227 return LLDB_INVALID_ADDRESS;
2228}
2229
2230
2231bool
2232Process::WritePointerToMemory (lldb::addr_t vm_addr,
2233 lldb::addr_t ptr_value,
2234 Error &error)
2235{
2236 Scalar scalar;
2237 const uint32_t addr_byte_size = GetAddressByteSize();
2238 if (addr_byte_size <= 4)
2239 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002240 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002241 scalar = ptr_value;
2242 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002243}
2244
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002245size_t
2246Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2247{
2248 size_t bytes_written = 0;
2249 const uint8_t *bytes = (const uint8_t *)buf;
2250
2251 while (bytes_written < size)
2252 {
2253 const size_t curr_size = size - bytes_written;
2254 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2255 bytes + bytes_written,
2256 curr_size,
2257 error);
2258 bytes_written += curr_bytes_written;
2259 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2260 break;
2261 }
2262 return bytes_written;
2263}
2264
2265size_t
2266Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2267{
Greg Clayton58be07b2011-01-07 06:08:19 +00002268#if defined (ENABLE_MEMORY_CACHING)
2269 m_memory_cache.Flush (addr, size);
2270#endif
2271
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002272 if (buf == NULL || size == 0)
2273 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002274
Jim Ingham4b536182011-08-09 02:12:22 +00002275 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002276
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002277 // We need to write any data that would go where any current software traps
2278 // (enabled software breakpoints) any software traps (breakpoints) that we
2279 // may have placed in our tasks memory.
2280
2281 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2282 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2283
2284 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002285 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002286
2287 BreakpointSiteList::collection::const_iterator pos;
2288 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002289 addr_t intersect_addr = 0;
2290 size_t intersect_size = 0;
2291 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292 const uint8_t *ubuf = (const uint8_t *)buf;
2293
2294 for (pos = iter; pos != end; ++pos)
2295 {
2296 BreakpointSiteSP bp;
2297 bp = pos->second;
2298
2299 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2300 assert(addr <= intersect_addr && intersect_addr < addr + size);
2301 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2302 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2303
2304 // Check for bytes before this breakpoint
2305 const addr_t curr_addr = addr + bytes_written;
2306 if (intersect_addr > curr_addr)
2307 {
2308 // There are some bytes before this breakpoint that we need to
2309 // just write to memory
2310 size_t curr_size = intersect_addr - curr_addr;
2311 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2312 ubuf + bytes_written,
2313 curr_size,
2314 error);
2315 bytes_written += curr_bytes_written;
2316 if (curr_bytes_written != curr_size)
2317 {
2318 // We weren't able to write all of the requested bytes, we
2319 // are done looping and will return the number of bytes that
2320 // we have written so far.
2321 break;
2322 }
2323 }
2324
2325 // Now write any bytes that would cover up any software breakpoints
2326 // directly into the breakpoint opcode buffer
2327 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2328 bytes_written += intersect_size;
2329 }
2330
2331 // Write any remaining bytes after the last breakpoint if we have any left
2332 if (bytes_written < size)
2333 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2334 ubuf + bytes_written,
2335 size - bytes_written,
2336 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002337
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002338 return bytes_written;
2339}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002340
2341size_t
2342Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2343{
2344 if (byte_size == UINT32_MAX)
2345 byte_size = scalar.GetByteSize();
2346 if (byte_size > 0)
2347 {
2348 uint8_t buf[32];
2349 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2350 if (mem_size > 0)
2351 return WriteMemory(addr, buf, mem_size, error);
2352 else
2353 error.SetErrorString ("failed to get scalar as memory data");
2354 }
2355 else
2356 {
2357 error.SetErrorString ("invalid scalar value");
2358 }
2359 return 0;
2360}
2361
2362size_t
2363Process::ReadScalarIntegerFromMemory (addr_t addr,
2364 uint32_t byte_size,
2365 bool is_signed,
2366 Scalar &scalar,
2367 Error &error)
2368{
2369 uint64_t uval;
2370
2371 if (byte_size <= sizeof(uval))
2372 {
2373 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2374 if (bytes_read == byte_size)
2375 {
2376 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2377 uint32_t offset = 0;
2378 if (byte_size <= 4)
2379 scalar = data.GetMaxU32 (&offset, byte_size);
2380 else
2381 scalar = data.GetMaxU64 (&offset, byte_size);
2382
2383 if (is_signed)
2384 scalar.SignExtend(byte_size * 8);
2385 return bytes_read;
2386 }
2387 }
2388 else
2389 {
2390 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2391 }
2392 return 0;
2393}
2394
Greg Claytond495c532011-05-17 03:37:42 +00002395#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002396addr_t
2397Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2398{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002399 if (GetPrivateState() != eStateStopped)
2400 return LLDB_INVALID_ADDRESS;
2401
Greg Claytond495c532011-05-17 03:37:42 +00002402#if defined (USE_ALLOCATE_MEMORY_CACHE)
2403 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2404#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002405 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2406 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2407 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002408 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002409 size,
Greg Claytond495c532011-05-17 03:37:42 +00002410 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002411 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002412 m_mod_id.GetStopID(),
2413 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002414 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002415#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002416}
2417
Sean Callanan90539452011-09-20 23:01:51 +00002418bool
2419Process::CanJIT ()
2420{
Sean Callanana7b443a2012-02-14 22:50:38 +00002421 if (m_can_jit == eCanJITDontKnow)
2422 {
2423 Error err;
2424
2425 uint64_t allocated_memory = AllocateMemory(8,
2426 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2427 err);
2428
2429 if (err.Success())
2430 m_can_jit = eCanJITYes;
2431 else
2432 m_can_jit = eCanJITNo;
2433
2434 DeallocateMemory (allocated_memory);
2435 }
2436
Sean Callanan90539452011-09-20 23:01:51 +00002437 return m_can_jit == eCanJITYes;
2438}
2439
2440void
2441Process::SetCanJIT (bool can_jit)
2442{
2443 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2444}
2445
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446Error
2447Process::DeallocateMemory (addr_t ptr)
2448{
Greg Claytond495c532011-05-17 03:37:42 +00002449 Error error;
2450#if defined (USE_ALLOCATE_MEMORY_CACHE)
2451 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2452 {
2453 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2454 }
2455#else
2456 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002457
2458 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2459 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002460 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002461 ptr,
2462 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002463 m_mod_id.GetStopID(),
2464 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002465#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002466 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002467}
2468
Greg Claytonc9660542012-02-05 02:38:54 +00002469ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002470Process::ReadModuleFromMemory (const FileSpec& file_spec,
2471 lldb::addr_t header_addr,
2472 bool add_image_to_target,
2473 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002474{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002475 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002476 if (module_sp)
2477 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002478 Error error;
2479 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2480 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002481 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002482 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002483 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002484 m_target.GetImages().Append(module_sp);
2485 if (load_sections_in_target)
2486 {
2487 bool changed = false;
2488 module_sp->SetLoadAddress (m_target, 0, changed);
2489 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002490 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002491 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002492 }
Greg Claytonc9660542012-02-05 02:38:54 +00002493 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002494 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002495}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002496
2497Error
Johnny Chen01a67862011-10-14 00:42:25 +00002498Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002499{
2500 Error error;
2501 error.SetErrorString("watchpoints are not supported");
2502 return error;
2503}
2504
2505Error
Johnny Chen01a67862011-10-14 00:42:25 +00002506Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002507{
2508 Error error;
2509 error.SetErrorString("watchpoints are not supported");
2510 return error;
2511}
2512
2513StateType
2514Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2515{
2516 StateType state;
2517 // Now wait for the process to launch and return control to us, and then
2518 // call DidLaunch:
2519 while (1)
2520 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002521 event_sp.reset();
2522 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2523
Greg Clayton2637f822011-11-17 01:23:07 +00002524 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002525 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002526
2527 // If state is invalid, then we timed out
2528 if (state == eStateInvalid)
2529 break;
2530
2531 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002532 HandlePrivateEvent (event_sp);
2533 }
2534 return state;
2535}
2536
2537Error
Greg Clayton982c9762011-11-03 21:22:33 +00002538Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002539{
2540 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002541 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002542 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002543 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002544 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002545
Greg Claytonaa149cb2011-08-11 02:48:45 +00002546 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002547 if (exe_module)
2548 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002549 char local_exec_file_path[PATH_MAX];
2550 char platform_exec_file_path[PATH_MAX];
2551 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2552 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002553 if (exe_module->GetFileSpec().Exists())
2554 {
Greg Clayton71337622011-02-24 22:24:29 +00002555 if (PrivateStateThreadIsValid ())
2556 PausePrivateStateThread ();
2557
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002558 error = WillLaunch (exe_module);
2559 if (error.Success())
2560 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002561 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002562 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002563
Greg Clayton69fd4be2012-09-04 20:29:05 +00002564 if (m_run_lock.WriteTryLock())
2565 {
2566 // Now launch using these arguments.
2567 error = DoLaunch (exe_module, launch_info);
2568 }
2569 else
2570 {
2571 // This shouldn't happen
2572 error.SetErrorString("failed to acquire process run lock");
2573 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002574
2575 if (error.Fail())
2576 {
2577 if (GetID() != LLDB_INVALID_PROCESS_ID)
2578 {
2579 SetID (LLDB_INVALID_PROCESS_ID);
2580 const char *error_string = error.AsCString();
2581 if (error_string == NULL)
2582 error_string = "launch failed";
2583 SetExitStatus (-1, error_string);
2584 }
2585 }
2586 else
2587 {
2588 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002589 TimeValue timeout_time;
2590 timeout_time = TimeValue::Now();
2591 timeout_time.OffsetWithSeconds(10);
2592 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002593
Greg Clayton1a38ea72011-06-22 01:42:17 +00002594 if (state == eStateInvalid || event_sp.get() == NULL)
2595 {
2596 // We were able to launch the process, but we failed to
2597 // catch the initial stop.
2598 SetExitStatus (0, "failed to catch stop after launch");
2599 Destroy();
2600 }
2601 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002602 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002603
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002604 DidLaunch ();
2605
Greg Claytonc859e2d2012-02-13 23:10:39 +00002606 DynamicLoader *dyld = GetDynamicLoader ();
2607 if (dyld)
2608 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002609
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002610 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002611 // This delays passing the stopped event to listeners till DidLaunch gets
2612 // a chance to complete...
2613 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002614
2615 if (PrivateStateThreadIsValid ())
2616 ResumePrivateStateThread ();
2617 else
2618 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002619 }
2620 else if (state == eStateExited)
2621 {
2622 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2623 // not likely to work, and return an invalid pid.
2624 HandlePrivateEvent (event_sp);
2625 }
2626 }
2627 }
2628 }
2629 else
2630 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002631 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002632 }
2633 }
2634 return error;
2635}
2636
Greg Claytonc3776bf2012-02-09 06:16:32 +00002637
2638Error
2639Process::LoadCore ()
2640{
2641 Error error = DoLoadCore();
2642 if (error.Success())
2643 {
2644 if (PrivateStateThreadIsValid ())
2645 ResumePrivateStateThread ();
2646 else
2647 StartPrivateStateThread ();
2648
Greg Claytonc859e2d2012-02-13 23:10:39 +00002649 DynamicLoader *dyld = GetDynamicLoader ();
2650 if (dyld)
2651 dyld->DidAttach();
2652
2653 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002654 // We successfully loaded a core file, now pretend we stopped so we can
2655 // show all of the threads in the core file and explore the crashed
2656 // state.
2657 SetPrivateState (eStateStopped);
2658
2659 }
2660 return error;
2661}
2662
Greg Claytonc859e2d2012-02-13 23:10:39 +00002663DynamicLoader *
2664Process::GetDynamicLoader ()
2665{
2666 if (m_dyld_ap.get() == NULL)
2667 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2668 return m_dyld_ap.get();
2669}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002670
2671
Jim Inghambb3a2832011-01-29 01:49:25 +00002672Process::NextEventAction::EventActionResult
2673Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002674{
Jim Inghambb3a2832011-01-29 01:49:25 +00002675 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2676 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002677 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002678 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002679 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002680 return eEventActionRetry;
2681
2682 case eStateStopped:
2683 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002684 {
2685 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002686 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002687 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2688 if (m_exec_count > 0)
2689 {
2690 --m_exec_count;
Jim Ingham3b8285d2012-04-19 01:40:33 +00002691 m_process->PrivateResume ();
Jim Ingham04e0a222012-05-23 15:46:31 +00002692 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Claytonc9ed4782011-11-12 02:10:56 +00002693 return eEventActionRetry;
2694 }
2695 else
2696 {
2697 m_process->CompleteAttach ();
2698 return eEventActionSuccess;
2699 }
2700 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002701 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002702
Greg Clayton513c26c2011-01-29 07:10:55 +00002703 default:
2704 case eStateExited:
2705 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002706 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002707 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002708
2709 m_exit_string.assign ("No valid Process");
2710 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002711}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712
Jim Inghambb3a2832011-01-29 01:49:25 +00002713Process::NextEventAction::EventActionResult
2714Process::AttachCompletionHandler::HandleBeingInterrupted()
2715{
2716 return eEventActionSuccess;
2717}
2718
2719const char *
2720Process::AttachCompletionHandler::GetExitString ()
2721{
2722 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002723}
2724
2725Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002726Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002727{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002728 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002729 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002730 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002731 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002732
Greg Clayton144f3a92011-11-15 03:53:30 +00002733 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002734 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002735 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002736 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002737 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002738
Greg Clayton144f3a92011-11-15 03:53:30 +00002739 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002740 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002741 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2742
2743 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002744 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002745 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2746 if (error.Success())
2747 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002748 m_should_detach = true;
2749
Greg Clayton144f3a92011-11-15 03:53:30 +00002750 SetPublicState (eStateAttaching);
Han Ming Ong84647042012-02-25 01:07:38 +00002751 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002752 if (error.Fail())
2753 {
2754 if (GetID() != LLDB_INVALID_PROCESS_ID)
2755 {
2756 SetID (LLDB_INVALID_PROCESS_ID);
2757 if (error.AsCString() == NULL)
2758 error.SetErrorString("attach failed");
2759
2760 SetExitStatus(-1, error.AsCString());
2761 }
2762 }
2763 else
2764 {
2765 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2766 StartPrivateStateThread();
2767 }
2768 return error;
2769 }
Greg Claytone996fd32011-03-08 22:40:15 +00002770 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002771 else
Greg Claytone996fd32011-03-08 22:40:15 +00002772 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002773 ProcessInstanceInfoList process_infos;
2774 PlatformSP platform_sp (m_target.GetPlatform ());
2775
2776 if (platform_sp)
2777 {
2778 ProcessInstanceInfoMatch match_info;
2779 match_info.GetProcessInfo() = attach_info;
2780 match_info.SetNameMatchType (eNameMatchEquals);
2781 platform_sp->FindProcesses (match_info, process_infos);
2782 const uint32_t num_matches = process_infos.GetSize();
2783 if (num_matches == 1)
2784 {
2785 attach_pid = process_infos.GetProcessIDAtIndex(0);
2786 // Fall through and attach using the above process ID
2787 }
2788 else
2789 {
2790 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2791 if (num_matches > 1)
2792 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2793 else
2794 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2795 }
2796 }
2797 else
2798 {
2799 error.SetErrorString ("invalid platform, can't find processes by name");
2800 return error;
2801 }
Greg Claytone996fd32011-03-08 22:40:15 +00002802 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002803 }
2804 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002805 {
2806 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002807 }
2808 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002809
2810 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002811 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002812 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002813 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002814 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002815 m_should_detach = true;
Greg Claytone996fd32011-03-08 22:40:15 +00002816 SetPublicState (eStateAttaching);
Greg Clayton144f3a92011-11-15 03:53:30 +00002817
Han Ming Ong84647042012-02-25 01:07:38 +00002818 error = DoAttachToProcessWithID (attach_pid, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002819 if (error.Success())
2820 {
2821
2822 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2823 StartPrivateStateThread();
2824 }
2825 else
Greg Claytone996fd32011-03-08 22:40:15 +00002826 {
2827 if (GetID() != LLDB_INVALID_PROCESS_ID)
2828 {
2829 SetID (LLDB_INVALID_PROCESS_ID);
2830 const char *error_string = error.AsCString();
2831 if (error_string == NULL)
2832 error_string = "attach failed";
2833
2834 SetExitStatus(-1, error_string);
2835 }
2836 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002837 }
2838 }
2839 return error;
2840}
2841
Greg Clayton93d3c8332011-02-16 04:46:07 +00002842void
2843Process::CompleteAttach ()
2844{
2845 // Let the process subclass figure out at much as it can about the process
2846 // before we go looking for a dynamic loader plug-in.
2847 DidAttach();
2848
Jim Ingham4299fdb2011-09-15 01:10:17 +00002849 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2850 // the same as the one we've already set, switch architectures.
2851 PlatformSP platform_sp (m_target.GetPlatform ());
2852 assert (platform_sp.get());
2853 if (platform_sp)
2854 {
Greg Clayton70512312012-05-08 01:45:38 +00002855 const ArchSpec &target_arch = m_target.GetArchitecture();
2856 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2857 {
2858 ArchSpec platform_arch;
2859 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2860 if (platform_sp)
2861 {
2862 m_target.SetPlatform (platform_sp);
2863 m_target.SetArchitecture(platform_arch);
2864 }
2865 }
2866 else
2867 {
2868 ProcessInstanceInfo process_info;
2869 platform_sp->GetProcessInfo (GetID(), process_info);
2870 const ArchSpec &process_arch = process_info.GetArchitecture();
2871 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2872 m_target.SetArchitecture (process_arch);
2873 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00002874 }
2875
2876 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002877 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002878 DynamicLoader *dyld = GetDynamicLoader ();
2879 if (dyld)
2880 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002881
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002882 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002883 // Figure out which one is the executable, and set that in our target:
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002884 ModuleList &target_modules = m_target.GetImages();
2885 Mutex::Locker modules_locker(target_modules.GetMutex());
2886 size_t num_modules = target_modules.GetSize();
2887 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002888
Greg Clayton93d3c8332011-02-16 04:46:07 +00002889 for (int i = 0; i < num_modules; i++)
2890 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002891 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002892 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002893 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002894 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002895 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002896 break;
2897 }
2898 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002899 if (new_executable_module_sp)
2900 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00002901}
2902
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903Error
Greg Claytonb766a732011-02-04 01:58:07 +00002904Process::ConnectRemote (const char *remote_url)
2905{
Greg Claytonb766a732011-02-04 01:58:07 +00002906 m_abi_sp.reset();
2907 m_process_input_reader.reset();
2908
2909 // Find the process and its architecture. Make sure it matches the architecture
2910 // of the current Target, and if not adjust it.
2911
2912 Error error (DoConnectRemote (remote_url));
2913 if (error.Success())
2914 {
Greg Clayton71337622011-02-24 22:24:29 +00002915 if (GetID() != LLDB_INVALID_PROCESS_ID)
2916 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002917 EventSP event_sp;
2918 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2919
2920 if (state == eStateStopped || state == eStateCrashed)
2921 {
2922 // If we attached and actually have a process on the other end, then
2923 // this ended up being the equivalent of an attach.
2924 CompleteAttach ();
2925
2926 // This delays passing the stopped event to listeners till
2927 // CompleteAttach gets a chance to complete...
2928 HandlePrivateEvent (event_sp);
2929
2930 }
Greg Clayton71337622011-02-24 22:24:29 +00002931 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002932
2933 if (PrivateStateThreadIsValid ())
2934 ResumePrivateStateThread ();
2935 else
2936 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002937 }
2938 return error;
2939}
2940
2941
2942Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00002943Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002944{
Jim Ingham46ef1802012-09-06 19:24:17 +00002945 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_STEP));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002947 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002948 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002949 StateAsCString(m_public_state.GetValue()),
2950 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002951
2952 Error error (WillResume());
2953 // Tell the process it is about to resume before the thread list
2954 if (error.Success())
2955 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002956 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002957 // can let all of our threads know that they are about to be
2958 // resumed. Threads will each be called with
2959 // Thread::WillResume(StateType) where StateType contains the state
2960 // that they are supposed to have when the process is resumed
2961 // (suspended/running/stepping). Threads should also check
2962 // their resume signal in lldb::Thread::GetResumeSignal()
2963 // to see if they are suppoed to start back up with a signal.
2964 if (m_thread_list.WillResume())
2965 {
Jim Ingham372787f2012-04-07 00:00:41 +00002966 // Last thing, do the PreResumeActions.
2967 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002968 {
Jim Ingham372787f2012-04-07 00:00:41 +00002969 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
2970 }
2971 else
2972 {
2973 m_mod_id.BumpResumeID();
2974 error = DoResume();
2975 if (error.Success())
2976 {
2977 DidResume();
2978 m_thread_list.DidResume();
2979 if (log)
2980 log->Printf ("Process thinks the process has resumed.");
2981 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002982 }
2983 }
2984 else
2985 {
Jim Ingham513c6bb2012-09-01 01:02:41 +00002986 // Somebody wanted to run without running. So generate a continue & a stopped event,
2987 // and let the world handle them.
2988 if (log)
2989 log->Printf ("Process::PrivateResume() asked to simulate a start & stop.");
2990
2991 SetPrivateState(eStateRunning);
2992 SetPrivateState(eStateStopped);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002993 }
2994 }
Jim Ingham444586b2011-01-24 06:34:17 +00002995 else if (log)
2996 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997 return error;
2998}
2999
3000Error
3001Process::Halt ()
3002{
Jim Inghamaacc3182012-06-06 00:29:30 +00003003 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
3004 // we could just straightaway get another event. It just narrows the window...
3005 m_currently_handling_event.WaitForValueEqualTo(false);
3006
3007
Jim Inghambb3a2832011-01-29 01:49:25 +00003008 // Pause our private state thread so we can ensure no one else eats
3009 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00003010 Listener halt_listener ("lldb.process.halt_listener");
3011 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00003012
Jim Inghambb3a2832011-01-29 01:49:25 +00003013 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00003014 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00003015
Greg Clayton513c26c2011-01-29 07:10:55 +00003016 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003017 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003018
Greg Clayton513c26c2011-01-29 07:10:55 +00003019 bool caused_stop = false;
3020
3021 // Ask the process subclass to actually halt our process
3022 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003023 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003024 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003025 if (m_public_state.GetValue() == eStateAttaching)
3026 {
3027 SetExitStatus(SIGKILL, "Cancelled async attach.");
3028 Destroy ();
3029 }
3030 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003031 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003032 // If "caused_stop" is true, then DoHalt stopped the process. If
3033 // "caused_stop" is false, the process was already stopped.
3034 // If the DoHalt caused the process to stop, then we want to catch
3035 // this event and set the interrupted bool to true before we pass
3036 // this along so clients know that the process was interrupted by
3037 // a halt command.
3038 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003039 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003040 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003041 TimeValue timeout_time;
3042 timeout_time = TimeValue::Now();
3043 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003044 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3045 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003046
Jim Ingham0f16e732011-02-08 05:20:59 +00003047 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003048 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003049 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003050 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003051 }
3052 else
3053 {
Greg Clayton2637f822011-11-17 01:23:07 +00003054 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003055 {
3056 // We caused the process to interrupt itself, so mark this
3057 // as such in the stop event so clients can tell an interrupted
3058 // process from a natural stop
3059 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3060 }
3061 else
3062 {
3063 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3064 if (log)
3065 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3066 error.SetErrorString ("Did not get stopped event after halt.");
3067 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003068 }
3069 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003070 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003071 }
3072 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003073 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003074 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003075 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003076
3077 // Post any event we might have consumed. If all goes well, we will have
3078 // stopped the process, intercepted the event and set the interrupted
3079 // bool in the event. Post it to the private event queue and that will end up
3080 // correctly setting the state.
3081 if (event_sp)
3082 m_private_state_broadcaster.BroadcastEvent(event_sp);
3083
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003084 return error;
3085}
3086
3087Error
3088Process::Detach ()
3089{
3090 Error error (WillDetach());
3091
3092 if (error.Success())
3093 {
3094 DisableAllBreakpointSites();
3095 error = DoDetach();
3096 if (error.Success())
3097 {
3098 DidDetach();
3099 StopPrivateStateThread();
3100 }
3101 }
3102 return error;
3103}
3104
3105Error
3106Process::Destroy ()
3107{
3108 Error error (WillDestroy());
3109 if (error.Success())
3110 {
Jim Ingham04e0a222012-05-23 15:46:31 +00003111 if (m_public_state.GetValue() == eStateRunning)
3112 {
Greg Claytona28d2032012-09-05 00:37:58 +00003113 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003114 if (log)
3115 log->Printf("Process::Destroy() About to halt.");
Jim Ingham04e0a222012-05-23 15:46:31 +00003116 error = Halt();
3117 if (error.Success())
3118 {
3119 // Consume the halt event.
3120 EventSP stop_event;
3121 TimeValue timeout (TimeValue::Now());
Jim Inghamaacc3182012-06-06 00:29:30 +00003122 timeout.OffsetWithSeconds(1);
Jim Ingham04e0a222012-05-23 15:46:31 +00003123 StateType state = WaitForProcessToStop (&timeout);
3124 if (state != eStateStopped)
3125 {
Greg Claytona28d2032012-09-05 00:37:58 +00003126 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham04e0a222012-05-23 15:46:31 +00003127 if (log)
3128 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Inghamaacc3182012-06-06 00:29:30 +00003129 // If we really couldn't stop the process then we should just error out here, but if the
3130 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3131 StateType private_state = m_private_state.GetValue();
3132 if (private_state != eStateStopped && private_state != eStateExited)
3133 {
3134 return error;
3135 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003136 }
3137 }
3138 else
3139 {
Greg Claytona28d2032012-09-05 00:37:58 +00003140 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham04e0a222012-05-23 15:46:31 +00003141 if (log)
3142 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
Jim Inghamaacc3182012-06-06 00:29:30 +00003143 return error;
Jim Ingham04e0a222012-05-23 15:46:31 +00003144 }
3145 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003146
3147 if (m_public_state.GetValue() != eStateRunning)
3148 {
3149 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3150 // kill it, we don't want it hitting a breakpoint...
3151 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3152 // we're not going to have much luck doing this now.
3153 m_thread_list.DiscardThreadPlans();
3154 DisableAllBreakpointSites();
3155 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003156
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003157 error = DoDestroy();
3158 if (error.Success())
3159 {
3160 DidDestroy();
3161 StopPrivateStateThread();
3162 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003163 m_stdio_communication.StopReadThread();
3164 m_stdio_communication.Disconnect();
3165 if (m_process_input_reader && m_process_input_reader->IsActive())
3166 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3167 if (m_process_input_reader)
3168 m_process_input_reader.reset();
Jim Inghamb1e2e842012-04-12 18:49:31 +00003169
3170 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3171 // the last events through the event system, in which case we might strand the write lock. Unlock
3172 // it here so when we do to tear down the process we don't get an error destroying the lock.
3173 m_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003174 }
3175 return error;
3176}
3177
3178Error
3179Process::Signal (int signal)
3180{
3181 Error error (WillSignal());
3182 if (error.Success())
3183 {
3184 error = DoSignal(signal);
3185 if (error.Success())
3186 DidSignal();
3187 }
3188 return error;
3189}
3190
Greg Clayton514487e2011-02-15 21:59:32 +00003191lldb::ByteOrder
3192Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003193{
Greg Clayton514487e2011-02-15 21:59:32 +00003194 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003195}
3196
3197uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003198Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003199{
Greg Clayton514487e2011-02-15 21:59:32 +00003200 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003201}
3202
Greg Clayton514487e2011-02-15 21:59:32 +00003203
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003204bool
3205Process::ShouldBroadcastEvent (Event *event_ptr)
3206{
3207 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3208 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003209 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003210
3211 switch (state)
3212 {
Greg Claytonb766a732011-02-04 01:58:07 +00003213 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003214 case eStateAttaching:
3215 case eStateLaunching:
3216 case eStateDetached:
3217 case eStateExited:
3218 case eStateUnloaded:
3219 // These events indicate changes in the state of the debugging session, always report them.
3220 return_value = true;
3221 break;
3222 case eStateInvalid:
3223 // We stopped for no apparent reason, don't report it.
3224 return_value = false;
3225 break;
3226 case eStateRunning:
3227 case eStateStepping:
3228 // If we've started the target running, we handle the cases where we
3229 // are already running and where there is a transition from stopped to
3230 // running differently.
3231 // running -> running: Automatically suppress extra running events
3232 // stopped -> running: Report except when there is one or more no votes
3233 // and no yes votes.
3234 SynchronouslyNotifyStateChanged (state);
3235 switch (m_public_state.GetValue())
3236 {
3237 case eStateRunning:
3238 case eStateStepping:
3239 // We always suppress multiple runnings with no PUBLIC stop in between.
3240 return_value = false;
3241 break;
3242 default:
3243 // TODO: make this work correctly. For now always report
3244 // run if we aren't running so we don't miss any runnning
3245 // events. If I run the lldb/test/thread/a.out file and
3246 // break at main.cpp:58, run and hit the breakpoints on
3247 // multiple threads, then somehow during the stepping over
3248 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003249
3250 // This is a transition from stop to run.
3251 switch (m_thread_list.ShouldReportRun (event_ptr))
3252 {
Greg Clayton23f59502012-07-17 03:23:13 +00003253 default:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003254 case eVoteYes:
3255 case eVoteNoOpinion:
3256 return_value = true;
3257 break;
3258 case eVoteNo:
3259 return_value = false;
3260 break;
3261 }
3262 break;
3263 }
3264 break;
3265 case eStateStopped:
3266 case eStateCrashed:
3267 case eStateSuspended:
3268 {
3269 // We've stopped. First see if we're going to restart the target.
3270 // If we are going to stop, then we always broadcast the event.
3271 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00003272 // If no thread has an opinion, we don't report it.
Jim Inghamcb4ca112012-05-16 01:32:14 +00003273
3274 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003275 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003276 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003277 if (log)
3278 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003279 return true;
3280 }
3281 else
3282 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003283
3284 if (m_thread_list.ShouldStop (event_ptr) == false)
3285 {
Jim Inghamcb95f342012-09-05 21:13:56 +00003286 // ShouldStop may have restarted the target already. If so, don't
3287 // resume it twice.
3288 bool was_restarted = ProcessEventData::GetRestartedFromEvent (event_ptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003289 switch (m_thread_list.ShouldReportStop (event_ptr))
3290 {
3291 case eVoteYes:
3292 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003293 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003294 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003295 case eVoteNo:
3296 return_value = false;
3297 break;
3298 }
3299
3300 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003301 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Inghamcb95f342012-09-05 21:13:56 +00003302 if (!was_restarted)
3303 PrivateResume ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003304 }
3305 else
3306 {
3307 return_value = true;
3308 SynchronouslyNotifyStateChanged (state);
3309 }
3310 }
3311 }
3312 }
3313
3314 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003315 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003316 return return_value;
3317}
3318
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003319
3320bool
Jim Ingham372787f2012-04-07 00:00:41 +00003321Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003322{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003323 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003324
Greg Clayton8b82f082011-04-12 05:54:46 +00003325 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003326 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003327 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3328
Jim Ingham372787f2012-04-07 00:00:41 +00003329 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003330 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003331
3332 // Create a thread that watches our internal state and controls which
3333 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003334 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003335 if (already_running)
3336 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3337 else
3338 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003339
3340 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003341 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003342 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3343 if (success)
3344 {
3345 ResumePrivateStateThread();
3346 return true;
3347 }
3348 else
3349 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003350}
3351
3352void
3353Process::PausePrivateStateThread ()
3354{
3355 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3356}
3357
3358void
3359Process::ResumePrivateStateThread ()
3360{
3361 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3362}
3363
3364void
3365Process::StopPrivateStateThread ()
3366{
Greg Clayton8b82f082011-04-12 05:54:46 +00003367 if (PrivateStateThreadIsValid ())
3368 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003369 else
3370 {
3371 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3372 if (log)
3373 printf ("Went to stop the private state thread, but it was already invalid.");
3374 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003375}
3376
3377void
3378Process::ControlPrivateStateThread (uint32_t signal)
3379{
Jim Inghamb1e2e842012-04-12 18:49:31 +00003380 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003381
3382 assert (signal == eBroadcastInternalStateControlStop ||
3383 signal == eBroadcastInternalStateControlPause ||
3384 signal == eBroadcastInternalStateControlResume);
3385
3386 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003387 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003388
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003389 // Signal the private state thread. First we should copy this is case the
3390 // thread starts exiting since the private state thread will NULL this out
3391 // when it exits
3392 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003393 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003394 {
3395 TimeValue timeout_time;
3396 bool timed_out;
3397
3398 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3399
3400 timeout_time = TimeValue::Now();
3401 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003402 if (log)
3403 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003404 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3405 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3406
3407 if (signal == eBroadcastInternalStateControlStop)
3408 {
3409 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003410 {
3411 Error error;
3412 Host::ThreadCancel (private_state_thread, &error);
3413 if (log)
3414 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3415 }
3416 else
3417 {
3418 if (log)
3419 log->Printf ("The control event killed the private state thread without having to cancel.");
3420 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003421
3422 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003423 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003424 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003425 }
3426 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003427 else
3428 {
3429 if (log)
3430 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3431 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003432}
3433
3434void
Jim Inghamcfc09352012-07-27 23:57:19 +00003435Process::SendAsyncInterrupt ()
3436{
3437 if (PrivateStateThreadIsValid())
3438 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3439 else
3440 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3441}
3442
3443void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003444Process::HandlePrivateEvent (EventSP &event_sp)
3445{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003446 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003447 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003448
Greg Clayton414f5d32011-01-25 02:58:48 +00003449 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003450
3451 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003452 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003453 {
Jim Ingham754ab982011-01-29 04:05:41 +00003454 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003455 switch (action_result)
3456 {
3457 case NextEventAction::eEventActionSuccess:
3458 SetNextEventAction(NULL);
3459 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003460
Jim Inghambb3a2832011-01-29 01:49:25 +00003461 case NextEventAction::eEventActionRetry:
3462 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003463
Jim Inghambb3a2832011-01-29 01:49:25 +00003464 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003465 // Handle Exiting Here. If we already got an exited event,
3466 // we should just propagate it. Otherwise, swallow this event,
3467 // and set our state to exit so the next event will kill us.
3468 if (new_state != eStateExited)
3469 {
3470 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003471 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003472 SetNextEventAction(NULL);
3473 return;
3474 }
3475 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003476 break;
3477 }
3478 }
3479
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003480 // See if we should broadcast this state to external clients?
3481 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003482
3483 if (should_broadcast)
3484 {
3485 if (log)
3486 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003487 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003488 __FUNCTION__,
3489 GetID(),
3490 StateAsCString(new_state),
3491 StateAsCString (GetState ()),
3492 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003493 }
Jim Ingham9575d842011-03-11 03:53:59 +00003494 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003495 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003496 PushProcessInputReader ();
3497 else
3498 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003499
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003500 BroadcastEvent (event_sp);
3501 }
3502 else
3503 {
3504 if (log)
3505 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003506 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003507 __FUNCTION__,
3508 GetID(),
3509 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003510 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003511 }
3512 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003513 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003514}
3515
3516void *
3517Process::PrivateStateThread (void *arg)
3518{
3519 Process *proc = static_cast<Process*> (arg);
3520 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003521 return result;
3522}
3523
3524void *
3525Process::RunPrivateStateThread ()
3526{
Jim Ingham076b3042012-04-10 01:21:57 +00003527 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003528 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003529
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003530 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003531 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003532 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003533
3534 bool exit_now = false;
3535 while (!exit_now)
3536 {
3537 EventSP event_sp;
3538 WaitForEventsPrivate (NULL, event_sp, control_only);
3539 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3540 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003541 if (log)
3542 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3543
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003544 switch (event_sp->GetType())
3545 {
3546 case eBroadcastInternalStateControlStop:
3547 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003548 break; // doing any internal state managment below
3549
3550 case eBroadcastInternalStateControlPause:
3551 control_only = true;
3552 break;
3553
3554 case eBroadcastInternalStateControlResume:
3555 control_only = false;
3556 break;
3557 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003558
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003559 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003560 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003561 }
Jim Inghamcfc09352012-07-27 23:57:19 +00003562 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3563 {
3564 if (m_public_state.GetValue() == eStateAttaching)
3565 {
3566 if (log)
3567 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3568 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3569 }
3570 else
3571 {
3572 if (log)
3573 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3574 Halt();
3575 }
3576 continue;
3577 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003578
3579 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3580
3581 if (internal_state != eStateInvalid)
3582 {
3583 HandlePrivateEvent (event_sp);
3584 }
3585
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003586 if (internal_state == eStateInvalid ||
3587 internal_state == eStateExited ||
3588 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003589 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003590 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003591 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003592
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003593 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003594 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003595 }
3596
Caroline Tice20ad3c42010-10-29 21:48:37 +00003597 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003598 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003599 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003600
Greg Clayton6ed95942011-01-22 07:12:45 +00003601 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3602 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003603 return NULL;
3604}
3605
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003606//------------------------------------------------------------------
3607// Process Event Data
3608//------------------------------------------------------------------
3609
3610Process::ProcessEventData::ProcessEventData () :
3611 EventData (),
3612 m_process_sp (),
3613 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003614 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003615 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003616 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003617{
3618}
3619
3620Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3621 EventData (),
3622 m_process_sp (process_sp),
3623 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003624 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003625 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003626 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003627{
3628}
3629
3630Process::ProcessEventData::~ProcessEventData()
3631{
3632}
3633
3634const ConstString &
3635Process::ProcessEventData::GetFlavorString ()
3636{
3637 static ConstString g_flavor ("Process::ProcessEventData");
3638 return g_flavor;
3639}
3640
3641const ConstString &
3642Process::ProcessEventData::GetFlavor () const
3643{
3644 return ProcessEventData::GetFlavorString ();
3645}
3646
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003647void
3648Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3649{
3650 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003651 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3652 // the public event queue, then other times when we're pretending that this is where we stopped at the
3653 // end of expression evaluation. m_update_state is used to distinguish these
3654 // three cases; it is 0 when we're just pulling it off for private handling,
3655 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003656
Jim Inghama8604692011-05-22 21:45:01 +00003657 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003658 return;
3659
3660 m_process_sp->SetPublicState (m_state);
3661
3662 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3663 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003664 {
3665 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003666 uint32_t num_threads = curr_thread_list.GetSize();
3667 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003668
Jim Ingham4b536182011-08-09 02:12:22 +00003669 // The actions might change one of the thread's stop_info's opinions about whether we should
3670 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003671
3672 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3673 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3674 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3675 // 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
3676 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003677 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003678 for (idx = 0; idx < num_threads; ++idx)
3679 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3680
Jim Ingham4b536182011-08-09 02:12:22 +00003681 bool still_should_stop = true;
3682
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003683 for (idx = 0; idx < num_threads; ++idx)
3684 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003685 curr_thread_list = m_process_sp->GetThreadList();
3686 if (curr_thread_list.GetSize() != num_threads)
3687 {
3688 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003689 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003690 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003691 break;
3692 }
3693
3694 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3695
3696 if (thread_sp->GetIndexID() != thread_index_array[idx])
3697 {
3698 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003699 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003700 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003701 idx,
3702 thread_index_array[idx],
3703 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003704 break;
3705 }
3706
Jim Inghamb15bfc72010-10-20 00:39:53 +00003707 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3708 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003709 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003710 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003711 // The stop action might restart the target. If it does, then we want to mark that in the
3712 // event so that whoever is receiving it will know to wait for the running event and reflect
3713 // that state appropriately.
3714 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003715
3716 // FIXME: we might have run.
3717 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003718 {
3719 SetRestarted (true);
3720 break;
3721 }
3722 else if (!stop_info_sp->ShouldStop(event_ptr))
3723 {
3724 still_should_stop = false;
3725 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003726 }
3727 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003728
Jim Ingham4b536182011-08-09 02:12:22 +00003729
3730 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003731 {
Jim Ingham4b536182011-08-09 02:12:22 +00003732 if (!still_should_stop)
3733 {
3734 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003735 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00003736 // Use the public resume method here, since this is just
3737 // extending a public resume.
Jim Ingham4b536182011-08-09 02:12:22 +00003738 m_process_sp->Resume();
3739 }
3740 else
3741 {
3742 // If we didn't restart, run the Stop Hooks here:
3743 // They might also restart the target, so watch for that.
3744 m_process_sp->GetTarget().RunStopHooks();
3745 if (m_process_sp->GetPrivateState() == eStateRunning)
3746 SetRestarted(true);
3747 }
Jim Ingham9575d842011-03-11 03:53:59 +00003748 }
3749
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003750 }
3751}
3752
3753void
3754Process::ProcessEventData::Dump (Stream *s) const
3755{
3756 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003757 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003758
Greg Clayton8b82f082011-04-12 05:54:46 +00003759 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003760}
3761
3762const Process::ProcessEventData *
3763Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3764{
3765 if (event_ptr)
3766 {
3767 const EventData *event_data = event_ptr->GetData();
3768 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3769 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3770 }
3771 return NULL;
3772}
3773
3774ProcessSP
3775Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3776{
3777 ProcessSP process_sp;
3778 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3779 if (data)
3780 process_sp = data->GetProcessSP();
3781 return process_sp;
3782}
3783
3784StateType
3785Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3786{
3787 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3788 if (data == NULL)
3789 return eStateInvalid;
3790 else
3791 return data->GetState();
3792}
3793
3794bool
3795Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3796{
3797 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3798 if (data == NULL)
3799 return false;
3800 else
3801 return data->GetRestarted();
3802}
3803
3804void
3805Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3806{
3807 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3808 if (data != NULL)
3809 data->SetRestarted(new_value);
3810}
3811
3812bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003813Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3814{
3815 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3816 if (data == NULL)
3817 return false;
3818 else
3819 return data->GetInterrupted ();
3820}
3821
3822void
3823Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3824{
3825 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3826 if (data != NULL)
3827 data->SetInterrupted(new_value);
3828}
3829
3830bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003831Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3832{
3833 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3834 if (data)
3835 {
3836 data->SetUpdateStateOnRemoval();
3837 return true;
3838 }
3839 return false;
3840}
3841
Greg Claytond9e416c2012-02-18 05:35:26 +00003842lldb::TargetSP
3843Process::CalculateTarget ()
3844{
3845 return m_target.shared_from_this();
3846}
3847
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003848void
Greg Clayton0603aa92010-10-04 01:05:56 +00003849Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003850{
Greg Claytonc14ee322011-09-22 04:58:26 +00003851 exe_ctx.SetTargetPtr (&m_target);
3852 exe_ctx.SetProcessPtr (this);
3853 exe_ctx.SetThreadPtr(NULL);
3854 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003855}
3856
Greg Claytone996fd32011-03-08 22:40:15 +00003857//uint32_t
3858//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3859//{
3860// return 0;
3861//}
3862//
3863//ArchSpec
3864//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3865//{
3866// return Host::GetArchSpecForExistingProcess (pid);
3867//}
3868//
3869//ArchSpec
3870//Process::GetArchSpecForExistingProcess (const char *process_name)
3871//{
3872// return Host::GetArchSpecForExistingProcess (process_name);
3873//}
3874//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003875void
3876Process::AppendSTDOUT (const char * s, size_t len)
3877{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003878 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003879 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003880 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003881}
3882
3883void
Greg Clayton93e86192011-11-13 04:45:22 +00003884Process::AppendSTDERR (const char * s, size_t len)
3885{
3886 Mutex::Locker locker (m_stdio_communication_mutex);
3887 m_stderr_data.append (s, len);
3888 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3889}
3890
3891//------------------------------------------------------------------
3892// Process STDIO
3893//------------------------------------------------------------------
3894
3895size_t
3896Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3897{
3898 Mutex::Locker locker(m_stdio_communication_mutex);
3899 size_t bytes_available = m_stdout_data.size();
3900 if (bytes_available > 0)
3901 {
3902 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3903 if (log)
3904 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3905 if (bytes_available > buf_size)
3906 {
3907 memcpy(buf, m_stdout_data.c_str(), buf_size);
3908 m_stdout_data.erase(0, buf_size);
3909 bytes_available = buf_size;
3910 }
3911 else
3912 {
3913 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3914 m_stdout_data.clear();
3915 }
3916 }
3917 return bytes_available;
3918}
3919
3920
3921size_t
3922Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3923{
3924 Mutex::Locker locker(m_stdio_communication_mutex);
3925 size_t bytes_available = m_stderr_data.size();
3926 if (bytes_available > 0)
3927 {
3928 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3929 if (log)
3930 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3931 if (bytes_available > buf_size)
3932 {
3933 memcpy(buf, m_stderr_data.c_str(), buf_size);
3934 m_stderr_data.erase(0, buf_size);
3935 bytes_available = buf_size;
3936 }
3937 else
3938 {
3939 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3940 m_stderr_data.clear();
3941 }
3942 }
3943 return bytes_available;
3944}
3945
3946void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003947Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3948{
3949 Process *process = (Process *) baton;
3950 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3951}
3952
3953size_t
3954Process::ProcessInputReaderCallback (void *baton,
3955 InputReader &reader,
3956 lldb::InputReaderAction notification,
3957 const char *bytes,
3958 size_t bytes_len)
3959{
3960 Process *process = (Process *) baton;
3961
3962 switch (notification)
3963 {
3964 case eInputReaderActivate:
3965 break;
3966
3967 case eInputReaderDeactivate:
3968 break;
3969
3970 case eInputReaderReactivate:
3971 break;
3972
Caroline Tice969ed3d2011-05-02 20:41:46 +00003973 case eInputReaderAsynchronousOutputWritten:
3974 break;
3975
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003976 case eInputReaderGotToken:
3977 {
3978 Error error;
3979 process->PutSTDIN (bytes, bytes_len, error);
3980 }
3981 break;
3982
Caroline Ticeefed6132010-11-19 20:47:54 +00003983 case eInputReaderInterrupt:
3984 process->Halt ();
3985 break;
3986
3987 case eInputReaderEndOfFile:
3988 process->AppendSTDOUT ("^D", 2);
3989 break;
3990
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003991 case eInputReaderDone:
3992 break;
3993
3994 }
3995
3996 return bytes_len;
3997}
3998
3999void
4000Process::ResetProcessInputReader ()
4001{
4002 m_process_input_reader.reset();
4003}
4004
4005void
Greg Claytonee95ed52011-11-17 22:14:31 +00004006Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00004007{
4008 // First set up the Read Thread for reading/handling process I/O
4009
4010 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
4011
4012 if (conn_ap.get())
4013 {
4014 m_stdio_communication.SetConnection (conn_ap.release());
4015 if (m_stdio_communication.IsConnected())
4016 {
4017 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
4018 m_stdio_communication.StartReadThread();
4019
4020 // Now read thread is set up, set up input reader.
4021
4022 if (!m_process_input_reader.get())
4023 {
4024 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4025 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4026 this,
4027 eInputReaderGranularityByte,
4028 NULL,
4029 NULL,
4030 false));
4031
4032 if (err.Fail())
4033 m_process_input_reader.reset();
4034 }
4035 }
4036 }
4037}
4038
4039void
4040Process::PushProcessInputReader ()
4041{
4042 if (m_process_input_reader && !m_process_input_reader->IsActive())
4043 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4044}
4045
4046void
4047Process::PopProcessInputReader ()
4048{
4049 if (m_process_input_reader && m_process_input_reader->IsActive())
4050 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4051}
4052
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004053// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004054void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004055Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004056{
Greg Clayton67cc0632012-08-22 17:17:09 +00004057// static std::vector<OptionEnumValueElement> g_plugins;
4058//
4059// int i=0;
4060// const char *name;
4061// OptionEnumValueElement option_enum;
4062// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4063// {
4064// if (name)
4065// {
4066// option_enum.value = i;
4067// option_enum.string_value = name;
4068// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4069// g_plugins.push_back (option_enum);
4070// }
4071// ++i;
4072// }
4073// option_enum.value = 0;
4074// option_enum.string_value = NULL;
4075// option_enum.usage = NULL;
4076// g_plugins.push_back (option_enum);
4077//
4078// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4079// {
4080// if (::strcmp (name, "plugin") == 0)
4081// {
4082// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4083// break;
4084// }
4085// }
Greg Clayton67cc0632012-08-22 17:17:09 +00004086//
Greg Clayton6920b522012-08-22 18:39:03 +00004087 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004088}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004089
Greg Clayton99d0faf2010-11-18 23:32:35 +00004090void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004091Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004092{
Greg Clayton6920b522012-08-22 18:39:03 +00004093 Thread::SettingsTerminate ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004094}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004095
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004096ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004097Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004098 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00004099 bool stop_others,
4100 bool try_all_threads,
4101 bool discard_on_error,
4102 uint32_t single_thread_timeout_usec,
4103 Stream &errors)
4104{
4105 ExecutionResults return_value = eExecutionSetupError;
4106
Jim Ingham77787032011-01-20 02:03:18 +00004107 if (thread_plan_sp.get() == NULL)
4108 {
4109 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004110 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004111 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004112
4113 if (exe_ctx.GetProcessPtr() != this)
4114 {
4115 errors.Printf("RunThreadPlan called on wrong process.");
4116 return eExecutionSetupError;
4117 }
4118
4119 Thread *thread = exe_ctx.GetThreadPtr();
4120 if (thread == NULL)
4121 {
4122 errors.Printf("RunThreadPlan called with invalid thread.");
4123 return eExecutionSetupError;
4124 }
Jim Ingham77787032011-01-20 02:03:18 +00004125
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004126 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4127 // For that to be true the plan can't be private - since private plans suppress themselves in the
4128 // GetCompletedPlan call.
4129
4130 bool orig_plan_private = thread_plan_sp->GetPrivate();
4131 thread_plan_sp->SetPrivate(false);
4132
Jim Ingham444586b2011-01-24 06:34:17 +00004133 if (m_private_state.GetValue() != eStateStopped)
4134 {
4135 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004136 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004137 }
4138
Jim Ingham66243842011-08-13 00:56:10 +00004139 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004140 const uint32_t thread_idx_id = thread->GetIndexID();
4141 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004142
4143 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4144 // so we should arrange to reset them as well.
4145
Greg Claytonc14ee322011-09-22 04:58:26 +00004146 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004147
Jim Ingham66243842011-08-13 00:56:10 +00004148 uint32_t selected_tid;
4149 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004150 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004151 {
4152 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004153 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004154 }
4155 else
4156 {
4157 selected_tid = LLDB_INVALID_THREAD_ID;
4158 }
4159
Jim Ingham372787f2012-04-07 00:00:41 +00004160 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004161 lldb::StateType old_state;
4162 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004163
Jim Ingham076b3042012-04-10 01:21:57 +00004164 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004165 if (Host::GetCurrentThread() == m_private_state_thread)
4166 {
Jim Ingham076b3042012-04-10 01:21:57 +00004167 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4168 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004169 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Ingham076b3042012-04-10 01:21:57 +00004170 // we are fielding public events here.
4171 if (log)
4172 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4173
4174
Jim Ingham372787f2012-04-07 00:00:41 +00004175 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004176
4177 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4178 // returning control here.
4179 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4180 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4181 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4182 // do just what we want.
4183 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4184 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4185 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4186 old_state = m_public_state.GetValue();
4187 m_public_state.SetValueNoLock(eStateStopped);
4188
4189 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004190 StartPrivateStateThread(true);
4191 }
4192
4193 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004194
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004195 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004196
Sean Callanana46ec452012-07-11 21:31:24 +00004197 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004198
Jim Ingham77787032011-01-20 02:03:18 +00004199 {
Sean Callanana46ec452012-07-11 21:31:24 +00004200 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4201 // restored on exit to the function.
4202 //
4203 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4204 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004205
Sean Callanana46ec452012-07-11 21:31:24 +00004206 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004207
Jim Inghamf48169b2010-11-30 02:22:11 +00004208 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004209 {
4210 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004211 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4212 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4213 thread->GetIndexID(),
4214 thread->GetID(),
4215 s.GetData());
4216 }
4217
4218 bool got_event;
4219 lldb::EventSP event_sp;
4220 lldb::StateType stop_state = lldb::eStateInvalid;
4221
4222 TimeValue* timeout_ptr = NULL;
4223 TimeValue real_timeout;
4224
4225 bool first_timeout = true;
4226 bool do_resume = true;
4227
4228 while (1)
4229 {
4230 // We usually want to resume the process if we get to the top of the loop.
4231 // The only exception is if we get two running events with no intervening
4232 // stop, which can happen, we will just wait for then next stop event.
4233
4234 if (do_resume)
4235 {
4236 // Do the initial resume and wait for the running event before going further.
4237
4238 Error resume_error = PrivateResume ();
4239 if (!resume_error.Success())
4240 {
4241 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4242 return_value = eExecutionSetupError;
4243 break;
4244 }
4245
4246 real_timeout = TimeValue::Now();
4247 real_timeout.OffsetWithMicroSeconds(500000);
4248 timeout_ptr = &real_timeout;
4249
4250 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4251 if (!got_event)
4252 {
4253 if (log)
4254 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4255
4256 errors.Printf("Didn't get any event after initial resume, exiting.");
4257 return_value = eExecutionSetupError;
4258 break;
4259 }
4260
4261 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4262 if (stop_state != eStateRunning)
4263 {
4264 if (log)
4265 log->Printf("Process::RunThreadPlan(): didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
4266
4267 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
4268 return_value = eExecutionSetupError;
4269 break;
4270 }
4271
4272 if (log)
4273 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4274 // We need to call the function synchronously, so spin waiting for it to return.
4275 // If we get interrupted while executing, we're going to lose our context, and
4276 // won't be able to gather the result at this point.
4277 // We set the timeout AFTER the resume, since the resume takes some time and we
4278 // don't want to charge that to the timeout.
4279
4280 if (single_thread_timeout_usec != 0)
4281 {
Enrico Granata3372f582012-07-16 23:10:35 +00004282 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanana46ec452012-07-11 21:31:24 +00004283 real_timeout = TimeValue::Now();
4284 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
4285
4286 timeout_ptr = &real_timeout;
4287 }
Enrico Granata3372f582012-07-16 23:10:35 +00004288 else if (first_timeout)
4289 {
4290 // if we are willing to wait "forever" we still need to have an initial timeout
4291 // this timeout is going to induce all threads to run when hit. we do this so that
4292 // we can avoid ending locked up because of multithreaded contention issues
4293 real_timeout = TimeValue::Now();
4294 real_timeout.OffsetWithNanoSeconds(500000000UL);
4295 timeout_ptr = &real_timeout;
4296 }
4297 else
4298 {
4299 timeout_ptr = NULL; // if we are in a no-timeout scenario, then we only need a fake timeout the first time through
4300 // at this point in the code, all threads will be running so we are willing to wait forever, and do not
4301 // need a timeout
4302 }
Sean Callanana46ec452012-07-11 21:31:24 +00004303 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004304 else
4305 {
Sean Callanana46ec452012-07-11 21:31:24 +00004306 if (log)
4307 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4308 do_resume = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00004309 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004310
Sean Callanana46ec452012-07-11 21:31:24 +00004311 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00004312 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00004313
Jim Ingham0f16e732011-02-08 05:20:59 +00004314 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004315 {
Sean Callanana46ec452012-07-11 21:31:24 +00004316 if (timeout_ptr)
4317 {
4318 StreamString s;
4319 s.Printf ("about to wait - timeout is:\n ");
4320 timeout_ptr->Dump (&s, 120);
4321 s.Printf ("\nNow is:\n ");
4322 TimeValue::Now().Dump (&s, 120);
4323 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4324 }
Jim Ingham20829ac2011-08-09 22:24:33 +00004325 else
Sean Callanana46ec452012-07-11 21:31:24 +00004326 {
4327 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4328 }
4329 }
4330
4331 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4332
4333 if (got_event)
4334 {
4335 if (event_sp.get())
4336 {
4337 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00004338 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004339 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004340 Halt();
4341 keep_going = false;
4342 return_value = eExecutionInterrupted;
4343 errors.Printf ("Execution halted by user interrupt.");
4344 if (log)
4345 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4346 }
4347 else
4348 {
4349 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4350 if (log)
4351 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4352
4353 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00004354 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004355 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00004356 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004357 // Yay, we're done. Now make sure that our thread plan actually completed.
4358 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4359 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004360 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004361 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00004362 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00004363 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4364 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00004365 }
4366 else
4367 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004368 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4369 StopReason stop_reason = eStopReasonInvalid;
4370 if (stop_info_sp)
4371 stop_reason = stop_info_sp->GetStopReason();
4372 if (stop_reason == eStopReasonPlanComplete)
4373 {
4374 if (log)
4375 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4376 // Now mark this plan as private so it doesn't get reported as the stop reason
4377 // after this point.
4378 if (thread_plan_sp)
4379 thread_plan_sp->SetPrivate (orig_plan_private);
4380 return_value = eExecutionCompleted;
4381 }
4382 else
4383 {
4384 if (log)
4385 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanana46ec452012-07-11 21:31:24 +00004386
Jim Inghamcfc09352012-07-27 23:57:19 +00004387 return_value = eExecutionInterrupted;
4388 }
Sean Callanana46ec452012-07-11 21:31:24 +00004389 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004390 }
4391 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004392
Jim Inghamcfc09352012-07-27 23:57:19 +00004393 case lldb::eStateCrashed:
4394 if (log)
4395 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4396 return_value = eExecutionInterrupted;
4397 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004398
Jim Inghamcfc09352012-07-27 23:57:19 +00004399 case lldb::eStateRunning:
4400 do_resume = false;
4401 keep_going = true;
4402 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004403
Jim Inghamcfc09352012-07-27 23:57:19 +00004404 default:
4405 if (log)
4406 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4407
4408 if (stop_state == eStateExited)
4409 event_to_broadcast_sp = event_sp;
4410
Sean Callananbf154da2012-08-08 17:35:10 +00004411 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00004412 return_value = eExecutionInterrupted;
4413 break;
4414 }
Sean Callanana46ec452012-07-11 21:31:24 +00004415 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004416
Sean Callanana46ec452012-07-11 21:31:24 +00004417 if (keep_going)
4418 continue;
4419 else
4420 break;
4421 }
4422 else
4423 {
4424 if (log)
4425 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4426 return_value = eExecutionInterrupted;
4427 break;
4428 }
4429 }
4430 else
4431 {
4432 // If we didn't get an event that means we've timed out...
4433 // We will interrupt the process here. Depending on what we were asked to do we will
4434 // either exit, or try with all threads running for the same timeout.
4435 // Not really sure what to do if Halt fails here...
4436
4437 if (log) {
4438 if (try_all_threads)
4439 {
4440 if (first_timeout)
4441 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4442 "trying with all threads enabled.",
4443 single_thread_timeout_usec);
4444 else
4445 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4446 "and timeout: %d timed out.",
4447 single_thread_timeout_usec);
4448 }
4449 else
4450 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4451 "halt and abandoning execution.",
4452 single_thread_timeout_usec);
4453 }
4454
4455 Error halt_error = Halt();
4456 if (halt_error.Success())
4457 {
4458 if (log)
4459 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4460
4461 // If halt succeeds, it always produces a stopped event. Wait for that:
4462
4463 real_timeout = TimeValue::Now();
4464 real_timeout.OffsetWithMicroSeconds(500000);
4465
4466 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4467
4468 if (got_event)
4469 {
4470 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4471 if (log)
4472 {
4473 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4474 if (stop_state == lldb::eStateStopped
4475 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4476 log->PutCString (" Event was the Halt interruption event.");
4477 }
4478
4479 if (stop_state == lldb::eStateStopped)
4480 {
4481 // Between the time we initiated the Halt and the time we delivered it, the process could have
4482 // already finished its job. Check that here:
4483
4484 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4485 {
4486 if (log)
4487 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4488 "Exiting wait loop.");
4489 return_value = eExecutionCompleted;
4490 break;
4491 }
4492
4493 if (!try_all_threads)
4494 {
4495 if (log)
4496 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4497 return_value = eExecutionInterrupted;
4498 break;
4499 }
4500
4501 if (first_timeout)
4502 {
4503 // Set all the other threads to run, and return to the top of the loop, which will continue;
4504 first_timeout = false;
4505 thread_plan_sp->SetStopOthers (false);
4506 if (log)
4507 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4508
4509 continue;
4510 }
4511 else
4512 {
4513 // Running all threads failed, so return Interrupted.
4514 if (log)
4515 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4516 return_value = eExecutionInterrupted;
4517 break;
4518 }
4519 }
4520 }
4521 else
4522 { if (log)
4523 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4524 "I'm getting out of here passing Interrupted.");
4525 return_value = eExecutionInterrupted;
4526 break;
4527 }
4528 }
4529 else
4530 {
4531 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4532 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4533 if (log)
4534 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.",
4535 halt_error.AsCString());
4536 real_timeout = TimeValue::Now();
4537 real_timeout.OffsetWithMicroSeconds(500000);
4538 timeout_ptr = &real_timeout;
4539 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4540 if (!got_event || event_sp.get() == NULL)
4541 {
4542 // This is not going anywhere, bag out.
4543 if (log)
4544 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4545 return_value = eExecutionInterrupted;
4546 break;
4547 }
4548 else
4549 {
4550 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4551 if (log)
4552 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4553 if (stop_state == lldb::eStateStopped)
4554 {
4555 // Between the time we initiated the Halt and the time we delivered it, the process could have
4556 // already finished its job. Check that here:
4557
4558 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4559 {
4560 if (log)
4561 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4562 "Exiting wait loop.");
4563 return_value = eExecutionCompleted;
4564 break;
4565 }
4566
4567 if (first_timeout)
4568 {
4569 // Set all the other threads to run, and return to the top of the loop, which will continue;
4570 first_timeout = false;
4571 thread_plan_sp->SetStopOthers (false);
4572 if (log)
4573 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4574
4575 continue;
4576 }
4577 else
4578 {
4579 // Running all threads failed, so return Interrupted.
4580 if (log)
4581 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4582 return_value = eExecutionInterrupted;
4583 break;
4584 }
4585 }
4586 else
4587 {
4588 if (log)
4589 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4590 " a stopped event, instead got %s.", StateAsCString(stop_state));
4591 return_value = eExecutionInterrupted;
4592 break;
4593 }
4594 }
4595 }
4596
4597 }
4598
4599 } // END WAIT LOOP
4600
4601 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4602 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4603 {
4604 StopPrivateStateThread();
4605 Error error;
4606 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00004607 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004608 {
4609 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4610 }
4611 m_public_state.SetValueNoLock(old_state);
4612
4613 }
4614
4615
4616 // Now do some processing on the results of the run:
4617 if (return_value == eExecutionInterrupted)
4618 {
4619 if (log)
4620 {
4621 StreamString s;
4622 if (event_sp)
4623 event_sp->Dump (&s);
4624 else
4625 {
4626 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4627 }
4628
4629 StreamString ts;
4630
4631 const char *event_explanation = NULL;
4632
4633 do
4634 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004635 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004636 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004637 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00004638 break;
4639 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004640 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004641 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004642 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00004643 break;
4644 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004645 else
Sean Callanana46ec452012-07-11 21:31:24 +00004646 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004647 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4648
4649 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00004650 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004651 event_explanation = "<no event data>";
4652 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004653 }
4654
Jim Inghamcfc09352012-07-27 23:57:19 +00004655 Process *process = event_data->GetProcessSP().get();
4656
4657 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00004658 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004659 event_explanation = "<no process>";
4660 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004661 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004662
4663 ThreadList &thread_list = process->GetThreadList();
4664
4665 uint32_t num_threads = thread_list.GetSize();
4666 uint32_t thread_index;
4667
4668 ts.Printf("<%u threads> ", num_threads);
4669
4670 for (thread_index = 0;
4671 thread_index < num_threads;
4672 ++thread_index)
4673 {
4674 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4675
4676 if (!thread)
4677 {
4678 ts.Printf("<?> ");
4679 continue;
4680 }
4681
4682 ts.Printf("<0x%4.4llx ", thread->GetID());
4683 RegisterContext *register_context = thread->GetRegisterContext().get();
4684
4685 if (register_context)
4686 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4687 else
4688 ts.Printf("[ip unknown] ");
4689
4690 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4691 if (stop_info_sp)
4692 {
4693 const char *stop_desc = stop_info_sp->GetDescription();
4694 if (stop_desc)
4695 ts.PutCString (stop_desc);
4696 }
4697 ts.Printf(">");
4698 }
4699
4700 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00004701 }
Sean Callanana46ec452012-07-11 21:31:24 +00004702 } while (0);
4703
Jim Inghamcfc09352012-07-27 23:57:19 +00004704 if (event_explanation)
4705 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00004706 else
Jim Inghamcfc09352012-07-27 23:57:19 +00004707 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4708 }
4709
4710 if (discard_on_error && thread_plan_sp)
4711 {
4712 if (log)
4713 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4714 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4715 thread_plan_sp->SetPrivate (orig_plan_private);
4716 }
4717 else
4718 {
4719 if (log)
4720 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00004721 }
4722 }
4723 else if (return_value == eExecutionSetupError)
4724 {
4725 if (log)
4726 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004727
4728 if (discard_on_error && thread_plan_sp)
4729 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004730 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004731 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004732 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004733 }
4734 else
4735 {
Sean Callanana46ec452012-07-11 21:31:24 +00004736 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004737 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004738 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00004739 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4740 return_value = eExecutionCompleted;
4741 }
4742 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4743 {
4744 if (log)
4745 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4746 return_value = eExecutionDiscarded;
4747 }
4748 else
4749 {
4750 if (log)
4751 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4752 if (discard_on_error && thread_plan_sp)
4753 {
4754 if (log)
4755 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4756 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4757 thread_plan_sp->SetPrivate (orig_plan_private);
4758 }
4759 }
4760 }
4761
4762 // Thread we ran the function in may have gone away because we ran the target
4763 // Check that it's still there, and if it is put it back in the context. Also restore the
4764 // frame in the context if it is still present.
4765 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4766 if (thread)
4767 {
4768 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4769 }
4770
4771 // Also restore the current process'es selected frame & thread, since this function calling may
4772 // be done behind the user's back.
4773
4774 if (selected_tid != LLDB_INVALID_THREAD_ID)
4775 {
4776 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4777 {
4778 // We were able to restore the selected thread, now restore the frame:
4779 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4780 if (old_frame_sp)
4781 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004782 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004783 }
4784 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004785
Sean Callanana46ec452012-07-11 21:31:24 +00004786 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00004787
Sean Callanana46ec452012-07-11 21:31:24 +00004788 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004789 {
Sean Callanana46ec452012-07-11 21:31:24 +00004790 if (log)
4791 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4792 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004793 }
4794
4795 return return_value;
4796}
4797
4798const char *
4799Process::ExecutionResultAsCString (ExecutionResults result)
4800{
4801 const char *result_name;
4802
4803 switch (result)
4804 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004805 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004806 result_name = "eExecutionCompleted";
4807 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004808 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004809 result_name = "eExecutionDiscarded";
4810 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004811 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004812 result_name = "eExecutionInterrupted";
4813 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004814 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004815 result_name = "eExecutionSetupError";
4816 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004817 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004818 result_name = "eExecutionTimedOut";
4819 break;
4820 }
4821 return result_name;
4822}
4823
Greg Clayton7260f622011-04-18 08:33:37 +00004824void
4825Process::GetStatus (Stream &strm)
4826{
4827 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00004828 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00004829 {
4830 if (state == eStateExited)
4831 {
4832 int exit_status = GetExitStatus();
4833 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004834 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004835 GetID(),
4836 exit_status,
4837 exit_status,
4838 exit_description ? exit_description : "");
4839 }
4840 else
4841 {
4842 if (state == eStateConnected)
4843 strm.Printf ("Connected to remote target.\n");
4844 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004845 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004846 }
4847 }
4848 else
4849 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004850 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004851 }
4852}
4853
4854size_t
4855Process::GetThreadStatus (Stream &strm,
4856 bool only_threads_with_stop_reason,
4857 uint32_t start_frame,
4858 uint32_t num_frames,
4859 uint32_t num_frames_with_source)
4860{
4861 size_t num_thread_infos_dumped = 0;
4862
4863 const size_t num_threads = GetThreadList().GetSize();
4864 for (uint32_t i = 0; i < num_threads; i++)
4865 {
4866 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4867 if (thread)
4868 {
4869 if (only_threads_with_stop_reason)
4870 {
4871 if (thread->GetStopInfo().get() == NULL)
4872 continue;
4873 }
4874 thread->GetStatus (strm,
4875 start_frame,
4876 num_frames,
4877 num_frames_with_source);
4878 ++num_thread_infos_dumped;
4879 }
4880 }
4881 return num_thread_infos_dumped;
4882}
4883
Greg Claytona9f40ad2012-02-22 04:37:26 +00004884void
4885Process::AddInvalidMemoryRegion (const LoadRange &region)
4886{
4887 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4888}
4889
4890bool
4891Process::RemoveInvalidMemoryRange (const LoadRange &region)
4892{
4893 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4894}
4895
Jim Ingham372787f2012-04-07 00:00:41 +00004896void
4897Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4898{
4899 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4900}
4901
4902bool
4903Process::RunPreResumeActions ()
4904{
4905 bool result = true;
4906 while (!m_pre_resume_actions.empty())
4907 {
4908 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
4909 m_pre_resume_actions.pop_back();
4910 bool this_result = action.callback (action.baton);
4911 if (result == true) result = this_result;
4912 }
4913 return result;
4914}
4915
4916void
4917Process::ClearPreResumeActions ()
4918{
4919 m_pre_resume_actions.clear();
4920}
Greg Claytona9f40ad2012-02-22 04:37:26 +00004921
Greg Claytonfa559e52012-05-18 02:38:05 +00004922void
4923Process::Flush ()
4924{
4925 m_thread_list.Flush();
4926}