blob: 47b64aa971c9cfaf13ea34225f7d5b7b225a1b1a [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"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000039#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040
41using namespace lldb;
42using namespace lldb_private;
43
Greg Clayton67cc0632012-08-22 17:17:09 +000044
45// Comment out line below to disable memory caching, overriding the process setting
46// target.process.disable-memory-cache
47#define ENABLE_MEMORY_CACHING
48
49#ifdef ENABLE_MEMORY_CACHING
50#define DISABLE_MEM_CACHE_DEFAULT false
51#else
52#define DISABLE_MEM_CACHE_DEFAULT true
53#endif
54
55class ProcessOptionValueProperties : public OptionValueProperties
56{
57public:
58 ProcessOptionValueProperties (const ConstString &name) :
59 OptionValueProperties (name)
60 {
61 }
62
63 // This constructor is used when creating ProcessOptionValueProperties when it
64 // is part of a new lldb_private::Process instance. It will copy all current
65 // global property values as needed
66 ProcessOptionValueProperties (ProcessProperties *global_properties) :
67 OptionValueProperties(*global_properties->GetValueProperties())
68 {
69 }
70
71 virtual const Property *
72 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
73 {
74 // When gettings the value for a key from the process options, we will always
75 // try and grab the setting from the current process if there is one. Else we just
76 // use the one from this instance.
77 if (exe_ctx)
78 {
79 Process *process = exe_ctx->GetProcessPtr();
80 if (process)
81 {
82 ProcessOptionValueProperties *instance_properties = static_cast<ProcessOptionValueProperties *>(process->GetValueProperties().get());
83 if (this != instance_properties)
84 return instance_properties->ProtectedGetPropertyAtIndex (idx);
85 }
86 }
87 return ProtectedGetPropertyAtIndex (idx);
88 }
89};
90
91static PropertyDefinition
92g_properties[] =
93{
94 { "disable-memory-cache" , OptionValue::eTypeBoolean, false, DISABLE_MEM_CACHE_DEFAULT, NULL, NULL, "Disable reading and caching of memory in fixed-size units." },
95 { "extra-startup-command", OptionValue::eTypeArray , false, OptionValue::eTypeString, NULL, NULL, "A list containing extra commands understood by the particular process plugin used." },
96 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
97};
98
99enum {
100 ePropertyDisableMemCache,
101 ePropertyExtraStartCommand
102};
103
104ProcessProperties::ProcessProperties (bool is_global) :
105 Properties ()
106{
107 if (is_global)
108 {
109 m_collection_sp.reset (new ProcessOptionValueProperties(ConstString("process")));
110 m_collection_sp->Initialize(g_properties);
111 m_collection_sp->AppendProperty(ConstString("thread"),
112 ConstString("Settings specify to threads."),
113 true,
114 Thread::GetGlobalProperties()->GetValueProperties());
115 }
116 else
117 m_collection_sp.reset (new ProcessOptionValueProperties(Process::GetGlobalProperties().get()));
118}
119
120ProcessProperties::~ProcessProperties()
121{
122}
123
124bool
125ProcessProperties::GetDisableMemoryCache() const
126{
127 const uint32_t idx = ePropertyDisableMemCache;
128 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
129}
130
131Args
132ProcessProperties::GetExtraStartupCommands () const
133{
134 Args args;
135 const uint32_t idx = ePropertyExtraStartCommand;
136 m_collection_sp->GetPropertyAtIndexAsArgs(NULL, idx, args);
137 return args;
138}
139
140void
141ProcessProperties::SetExtraStartupCommands (const Args &args)
142{
143 const uint32_t idx = ePropertyExtraStartCommand;
144 m_collection_sp->SetPropertyAtIndexFromArgs(NULL, idx, args);
145}
146
Greg Clayton32e0a752011-03-30 18:16:51 +0000147void
Greg Clayton8b82f082011-04-12 05:54:46 +0000148ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000149{
150 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000151 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +0000152 s.Printf (" pid = %llu\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000153
154 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +0000155 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000156
157 if (m_executable)
158 {
159 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
160 s.PutCString (" file = ");
161 m_executable.Dump(&s);
162 s.EOL();
163 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000164 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000165 if (argc > 0)
166 {
167 for (uint32_t i=0; i<argc; i++)
168 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000169 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000170 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +0000171 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000172 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000173 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000174 }
175 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000176
177 const uint32_t envc = m_environment.GetArgumentCount();
178 if (envc > 0)
179 {
180 for (uint32_t i=0; i<envc; i++)
181 {
182 const char *env = m_environment.GetArgumentAtIndex(i);
183 if (i < 10)
184 s.Printf (" env[%u] = %s\n", i, env);
185 else
186 s.Printf ("env[%u] = %s\n", i, env);
187 }
188 }
189
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000190 if (m_arch.IsValid())
191 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
192
Greg Clayton8b82f082011-04-12 05:54:46 +0000193 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000194 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000195 cstr = platform->GetUserName (m_uid);
196 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000197 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000198 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000199 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000200 cstr = platform->GetGroupName (m_gid);
201 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000202 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000203 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000204 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000205 cstr = platform->GetUserName (m_euid);
206 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000207 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000208 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000209 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000210 cstr = platform->GetGroupName (m_egid);
211 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000212 }
213}
214
215void
Greg Clayton8b82f082011-04-12 05:54:46 +0000216ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000217{
Greg Clayton8b82f082011-04-12 05:54:46 +0000218 const char *label;
219 if (show_args || verbose)
220 label = "ARGUMENTS";
221 else
222 label = "NAME";
223
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000224 if (verbose)
225 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000226 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000227 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
228 }
229 else
230 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000231 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000232 s.PutCString ("====== ====== ========== ======= ============================\n");
233 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000234}
235
236void
Greg Clayton8b82f082011-04-12 05:54:46 +0000237ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000238{
239 if (m_pid != LLDB_INVALID_PROCESS_ID)
240 {
241 const char *cstr;
Greg Clayton61e7a582011-12-01 23:28:38 +0000242 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000243
Greg Clayton32e0a752011-03-30 18:16:51 +0000244
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000245 if (verbose)
246 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000247 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000248 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
249 s.Printf ("%-10s ", cstr);
250 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000251 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000252
Greg Clayton8b82f082011-04-12 05:54:46 +0000253 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000254 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
255 s.Printf ("%-10s ", cstr);
256 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000257 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000258
Greg Clayton8b82f082011-04-12 05:54:46 +0000259 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000260 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
261 s.Printf ("%-10s ", cstr);
262 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000263 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000264
Greg Clayton8b82f082011-04-12 05:54:46 +0000265 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000266 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
267 s.Printf ("%-10s ", cstr);
268 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000269 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000270 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
271 }
272 else
273 {
Jason Molendafd54b362011-09-20 21:44:10 +0000274 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000275 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000276 (int)m_arch.GetTriple().getArchName().size(),
277 m_arch.GetTriple().getArchName().data());
278 }
279
Greg Clayton8b82f082011-04-12 05:54:46 +0000280 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000281 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000282 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000283 if (argc > 0)
284 {
285 for (uint32_t i=0; i<argc; i++)
286 {
287 if (i > 0)
288 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000289 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000290 }
291 }
292 }
293 else
294 {
295 s.PutCString (GetName());
296 }
297
298 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000299 }
300}
301
Greg Clayton8b82f082011-04-12 05:54:46 +0000302
303void
Greg Clayton982c9762011-11-03 21:22:33 +0000304ProcessInfo::SetArguments (char const **argv,
305 bool first_arg_is_executable,
306 bool first_arg_is_executable_and_argument)
307{
308 m_arguments.SetArguments (argv);
309
310 // Is the first argument the executable?
311 if (first_arg_is_executable)
312 {
313 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
314 if (first_arg)
315 {
316 // Yes the first argument is an executable, set it as the executable
317 // in the launch options. Don't resolve the file path as the path
318 // could be a remote platform path
319 const bool resolve = false;
320 m_executable.SetFile(first_arg, resolve);
321
322 // If argument zero is an executable and shouldn't be included
323 // in the arguments, remove it from the front of the arguments
324 if (first_arg_is_executable_and_argument == false)
325 m_arguments.DeleteArgumentAtIndex (0);
326 }
327 }
328}
329void
330ProcessInfo::SetArguments (const Args& args,
331 bool first_arg_is_executable,
332 bool first_arg_is_executable_and_argument)
Greg Clayton8b82f082011-04-12 05:54:46 +0000333{
334 // Copy all arguments
335 m_arguments = args;
336
337 // Is the first argument the executable?
338 if (first_arg_is_executable)
339 {
Greg Clayton982c9762011-11-03 21:22:33 +0000340 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000341 if (first_arg)
342 {
343 // Yes the first argument is an executable, set it as the executable
344 // in the launch options. Don't resolve the file path as the path
345 // could be a remote platform path
346 const bool resolve = false;
347 m_executable.SetFile(first_arg, resolve);
348
349 // If argument zero is an executable and shouldn't be included
350 // in the arguments, remove it from the front of the arguments
351 if (first_arg_is_executable_and_argument == false)
352 m_arguments.DeleteArgumentAtIndex (0);
353 }
354 }
355}
356
Greg Clayton1d885962011-11-08 02:43:13 +0000357void
Greg Claytonee95ed52011-11-17 22:14:31 +0000358ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-11-08 02:43:13 +0000359{
360 // If notthing was specified, then check the process for any default
361 // settings that were set with "settings set"
362 if (m_file_actions.empty())
363 {
Greg Clayton1d885962011-11-08 02:43:13 +0000364 if (m_flags.Test(eLaunchFlagDisableSTDIO))
365 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000366 AppendSuppressFileAction (STDIN_FILENO , true, false);
367 AppendSuppressFileAction (STDOUT_FILENO, false, true);
368 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000369 }
370 else
371 {
372 // Check for any values that might have gotten set with any of:
373 // (lldb) settings set target.input-path
374 // (lldb) settings set target.output-path
375 // (lldb) settings set target.error-path
Greg Clayton67cc0632012-08-22 17:17:09 +0000376 FileSpec in_path;
377 FileSpec out_path;
378 FileSpec err_path;
Greg Clayton1d885962011-11-08 02:43:13 +0000379 if (target)
380 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000381 in_path = target->GetStandardInputPath();
382 out_path = target->GetStandardOutputPath();
383 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000384 }
385
Greg Clayton67cc0632012-08-22 17:17:09 +0000386 if (in_path || out_path || err_path)
387 {
388 char path[PATH_MAX];
389 if (in_path && in_path.GetPath(path, sizeof(path)))
390 AppendOpenFileAction(STDIN_FILENO, path, true, false);
391
392 if (out_path && out_path.GetPath(path, sizeof(path)))
393 AppendOpenFileAction(STDOUT_FILENO, path, false, true);
394
395 if (err_path && err_path.GetPath(path, sizeof(path)))
396 AppendOpenFileAction(STDERR_FILENO, path, false, true);
397 }
398 else if (default_to_use_pty)
Greg Claytonee95ed52011-11-17 22:14:31 +0000399 {
400 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000401 {
Greg Clayton67cc0632012-08-22 17:17:09 +0000402 const char *slave_path = m_pty.GetSlaveName (NULL, 0);
403 AppendOpenFileAction(STDIN_FILENO, slave_path, true, false);
404 AppendOpenFileAction(STDOUT_FILENO, slave_path, false, true);
405 AppendOpenFileAction(STDERR_FILENO, slave_path, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000406 }
407 }
Greg Clayton1d885962011-11-08 02:43:13 +0000408 }
409 }
410}
411
Greg Clayton144f3a92011-11-15 03:53:30 +0000412
413bool
Greg Claytond1cf11a2012-04-14 01:42:46 +0000414ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
415 bool localhost,
416 bool will_debug,
417 bool first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000418{
419 error.Clear();
420
421 if (GetFlags().Test (eLaunchFlagLaunchInShell))
422 {
423 const char *shell_executable = GetShell();
424 if (shell_executable)
425 {
426 char shell_resolved_path[PATH_MAX];
427
428 if (localhost)
429 {
430 FileSpec shell_filespec (shell_executable, true);
431
432 if (!shell_filespec.Exists())
433 {
434 // Resolve the path in case we just got "bash", "sh" or "tcsh"
435 if (!shell_filespec.ResolveExecutableLocation ())
436 {
437 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
438 return false;
439 }
440 }
441 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
442 shell_executable = shell_resolved_path;
443 }
444
445 Args shell_arguments;
446 std::string safe_arg;
447 shell_arguments.AppendArgument (shell_executable);
Greg Clayton144f3a92011-11-15 03:53:30 +0000448 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000449
450 StreamString shell_command;
451 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000452 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000453 shell_command.PutCString ("exec");
454 if (GetArchitecture().IsValid())
455 {
456 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
457 // Set the resume count to 2:
458 // 1 - stop in shell
459 // 2 - stop in /usr/bin/arch
460 // 3 - then we will stop in our program
461 SetResumeCount(2);
462 }
463 else
464 {
465 // Set the resume count to 1:
466 // 1 - stop in shell
467 // 2 - then we will stop in our program
468 SetResumeCount(1);
469 }
Greg Clayton144f3a92011-11-15 03:53:30 +0000470 }
471
472 const char **argv = GetArguments().GetConstArgumentVector ();
473 if (argv)
474 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000475 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000476 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000477 // There should only be one argument that is the shell command itself to be used as is
478 if (argv[0] && !argv[1])
479 shell_command.Printf("%s", argv[0]);
480 else
481 return false;
Greg Clayton144f3a92011-11-15 03:53:30 +0000482 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000483 else
484 {
485 for (size_t i=0; argv[i] != NULL; ++i)
486 {
487 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
488 shell_command.Printf(" %s", arg);
489 }
490 }
491 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton144f3a92011-11-15 03:53:30 +0000492 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000493 else
494 {
495 return false;
496 }
497
Greg Clayton144f3a92011-11-15 03:53:30 +0000498 m_executable.SetFile(shell_executable, false);
499 m_arguments = shell_arguments;
500 return true;
501 }
502 else
503 {
504 error.SetErrorString ("invalid shell path");
505 }
506 }
507 else
508 {
509 error.SetErrorString ("not launching in shell");
510 }
511 return false;
512}
513
514
Greg Clayton32e0a752011-03-30 18:16:51 +0000515bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000516ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
517{
518 if ((read || write) && fd >= 0 && path && path[0])
519 {
520 m_action = eFileActionOpen;
521 m_fd = fd;
522 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000523 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000524 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000525 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000526 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000527 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000528 m_path.assign (path);
529 return true;
530 }
531 else
532 {
533 Clear();
534 }
535 return false;
536}
537
538bool
539ProcessLaunchInfo::FileAction::Close (int fd)
540{
541 Clear();
542 if (fd >= 0)
543 {
544 m_action = eFileActionClose;
545 m_fd = fd;
546 }
547 return m_fd >= 0;
548}
549
550
551bool
552ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
553{
554 Clear();
555 if (fd >= 0 && dup_fd >= 0)
556 {
557 m_action = eFileActionDuplicate;
558 m_fd = fd;
559 m_arg = dup_fd;
560 }
561 return m_fd >= 0;
562}
563
564
565
566bool
567ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
568 const FileAction *info,
569 Log *log,
570 Error& error)
571{
572 if (info == NULL)
573 return false;
574
575 switch (info->m_action)
576 {
577 case eFileActionNone:
578 error.Clear();
579 break;
580
581 case eFileActionClose:
582 if (info->m_fd == -1)
583 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
584 else
585 {
586 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
587 eErrorTypePOSIX);
588 if (log && (error.Fail() || log))
589 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
590 file_actions, info->m_fd);
591 }
592 break;
593
594 case eFileActionDuplicate:
595 if (info->m_fd == -1)
596 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
597 else if (info->m_arg == -1)
598 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
599 else
600 {
601 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
602 eErrorTypePOSIX);
603 if (log && (error.Fail() || log))
604 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
605 file_actions, info->m_fd, info->m_arg);
606 }
607 break;
608
609 case eFileActionOpen:
610 if (info->m_fd == -1)
611 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
612 else
613 {
614 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000615
Greg Clayton8b82f082011-04-12 05:54:46 +0000616 mode_t mode = 0;
617
Greg Clayton144f3a92011-11-15 03:53:30 +0000618 if (oflag & O_CREAT)
619 mode = 0640;
620
Greg Clayton8b82f082011-04-12 05:54:46 +0000621 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
622 info->m_fd,
623 info->m_path.c_str(),
624 oflag,
625 mode),
626 eErrorTypePOSIX);
627 if (error.Fail() || log)
628 error.PutToLog(log,
629 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
630 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
631 }
632 break;
633
634 default:
635 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
636 break;
637 }
638 return error.Success();
639}
640
641Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000642ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000643{
644 Error error;
645 char short_option = (char) m_getopt_table[option_idx].val;
646
647 switch (short_option)
648 {
649 case 's': // Stop at program entry point
650 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
651 break;
652
Greg Clayton8b82f082011-04-12 05:54:46 +0000653 case 'i': // STDIN for read only
654 {
655 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000656 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000657 launch_info.AppendFileAction (action);
658 }
659 break;
660
661 case 'o': // Open STDOUT for write only
662 {
663 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000664 if (action.Open (STDOUT_FILENO, option_arg, false, true))
665 launch_info.AppendFileAction (action);
666 }
667 break;
668
669 case 'e': // STDERR for write only
670 {
671 ProcessLaunchInfo::FileAction action;
672 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000673 launch_info.AppendFileAction (action);
674 }
675 break;
676
Greg Clayton9845a8d2012-03-06 04:01:04 +0000677
Greg Clayton8b82f082011-04-12 05:54:46 +0000678 case 'p': // Process plug-in name
679 launch_info.SetProcessPluginName (option_arg);
680 break;
681
682 case 'n': // Disable STDIO
683 {
684 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000685 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000686 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000687 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000688 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000689 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000690 launch_info.AppendFileAction (action);
691 }
692 break;
693
694 case 'w':
695 launch_info.SetWorkingDirectory (option_arg);
696 break;
697
698 case 't': // Open process in new terminal window
699 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
700 break;
701
702 case 'a':
Greg Clayton70512312012-05-08 01:45:38 +0000703 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
704 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Clayton8b82f082011-04-12 05:54:46 +0000705 break;
706
707 case 'A':
708 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
709 break;
710
Greg Clayton982c9762011-11-03 21:22:33 +0000711 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000712 if (option_arg && option_arg[0])
713 launch_info.SetShell (option_arg);
714 else
715 launch_info.SetShell ("/bin/bash");
Greg Clayton982c9762011-11-03 21:22:33 +0000716 break;
717
Greg Clayton8b82f082011-04-12 05:54:46 +0000718 case 'v':
719 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
720 break;
721
722 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000723 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000724 break;
725
726 }
727 return error;
728}
729
730OptionDefinition
731ProcessLaunchCommandOptions::g_option_table[] =
732{
733{ 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."},
734{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
735{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
736{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
737{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
738{ 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 +0000739{ 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 +0000740
741{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
742{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
743{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
744
745{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
746
747{ 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."},
748
749{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
750};
751
752
753
754bool
755ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000756{
757 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
758 return true;
759 const char *match_name = m_match_info.GetName();
760 if (!match_name)
761 return true;
762
763 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
764}
765
766bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000767ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000768{
769 if (!NameMatches (proc_info.GetName()))
770 return false;
771
772 if (m_match_info.ProcessIDIsValid() &&
773 m_match_info.GetProcessID() != proc_info.GetProcessID())
774 return false;
775
776 if (m_match_info.ParentProcessIDIsValid() &&
777 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
778 return false;
779
Greg Clayton8b82f082011-04-12 05:54:46 +0000780 if (m_match_info.UserIDIsValid () &&
781 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000782 return false;
783
Greg Clayton8b82f082011-04-12 05:54:46 +0000784 if (m_match_info.GroupIDIsValid () &&
785 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000786 return false;
787
788 if (m_match_info.EffectiveUserIDIsValid () &&
789 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
790 return false;
791
792 if (m_match_info.EffectiveGroupIDIsValid () &&
793 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
794 return false;
795
796 if (m_match_info.GetArchitecture().IsValid() &&
797 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
798 return false;
799 return true;
800}
801
802bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000803ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000804{
805 if (m_name_match_type != eNameMatchIgnore)
806 return false;
807
808 if (m_match_info.ProcessIDIsValid())
809 return false;
810
811 if (m_match_info.ParentProcessIDIsValid())
812 return false;
813
Greg Clayton8b82f082011-04-12 05:54:46 +0000814 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000815 return false;
816
Greg Clayton8b82f082011-04-12 05:54:46 +0000817 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000818 return false;
819
820 if (m_match_info.EffectiveUserIDIsValid ())
821 return false;
822
823 if (m_match_info.EffectiveGroupIDIsValid ())
824 return false;
825
826 if (m_match_info.GetArchitecture().IsValid())
827 return false;
828
829 if (m_match_all_users)
830 return false;
831
832 return true;
833
834}
835
836void
Greg Clayton8b82f082011-04-12 05:54:46 +0000837ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000838{
839 m_match_info.Clear();
840 m_name_match_type = eNameMatchIgnore;
841 m_match_all_users = false;
842}
Greg Clayton58be07b2011-01-07 06:08:19 +0000843
Greg Claytonc3776bf2012-02-09 06:16:32 +0000844ProcessSP
845Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000846{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000847 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000848 ProcessCreateInstance create_callback = NULL;
849 if (plugin_name)
850 {
851 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
852 if (create_callback)
853 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000854 process_sp = create_callback(target, listener, crash_file_path);
855 if (process_sp)
856 {
857 if (!process_sp->CanDebug(target, true))
858 process_sp.reset();
859 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000860 }
861 }
862 else
863 {
Greg Claytonc982c762010-07-09 20:39:50 +0000864 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000865 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000866 process_sp = create_callback(target, listener, crash_file_path);
867 if (process_sp)
868 {
869 if (!process_sp->CanDebug(target, false))
870 process_sp.reset();
871 else
872 break;
873 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000874 }
875 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000876 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000877}
878
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000879ConstString &
880Process::GetStaticBroadcasterClass ()
881{
882 static ConstString class_name ("lldb.process");
883 return class_name;
884}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885
886//----------------------------------------------------------------------
887// Process constructor
888//----------------------------------------------------------------------
889Process::Process(Target &target, Listener &listener) :
Greg Clayton67cc0632012-08-22 17:17:09 +0000890 ProcessProperties (false),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000891 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000892 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000893 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000894 m_public_state (eStateUnloaded),
895 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000896 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
897 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000898 m_private_state_listener ("lldb.process.internal_state_listener"),
899 m_private_state_control_wait(),
900 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000901 m_mod_id (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000902 m_thread_index_id (0),
903 m_exit_status (-1),
904 m_exit_string (),
905 m_thread_list (this),
906 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000907 m_image_tokens (),
908 m_listener (listener),
909 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000910 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000911 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000912 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000913 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000914 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000915 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000916 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000917 m_stderr_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000918 m_memory_cache (*this),
919 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000920 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000921 m_next_event_action_ap(),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000922 m_run_lock (),
Jim Inghamaacc3182012-06-06 00:29:30 +0000923 m_currently_handling_event(false),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000924 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000925{
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000926 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000927
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000928 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000929 if (log)
930 log->Printf ("%p Process::Process()", this);
931
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000932 SetEventName (eBroadcastBitStateChanged, "state-changed");
933 SetEventName (eBroadcastBitInterrupt, "interrupt");
934 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
935 SetEventName (eBroadcastBitSTDERR, "stderr-available");
936
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000937 listener.StartListeningForEvents (this,
938 eBroadcastBitStateChanged |
939 eBroadcastBitInterrupt |
940 eBroadcastBitSTDOUT |
941 eBroadcastBitSTDERR);
942
943 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +0000944 eBroadcastBitStateChanged |
945 eBroadcastBitInterrupt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000946
947 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
948 eBroadcastInternalStateControlStop |
949 eBroadcastInternalStateControlPause |
950 eBroadcastInternalStateControlResume);
951}
952
953//----------------------------------------------------------------------
954// Destructor
955//----------------------------------------------------------------------
956Process::~Process()
957{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000958 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000959 if (log)
960 log->Printf ("%p Process::~Process()", this);
961 StopPrivateStateThread();
962}
963
Greg Clayton67cc0632012-08-22 17:17:09 +0000964const ProcessPropertiesSP &
965Process::GetGlobalProperties()
966{
967 static ProcessPropertiesSP g_settings_sp;
968 if (!g_settings_sp)
969 g_settings_sp.reset (new ProcessProperties (true));
970 return g_settings_sp;
971}
972
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000973void
974Process::Finalize()
975{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000976 switch (GetPrivateState())
977 {
978 case eStateConnected:
979 case eStateAttaching:
980 case eStateLaunching:
981 case eStateStopped:
982 case eStateRunning:
983 case eStateStepping:
984 case eStateCrashed:
985 case eStateSuspended:
986 if (GetShouldDetach())
987 Detach();
988 else
989 Destroy();
990 break;
991
992 case eStateInvalid:
993 case eStateUnloaded:
994 case eStateDetached:
995 case eStateExited:
996 break;
997 }
998
Greg Clayton1ed54f52011-10-01 00:45:15 +0000999 // Clear our broadcaster before we proceed with destroying
1000 Broadcaster::Clear();
1001
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002 // Do any cleanup needed prior to being destructed... Subclasses
1003 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +00001004
1005 // We need to destroy the loader before the derived Process class gets destroyed
1006 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +00001007 m_dynamic_checkers_ap.reset();
1008 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001009 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +00001010 m_dyld_ap.reset();
Greg Claytone1cd1be2012-01-29 20:56:30 +00001011 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +00001012 std::vector<Notifications> empty_notifications;
1013 m_notifications.swap(empty_notifications);
1014 m_image_tokens.clear();
1015 m_memory_cache.Clear();
1016 m_allocated_memory_cache.Clear();
1017 m_language_runtimes.clear();
1018 m_next_event_action_ap.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001019}
1020
1021void
1022Process::RegisterNotificationCallbacks (const Notifications& callbacks)
1023{
1024 m_notifications.push_back(callbacks);
1025 if (callbacks.initialize != NULL)
1026 callbacks.initialize (callbacks.baton, this);
1027}
1028
1029bool
1030Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
1031{
1032 std::vector<Notifications>::iterator pos, end = m_notifications.end();
1033 for (pos = m_notifications.begin(); pos != end; ++pos)
1034 {
1035 if (pos->baton == callbacks.baton &&
1036 pos->initialize == callbacks.initialize &&
1037 pos->process_state_changed == callbacks.process_state_changed)
1038 {
1039 m_notifications.erase(pos);
1040 return true;
1041 }
1042 }
1043 return false;
1044}
1045
1046void
1047Process::SynchronouslyNotifyStateChanged (StateType state)
1048{
1049 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
1050 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
1051 {
1052 if (notification_pos->process_state_changed)
1053 notification_pos->process_state_changed (notification_pos->baton, this, state);
1054 }
1055}
1056
1057// FIXME: We need to do some work on events before the general Listener sees them.
1058// For instance if we are continuing from a breakpoint, we need to ensure that we do
1059// the little "insert real insn, step & stop" trick. But we can't do that when the
1060// event is delivered by the broadcaster - since that is done on the thread that is
1061// waiting for new events, so if we needed more than one event for our handling, we would
1062// stall. So instead we do it when we fetch the event off of the queue.
1063//
1064
1065StateType
1066Process::GetNextEvent (EventSP &event_sp)
1067{
1068 StateType state = eStateInvalid;
1069
1070 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
1071 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
1072
1073 return state;
1074}
1075
1076
1077StateType
1078Process::WaitForProcessToStop (const TimeValue *timeout)
1079{
Jim Ingham4b536182011-08-09 02:12:22 +00001080 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
1081 // We have to actually check each event, and in the case of a stopped event check the restarted flag
1082 // on the event.
1083 EventSP event_sp;
1084 StateType state = GetState();
1085 // If we are exited or detached, we won't ever get back to any
1086 // other valid state...
1087 if (state == eStateDetached || state == eStateExited)
1088 return state;
1089
1090 while (state != eStateInvalid)
1091 {
1092 state = WaitForStateChangedEvents (timeout, event_sp);
1093 switch (state)
1094 {
1095 case eStateCrashed:
1096 case eStateDetached:
1097 case eStateExited:
1098 case eStateUnloaded:
1099 return state;
1100 case eStateStopped:
1101 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
1102 continue;
1103 else
1104 return state;
1105 default:
1106 continue;
1107 }
1108 }
1109 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001110}
1111
1112
1113StateType
1114Process::WaitForState
1115(
1116 const TimeValue *timeout,
1117 const StateType *match_states, const uint32_t num_match_states
1118)
1119{
1120 EventSP event_sp;
1121 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001122 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123 while (state != eStateInvalid)
1124 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001125 // If we are exited or detached, we won't ever get back to any
1126 // other valid state...
1127 if (state == eStateDetached || state == eStateExited)
1128 return state;
1129
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001130 state = WaitForStateChangedEvents (timeout, event_sp);
1131
1132 for (i=0; i<num_match_states; ++i)
1133 {
1134 if (match_states[i] == state)
1135 return state;
1136 }
1137 }
1138 return state;
1139}
1140
Jim Ingham30f9b212010-10-11 23:53:14 +00001141bool
1142Process::HijackProcessEvents (Listener *listener)
1143{
1144 if (listener != NULL)
1145 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001146 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham30f9b212010-10-11 23:53:14 +00001147 }
1148 else
1149 return false;
1150}
1151
1152void
1153Process::RestoreProcessEvents ()
1154{
1155 RestoreBroadcaster();
1156}
1157
Jim Ingham0f16e732011-02-08 05:20:59 +00001158bool
1159Process::HijackPrivateProcessEvents (Listener *listener)
1160{
1161 if (listener != NULL)
1162 {
Jim Inghamcfc09352012-07-27 23:57:19 +00001163 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham0f16e732011-02-08 05:20:59 +00001164 }
1165 else
1166 return false;
1167}
1168
1169void
1170Process::RestorePrivateProcessEvents ()
1171{
1172 m_private_state_broadcaster.RestoreBroadcaster();
1173}
1174
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175StateType
1176Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1177{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001178 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001179
1180 if (log)
1181 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1182
1183 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001184 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1185 this,
Jim Inghamcfc09352012-07-27 23:57:19 +00001186 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton3fcbed62010-10-19 03:25:40 +00001187 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001188 {
1189 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1190 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1191 else if (log)
1192 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1193 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194
1195 if (log)
1196 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1197 __FUNCTION__,
1198 timeout,
1199 StateAsCString(state));
1200 return state;
1201}
1202
1203Event *
1204Process::PeekAtStateChangedEvents ()
1205{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001206 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001207
1208 if (log)
1209 log->Printf ("Process::%s...", __FUNCTION__);
1210
1211 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001212 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1213 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001214 if (log)
1215 {
1216 if (event_ptr)
1217 {
1218 log->Printf ("Process::%s (event_ptr) => %s",
1219 __FUNCTION__,
1220 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1221 }
1222 else
1223 {
1224 log->Printf ("Process::%s no events found",
1225 __FUNCTION__);
1226 }
1227 }
1228 return event_ptr;
1229}
1230
1231StateType
1232Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1233{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001234 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001235
1236 if (log)
1237 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1238
1239 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001240 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1241 &m_private_state_broadcaster,
Jim Inghamcfc09352012-07-27 23:57:19 +00001242 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton6779606a2011-01-22 23:43:18 +00001243 event_sp))
Jim Inghamcfc09352012-07-27 23:57:19 +00001244 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1245 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001246
1247 // This is a bit of a hack, but when we wait here we could very well return
1248 // to the command-line, and that could disable the log, which would render the
1249 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001250 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001251 {
1252 if (state == eStateInvalid)
1253 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1254 else
1255 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1256 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001257 return state;
1258}
1259
1260bool
1261Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1262{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001263 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001264
1265 if (log)
1266 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1267
1268 if (control_only)
1269 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1270 else
1271 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1272}
1273
1274bool
1275Process::IsRunning () const
1276{
1277 return StateIsRunningState (m_public_state.GetValue());
1278}
1279
1280int
1281Process::GetExitStatus ()
1282{
1283 if (m_public_state.GetValue() == eStateExited)
1284 return m_exit_status;
1285 return -1;
1286}
1287
Greg Clayton85851dd2010-12-04 00:10:17 +00001288
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001289const char *
1290Process::GetExitDescription ()
1291{
1292 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1293 return m_exit_string.c_str();
1294 return NULL;
1295}
1296
Greg Clayton6779606a2011-01-22 23:43:18 +00001297bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001298Process::SetExitStatus (int status, const char *cstr)
1299{
Greg Clayton414f5d32011-01-25 02:58:48 +00001300 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1301 if (log)
1302 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1303 status, status,
1304 cstr ? "\"" : "",
1305 cstr ? cstr : "NULL",
1306 cstr ? "\"" : "");
1307
Greg Clayton6779606a2011-01-22 23:43:18 +00001308 // We were already in the exited state
1309 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001310 {
Greg Clayton385d6032011-01-26 23:47:29 +00001311 if (log)
1312 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001313 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001314 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001315
1316 m_exit_status = status;
1317 if (cstr)
1318 m_exit_string = cstr;
1319 else
1320 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001321
Greg Clayton6779606a2011-01-22 23:43:18 +00001322 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001323
Greg Clayton6779606a2011-01-22 23:43:18 +00001324 SetPrivateState (eStateExited);
1325 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001326}
1327
1328// This static callback can be used to watch for local child processes on
1329// the current host. The the child process exits, the process will be
1330// found in the global target list (we want to be completely sure that the
1331// lldb_private::Process doesn't go away before we can deliver the signal.
1332bool
Greg Claytone4e45922011-11-16 05:37:56 +00001333Process::SetProcessExitStatus (void *callback_baton,
1334 lldb::pid_t pid,
1335 bool exited,
1336 int signo, // Zero for no signal
1337 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001338)
1339{
Greg Claytone4e45922011-11-16 05:37:56 +00001340 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1341 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00001342 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001343 callback_baton,
1344 pid,
1345 exited,
1346 signo,
1347 exit_status);
1348
1349 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001350 {
Greg Clayton66111032010-06-23 01:19:29 +00001351 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001352 if (target_sp)
1353 {
1354 ProcessSP process_sp (target_sp->GetProcessSP());
1355 if (process_sp)
1356 {
1357 const char *signal_cstr = NULL;
1358 if (signo)
1359 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1360
1361 process_sp->SetExitStatus (exit_status, signal_cstr);
1362 }
1363 }
1364 return true;
1365 }
1366 return false;
1367}
1368
1369
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001370void
1371Process::UpdateThreadListIfNeeded ()
1372{
1373 const uint32_t stop_id = GetStopID();
1374 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1375 {
Greg Clayton2637f822011-11-17 01:23:07 +00001376 const StateType state = GetPrivateState();
1377 if (StateIsStoppedState (state, true))
1378 {
1379 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001380 // m_thread_list does have its own mutex, but we need to
1381 // hold onto the mutex between the call to UpdateThreadList(...)
1382 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton2637f822011-11-17 01:23:07 +00001383 ThreadList new_thread_list(this);
1384 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001385 // thread list, but only update if "true" is returned
1386 if (UpdateThreadList (m_thread_list, new_thread_list))
1387 {
1388 OperatingSystem *os = GetOperatingSystem ();
1389 if (os)
1390 os->UpdateThreadList (m_thread_list, new_thread_list);
1391 m_thread_list.Update (new_thread_list);
1392 m_thread_list.SetStopID (stop_id);
1393 }
Greg Clayton2637f822011-11-17 01:23:07 +00001394 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001395 }
1396}
1397
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001398uint32_t
1399Process::GetNextThreadIndexID ()
1400{
1401 return ++m_thread_index_id;
1402}
1403
1404StateType
1405Process::GetState()
1406{
1407 // If any other threads access this we will need a mutex for it
1408 return m_public_state.GetValue ();
1409}
1410
1411void
1412Process::SetPublicState (StateType new_state)
1413{
Greg Clayton414f5d32011-01-25 02:58:48 +00001414 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001415 if (log)
1416 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001417 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001418 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001419
1420 // On the transition from Run to Stopped, we unlock the writer end of the
1421 // run lock. The lock gets locked in Resume, which is the public API
1422 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001423 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1424 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001425 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001426 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001427 if (log)
1428 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1429 m_run_lock.WriteUnlock();
1430 }
1431 else
1432 {
1433 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1434 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1435 if (old_state_is_stopped != new_state_is_stopped)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001436 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001437 if (new_state_is_stopped)
1438 {
1439 if (log)
1440 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1441 m_run_lock.WriteUnlock();
1442 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001443 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001444 }
1445 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001446}
1447
Jim Ingham3b8285d2012-04-19 01:40:33 +00001448Error
1449Process::Resume ()
1450{
1451 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1452 if (log)
1453 log->Printf("Process::Resume -- locking run lock");
1454 if (!m_run_lock.WriteTryLock())
1455 {
1456 Error error("Resume request failed - process still running.");
1457 if (log)
1458 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1459 return error;
1460 }
1461 return PrivateResume();
1462}
1463
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001464StateType
1465Process::GetPrivateState ()
1466{
1467 return m_private_state.GetValue();
1468}
1469
1470void
1471Process::SetPrivateState (StateType new_state)
1472{
Greg Clayton414f5d32011-01-25 02:58:48 +00001473 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001474 bool state_changed = false;
1475
1476 if (log)
1477 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1478
1479 Mutex::Locker locker(m_private_state.GetMutex());
1480
1481 const StateType old_state = m_private_state.GetValueNoLock ();
1482 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001483 // This code is left commented out in case we ever need to control
1484 // the private process state with another run lock. Right now it doesn't
1485 // seem like we need to do this, but if we ever do, we can uncomment and
1486 // use this code.
1487// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1488// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1489// if (old_state_is_stopped != new_state_is_stopped)
1490// {
1491// if (new_state_is_stopped)
1492// m_private_run_lock.WriteUnlock();
1493// else
1494// m_private_run_lock.WriteLock();
1495// }
1496
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001497 if (state_changed)
1498 {
1499 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001500 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001501 {
Jim Ingham4b536182011-08-09 02:12:22 +00001502 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001503 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001504 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001505 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001506 }
1507 // Use our target to get a shared pointer to ourselves...
1508 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1509 }
1510 else
1511 {
1512 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001513 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001514 }
1515}
1516
Jim Ingham0faa43f2011-11-08 03:00:11 +00001517void
1518Process::SetRunningUserExpression (bool on)
1519{
1520 m_mod_id.SetRunningUserExpression (on);
1521}
1522
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001523addr_t
1524Process::GetImageInfoAddress()
1525{
1526 return LLDB_INVALID_ADDRESS;
1527}
1528
Greg Clayton8f343b02010-11-04 01:54:29 +00001529//----------------------------------------------------------------------
1530// LoadImage
1531//
1532// This function provides a default implementation that works for most
1533// unix variants. Any Process subclasses that need to do shared library
1534// loading differently should override LoadImage and UnloadImage and
1535// do what is needed.
1536//----------------------------------------------------------------------
1537uint32_t
1538Process::LoadImage (const FileSpec &image_spec, Error &error)
1539{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001540 char path[PATH_MAX];
1541 image_spec.GetPath(path, sizeof(path));
1542
Greg Clayton8f343b02010-11-04 01:54:29 +00001543 DynamicLoader *loader = GetDynamicLoader();
1544 if (loader)
1545 {
1546 error = loader->CanLoadImage();
1547 if (error.Fail())
1548 return LLDB_INVALID_IMAGE_TOKEN;
1549 }
1550
1551 if (error.Success())
1552 {
1553 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001554
1555 if (thread_sp)
1556 {
1557 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1558
1559 if (frame_sp)
1560 {
1561 ExecutionContext exe_ctx;
1562 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001563 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001564 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001565 expr.Printf("dlopen (\"%s\", 2)", path);
1566 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001567 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001568 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 +00001569 error = result_valobj_sp->GetError();
1570 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001571 {
1572 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001573 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001574 {
1575 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1576 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1577 {
1578 uint32_t image_token = m_image_tokens.size();
1579 m_image_tokens.push_back (image_ptr);
1580 return image_token;
1581 }
1582 }
1583 }
1584 }
1585 }
1586 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001587 if (!error.AsCString())
1588 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001589 return LLDB_INVALID_IMAGE_TOKEN;
1590}
1591
1592//----------------------------------------------------------------------
1593// UnloadImage
1594//
1595// This function provides a default implementation that works for most
1596// unix variants. Any Process subclasses that need to do shared library
1597// loading differently should override LoadImage and UnloadImage and
1598// do what is needed.
1599//----------------------------------------------------------------------
1600Error
1601Process::UnloadImage (uint32_t image_token)
1602{
1603 Error error;
1604 if (image_token < m_image_tokens.size())
1605 {
1606 const addr_t image_addr = m_image_tokens[image_token];
1607 if (image_addr == LLDB_INVALID_ADDRESS)
1608 {
1609 error.SetErrorString("image already unloaded");
1610 }
1611 else
1612 {
1613 DynamicLoader *loader = GetDynamicLoader();
1614 if (loader)
1615 error = loader->CanLoadImage();
1616
1617 if (error.Success())
1618 {
1619 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001620
1621 if (thread_sp)
1622 {
1623 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1624
1625 if (frame_sp)
1626 {
1627 ExecutionContext exe_ctx;
1628 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001629 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001630 StreamString expr;
1631 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1632 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001633 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001634 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 +00001635 if (result_valobj_sp->GetError().Success())
1636 {
1637 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001638 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001639 {
1640 if (scalar.UInt(1))
1641 {
1642 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1643 }
1644 else
1645 {
1646 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1647 }
1648 }
1649 }
1650 else
1651 {
1652 error = result_valobj_sp->GetError();
1653 }
1654 }
1655 }
1656 }
1657 }
1658 }
1659 else
1660 {
1661 error.SetErrorString("invalid image token");
1662 }
1663 return error;
1664}
1665
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001666const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001667Process::GetABI()
1668{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001669 if (!m_abi_sp)
1670 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1671 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001672}
1673
Jim Ingham22777012010-09-23 02:01:19 +00001674LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001675Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001676{
1677 LanguageRuntimeCollection::iterator pos;
1678 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001679 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001680 {
Jim Inghamab175242012-03-10 00:22:19 +00001681 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001682
Jim Inghamab175242012-03-10 00:22:19 +00001683 m_language_runtimes[language] = runtime_sp;
1684 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001685 }
1686 else
1687 return (*pos).second.get();
1688}
1689
1690CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001691Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001692{
Jim Inghamab175242012-03-10 00:22:19 +00001693 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001694 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1695 return static_cast<CPPLanguageRuntime *> (runtime);
1696 return NULL;
1697}
1698
1699ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001700Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001701{
Jim Inghamab175242012-03-10 00:22:19 +00001702 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001703 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1704 return static_cast<ObjCLanguageRuntime *> (runtime);
1705 return NULL;
1706}
1707
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001708bool
1709Process::IsPossibleDynamicValue (ValueObject& in_value)
1710{
1711 if (in_value.IsDynamic())
1712 return false;
1713 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1714
1715 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1716 {
1717 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1718 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1719 }
1720
1721 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1722 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1723 return true;
1724
1725 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1726 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1727}
1728
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001729BreakpointSiteList &
1730Process::GetBreakpointSiteList()
1731{
1732 return m_breakpoint_site_list;
1733}
1734
1735const BreakpointSiteList &
1736Process::GetBreakpointSiteList() const
1737{
1738 return m_breakpoint_site_list;
1739}
1740
1741
1742void
1743Process::DisableAllBreakpointSites ()
1744{
1745 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham43c555d2012-07-04 00:35:43 +00001746 size_t num_sites = m_breakpoint_site_list.GetSize();
1747 for (size_t i = 0; i < num_sites; i++)
1748 {
1749 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1750 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001751}
1752
1753Error
1754Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1755{
1756 Error error (DisableBreakpointSiteByID (break_id));
1757
1758 if (error.Success())
1759 m_breakpoint_site_list.Remove(break_id);
1760
1761 return error;
1762}
1763
1764Error
1765Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1766{
1767 Error error;
1768 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1769 if (bp_site_sp)
1770 {
1771 if (bp_site_sp->IsEnabled())
1772 error = DisableBreakpoint (bp_site_sp.get());
1773 }
1774 else
1775 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001776 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001777 }
1778
1779 return error;
1780}
1781
1782Error
1783Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1784{
1785 Error error;
1786 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1787 if (bp_site_sp)
1788 {
1789 if (!bp_site_sp->IsEnabled())
1790 error = EnableBreakpoint (bp_site_sp.get());
1791 }
1792 else
1793 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001794 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001795 }
1796 return error;
1797}
1798
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001799lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001800Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001801{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001802 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803 if (load_addr != LLDB_INVALID_ADDRESS)
1804 {
1805 BreakpointSiteSP bp_site_sp;
1806
1807 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1808 // create a new breakpoint site and add it.
1809
1810 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1811
1812 if (bp_site_sp)
1813 {
1814 bp_site_sp->AddOwner (owner);
1815 owner->SetBreakpointSite (bp_site_sp);
1816 return bp_site_sp->GetID();
1817 }
1818 else
1819 {
1820 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1821 if (bp_site_sp)
1822 {
1823 if (EnableBreakpoint (bp_site_sp.get()).Success())
1824 {
1825 owner->SetBreakpointSite (bp_site_sp);
1826 return m_breakpoint_site_list.Add (bp_site_sp);
1827 }
1828 }
1829 }
1830 }
1831 // We failed to enable the breakpoint
1832 return LLDB_INVALID_BREAK_ID;
1833
1834}
1835
1836void
1837Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1838{
1839 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1840 if (num_owners == 0)
1841 {
1842 DisableBreakpoint(bp_site_sp.get());
1843 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1844 }
1845}
1846
1847
1848size_t
1849Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1850{
1851 size_t bytes_removed = 0;
1852 addr_t intersect_addr;
1853 size_t intersect_size;
1854 size_t opcode_offset;
1855 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001856 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001857 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001858
Jim Ingham20c77192011-06-29 19:42:28 +00001859 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001860 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001861 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001862 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001863 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001865 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001866 {
1867 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1868 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001869 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001870 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001871 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001872 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001873 }
1874 }
1875 }
1876 return bytes_removed;
1877}
1878
1879
Greg Claytonded470d2011-03-19 01:12:21 +00001880
1881size_t
1882Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1883{
1884 PlatformSP platform_sp (m_target.GetPlatform());
1885 if (platform_sp)
1886 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1887 return 0;
1888}
1889
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001890Error
1891Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1892{
1893 Error error;
1894 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001895 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001896 const addr_t bp_addr = bp_site->GetLoadAddress();
1897 if (log)
1898 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1899 if (bp_site->IsEnabled())
1900 {
1901 if (log)
1902 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1903 return error;
1904 }
1905
1906 if (bp_addr == LLDB_INVALID_ADDRESS)
1907 {
1908 error.SetErrorString("BreakpointSite contains an invalid load address.");
1909 return error;
1910 }
1911 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1912 // trap for the breakpoint site
1913 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1914
1915 if (bp_opcode_size == 0)
1916 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001917 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001918 }
1919 else
1920 {
1921 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1922
1923 if (bp_opcode_bytes == NULL)
1924 {
1925 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1926 return error;
1927 }
1928
1929 // Save the original opcode by reading it
1930 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1931 {
1932 // Write a software breakpoint in place of the original opcode
1933 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1934 {
1935 uint8_t verify_bp_opcode_bytes[64];
1936 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1937 {
1938 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1939 {
1940 bp_site->SetEnabled(true);
1941 bp_site->SetType (BreakpointSite::eSoftware);
1942 if (log)
1943 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1944 bp_site->GetID(),
1945 (uint64_t)bp_addr);
1946 }
1947 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001948 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001949 }
1950 else
1951 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1952 }
1953 else
1954 error.SetErrorString("Unable to write breakpoint trap to memory.");
1955 }
1956 else
1957 error.SetErrorString("Unable to read memory at breakpoint address.");
1958 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001959 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001960 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1961 bp_site->GetID(),
1962 (uint64_t)bp_addr,
1963 error.AsCString());
1964 return error;
1965}
1966
1967Error
1968Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1969{
1970 Error error;
1971 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001972 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001973 addr_t bp_addr = bp_site->GetLoadAddress();
1974 lldb::user_id_t breakID = bp_site->GetID();
1975 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001976 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001977
1978 if (bp_site->IsHardware())
1979 {
1980 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1981 }
1982 else if (bp_site->IsEnabled())
1983 {
1984 const size_t break_op_size = bp_site->GetByteSize();
1985 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1986 if (break_op_size > 0)
1987 {
1988 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001989 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001990 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001991 bool break_op_found = false;
1992
1993 // Read the breakpoint opcode
1994 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1995 {
1996 bool verify = false;
1997 // Make sure we have the a breakpoint opcode exists at this address
1998 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1999 {
2000 break_op_found = true;
2001 // We found a valid breakpoint opcode at this address, now restore
2002 // the saved opcode.
2003 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
2004 {
2005 verify = true;
2006 }
2007 else
2008 error.SetErrorString("Memory write failed when restoring original opcode.");
2009 }
2010 else
2011 {
2012 error.SetErrorString("Original breakpoint trap is no longer in memory.");
2013 // Set verify to true and so we can check if the original opcode has already been restored
2014 verify = true;
2015 }
2016
2017 if (verify)
2018 {
Greg Claytonc982c762010-07-09 20:39:50 +00002019 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00002020 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002021 // Verify that our original opcode made it back to the inferior
2022 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
2023 {
2024 // compare the memory we just read with the original opcode
2025 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
2026 {
2027 // SUCCESS
2028 bp_site->SetEnabled(false);
2029 if (log)
2030 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
2031 return error;
2032 }
2033 else
2034 {
2035 if (break_op_found)
2036 error.SetErrorString("Failed to restore original opcode.");
2037 }
2038 }
2039 else
2040 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
2041 }
2042 }
2043 else
2044 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
2045 }
2046 }
2047 else
2048 {
2049 if (log)
2050 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
2051 return error;
2052 }
2053
2054 if (log)
2055 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
2056 bp_site->GetID(),
2057 (uint64_t)bp_addr,
2058 error.AsCString());
2059 return error;
2060
2061}
2062
Greg Clayton58be07b2011-01-07 06:08:19 +00002063// Uncomment to verify memory caching works after making changes to caching code
2064//#define VERIFY_MEMORY_READS
2065
Sean Callanan64c0cf22012-06-07 22:26:42 +00002066size_t
2067Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2068{
2069 if (!GetDisableMemoryCache())
2070 {
Greg Clayton58be07b2011-01-07 06:08:19 +00002071#if defined (VERIFY_MEMORY_READS)
Sean Callanan64c0cf22012-06-07 22:26:42 +00002072 // Memory caching is enabled, with debug verification
2073
2074 if (buf && size)
2075 {
2076 // Uncomment the line below to make sure memory caching is working.
2077 // I ran this through the test suite and got no assertions, so I am
2078 // pretty confident this is working well. If any changes are made to
2079 // memory caching, uncomment the line below and test your changes!
2080
2081 // Verify all memory reads by using the cache first, then redundantly
2082 // reading the same memory from the inferior and comparing to make sure
2083 // everything is exactly the same.
2084 std::string verify_buf (size, '\0');
2085 assert (verify_buf.size() == size);
2086 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
2087 Error verify_error;
2088 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
2089 assert (cache_bytes_read == verify_bytes_read);
2090 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2091 assert (verify_error.Success() == error.Success());
2092 return cache_bytes_read;
2093 }
2094 return 0;
2095#else // !defined(VERIFY_MEMORY_READS)
2096 // Memory caching is enabled, without debug verification
2097
2098 return m_memory_cache.Read (addr, buf, size, error);
2099#endif // defined (VERIFY_MEMORY_READS)
Greg Clayton58be07b2011-01-07 06:08:19 +00002100 }
Sean Callanan64c0cf22012-06-07 22:26:42 +00002101 else
2102 {
2103 // Memory caching is disabled
2104
2105 return ReadMemoryFromInferior (addr, buf, size, error);
2106 }
Greg Clayton58be07b2011-01-07 06:08:19 +00002107}
Greg Clayton58be07b2011-01-07 06:08:19 +00002108
Greg Clayton4c82d422012-05-18 23:20:01 +00002109size_t
2110Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
2111{
Greg Claytonde87c0f2012-05-19 00:18:00 +00002112 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00002113 out_str.clear();
2114 addr_t curr_addr = addr;
2115 while (1)
2116 {
2117 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2118 if (length == 0)
2119 break;
2120 out_str.append(buf, length);
2121 // If we got "length - 1" bytes, we didn't get the whole C string, we
2122 // need to read some more characters
2123 if (length == sizeof(buf) - 1)
2124 curr_addr += length;
2125 else
2126 break;
2127 }
2128 return out_str.size();
2129}
2130
Greg Clayton58be07b2011-01-07 06:08:19 +00002131
2132size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002133Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002134{
2135 size_t total_cstr_len = 0;
2136 if (dst && dst_max_len)
2137 {
Greg Claytone91b7952011-12-15 03:14:23 +00002138 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002139 // NULL out everything just to be safe
2140 memset (dst, 0, dst_max_len);
2141 Error error;
2142 addr_t curr_addr = addr;
2143 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2144 size_t bytes_left = dst_max_len - 1;
2145 char *curr_dst = dst;
2146
2147 while (bytes_left > 0)
2148 {
2149 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2150 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2151 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2152
2153 if (bytes_read == 0)
2154 {
Greg Claytone91b7952011-12-15 03:14:23 +00002155 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002156 dst[total_cstr_len] = '\0';
2157 break;
2158 }
2159 const size_t len = strlen(curr_dst);
2160
2161 total_cstr_len += len;
2162
2163 if (len < bytes_to_read)
2164 break;
2165
2166 curr_dst += bytes_read;
2167 curr_addr += bytes_read;
2168 bytes_left -= bytes_read;
2169 }
2170 }
Greg Claytone91b7952011-12-15 03:14:23 +00002171 else
2172 {
2173 if (dst == NULL)
2174 result_error.SetErrorString("invalid arguments");
2175 else
2176 result_error.Clear();
2177 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002178 return total_cstr_len;
2179}
2180
2181size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002182Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2183{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002184 if (buf == NULL || size == 0)
2185 return 0;
2186
2187 size_t bytes_read = 0;
2188 uint8_t *bytes = (uint8_t *)buf;
2189
2190 while (bytes_read < size)
2191 {
2192 const size_t curr_size = size - bytes_read;
2193 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2194 bytes + bytes_read,
2195 curr_size,
2196 error);
2197 bytes_read += curr_bytes_read;
2198 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2199 break;
2200 }
2201
2202 // Replace any software breakpoint opcodes that fall into this range back
2203 // into "buf" before we return
2204 if (bytes_read > 0)
2205 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2206 return bytes_read;
2207}
2208
Greg Clayton58a4c462010-12-16 20:01:20 +00002209uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002210Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002211{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002212 Scalar scalar;
2213 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2214 return scalar.ULongLong(fail_value);
2215 return fail_value;
2216}
2217
2218addr_t
2219Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2220{
2221 Scalar scalar;
2222 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2223 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2224 return LLDB_INVALID_ADDRESS;
2225}
2226
2227
2228bool
2229Process::WritePointerToMemory (lldb::addr_t vm_addr,
2230 lldb::addr_t ptr_value,
2231 Error &error)
2232{
2233 Scalar scalar;
2234 const uint32_t addr_byte_size = GetAddressByteSize();
2235 if (addr_byte_size <= 4)
2236 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002237 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002238 scalar = ptr_value;
2239 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002240}
2241
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002242size_t
2243Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2244{
2245 size_t bytes_written = 0;
2246 const uint8_t *bytes = (const uint8_t *)buf;
2247
2248 while (bytes_written < size)
2249 {
2250 const size_t curr_size = size - bytes_written;
2251 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2252 bytes + bytes_written,
2253 curr_size,
2254 error);
2255 bytes_written += curr_bytes_written;
2256 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2257 break;
2258 }
2259 return bytes_written;
2260}
2261
2262size_t
2263Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2264{
Greg Clayton58be07b2011-01-07 06:08:19 +00002265#if defined (ENABLE_MEMORY_CACHING)
2266 m_memory_cache.Flush (addr, size);
2267#endif
2268
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002269 if (buf == NULL || size == 0)
2270 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002271
Jim Ingham4b536182011-08-09 02:12:22 +00002272 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002273
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002274 // We need to write any data that would go where any current software traps
2275 // (enabled software breakpoints) any software traps (breakpoints) that we
2276 // may have placed in our tasks memory.
2277
2278 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2279 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2280
2281 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002282 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283
2284 BreakpointSiteList::collection::const_iterator pos;
2285 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002286 addr_t intersect_addr = 0;
2287 size_t intersect_size = 0;
2288 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002289 const uint8_t *ubuf = (const uint8_t *)buf;
2290
2291 for (pos = iter; pos != end; ++pos)
2292 {
2293 BreakpointSiteSP bp;
2294 bp = pos->second;
2295
2296 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2297 assert(addr <= intersect_addr && intersect_addr < addr + size);
2298 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2299 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2300
2301 // Check for bytes before this breakpoint
2302 const addr_t curr_addr = addr + bytes_written;
2303 if (intersect_addr > curr_addr)
2304 {
2305 // There are some bytes before this breakpoint that we need to
2306 // just write to memory
2307 size_t curr_size = intersect_addr - curr_addr;
2308 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2309 ubuf + bytes_written,
2310 curr_size,
2311 error);
2312 bytes_written += curr_bytes_written;
2313 if (curr_bytes_written != curr_size)
2314 {
2315 // We weren't able to write all of the requested bytes, we
2316 // are done looping and will return the number of bytes that
2317 // we have written so far.
2318 break;
2319 }
2320 }
2321
2322 // Now write any bytes that would cover up any software breakpoints
2323 // directly into the breakpoint opcode buffer
2324 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2325 bytes_written += intersect_size;
2326 }
2327
2328 // Write any remaining bytes after the last breakpoint if we have any left
2329 if (bytes_written < size)
2330 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2331 ubuf + bytes_written,
2332 size - bytes_written,
2333 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002334
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002335 return bytes_written;
2336}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002337
2338size_t
2339Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2340{
2341 if (byte_size == UINT32_MAX)
2342 byte_size = scalar.GetByteSize();
2343 if (byte_size > 0)
2344 {
2345 uint8_t buf[32];
2346 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2347 if (mem_size > 0)
2348 return WriteMemory(addr, buf, mem_size, error);
2349 else
2350 error.SetErrorString ("failed to get scalar as memory data");
2351 }
2352 else
2353 {
2354 error.SetErrorString ("invalid scalar value");
2355 }
2356 return 0;
2357}
2358
2359size_t
2360Process::ReadScalarIntegerFromMemory (addr_t addr,
2361 uint32_t byte_size,
2362 bool is_signed,
2363 Scalar &scalar,
2364 Error &error)
2365{
2366 uint64_t uval;
2367
2368 if (byte_size <= sizeof(uval))
2369 {
2370 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2371 if (bytes_read == byte_size)
2372 {
2373 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2374 uint32_t offset = 0;
2375 if (byte_size <= 4)
2376 scalar = data.GetMaxU32 (&offset, byte_size);
2377 else
2378 scalar = data.GetMaxU64 (&offset, byte_size);
2379
2380 if (is_signed)
2381 scalar.SignExtend(byte_size * 8);
2382 return bytes_read;
2383 }
2384 }
2385 else
2386 {
2387 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2388 }
2389 return 0;
2390}
2391
Greg Claytond495c532011-05-17 03:37:42 +00002392#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002393addr_t
2394Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2395{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002396 if (GetPrivateState() != eStateStopped)
2397 return LLDB_INVALID_ADDRESS;
2398
Greg Claytond495c532011-05-17 03:37:42 +00002399#if defined (USE_ALLOCATE_MEMORY_CACHE)
2400 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2401#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002402 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2403 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2404 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002405 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 +00002406 size,
Greg Claytond495c532011-05-17 03:37:42 +00002407 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002408 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002409 m_mod_id.GetStopID(),
2410 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002411 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002412#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413}
2414
Sean Callanan90539452011-09-20 23:01:51 +00002415bool
2416Process::CanJIT ()
2417{
Sean Callanana7b443a2012-02-14 22:50:38 +00002418 if (m_can_jit == eCanJITDontKnow)
2419 {
2420 Error err;
2421
2422 uint64_t allocated_memory = AllocateMemory(8,
2423 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2424 err);
2425
2426 if (err.Success())
2427 m_can_jit = eCanJITYes;
2428 else
2429 m_can_jit = eCanJITNo;
2430
2431 DeallocateMemory (allocated_memory);
2432 }
2433
Sean Callanan90539452011-09-20 23:01:51 +00002434 return m_can_jit == eCanJITYes;
2435}
2436
2437void
2438Process::SetCanJIT (bool can_jit)
2439{
2440 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2441}
2442
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002443Error
2444Process::DeallocateMemory (addr_t ptr)
2445{
Greg Claytond495c532011-05-17 03:37:42 +00002446 Error error;
2447#if defined (USE_ALLOCATE_MEMORY_CACHE)
2448 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2449 {
2450 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2451 }
2452#else
2453 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002454
2455 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2456 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002457 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 +00002458 ptr,
2459 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002460 m_mod_id.GetStopID(),
2461 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002462#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002463 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002464}
2465
Greg Claytonc9660542012-02-05 02:38:54 +00002466ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002467Process::ReadModuleFromMemory (const FileSpec& file_spec,
2468 lldb::addr_t header_addr,
2469 bool add_image_to_target,
2470 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002471{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002472 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002473 if (module_sp)
2474 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002475 Error error;
2476 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2477 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002478 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002479 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002480 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002481 m_target.GetImages().Append(module_sp);
2482 if (load_sections_in_target)
2483 {
2484 bool changed = false;
2485 module_sp->SetLoadAddress (m_target, 0, changed);
2486 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002487 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002488 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002489 }
Greg Claytonc9660542012-02-05 02:38:54 +00002490 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002491 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002492}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002493
2494Error
Johnny Chen01a67862011-10-14 00:42:25 +00002495Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002496{
2497 Error error;
2498 error.SetErrorString("watchpoints are not supported");
2499 return error;
2500}
2501
2502Error
Johnny Chen01a67862011-10-14 00:42:25 +00002503Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002504{
2505 Error error;
2506 error.SetErrorString("watchpoints are not supported");
2507 return error;
2508}
2509
2510StateType
2511Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2512{
2513 StateType state;
2514 // Now wait for the process to launch and return control to us, and then
2515 // call DidLaunch:
2516 while (1)
2517 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002518 event_sp.reset();
2519 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2520
Greg Clayton2637f822011-11-17 01:23:07 +00002521 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002522 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002523
2524 // If state is invalid, then we timed out
2525 if (state == eStateInvalid)
2526 break;
2527
2528 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002529 HandlePrivateEvent (event_sp);
2530 }
2531 return state;
2532}
2533
2534Error
Greg Clayton982c9762011-11-03 21:22:33 +00002535Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002536{
2537 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002538 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002539 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002540 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002541 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002542
Greg Claytonaa149cb2011-08-11 02:48:45 +00002543 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002544 if (exe_module)
2545 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002546 char local_exec_file_path[PATH_MAX];
2547 char platform_exec_file_path[PATH_MAX];
2548 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2549 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002550 if (exe_module->GetFileSpec().Exists())
2551 {
Greg Clayton71337622011-02-24 22:24:29 +00002552 if (PrivateStateThreadIsValid ())
2553 PausePrivateStateThread ();
2554
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002555 error = WillLaunch (exe_module);
2556 if (error.Success())
2557 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002558 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002559 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002560
2561 // Now launch using these arguments.
Greg Clayton982c9762011-11-03 21:22:33 +00002562 error = DoLaunch (exe_module, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002563
2564 if (error.Fail())
2565 {
2566 if (GetID() != LLDB_INVALID_PROCESS_ID)
2567 {
2568 SetID (LLDB_INVALID_PROCESS_ID);
2569 const char *error_string = error.AsCString();
2570 if (error_string == NULL)
2571 error_string = "launch failed";
2572 SetExitStatus (-1, error_string);
2573 }
2574 }
2575 else
2576 {
2577 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002578 TimeValue timeout_time;
2579 timeout_time = TimeValue::Now();
2580 timeout_time.OffsetWithSeconds(10);
2581 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002582
Greg Clayton1a38ea72011-06-22 01:42:17 +00002583 if (state == eStateInvalid || event_sp.get() == NULL)
2584 {
2585 // We were able to launch the process, but we failed to
2586 // catch the initial stop.
2587 SetExitStatus (0, "failed to catch stop after launch");
2588 Destroy();
2589 }
2590 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002591 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002592
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002593 DidLaunch ();
2594
Greg Claytonc859e2d2012-02-13 23:10:39 +00002595 DynamicLoader *dyld = GetDynamicLoader ();
2596 if (dyld)
2597 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002598
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002599 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002600 // This delays passing the stopped event to listeners till DidLaunch gets
2601 // a chance to complete...
2602 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002603
2604 if (PrivateStateThreadIsValid ())
2605 ResumePrivateStateThread ();
2606 else
2607 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002608 }
2609 else if (state == eStateExited)
2610 {
2611 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2612 // not likely to work, and return an invalid pid.
2613 HandlePrivateEvent (event_sp);
2614 }
2615 }
2616 }
2617 }
2618 else
2619 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002620 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002621 }
2622 }
2623 return error;
2624}
2625
Greg Claytonc3776bf2012-02-09 06:16:32 +00002626
2627Error
2628Process::LoadCore ()
2629{
2630 Error error = DoLoadCore();
2631 if (error.Success())
2632 {
2633 if (PrivateStateThreadIsValid ())
2634 ResumePrivateStateThread ();
2635 else
2636 StartPrivateStateThread ();
2637
Greg Claytonc859e2d2012-02-13 23:10:39 +00002638 DynamicLoader *dyld = GetDynamicLoader ();
2639 if (dyld)
2640 dyld->DidAttach();
2641
2642 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002643 // We successfully loaded a core file, now pretend we stopped so we can
2644 // show all of the threads in the core file and explore the crashed
2645 // state.
2646 SetPrivateState (eStateStopped);
2647
2648 }
2649 return error;
2650}
2651
Greg Claytonc859e2d2012-02-13 23:10:39 +00002652DynamicLoader *
2653Process::GetDynamicLoader ()
2654{
2655 if (m_dyld_ap.get() == NULL)
2656 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2657 return m_dyld_ap.get();
2658}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002659
2660
Jim Inghambb3a2832011-01-29 01:49:25 +00002661Process::NextEventAction::EventActionResult
2662Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002663{
Jim Inghambb3a2832011-01-29 01:49:25 +00002664 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2665 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002666 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002667 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002668 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002669 return eEventActionRetry;
2670
2671 case eStateStopped:
2672 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002673 {
2674 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002675 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002676 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2677 if (m_exec_count > 0)
2678 {
2679 --m_exec_count;
Jim Ingham3b8285d2012-04-19 01:40:33 +00002680 m_process->PrivateResume ();
Jim Ingham04e0a222012-05-23 15:46:31 +00002681 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Claytonc9ed4782011-11-12 02:10:56 +00002682 return eEventActionRetry;
2683 }
2684 else
2685 {
2686 m_process->CompleteAttach ();
2687 return eEventActionSuccess;
2688 }
2689 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002690 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002691
Greg Clayton513c26c2011-01-29 07:10:55 +00002692 default:
2693 case eStateExited:
2694 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002695 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002696 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002697
2698 m_exit_string.assign ("No valid Process");
2699 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002700}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002701
Jim Inghambb3a2832011-01-29 01:49:25 +00002702Process::NextEventAction::EventActionResult
2703Process::AttachCompletionHandler::HandleBeingInterrupted()
2704{
2705 return eEventActionSuccess;
2706}
2707
2708const char *
2709Process::AttachCompletionHandler::GetExitString ()
2710{
2711 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712}
2713
2714Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002715Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002716{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002718 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002719 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002720 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002721
Greg Clayton144f3a92011-11-15 03:53:30 +00002722 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002723 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002724 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002725 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002726 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002727
Greg Clayton144f3a92011-11-15 03:53:30 +00002728 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002729 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002730 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2731
2732 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002733 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002734 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2735 if (error.Success())
2736 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002737 m_should_detach = true;
2738
Greg Clayton144f3a92011-11-15 03:53:30 +00002739 SetPublicState (eStateAttaching);
Han Ming Ong84647042012-02-25 01:07:38 +00002740 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002741 if (error.Fail())
2742 {
2743 if (GetID() != LLDB_INVALID_PROCESS_ID)
2744 {
2745 SetID (LLDB_INVALID_PROCESS_ID);
2746 if (error.AsCString() == NULL)
2747 error.SetErrorString("attach failed");
2748
2749 SetExitStatus(-1, error.AsCString());
2750 }
2751 }
2752 else
2753 {
2754 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2755 StartPrivateStateThread();
2756 }
2757 return error;
2758 }
Greg Claytone996fd32011-03-08 22:40:15 +00002759 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002760 else
Greg Claytone996fd32011-03-08 22:40:15 +00002761 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002762 ProcessInstanceInfoList process_infos;
2763 PlatformSP platform_sp (m_target.GetPlatform ());
2764
2765 if (platform_sp)
2766 {
2767 ProcessInstanceInfoMatch match_info;
2768 match_info.GetProcessInfo() = attach_info;
2769 match_info.SetNameMatchType (eNameMatchEquals);
2770 platform_sp->FindProcesses (match_info, process_infos);
2771 const uint32_t num_matches = process_infos.GetSize();
2772 if (num_matches == 1)
2773 {
2774 attach_pid = process_infos.GetProcessIDAtIndex(0);
2775 // Fall through and attach using the above process ID
2776 }
2777 else
2778 {
2779 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2780 if (num_matches > 1)
2781 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2782 else
2783 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2784 }
2785 }
2786 else
2787 {
2788 error.SetErrorString ("invalid platform, can't find processes by name");
2789 return error;
2790 }
Greg Claytone996fd32011-03-08 22:40:15 +00002791 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002792 }
2793 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002794 {
2795 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002796 }
2797 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002798
2799 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002800 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002801 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002802 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002803 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002804 m_should_detach = true;
Greg Claytone996fd32011-03-08 22:40:15 +00002805 SetPublicState (eStateAttaching);
Greg Clayton144f3a92011-11-15 03:53:30 +00002806
Han Ming Ong84647042012-02-25 01:07:38 +00002807 error = DoAttachToProcessWithID (attach_pid, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002808 if (error.Success())
2809 {
2810
2811 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2812 StartPrivateStateThread();
2813 }
2814 else
Greg Claytone996fd32011-03-08 22:40:15 +00002815 {
2816 if (GetID() != LLDB_INVALID_PROCESS_ID)
2817 {
2818 SetID (LLDB_INVALID_PROCESS_ID);
2819 const char *error_string = error.AsCString();
2820 if (error_string == NULL)
2821 error_string = "attach failed";
2822
2823 SetExitStatus(-1, error_string);
2824 }
2825 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002826 }
2827 }
2828 return error;
2829}
2830
Greg Clayton93d3c8332011-02-16 04:46:07 +00002831void
2832Process::CompleteAttach ()
2833{
2834 // Let the process subclass figure out at much as it can about the process
2835 // before we go looking for a dynamic loader plug-in.
2836 DidAttach();
2837
Jim Ingham4299fdb2011-09-15 01:10:17 +00002838 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2839 // the same as the one we've already set, switch architectures.
2840 PlatformSP platform_sp (m_target.GetPlatform ());
2841 assert (platform_sp.get());
2842 if (platform_sp)
2843 {
Greg Clayton70512312012-05-08 01:45:38 +00002844 const ArchSpec &target_arch = m_target.GetArchitecture();
2845 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2846 {
2847 ArchSpec platform_arch;
2848 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2849 if (platform_sp)
2850 {
2851 m_target.SetPlatform (platform_sp);
2852 m_target.SetArchitecture(platform_arch);
2853 }
2854 }
2855 else
2856 {
2857 ProcessInstanceInfo process_info;
2858 platform_sp->GetProcessInfo (GetID(), process_info);
2859 const ArchSpec &process_arch = process_info.GetArchitecture();
2860 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2861 m_target.SetArchitecture (process_arch);
2862 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00002863 }
2864
2865 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002866 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002867 DynamicLoader *dyld = GetDynamicLoader ();
2868 if (dyld)
2869 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002870
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002871 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002872 // Figure out which one is the executable, and set that in our target:
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002873 ModuleList &target_modules = m_target.GetImages();
2874 Mutex::Locker modules_locker(target_modules.GetMutex());
2875 size_t num_modules = target_modules.GetSize();
2876 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002877
Greg Clayton93d3c8332011-02-16 04:46:07 +00002878 for (int i = 0; i < num_modules; i++)
2879 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002880 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002881 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002882 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002883 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002884 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002885 break;
2886 }
2887 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002888 if (new_executable_module_sp)
2889 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00002890}
2891
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002892Error
Greg Claytonb766a732011-02-04 01:58:07 +00002893Process::ConnectRemote (const char *remote_url)
2894{
Greg Claytonb766a732011-02-04 01:58:07 +00002895 m_abi_sp.reset();
2896 m_process_input_reader.reset();
2897
2898 // Find the process and its architecture. Make sure it matches the architecture
2899 // of the current Target, and if not adjust it.
2900
2901 Error error (DoConnectRemote (remote_url));
2902 if (error.Success())
2903 {
Greg Clayton71337622011-02-24 22:24:29 +00002904 if (GetID() != LLDB_INVALID_PROCESS_ID)
2905 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002906 EventSP event_sp;
2907 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2908
2909 if (state == eStateStopped || state == eStateCrashed)
2910 {
2911 // If we attached and actually have a process on the other end, then
2912 // this ended up being the equivalent of an attach.
2913 CompleteAttach ();
2914
2915 // This delays passing the stopped event to listeners till
2916 // CompleteAttach gets a chance to complete...
2917 HandlePrivateEvent (event_sp);
2918
2919 }
Greg Clayton71337622011-02-24 22:24:29 +00002920 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002921
2922 if (PrivateStateThreadIsValid ())
2923 ResumePrivateStateThread ();
2924 else
2925 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002926 }
2927 return error;
2928}
2929
2930
2931Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00002932Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002933{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002934 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002935 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002936 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002937 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002938 StateAsCString(m_public_state.GetValue()),
2939 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002940
2941 Error error (WillResume());
2942 // Tell the process it is about to resume before the thread list
2943 if (error.Success())
2944 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002945 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946 // can let all of our threads know that they are about to be
2947 // resumed. Threads will each be called with
2948 // Thread::WillResume(StateType) where StateType contains the state
2949 // that they are supposed to have when the process is resumed
2950 // (suspended/running/stepping). Threads should also check
2951 // their resume signal in lldb::Thread::GetResumeSignal()
2952 // to see if they are suppoed to start back up with a signal.
2953 if (m_thread_list.WillResume())
2954 {
Jim Ingham372787f2012-04-07 00:00:41 +00002955 // Last thing, do the PreResumeActions.
2956 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002957 {
Jim Ingham372787f2012-04-07 00:00:41 +00002958 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
2959 }
2960 else
2961 {
2962 m_mod_id.BumpResumeID();
2963 error = DoResume();
2964 if (error.Success())
2965 {
2966 DidResume();
2967 m_thread_list.DidResume();
2968 if (log)
2969 log->Printf ("Process thinks the process has resumed.");
2970 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002971 }
2972 }
2973 else
2974 {
Jim Ingham444586b2011-01-24 06:34:17 +00002975 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002976 }
2977 }
Jim Ingham444586b2011-01-24 06:34:17 +00002978 else if (log)
2979 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002980 return error;
2981}
2982
2983Error
2984Process::Halt ()
2985{
Jim Inghamaacc3182012-06-06 00:29:30 +00002986 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
2987 // we could just straightaway get another event. It just narrows the window...
2988 m_currently_handling_event.WaitForValueEqualTo(false);
2989
2990
Jim Inghambb3a2832011-01-29 01:49:25 +00002991 // Pause our private state thread so we can ensure no one else eats
2992 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002993 Listener halt_listener ("lldb.process.halt_listener");
2994 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002995
Jim Inghambb3a2832011-01-29 01:49:25 +00002996 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002997 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002998
Greg Clayton513c26c2011-01-29 07:10:55 +00002999 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00003000 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003001
Greg Clayton513c26c2011-01-29 07:10:55 +00003002 bool caused_stop = false;
3003
3004 // Ask the process subclass to actually halt our process
3005 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003006 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003007 {
Greg Clayton513c26c2011-01-29 07:10:55 +00003008 if (m_public_state.GetValue() == eStateAttaching)
3009 {
3010 SetExitStatus(SIGKILL, "Cancelled async attach.");
3011 Destroy ();
3012 }
3013 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003014 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003015 // If "caused_stop" is true, then DoHalt stopped the process. If
3016 // "caused_stop" is false, the process was already stopped.
3017 // If the DoHalt caused the process to stop, then we want to catch
3018 // this event and set the interrupted bool to true before we pass
3019 // this along so clients know that the process was interrupted by
3020 // a halt command.
3021 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003022 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003023 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00003024 TimeValue timeout_time;
3025 timeout_time = TimeValue::Now();
3026 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00003027 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
3028 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003029
Jim Ingham0f16e732011-02-08 05:20:59 +00003030 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00003031 {
Jim Inghambb3a2832011-01-29 01:49:25 +00003032 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00003033 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00003034 }
3035 else
3036 {
Greg Clayton2637f822011-11-17 01:23:07 +00003037 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00003038 {
3039 // We caused the process to interrupt itself, so mark this
3040 // as such in the stop event so clients can tell an interrupted
3041 // process from a natural stop
3042 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
3043 }
3044 else
3045 {
3046 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3047 if (log)
3048 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
3049 error.SetErrorString ("Did not get stopped event after halt.");
3050 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00003051 }
3052 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003053 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003054 }
3055 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003056 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003057 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003058 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003059
3060 // Post any event we might have consumed. If all goes well, we will have
3061 // stopped the process, intercepted the event and set the interrupted
3062 // bool in the event. Post it to the private event queue and that will end up
3063 // correctly setting the state.
3064 if (event_sp)
3065 m_private_state_broadcaster.BroadcastEvent(event_sp);
3066
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003067 return error;
3068}
3069
3070Error
3071Process::Detach ()
3072{
3073 Error error (WillDetach());
3074
3075 if (error.Success())
3076 {
3077 DisableAllBreakpointSites();
3078 error = DoDetach();
3079 if (error.Success())
3080 {
3081 DidDetach();
3082 StopPrivateStateThread();
3083 }
3084 }
3085 return error;
3086}
3087
3088Error
3089Process::Destroy ()
3090{
3091 Error error (WillDestroy());
3092 if (error.Success())
3093 {
Jim Ingham04e0a222012-05-23 15:46:31 +00003094 if (m_public_state.GetValue() == eStateRunning)
3095 {
Jim Inghamaacc3182012-06-06 00:29:30 +00003096 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TEMPORARY));
3097 if (log)
3098 log->Printf("Process::Destroy() About to halt.");
Jim Ingham04e0a222012-05-23 15:46:31 +00003099 error = Halt();
3100 if (error.Success())
3101 {
3102 // Consume the halt event.
3103 EventSP stop_event;
3104 TimeValue timeout (TimeValue::Now());
Jim Inghamaacc3182012-06-06 00:29:30 +00003105 timeout.OffsetWithSeconds(1);
Jim Ingham04e0a222012-05-23 15:46:31 +00003106 StateType state = WaitForProcessToStop (&timeout);
3107 if (state != eStateStopped)
3108 {
Jim Inghamaacc3182012-06-06 00:29:30 +00003109 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TEMPORARY));
Jim Ingham04e0a222012-05-23 15:46:31 +00003110 if (log)
3111 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Inghamaacc3182012-06-06 00:29:30 +00003112 // If we really couldn't stop the process then we should just error out here, but if the
3113 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3114 StateType private_state = m_private_state.GetValue();
3115 if (private_state != eStateStopped && private_state != eStateExited)
3116 {
3117 return error;
3118 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003119 }
3120 }
3121 else
3122 {
Jim Inghamaacc3182012-06-06 00:29:30 +00003123 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TEMPORARY));
Jim Ingham04e0a222012-05-23 15:46:31 +00003124 if (log)
3125 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
Jim Inghamaacc3182012-06-06 00:29:30 +00003126 return error;
Jim Ingham04e0a222012-05-23 15:46:31 +00003127 }
3128 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003129
3130 if (m_public_state.GetValue() != eStateRunning)
3131 {
3132 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3133 // kill it, we don't want it hitting a breakpoint...
3134 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3135 // we're not going to have much luck doing this now.
3136 m_thread_list.DiscardThreadPlans();
3137 DisableAllBreakpointSites();
3138 }
Jim Ingham04e0a222012-05-23 15:46:31 +00003139
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003140 error = DoDestroy();
3141 if (error.Success())
3142 {
3143 DidDestroy();
3144 StopPrivateStateThread();
3145 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003146 m_stdio_communication.StopReadThread();
3147 m_stdio_communication.Disconnect();
3148 if (m_process_input_reader && m_process_input_reader->IsActive())
3149 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3150 if (m_process_input_reader)
3151 m_process_input_reader.reset();
Jim Inghamb1e2e842012-04-12 18:49:31 +00003152
3153 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3154 // the last events through the event system, in which case we might strand the write lock. Unlock
3155 // it here so when we do to tear down the process we don't get an error destroying the lock.
3156 m_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003157 }
3158 return error;
3159}
3160
3161Error
3162Process::Signal (int signal)
3163{
3164 Error error (WillSignal());
3165 if (error.Success())
3166 {
3167 error = DoSignal(signal);
3168 if (error.Success())
3169 DidSignal();
3170 }
3171 return error;
3172}
3173
Greg Clayton514487e2011-02-15 21:59:32 +00003174lldb::ByteOrder
3175Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003176{
Greg Clayton514487e2011-02-15 21:59:32 +00003177 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003178}
3179
3180uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003181Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003182{
Greg Clayton514487e2011-02-15 21:59:32 +00003183 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003184}
3185
Greg Clayton514487e2011-02-15 21:59:32 +00003186
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187bool
3188Process::ShouldBroadcastEvent (Event *event_ptr)
3189{
3190 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3191 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003192 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003193
3194 switch (state)
3195 {
Greg Claytonb766a732011-02-04 01:58:07 +00003196 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003197 case eStateAttaching:
3198 case eStateLaunching:
3199 case eStateDetached:
3200 case eStateExited:
3201 case eStateUnloaded:
3202 // These events indicate changes in the state of the debugging session, always report them.
3203 return_value = true;
3204 break;
3205 case eStateInvalid:
3206 // We stopped for no apparent reason, don't report it.
3207 return_value = false;
3208 break;
3209 case eStateRunning:
3210 case eStateStepping:
3211 // If we've started the target running, we handle the cases where we
3212 // are already running and where there is a transition from stopped to
3213 // running differently.
3214 // running -> running: Automatically suppress extra running events
3215 // stopped -> running: Report except when there is one or more no votes
3216 // and no yes votes.
3217 SynchronouslyNotifyStateChanged (state);
3218 switch (m_public_state.GetValue())
3219 {
3220 case eStateRunning:
3221 case eStateStepping:
3222 // We always suppress multiple runnings with no PUBLIC stop in between.
3223 return_value = false;
3224 break;
3225 default:
3226 // TODO: make this work correctly. For now always report
3227 // run if we aren't running so we don't miss any runnning
3228 // events. If I run the lldb/test/thread/a.out file and
3229 // break at main.cpp:58, run and hit the breakpoints on
3230 // multiple threads, then somehow during the stepping over
3231 // of all breakpoints no run gets reported.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003232
3233 // This is a transition from stop to run.
3234 switch (m_thread_list.ShouldReportRun (event_ptr))
3235 {
Greg Clayton23f59502012-07-17 03:23:13 +00003236 default:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003237 case eVoteYes:
3238 case eVoteNoOpinion:
3239 return_value = true;
3240 break;
3241 case eVoteNo:
3242 return_value = false;
3243 break;
3244 }
3245 break;
3246 }
3247 break;
3248 case eStateStopped:
3249 case eStateCrashed:
3250 case eStateSuspended:
3251 {
3252 // We've stopped. First see if we're going to restart the target.
3253 // If we are going to stop, then we always broadcast the event.
3254 // 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 +00003255 // If no thread has an opinion, we don't report it.
Jim Inghamcb4ca112012-05-16 01:32:14 +00003256
3257 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003258 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003259 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003260 if (log)
3261 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003262 return true;
3263 }
3264 else
3265 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003266
3267 if (m_thread_list.ShouldStop (event_ptr) == false)
3268 {
3269 switch (m_thread_list.ShouldReportStop (event_ptr))
3270 {
3271 case eVoteYes:
3272 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003273 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003274 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003275 case eVoteNo:
3276 return_value = false;
3277 break;
3278 }
3279
3280 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003281 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham3b8285d2012-04-19 01:40:33 +00003282 PrivateResume ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003283 }
3284 else
3285 {
3286 return_value = true;
3287 SynchronouslyNotifyStateChanged (state);
3288 }
3289 }
3290 }
3291 }
3292
3293 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003294 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003295 return return_value;
3296}
3297
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003298
3299bool
Jim Ingham372787f2012-04-07 00:00:41 +00003300Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003301{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003302 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003303
Greg Clayton8b82f082011-04-12 05:54:46 +00003304 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003305 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003306 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3307
Jim Ingham372787f2012-04-07 00:00:41 +00003308 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003309 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003310
3311 // Create a thread that watches our internal state and controls which
3312 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003313 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003314 if (already_running)
3315 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3316 else
3317 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003318
3319 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003320 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003321 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3322 if (success)
3323 {
3324 ResumePrivateStateThread();
3325 return true;
3326 }
3327 else
3328 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003329}
3330
3331void
3332Process::PausePrivateStateThread ()
3333{
3334 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3335}
3336
3337void
3338Process::ResumePrivateStateThread ()
3339{
3340 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3341}
3342
3343void
3344Process::StopPrivateStateThread ()
3345{
Greg Clayton8b82f082011-04-12 05:54:46 +00003346 if (PrivateStateThreadIsValid ())
3347 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003348 else
3349 {
3350 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3351 if (log)
3352 printf ("Went to stop the private state thread, but it was already invalid.");
3353 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003354}
3355
3356void
3357Process::ControlPrivateStateThread (uint32_t signal)
3358{
Jim Inghamb1e2e842012-04-12 18:49:31 +00003359 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003360
3361 assert (signal == eBroadcastInternalStateControlStop ||
3362 signal == eBroadcastInternalStateControlPause ||
3363 signal == eBroadcastInternalStateControlResume);
3364
3365 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003366 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003367
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003368 // Signal the private state thread. First we should copy this is case the
3369 // thread starts exiting since the private state thread will NULL this out
3370 // when it exits
3371 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003372 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003373 {
3374 TimeValue timeout_time;
3375 bool timed_out;
3376
3377 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3378
3379 timeout_time = TimeValue::Now();
3380 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003381 if (log)
3382 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003383 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3384 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3385
3386 if (signal == eBroadcastInternalStateControlStop)
3387 {
3388 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003389 {
3390 Error error;
3391 Host::ThreadCancel (private_state_thread, &error);
3392 if (log)
3393 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3394 }
3395 else
3396 {
3397 if (log)
3398 log->Printf ("The control event killed the private state thread without having to cancel.");
3399 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003400
3401 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003402 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003403 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003404 }
3405 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003406 else
3407 {
3408 if (log)
3409 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3410 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003411}
3412
3413void
Jim Inghamcfc09352012-07-27 23:57:19 +00003414Process::SendAsyncInterrupt ()
3415{
3416 if (PrivateStateThreadIsValid())
3417 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3418 else
3419 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3420}
3421
3422void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003423Process::HandlePrivateEvent (EventSP &event_sp)
3424{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003425 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamaacc3182012-06-06 00:29:30 +00003426 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghambb3a2832011-01-29 01:49:25 +00003427
Greg Clayton414f5d32011-01-25 02:58:48 +00003428 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003429
3430 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003431 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003432 {
Jim Ingham754ab982011-01-29 04:05:41 +00003433 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003434 switch (action_result)
3435 {
3436 case NextEventAction::eEventActionSuccess:
3437 SetNextEventAction(NULL);
3438 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003439
Jim Inghambb3a2832011-01-29 01:49:25 +00003440 case NextEventAction::eEventActionRetry:
3441 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003442
Jim Inghambb3a2832011-01-29 01:49:25 +00003443 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003444 // Handle Exiting Here. If we already got an exited event,
3445 // we should just propagate it. Otherwise, swallow this event,
3446 // and set our state to exit so the next event will kill us.
3447 if (new_state != eStateExited)
3448 {
3449 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003450 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003451 SetNextEventAction(NULL);
3452 return;
3453 }
3454 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003455 break;
3456 }
3457 }
3458
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003459 // See if we should broadcast this state to external clients?
3460 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003461
3462 if (should_broadcast)
3463 {
3464 if (log)
3465 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003466 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003467 __FUNCTION__,
3468 GetID(),
3469 StateAsCString(new_state),
3470 StateAsCString (GetState ()),
3471 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003472 }
Jim Ingham9575d842011-03-11 03:53:59 +00003473 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003474 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003475 PushProcessInputReader ();
3476 else
3477 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003478
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003479 BroadcastEvent (event_sp);
3480 }
3481 else
3482 {
3483 if (log)
3484 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003485 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003486 __FUNCTION__,
3487 GetID(),
3488 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003489 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003490 }
3491 }
Jim Inghamaacc3182012-06-06 00:29:30 +00003492 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003493}
3494
3495void *
3496Process::PrivateStateThread (void *arg)
3497{
3498 Process *proc = static_cast<Process*> (arg);
3499 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003500 return result;
3501}
3502
3503void *
3504Process::RunPrivateStateThread ()
3505{
Jim Ingham076b3042012-04-10 01:21:57 +00003506 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003507 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003508
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003509 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003510 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003511 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003512
3513 bool exit_now = false;
3514 while (!exit_now)
3515 {
3516 EventSP event_sp;
3517 WaitForEventsPrivate (NULL, event_sp, control_only);
3518 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3519 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003520 if (log)
3521 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3522
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003523 switch (event_sp->GetType())
3524 {
3525 case eBroadcastInternalStateControlStop:
3526 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003527 break; // doing any internal state managment below
3528
3529 case eBroadcastInternalStateControlPause:
3530 control_only = true;
3531 break;
3532
3533 case eBroadcastInternalStateControlResume:
3534 control_only = false;
3535 break;
3536 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003537
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003538 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003539 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003540 }
Jim Inghamcfc09352012-07-27 23:57:19 +00003541 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3542 {
3543 if (m_public_state.GetValue() == eStateAttaching)
3544 {
3545 if (log)
3546 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3547 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3548 }
3549 else
3550 {
3551 if (log)
3552 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3553 Halt();
3554 }
3555 continue;
3556 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003557
3558 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3559
3560 if (internal_state != eStateInvalid)
3561 {
3562 HandlePrivateEvent (event_sp);
3563 }
3564
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003565 if (internal_state == eStateInvalid ||
3566 internal_state == eStateExited ||
3567 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003568 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003569 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003570 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 +00003571
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003572 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003573 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003574 }
3575
Caroline Tice20ad3c42010-10-29 21:48:37 +00003576 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003577 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003578 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003579
Greg Clayton6ed95942011-01-22 07:12:45 +00003580 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3581 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003582 return NULL;
3583}
3584
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003585//------------------------------------------------------------------
3586// Process Event Data
3587//------------------------------------------------------------------
3588
3589Process::ProcessEventData::ProcessEventData () :
3590 EventData (),
3591 m_process_sp (),
3592 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003593 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003594 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003595 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003596{
3597}
3598
3599Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3600 EventData (),
3601 m_process_sp (process_sp),
3602 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003603 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003604 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003605 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003606{
3607}
3608
3609Process::ProcessEventData::~ProcessEventData()
3610{
3611}
3612
3613const ConstString &
3614Process::ProcessEventData::GetFlavorString ()
3615{
3616 static ConstString g_flavor ("Process::ProcessEventData");
3617 return g_flavor;
3618}
3619
3620const ConstString &
3621Process::ProcessEventData::GetFlavor () const
3622{
3623 return ProcessEventData::GetFlavorString ();
3624}
3625
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003626void
3627Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3628{
3629 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003630 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3631 // the public event queue, then other times when we're pretending that this is where we stopped at the
3632 // end of expression evaluation. m_update_state is used to distinguish these
3633 // three cases; it is 0 when we're just pulling it off for private handling,
3634 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003635
Jim Inghama8604692011-05-22 21:45:01 +00003636 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003637 return;
3638
3639 m_process_sp->SetPublicState (m_state);
3640
3641 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3642 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003643 {
3644 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003645 uint32_t num_threads = curr_thread_list.GetSize();
3646 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003647
Jim Ingham4b536182011-08-09 02:12:22 +00003648 // The actions might change one of the thread's stop_info's opinions about whether we should
3649 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003650
3651 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3652 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3653 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3654 // 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
3655 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003656 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003657 for (idx = 0; idx < num_threads; ++idx)
3658 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3659
Jim Ingham4b536182011-08-09 02:12:22 +00003660 bool still_should_stop = true;
3661
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003662 for (idx = 0; idx < num_threads; ++idx)
3663 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003664 curr_thread_list = m_process_sp->GetThreadList();
3665 if (curr_thread_list.GetSize() != num_threads)
3666 {
3667 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003668 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003669 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 +00003670 break;
3671 }
3672
3673 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3674
3675 if (thread_sp->GetIndexID() != thread_index_array[idx])
3676 {
3677 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003678 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003679 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003680 idx,
3681 thread_index_array[idx],
3682 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003683 break;
3684 }
3685
Jim Inghamb15bfc72010-10-20 00:39:53 +00003686 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3687 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003688 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003689 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003690 // The stop action might restart the target. If it does, then we want to mark that in the
3691 // event so that whoever is receiving it will know to wait for the running event and reflect
3692 // that state appropriately.
3693 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003694
3695 // FIXME: we might have run.
3696 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003697 {
3698 SetRestarted (true);
3699 break;
3700 }
3701 else if (!stop_info_sp->ShouldStop(event_ptr))
3702 {
3703 still_should_stop = false;
3704 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003705 }
3706 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003707
Jim Ingham4b536182011-08-09 02:12:22 +00003708
3709 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003710 {
Jim Ingham4b536182011-08-09 02:12:22 +00003711 if (!still_should_stop)
3712 {
3713 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003714 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00003715 // Use the public resume method here, since this is just
3716 // extending a public resume.
Jim Ingham4b536182011-08-09 02:12:22 +00003717 m_process_sp->Resume();
3718 }
3719 else
3720 {
3721 // If we didn't restart, run the Stop Hooks here:
3722 // They might also restart the target, so watch for that.
3723 m_process_sp->GetTarget().RunStopHooks();
3724 if (m_process_sp->GetPrivateState() == eStateRunning)
3725 SetRestarted(true);
3726 }
Jim Ingham9575d842011-03-11 03:53:59 +00003727 }
3728
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003729 }
3730}
3731
3732void
3733Process::ProcessEventData::Dump (Stream *s) const
3734{
3735 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003736 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003737
Greg Clayton8b82f082011-04-12 05:54:46 +00003738 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003739}
3740
3741const Process::ProcessEventData *
3742Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3743{
3744 if (event_ptr)
3745 {
3746 const EventData *event_data = event_ptr->GetData();
3747 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3748 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3749 }
3750 return NULL;
3751}
3752
3753ProcessSP
3754Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3755{
3756 ProcessSP process_sp;
3757 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3758 if (data)
3759 process_sp = data->GetProcessSP();
3760 return process_sp;
3761}
3762
3763StateType
3764Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3765{
3766 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3767 if (data == NULL)
3768 return eStateInvalid;
3769 else
3770 return data->GetState();
3771}
3772
3773bool
3774Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3775{
3776 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3777 if (data == NULL)
3778 return false;
3779 else
3780 return data->GetRestarted();
3781}
3782
3783void
3784Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3785{
3786 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3787 if (data != NULL)
3788 data->SetRestarted(new_value);
3789}
3790
3791bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003792Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3793{
3794 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3795 if (data == NULL)
3796 return false;
3797 else
3798 return data->GetInterrupted ();
3799}
3800
3801void
3802Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3803{
3804 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3805 if (data != NULL)
3806 data->SetInterrupted(new_value);
3807}
3808
3809bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003810Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3811{
3812 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3813 if (data)
3814 {
3815 data->SetUpdateStateOnRemoval();
3816 return true;
3817 }
3818 return false;
3819}
3820
Greg Claytond9e416c2012-02-18 05:35:26 +00003821lldb::TargetSP
3822Process::CalculateTarget ()
3823{
3824 return m_target.shared_from_this();
3825}
3826
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003827void
Greg Clayton0603aa92010-10-04 01:05:56 +00003828Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003829{
Greg Claytonc14ee322011-09-22 04:58:26 +00003830 exe_ctx.SetTargetPtr (&m_target);
3831 exe_ctx.SetProcessPtr (this);
3832 exe_ctx.SetThreadPtr(NULL);
3833 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003834}
3835
Greg Claytone996fd32011-03-08 22:40:15 +00003836//uint32_t
3837//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3838//{
3839// return 0;
3840//}
3841//
3842//ArchSpec
3843//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3844//{
3845// return Host::GetArchSpecForExistingProcess (pid);
3846//}
3847//
3848//ArchSpec
3849//Process::GetArchSpecForExistingProcess (const char *process_name)
3850//{
3851// return Host::GetArchSpecForExistingProcess (process_name);
3852//}
3853//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003854void
3855Process::AppendSTDOUT (const char * s, size_t len)
3856{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003857 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003858 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003859 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003860}
3861
3862void
Greg Clayton93e86192011-11-13 04:45:22 +00003863Process::AppendSTDERR (const char * s, size_t len)
3864{
3865 Mutex::Locker locker (m_stdio_communication_mutex);
3866 m_stderr_data.append (s, len);
3867 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3868}
3869
3870//------------------------------------------------------------------
3871// Process STDIO
3872//------------------------------------------------------------------
3873
3874size_t
3875Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3876{
3877 Mutex::Locker locker(m_stdio_communication_mutex);
3878 size_t bytes_available = m_stdout_data.size();
3879 if (bytes_available > 0)
3880 {
3881 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3882 if (log)
3883 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3884 if (bytes_available > buf_size)
3885 {
3886 memcpy(buf, m_stdout_data.c_str(), buf_size);
3887 m_stdout_data.erase(0, buf_size);
3888 bytes_available = buf_size;
3889 }
3890 else
3891 {
3892 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3893 m_stdout_data.clear();
3894 }
3895 }
3896 return bytes_available;
3897}
3898
3899
3900size_t
3901Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3902{
3903 Mutex::Locker locker(m_stdio_communication_mutex);
3904 size_t bytes_available = m_stderr_data.size();
3905 if (bytes_available > 0)
3906 {
3907 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3908 if (log)
3909 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3910 if (bytes_available > buf_size)
3911 {
3912 memcpy(buf, m_stderr_data.c_str(), buf_size);
3913 m_stderr_data.erase(0, buf_size);
3914 bytes_available = buf_size;
3915 }
3916 else
3917 {
3918 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3919 m_stderr_data.clear();
3920 }
3921 }
3922 return bytes_available;
3923}
3924
3925void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003926Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3927{
3928 Process *process = (Process *) baton;
3929 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3930}
3931
3932size_t
3933Process::ProcessInputReaderCallback (void *baton,
3934 InputReader &reader,
3935 lldb::InputReaderAction notification,
3936 const char *bytes,
3937 size_t bytes_len)
3938{
3939 Process *process = (Process *) baton;
3940
3941 switch (notification)
3942 {
3943 case eInputReaderActivate:
3944 break;
3945
3946 case eInputReaderDeactivate:
3947 break;
3948
3949 case eInputReaderReactivate:
3950 break;
3951
Caroline Tice969ed3d2011-05-02 20:41:46 +00003952 case eInputReaderAsynchronousOutputWritten:
3953 break;
3954
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003955 case eInputReaderGotToken:
3956 {
3957 Error error;
3958 process->PutSTDIN (bytes, bytes_len, error);
3959 }
3960 break;
3961
Caroline Ticeefed6132010-11-19 20:47:54 +00003962 case eInputReaderInterrupt:
3963 process->Halt ();
3964 break;
3965
3966 case eInputReaderEndOfFile:
3967 process->AppendSTDOUT ("^D", 2);
3968 break;
3969
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003970 case eInputReaderDone:
3971 break;
3972
3973 }
3974
3975 return bytes_len;
3976}
3977
3978void
3979Process::ResetProcessInputReader ()
3980{
3981 m_process_input_reader.reset();
3982}
3983
3984void
Greg Claytonee95ed52011-11-17 22:14:31 +00003985Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003986{
3987 // First set up the Read Thread for reading/handling process I/O
3988
3989 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3990
3991 if (conn_ap.get())
3992 {
3993 m_stdio_communication.SetConnection (conn_ap.release());
3994 if (m_stdio_communication.IsConnected())
3995 {
3996 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3997 m_stdio_communication.StartReadThread();
3998
3999 // Now read thread is set up, set up input reader.
4000
4001 if (!m_process_input_reader.get())
4002 {
4003 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
4004 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
4005 this,
4006 eInputReaderGranularityByte,
4007 NULL,
4008 NULL,
4009 false));
4010
4011 if (err.Fail())
4012 m_process_input_reader.reset();
4013 }
4014 }
4015 }
4016}
4017
4018void
4019Process::PushProcessInputReader ()
4020{
4021 if (m_process_input_reader && !m_process_input_reader->IsActive())
4022 m_target.GetDebugger().PushInputReader (m_process_input_reader);
4023}
4024
4025void
4026Process::PopProcessInputReader ()
4027{
4028 if (m_process_input_reader && m_process_input_reader->IsActive())
4029 m_target.GetDebugger().PopInputReader (m_process_input_reader);
4030}
4031
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004032// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00004033void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004034Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004035{
Greg Clayton67cc0632012-08-22 17:17:09 +00004036// static std::vector<OptionEnumValueElement> g_plugins;
4037//
4038// int i=0;
4039// const char *name;
4040// OptionEnumValueElement option_enum;
4041// while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
4042// {
4043// if (name)
4044// {
4045// option_enum.value = i;
4046// option_enum.string_value = name;
4047// option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
4048// g_plugins.push_back (option_enum);
4049// }
4050// ++i;
4051// }
4052// option_enum.value = 0;
4053// option_enum.string_value = NULL;
4054// option_enum.usage = NULL;
4055// g_plugins.push_back (option_enum);
4056//
4057// for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
4058// {
4059// if (::strcmp (name, "plugin") == 0)
4060// {
4061// SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
4062// break;
4063// }
4064// }
4065// UserSettingsControllerSP &usc = GetSettingsController();
4066// UserSettingsController::InitializeSettingsController (usc,
4067// SettingsController::global_settings_table,
4068// SettingsController::instance_settings_table);
4069//
4070// // Now call SettingsInitialize() for each 'child' of Process settings
4071// Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004072}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004073
Greg Clayton99d0faf2010-11-18 23:32:35 +00004074void
Caroline Tice20bd37f2011-03-10 22:14:10 +00004075Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004076{
Greg Clayton67cc0632012-08-22 17:17:09 +00004077// // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
4078//
4079// Thread::SettingsTerminate ();
4080//
4081// // Now terminate Process Settings.
4082//
4083// UserSettingsControllerSP &usc = GetSettingsController();
4084// UserSettingsController::FinalizeSettingsController (usc);
4085// usc.reset();
Greg Clayton99d0faf2010-11-18 23:32:35 +00004086}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004087
Greg Clayton67cc0632012-08-22 17:17:09 +00004088//PropertiesSP &
4089//Process::GetProperties ()
4090//{
4091// static PropertiesSP g_settings_sp;
4092// if (!g_settings_sp)
4093// g_settings_sp.reset (new ProcessProperties());
4094// return g_settings_sp;
4095//}
Caroline Tice1559a462010-09-27 00:30:10 +00004096
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004097ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004098Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004099 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00004100 bool stop_others,
4101 bool try_all_threads,
4102 bool discard_on_error,
4103 uint32_t single_thread_timeout_usec,
4104 Stream &errors)
4105{
4106 ExecutionResults return_value = eExecutionSetupError;
4107
Jim Ingham77787032011-01-20 02:03:18 +00004108 if (thread_plan_sp.get() == NULL)
4109 {
4110 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004111 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004112 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004113
4114 if (exe_ctx.GetProcessPtr() != this)
4115 {
4116 errors.Printf("RunThreadPlan called on wrong process.");
4117 return eExecutionSetupError;
4118 }
4119
4120 Thread *thread = exe_ctx.GetThreadPtr();
4121 if (thread == NULL)
4122 {
4123 errors.Printf("RunThreadPlan called with invalid thread.");
4124 return eExecutionSetupError;
4125 }
Jim Ingham77787032011-01-20 02:03:18 +00004126
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004127 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4128 // For that to be true the plan can't be private - since private plans suppress themselves in the
4129 // GetCompletedPlan call.
4130
4131 bool orig_plan_private = thread_plan_sp->GetPrivate();
4132 thread_plan_sp->SetPrivate(false);
4133
Jim Ingham444586b2011-01-24 06:34:17 +00004134 if (m_private_state.GetValue() != eStateStopped)
4135 {
4136 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004137 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004138 }
4139
Jim Ingham66243842011-08-13 00:56:10 +00004140 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004141 const uint32_t thread_idx_id = thread->GetIndexID();
4142 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004143
4144 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4145 // so we should arrange to reset them as well.
4146
Greg Claytonc14ee322011-09-22 04:58:26 +00004147 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004148
Jim Ingham66243842011-08-13 00:56:10 +00004149 uint32_t selected_tid;
4150 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004151 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004152 {
4153 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004154 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004155 }
4156 else
4157 {
4158 selected_tid = LLDB_INVALID_THREAD_ID;
4159 }
4160
Jim Ingham372787f2012-04-07 00:00:41 +00004161 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004162 lldb::StateType old_state;
4163 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004164
Jim Ingham076b3042012-04-10 01:21:57 +00004165 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004166 if (Host::GetCurrentThread() == m_private_state_thread)
4167 {
Jim Ingham076b3042012-04-10 01:21:57 +00004168 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4169 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004170 // 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 +00004171 // we are fielding public events here.
4172 if (log)
4173 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4174
4175
Jim Ingham372787f2012-04-07 00:00:41 +00004176 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004177
4178 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4179 // returning control here.
4180 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4181 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4182 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4183 // do just what we want.
4184 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4185 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4186 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4187 old_state = m_public_state.GetValue();
4188 m_public_state.SetValueNoLock(eStateStopped);
4189
4190 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004191 StartPrivateStateThread(true);
4192 }
4193
4194 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004195
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004196 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004197
Sean Callanana46ec452012-07-11 21:31:24 +00004198 lldb::EventSP event_to_broadcast_sp;
Jim Ingham0f16e732011-02-08 05:20:59 +00004199
Jim Ingham77787032011-01-20 02:03:18 +00004200 {
Sean Callanana46ec452012-07-11 21:31:24 +00004201 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4202 // restored on exit to the function.
4203 //
4204 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4205 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Inghamf48169b2010-11-30 02:22:11 +00004206
Sean Callanana46ec452012-07-11 21:31:24 +00004207 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham0f16e732011-02-08 05:20:59 +00004208
Jim Inghamf48169b2010-11-30 02:22:11 +00004209 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004210 {
4211 StreamString s;
Sean Callanana46ec452012-07-11 21:31:24 +00004212 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4213 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4214 thread->GetIndexID(),
4215 thread->GetID(),
4216 s.GetData());
4217 }
4218
4219 bool got_event;
4220 lldb::EventSP event_sp;
4221 lldb::StateType stop_state = lldb::eStateInvalid;
4222
4223 TimeValue* timeout_ptr = NULL;
4224 TimeValue real_timeout;
4225
4226 bool first_timeout = true;
4227 bool do_resume = true;
4228
4229 while (1)
4230 {
4231 // We usually want to resume the process if we get to the top of the loop.
4232 // The only exception is if we get two running events with no intervening
4233 // stop, which can happen, we will just wait for then next stop event.
4234
4235 if (do_resume)
4236 {
4237 // Do the initial resume and wait for the running event before going further.
4238
4239 Error resume_error = PrivateResume ();
4240 if (!resume_error.Success())
4241 {
4242 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4243 return_value = eExecutionSetupError;
4244 break;
4245 }
4246
4247 real_timeout = TimeValue::Now();
4248 real_timeout.OffsetWithMicroSeconds(500000);
4249 timeout_ptr = &real_timeout;
4250
4251 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4252 if (!got_event)
4253 {
4254 if (log)
4255 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4256
4257 errors.Printf("Didn't get any event after initial resume, exiting.");
4258 return_value = eExecutionSetupError;
4259 break;
4260 }
4261
4262 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4263 if (stop_state != eStateRunning)
4264 {
4265 if (log)
4266 log->Printf("Process::RunThreadPlan(): didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
4267
4268 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
4269 return_value = eExecutionSetupError;
4270 break;
4271 }
4272
4273 if (log)
4274 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4275 // We need to call the function synchronously, so spin waiting for it to return.
4276 // If we get interrupted while executing, we're going to lose our context, and
4277 // won't be able to gather the result at this point.
4278 // We set the timeout AFTER the resume, since the resume takes some time and we
4279 // don't want to charge that to the timeout.
4280
4281 if (single_thread_timeout_usec != 0)
4282 {
Enrico Granata3372f582012-07-16 23:10:35 +00004283 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanana46ec452012-07-11 21:31:24 +00004284 real_timeout = TimeValue::Now();
4285 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
4286
4287 timeout_ptr = &real_timeout;
4288 }
Enrico Granata3372f582012-07-16 23:10:35 +00004289 else if (first_timeout)
4290 {
4291 // if we are willing to wait "forever" we still need to have an initial timeout
4292 // this timeout is going to induce all threads to run when hit. we do this so that
4293 // we can avoid ending locked up because of multithreaded contention issues
4294 real_timeout = TimeValue::Now();
4295 real_timeout.OffsetWithNanoSeconds(500000000UL);
4296 timeout_ptr = &real_timeout;
4297 }
4298 else
4299 {
4300 timeout_ptr = NULL; // if we are in a no-timeout scenario, then we only need a fake timeout the first time through
4301 // at this point in the code, all threads will be running so we are willing to wait forever, and do not
4302 // need a timeout
4303 }
Sean Callanana46ec452012-07-11 21:31:24 +00004304 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004305 else
4306 {
Sean Callanana46ec452012-07-11 21:31:24 +00004307 if (log)
4308 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4309 do_resume = true;
Jim Ingham0f16e732011-02-08 05:20:59 +00004310 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004311
Sean Callanana46ec452012-07-11 21:31:24 +00004312 // Now wait for the process to stop again:
Sean Callanana46ec452012-07-11 21:31:24 +00004313 event_sp.reset();
Jim Ingham0f16e732011-02-08 05:20:59 +00004314
Jim Ingham0f16e732011-02-08 05:20:59 +00004315 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004316 {
Sean Callanana46ec452012-07-11 21:31:24 +00004317 if (timeout_ptr)
4318 {
4319 StreamString s;
4320 s.Printf ("about to wait - timeout is:\n ");
4321 timeout_ptr->Dump (&s, 120);
4322 s.Printf ("\nNow is:\n ");
4323 TimeValue::Now().Dump (&s, 120);
4324 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4325 }
Jim Ingham20829ac2011-08-09 22:24:33 +00004326 else
Sean Callanana46ec452012-07-11 21:31:24 +00004327 {
4328 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4329 }
4330 }
4331
4332 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4333
4334 if (got_event)
4335 {
4336 if (event_sp.get())
4337 {
4338 bool keep_going = false;
Jim Inghamcfc09352012-07-27 23:57:19 +00004339 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004340 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004341 Halt();
4342 keep_going = false;
4343 return_value = eExecutionInterrupted;
4344 errors.Printf ("Execution halted by user interrupt.");
4345 if (log)
4346 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4347 }
4348 else
4349 {
4350 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4351 if (log)
4352 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4353
4354 switch (stop_state)
Sean Callanana46ec452012-07-11 21:31:24 +00004355 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004356 case lldb::eStateStopped:
Sean Callanana46ec452012-07-11 21:31:24 +00004357 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004358 // Yay, we're done. Now make sure that our thread plan actually completed.
4359 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4360 if (!thread_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004361 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004362 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanana46ec452012-07-11 21:31:24 +00004363 if (log)
Jim Inghamcfc09352012-07-27 23:57:19 +00004364 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4365 return_value = eExecutionInterrupted;
Sean Callanana46ec452012-07-11 21:31:24 +00004366 }
4367 else
4368 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004369 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4370 StopReason stop_reason = eStopReasonInvalid;
4371 if (stop_info_sp)
4372 stop_reason = stop_info_sp->GetStopReason();
4373 if (stop_reason == eStopReasonPlanComplete)
4374 {
4375 if (log)
4376 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4377 // Now mark this plan as private so it doesn't get reported as the stop reason
4378 // after this point.
4379 if (thread_plan_sp)
4380 thread_plan_sp->SetPrivate (orig_plan_private);
4381 return_value = eExecutionCompleted;
4382 }
4383 else
4384 {
4385 if (log)
4386 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanana46ec452012-07-11 21:31:24 +00004387
Jim Inghamcfc09352012-07-27 23:57:19 +00004388 return_value = eExecutionInterrupted;
4389 }
Sean Callanana46ec452012-07-11 21:31:24 +00004390 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004391 }
4392 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004393
Jim Inghamcfc09352012-07-27 23:57:19 +00004394 case lldb::eStateCrashed:
4395 if (log)
4396 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4397 return_value = eExecutionInterrupted;
4398 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004399
Jim Inghamcfc09352012-07-27 23:57:19 +00004400 case lldb::eStateRunning:
4401 do_resume = false;
4402 keep_going = true;
4403 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004404
Jim Inghamcfc09352012-07-27 23:57:19 +00004405 default:
4406 if (log)
4407 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4408
4409 if (stop_state == eStateExited)
4410 event_to_broadcast_sp = event_sp;
4411
Sean Callananbf154da2012-08-08 17:35:10 +00004412 errors.Printf ("Execution stopped with unexpected state.\n");
Jim Inghamcfc09352012-07-27 23:57:19 +00004413 return_value = eExecutionInterrupted;
4414 break;
4415 }
Sean Callanana46ec452012-07-11 21:31:24 +00004416 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004417
Sean Callanana46ec452012-07-11 21:31:24 +00004418 if (keep_going)
4419 continue;
4420 else
4421 break;
4422 }
4423 else
4424 {
4425 if (log)
4426 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4427 return_value = eExecutionInterrupted;
4428 break;
4429 }
4430 }
4431 else
4432 {
4433 // If we didn't get an event that means we've timed out...
4434 // We will interrupt the process here. Depending on what we were asked to do we will
4435 // either exit, or try with all threads running for the same timeout.
4436 // Not really sure what to do if Halt fails here...
4437
4438 if (log) {
4439 if (try_all_threads)
4440 {
4441 if (first_timeout)
4442 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4443 "trying with all threads enabled.",
4444 single_thread_timeout_usec);
4445 else
4446 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4447 "and timeout: %d timed out.",
4448 single_thread_timeout_usec);
4449 }
4450 else
4451 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4452 "halt and abandoning execution.",
4453 single_thread_timeout_usec);
4454 }
4455
4456 Error halt_error = Halt();
4457 if (halt_error.Success())
4458 {
4459 if (log)
4460 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4461
4462 // If halt succeeds, it always produces a stopped event. Wait for that:
4463
4464 real_timeout = TimeValue::Now();
4465 real_timeout.OffsetWithMicroSeconds(500000);
4466
4467 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4468
4469 if (got_event)
4470 {
4471 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4472 if (log)
4473 {
4474 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4475 if (stop_state == lldb::eStateStopped
4476 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4477 log->PutCString (" Event was the Halt interruption event.");
4478 }
4479
4480 if (stop_state == lldb::eStateStopped)
4481 {
4482 // Between the time we initiated the Halt and the time we delivered it, the process could have
4483 // already finished its job. Check that here:
4484
4485 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4486 {
4487 if (log)
4488 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4489 "Exiting wait loop.");
4490 return_value = eExecutionCompleted;
4491 break;
4492 }
4493
4494 if (!try_all_threads)
4495 {
4496 if (log)
4497 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4498 return_value = eExecutionInterrupted;
4499 break;
4500 }
4501
4502 if (first_timeout)
4503 {
4504 // Set all the other threads to run, and return to the top of the loop, which will continue;
4505 first_timeout = false;
4506 thread_plan_sp->SetStopOthers (false);
4507 if (log)
4508 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4509
4510 continue;
4511 }
4512 else
4513 {
4514 // Running all threads failed, so return Interrupted.
4515 if (log)
4516 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4517 return_value = eExecutionInterrupted;
4518 break;
4519 }
4520 }
4521 }
4522 else
4523 { if (log)
4524 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4525 "I'm getting out of here passing Interrupted.");
4526 return_value = eExecutionInterrupted;
4527 break;
4528 }
4529 }
4530 else
4531 {
4532 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4533 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4534 if (log)
4535 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.",
4536 halt_error.AsCString());
4537 real_timeout = TimeValue::Now();
4538 real_timeout.OffsetWithMicroSeconds(500000);
4539 timeout_ptr = &real_timeout;
4540 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4541 if (!got_event || event_sp.get() == NULL)
4542 {
4543 // This is not going anywhere, bag out.
4544 if (log)
4545 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4546 return_value = eExecutionInterrupted;
4547 break;
4548 }
4549 else
4550 {
4551 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4552 if (log)
4553 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4554 if (stop_state == lldb::eStateStopped)
4555 {
4556 // Between the time we initiated the Halt and the time we delivered it, the process could have
4557 // already finished its job. Check that here:
4558
4559 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4560 {
4561 if (log)
4562 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4563 "Exiting wait loop.");
4564 return_value = eExecutionCompleted;
4565 break;
4566 }
4567
4568 if (first_timeout)
4569 {
4570 // Set all the other threads to run, and return to the top of the loop, which will continue;
4571 first_timeout = false;
4572 thread_plan_sp->SetStopOthers (false);
4573 if (log)
4574 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4575
4576 continue;
4577 }
4578 else
4579 {
4580 // Running all threads failed, so return Interrupted.
4581 if (log)
4582 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4583 return_value = eExecutionInterrupted;
4584 break;
4585 }
4586 }
4587 else
4588 {
4589 if (log)
4590 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4591 " a stopped event, instead got %s.", StateAsCString(stop_state));
4592 return_value = eExecutionInterrupted;
4593 break;
4594 }
4595 }
4596 }
4597
4598 }
4599
4600 } // END WAIT LOOP
4601
4602 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4603 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4604 {
4605 StopPrivateStateThread();
4606 Error error;
4607 m_private_state_thread = backup_private_state_thread;
Sean Callanan9a028512012-08-09 00:50:26 +00004608 if (stopper_base_plan_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004609 {
4610 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4611 }
4612 m_public_state.SetValueNoLock(old_state);
4613
4614 }
4615
4616
4617 // Now do some processing on the results of the run:
4618 if (return_value == eExecutionInterrupted)
4619 {
4620 if (log)
4621 {
4622 StreamString s;
4623 if (event_sp)
4624 event_sp->Dump (&s);
4625 else
4626 {
4627 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4628 }
4629
4630 StreamString ts;
4631
4632 const char *event_explanation = NULL;
4633
4634 do
4635 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004636 if (!event_sp)
Sean Callanana46ec452012-07-11 21:31:24 +00004637 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004638 event_explanation = "<no event>";
Sean Callanana46ec452012-07-11 21:31:24 +00004639 break;
4640 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004641 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanana46ec452012-07-11 21:31:24 +00004642 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004643 event_explanation = "<user interrupt>";
Sean Callanana46ec452012-07-11 21:31:24 +00004644 break;
4645 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004646 else
Sean Callanana46ec452012-07-11 21:31:24 +00004647 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004648 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4649
4650 if (!event_data)
Sean Callanana46ec452012-07-11 21:31:24 +00004651 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004652 event_explanation = "<no event data>";
4653 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004654 }
4655
Jim Inghamcfc09352012-07-27 23:57:19 +00004656 Process *process = event_data->GetProcessSP().get();
4657
4658 if (!process)
Sean Callanana46ec452012-07-11 21:31:24 +00004659 {
Jim Inghamcfc09352012-07-27 23:57:19 +00004660 event_explanation = "<no process>";
4661 break;
Sean Callanana46ec452012-07-11 21:31:24 +00004662 }
Jim Inghamcfc09352012-07-27 23:57:19 +00004663
4664 ThreadList &thread_list = process->GetThreadList();
4665
4666 uint32_t num_threads = thread_list.GetSize();
4667 uint32_t thread_index;
4668
4669 ts.Printf("<%u threads> ", num_threads);
4670
4671 for (thread_index = 0;
4672 thread_index < num_threads;
4673 ++thread_index)
4674 {
4675 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4676
4677 if (!thread)
4678 {
4679 ts.Printf("<?> ");
4680 continue;
4681 }
4682
4683 ts.Printf("<0x%4.4llx ", thread->GetID());
4684 RegisterContext *register_context = thread->GetRegisterContext().get();
4685
4686 if (register_context)
4687 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4688 else
4689 ts.Printf("[ip unknown] ");
4690
4691 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4692 if (stop_info_sp)
4693 {
4694 const char *stop_desc = stop_info_sp->GetDescription();
4695 if (stop_desc)
4696 ts.PutCString (stop_desc);
4697 }
4698 ts.Printf(">");
4699 }
4700
4701 event_explanation = ts.GetData();
Sean Callanana46ec452012-07-11 21:31:24 +00004702 }
Sean Callanana46ec452012-07-11 21:31:24 +00004703 } while (0);
4704
Jim Inghamcfc09352012-07-27 23:57:19 +00004705 if (event_explanation)
4706 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanana46ec452012-07-11 21:31:24 +00004707 else
Jim Inghamcfc09352012-07-27 23:57:19 +00004708 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4709 }
4710
4711 if (discard_on_error && thread_plan_sp)
4712 {
4713 if (log)
4714 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4715 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4716 thread_plan_sp->SetPrivate (orig_plan_private);
4717 }
4718 else
4719 {
4720 if (log)
4721 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanana46ec452012-07-11 21:31:24 +00004722 }
4723 }
4724 else if (return_value == eExecutionSetupError)
4725 {
4726 if (log)
4727 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004728
4729 if (discard_on_error && thread_plan_sp)
4730 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004731 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004732 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004733 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004734 }
4735 else
4736 {
Sean Callanana46ec452012-07-11 21:31:24 +00004737 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004738 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004739 if (log)
Sean Callanana46ec452012-07-11 21:31:24 +00004740 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4741 return_value = eExecutionCompleted;
4742 }
4743 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4744 {
4745 if (log)
4746 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4747 return_value = eExecutionDiscarded;
4748 }
4749 else
4750 {
4751 if (log)
4752 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4753 if (discard_on_error && thread_plan_sp)
4754 {
4755 if (log)
4756 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4757 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4758 thread_plan_sp->SetPrivate (orig_plan_private);
4759 }
4760 }
4761 }
4762
4763 // Thread we ran the function in may have gone away because we ran the target
4764 // Check that it's still there, and if it is put it back in the context. Also restore the
4765 // frame in the context if it is still present.
4766 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4767 if (thread)
4768 {
4769 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4770 }
4771
4772 // Also restore the current process'es selected frame & thread, since this function calling may
4773 // be done behind the user's back.
4774
4775 if (selected_tid != LLDB_INVALID_THREAD_ID)
4776 {
4777 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4778 {
4779 // We were able to restore the selected thread, now restore the frame:
4780 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4781 if (old_frame_sp)
4782 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004783 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004784 }
4785 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004786
Sean Callanana46ec452012-07-11 21:31:24 +00004787 // If the process exited during the run of the thread plan, notify everyone.
Jim Inghamf48169b2010-11-30 02:22:11 +00004788
Sean Callanana46ec452012-07-11 21:31:24 +00004789 if (event_to_broadcast_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004790 {
Sean Callanana46ec452012-07-11 21:31:24 +00004791 if (log)
4792 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4793 BroadcastEvent(event_to_broadcast_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004794 }
4795
4796 return return_value;
4797}
4798
4799const char *
4800Process::ExecutionResultAsCString (ExecutionResults result)
4801{
4802 const char *result_name;
4803
4804 switch (result)
4805 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004806 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004807 result_name = "eExecutionCompleted";
4808 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004809 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004810 result_name = "eExecutionDiscarded";
4811 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004812 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004813 result_name = "eExecutionInterrupted";
4814 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004815 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004816 result_name = "eExecutionSetupError";
4817 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004818 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004819 result_name = "eExecutionTimedOut";
4820 break;
4821 }
4822 return result_name;
4823}
4824
Greg Clayton7260f622011-04-18 08:33:37 +00004825void
4826Process::GetStatus (Stream &strm)
4827{
4828 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00004829 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00004830 {
4831 if (state == eStateExited)
4832 {
4833 int exit_status = GetExitStatus();
4834 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004835 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004836 GetID(),
4837 exit_status,
4838 exit_status,
4839 exit_description ? exit_description : "");
4840 }
4841 else
4842 {
4843 if (state == eStateConnected)
4844 strm.Printf ("Connected to remote target.\n");
4845 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004846 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004847 }
4848 }
4849 else
4850 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004851 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004852 }
4853}
4854
4855size_t
4856Process::GetThreadStatus (Stream &strm,
4857 bool only_threads_with_stop_reason,
4858 uint32_t start_frame,
4859 uint32_t num_frames,
4860 uint32_t num_frames_with_source)
4861{
4862 size_t num_thread_infos_dumped = 0;
4863
4864 const size_t num_threads = GetThreadList().GetSize();
4865 for (uint32_t i = 0; i < num_threads; i++)
4866 {
4867 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4868 if (thread)
4869 {
4870 if (only_threads_with_stop_reason)
4871 {
4872 if (thread->GetStopInfo().get() == NULL)
4873 continue;
4874 }
4875 thread->GetStatus (strm,
4876 start_frame,
4877 num_frames,
4878 num_frames_with_source);
4879 ++num_thread_infos_dumped;
4880 }
4881 }
4882 return num_thread_infos_dumped;
4883}
4884
Greg Claytona9f40ad2012-02-22 04:37:26 +00004885void
4886Process::AddInvalidMemoryRegion (const LoadRange &region)
4887{
4888 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4889}
4890
4891bool
4892Process::RemoveInvalidMemoryRange (const LoadRange &region)
4893{
4894 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4895}
4896
Jim Ingham372787f2012-04-07 00:00:41 +00004897void
4898Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4899{
4900 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4901}
4902
4903bool
4904Process::RunPreResumeActions ()
4905{
4906 bool result = true;
4907 while (!m_pre_resume_actions.empty())
4908 {
4909 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
4910 m_pre_resume_actions.pop_back();
4911 bool this_result = action.callback (action.baton);
4912 if (result == true) result = this_result;
4913 }
4914 return result;
4915}
4916
4917void
4918Process::ClearPreResumeActions ()
4919{
4920 m_pre_resume_actions.clear();
4921}
Greg Claytona9f40ad2012-02-22 04:37:26 +00004922
Greg Claytonfa559e52012-05-18 02:38:05 +00004923void
4924Process::Flush ()
4925{
4926 m_thread_list.Flush();
4927}
4928
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004929//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004930// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004931//--------------------------------------------------------------
4932
Greg Clayton67cc0632012-08-22 17:17:09 +00004933//Process::SettingsController::SettingsController () :
4934// UserSettingsController ("process", Target::GetSettingsController())
4935//{
4936//}
4937//
4938//Process::SettingsController::~SettingsController ()
4939//{
4940//}
4941//
4942//lldb::InstanceSettingsSP
4943//Process::SettingsController::CreateInstanceSettings (const char *instance_name)
4944//{
4945// lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4946// false,
4947// instance_name));
4948// return new_settings_sp;
4949//}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004950
4951//--------------------------------------------------------------
4952// class ProcessInstanceSettings
4953//--------------------------------------------------------------
Greg Clayton67cc0632012-08-22 17:17:09 +00004954//
4955//ProcessInstanceSettings::ProcessInstanceSettings
4956//(
4957// const UserSettingsControllerSP &owner_sp,
4958// bool live_instance,
4959// const char *name
4960//) :
4961// InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
4962//{
4963// // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4964// // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4965// // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
4966// // This is true for CreateInstanceName() too.
4967//
4968// if (GetInstanceName () == InstanceSettings::InvalidName())
4969// {
4970// ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4971// owner_sp->RegisterInstanceSettings (this);
4972// }
4973//
4974// if (live_instance)
4975// {
4976// const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
4977// CopyInstanceSettings (pending_settings,false);
4978// }
4979//}
4980//
4981//ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
4982// InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString()),
4983// m_disable_memory_cache(rhs.m_disable_memory_cache),
4984// m_extra_startup_commands (rhs.m_extra_startup_commands)
4985//{
4986// if (m_instance_name != InstanceSettings::GetDefaultName())
4987// {
4988// UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4989// if (owner_sp)
4990// {
4991// CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4992// owner_sp->RemovePendingSettings (m_instance_name);
4993// }
4994// }
4995//}
4996//
4997//ProcessInstanceSettings::~ProcessInstanceSettings ()
4998//{
4999//}
5000//
5001//ProcessInstanceSettings&
5002//ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
5003//{
5004// if (this != &rhs)
5005// {
5006// m_disable_memory_cache = rhs.m_disable_memory_cache;
5007// m_extra_startup_commands = rhs.m_extra_startup_commands;
5008// }
5009//
5010// return *this;
5011//}
5012//
5013//
5014//void
5015//ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
5016// const char *index_value,
5017// const char *value,
5018// const ConstString &instance_name,
5019// const SettingEntry &entry,
5020// VarSetOperationType op,
5021// Error &err,
5022// bool pending)
5023//{
5024// if (var_name == GetDisableMemoryCacheVarName())
5025// {
5026// bool success;
5027// bool result = Args::StringToBoolean(value, false, &success);
5028//
5029// if (success)
5030// {
5031// m_disable_memory_cache = result;
5032// }
5033// else
5034// {
5035// err.SetErrorStringWithFormat ("Bad value \"%s\" for %s, should be Boolean.", value, GetDisableMemoryCacheVarName().AsCString());
5036// }
5037//
5038// }
5039// else if (var_name == GetExtraStartupCommandVarName())
5040// {
5041// UserSettingsController::UpdateStringArrayVariable (op, index_value, m_extra_startup_commands, value, err);
5042// }
5043//}
5044//
5045//void
5046//ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
5047// bool pending)
5048//{
5049// if (new_settings.get() == NULL)
5050// return;
5051//
5052// ProcessInstanceSettings *new_settings_ptr = static_cast <ProcessInstanceSettings *> (new_settings.get());
5053//
5054// if (!new_settings_ptr)
5055// return;
5056//
5057// *this = *new_settings_ptr;
5058//}
5059//
5060//bool
5061//ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
5062// const ConstString &var_name,
5063// StringList &value,
5064// Error *err)
5065//{
5066// if (var_name == GetDisableMemoryCacheVarName())
5067// {
5068// value.AppendString(m_disable_memory_cache ? "true" : "false");
5069// return true;
5070// }
5071// else if (var_name == GetExtraStartupCommandVarName())
5072// {
5073// if (m_extra_startup_commands.GetArgumentCount() > 0)
5074// {
5075// for (int i = 0; i < m_extra_startup_commands.GetArgumentCount(); ++i)
5076// value.AppendString (m_extra_startup_commands.GetArgumentAtIndex (i));
5077// }
5078// return true;
5079// }
5080// else
5081// {
5082// if (err)
5083// err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
5084// return false;
5085// }
5086//}
5087//
5088//const ConstString
5089//ProcessInstanceSettings::CreateInstanceName ()
5090//{
5091// static int instance_count = 1;
5092// StreamString sstr;
5093//
5094// sstr.Printf ("process_%d", instance_count);
5095// ++instance_count;
5096//
5097// const ConstString ret_val (sstr.GetData());
5098// return ret_val;
5099//}
5100//
5101//const ConstString &
5102//ProcessInstanceSettings::GetDisableMemoryCacheVarName () const
5103//{
5104// static ConstString disable_memory_cache_var_name ("disable-memory-cache");
5105//
5106// return disable_memory_cache_var_name;
5107//}
5108//
5109//const ConstString &
5110//ProcessInstanceSettings::GetExtraStartupCommandVarName () const
5111//{
5112// static ConstString extra_startup_command_var_name ("extra-startup-command");
5113//
5114// return extra_startup_command_var_name;
5115//}
5116//
5117////--------------------------------------------------
5118//// SettingsController Variable Tables
5119////--------------------------------------------------
5120//
5121//SettingEntry
5122//Process::SettingsController::global_settings_table[] =
5123//{
5124// //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
5125// { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
5126//};
5127//
5128//
5129//SettingEntry
5130//Process::SettingsController::instance_settings_table[] =
5131//{
5132// //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
5133// { "disable-memory-cache", eSetVarTypeBoolean,
5134//#ifdef ENABLE_MEMORY_CACHING
5135// "false",
5136//#else
5137// "true",
5138//#endif
5139// NULL, false, false, "Disable reading and caching of memory in fixed-size units." },
5140// { "extra-startup-command", eSetVarTypeArray, NULL, NULL, false, false, "A list containing extra commands understood by the particular process plugin used." },
5141// { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
5142//};
5143//
5144//
Jim Ingham5aee1622010-08-09 23:31:02 +00005145
Greg Clayton1d885962011-11-08 02:43:13 +00005146