blob: a7279c1bc59c377fde7bf8797e76568bca40390d [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-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"
39
40using namespace lldb;
41using namespace lldb_private;
42
Greg Clayton24bc5d92011-03-30 18:16:51 +000043void
Greg Claytonb72d0f02011-04-12 05:54:46 +000044ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +000045{
46 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +000047 if (m_pid != LLDB_INVALID_PROCESS_ID)
48 s.Printf (" pid = %i\n", m_pid);
49
50 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
51 s.Printf (" parent = %i\n", m_parent_pid);
52
53 if (m_executable)
54 {
55 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
56 s.PutCString (" file = ");
57 m_executable.Dump(&s);
58 s.EOL();
59 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000060 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +000061 if (argc > 0)
62 {
63 for (uint32_t i=0; i<argc; i++)
64 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000065 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +000066 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +000067 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000068 else
Greg Claytonb72d0f02011-04-12 05:54:46 +000069 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000070 }
71 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000072
73 const uint32_t envc = m_environment.GetArgumentCount();
74 if (envc > 0)
75 {
76 for (uint32_t i=0; i<envc; i++)
77 {
78 const char *env = m_environment.GetArgumentAtIndex(i);
79 if (i < 10)
80 s.Printf (" env[%u] = %s\n", i, env);
81 else
82 s.Printf ("env[%u] = %s\n", i, env);
83 }
84 }
85
Greg Claytonff39f742011-04-01 00:29:43 +000086 if (m_arch.IsValid())
87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
88
Greg Claytonb72d0f02011-04-12 05:54:46 +000089 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000090 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000091 cstr = platform->GetUserName (m_uid);
92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000093 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000094 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000095 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000096 cstr = platform->GetGroupName (m_gid);
97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000098 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000099 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000100 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000101 cstr = platform->GetUserName (m_euid);
102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000103 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000104 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000105 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000106 cstr = platform->GetGroupName (m_egid);
107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000108 }
109}
110
111void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000112ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000113{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000114 const char *label;
115 if (show_args || verbose)
116 label = "ARGUMENTS";
117 else
118 label = "NAME";
119
Greg Claytonff39f742011-04-01 00:29:43 +0000120 if (verbose)
121 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
124 }
125 else
126 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000127 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000128 s.PutCString ("====== ====== ========== ======= ============================\n");
129 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000130}
131
132void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000133ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000134{
135 if (m_pid != LLDB_INVALID_PROCESS_ID)
136 {
137 const char *cstr;
138 s.Printf ("%-6u %-6u ", m_pid, m_parent_pid);
139
Greg Clayton24bc5d92011-03-30 18:16:51 +0000140
Greg Claytonff39f742011-04-01 00:29:43 +0000141 if (verbose)
142 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000143 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000144 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
145 s.Printf ("%-10s ", cstr);
146 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000147 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000148
Greg Claytonb72d0f02011-04-12 05:54:46 +0000149 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000150 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
151 s.Printf ("%-10s ", cstr);
152 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000153 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000154
Greg Claytonb72d0f02011-04-12 05:54:46 +0000155 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000156 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
157 s.Printf ("%-10s ", cstr);
158 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000159 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000160
Greg Claytonb72d0f02011-04-12 05:54:46 +0000161 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000162 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
163 s.Printf ("%-10s ", cstr);
164 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000165 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000166 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
167 }
168 else
169 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000170 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000171 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000172 (int)m_arch.GetTriple().getArchName().size(),
173 m_arch.GetTriple().getArchName().data());
174 }
175
Greg Claytonb72d0f02011-04-12 05:54:46 +0000176 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000177 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000178 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000179 if (argc > 0)
180 {
181 for (uint32_t i=0; i<argc; i++)
182 {
183 if (i > 0)
184 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000185 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000186 }
187 }
188 }
189 else
190 {
191 s.PutCString (GetName());
192 }
193
194 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000195 }
196}
197
Greg Claytonb72d0f02011-04-12 05:54:46 +0000198
199void
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000200ProcessInfo::SetArguments (char const **argv,
201 bool first_arg_is_executable,
202 bool first_arg_is_executable_and_argument)
203{
204 m_arguments.SetArguments (argv);
205
206 // Is the first argument the executable?
207 if (first_arg_is_executable)
208 {
209 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
210 if (first_arg)
211 {
212 // Yes the first argument is an executable, set it as the executable
213 // in the launch options. Don't resolve the file path as the path
214 // could be a remote platform path
215 const bool resolve = false;
216 m_executable.SetFile(first_arg, resolve);
217
218 // If argument zero is an executable and shouldn't be included
219 // in the arguments, remove it from the front of the arguments
220 if (first_arg_is_executable_and_argument == false)
221 m_arguments.DeleteArgumentAtIndex (0);
222 }
223 }
224}
225void
226ProcessInfo::SetArguments (const Args& args,
227 bool first_arg_is_executable,
228 bool first_arg_is_executable_and_argument)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000229{
230 // Copy all arguments
231 m_arguments = args;
232
233 // Is the first argument the executable?
234 if (first_arg_is_executable)
235 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000236 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000237 if (first_arg)
238 {
239 // Yes the first argument is an executable, set it as the executable
240 // in the launch options. Don't resolve the file path as the path
241 // could be a remote platform path
242 const bool resolve = false;
243 m_executable.SetFile(first_arg, resolve);
244
245 // If argument zero is an executable and shouldn't be included
246 // in the arguments, remove it from the front of the arguments
247 if (first_arg_is_executable_and_argument == false)
248 m_arguments.DeleteArgumentAtIndex (0);
249 }
250 }
251}
252
Greg Clayton24bc5d92011-03-30 18:16:51 +0000253bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000254ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
255{
256 if ((read || write) && fd >= 0 && path && path[0])
257 {
258 m_action = eFileActionOpen;
259 m_fd = fd;
260 if (read && write)
261 m_arg = O_RDWR;
262 else if (read)
263 m_arg = O_RDONLY;
264 else
265 m_arg = O_WRONLY;
266 m_path.assign (path);
267 return true;
268 }
269 else
270 {
271 Clear();
272 }
273 return false;
274}
275
276bool
277ProcessLaunchInfo::FileAction::Close (int fd)
278{
279 Clear();
280 if (fd >= 0)
281 {
282 m_action = eFileActionClose;
283 m_fd = fd;
284 }
285 return m_fd >= 0;
286}
287
288
289bool
290ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
291{
292 Clear();
293 if (fd >= 0 && dup_fd >= 0)
294 {
295 m_action = eFileActionDuplicate;
296 m_fd = fd;
297 m_arg = dup_fd;
298 }
299 return m_fd >= 0;
300}
301
302
303
304bool
305ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
306 const FileAction *info,
307 Log *log,
308 Error& error)
309{
310 if (info == NULL)
311 return false;
312
313 switch (info->m_action)
314 {
315 case eFileActionNone:
316 error.Clear();
317 break;
318
319 case eFileActionClose:
320 if (info->m_fd == -1)
321 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
322 else
323 {
324 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
325 eErrorTypePOSIX);
326 if (log && (error.Fail() || log))
327 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
328 file_actions, info->m_fd);
329 }
330 break;
331
332 case eFileActionDuplicate:
333 if (info->m_fd == -1)
334 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
335 else if (info->m_arg == -1)
336 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
337 else
338 {
339 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
340 eErrorTypePOSIX);
341 if (log && (error.Fail() || log))
342 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
343 file_actions, info->m_fd, info->m_arg);
344 }
345 break;
346
347 case eFileActionOpen:
348 if (info->m_fd == -1)
349 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
350 else
351 {
352 int oflag = info->m_arg;
353 mode_t mode = 0;
354
355 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
356 info->m_fd,
357 info->m_path.c_str(),
358 oflag,
359 mode),
360 eErrorTypePOSIX);
361 if (error.Fail() || log)
362 error.PutToLog(log,
363 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
364 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
365 }
366 break;
367
368 default:
369 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
370 break;
371 }
372 return error.Success();
373}
374
375Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000376ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000377{
378 Error error;
379 char short_option = (char) m_getopt_table[option_idx].val;
380
381 switch (short_option)
382 {
383 case 's': // Stop at program entry point
384 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
385 break;
386
387 case 'e': // STDERR for read + write
388 {
389 ProcessLaunchInfo::FileAction action;
390 if (action.Open(STDERR_FILENO, option_arg, true, true))
391 launch_info.AppendFileAction (action);
392 }
393 break;
394
395 case 'i': // STDIN for read only
396 {
397 ProcessLaunchInfo::FileAction action;
398 if (action.Open(STDIN_FILENO, option_arg, true, false))
399 launch_info.AppendFileAction (action);
400 }
401 break;
402
403 case 'o': // Open STDOUT for write only
404 {
405 ProcessLaunchInfo::FileAction action;
406 if (action.Open(STDOUT_FILENO, option_arg, false, true))
407 launch_info.AppendFileAction (action);
408 }
409 break;
410
411 case 'p': // Process plug-in name
412 launch_info.SetProcessPluginName (option_arg);
413 break;
414
415 case 'n': // Disable STDIO
416 {
417 ProcessLaunchInfo::FileAction action;
418 if (action.Open(STDERR_FILENO, "/dev/null", true, true))
419 launch_info.AppendFileAction (action);
420 if (action.Open(STDOUT_FILENO, "/dev/null", false, true))
421 launch_info.AppendFileAction (action);
422 if (action.Open(STDIN_FILENO, "/dev/null", true, false))
423 launch_info.AppendFileAction (action);
424 }
425 break;
426
427 case 'w':
428 launch_info.SetWorkingDirectory (option_arg);
429 break;
430
431 case 't': // Open process in new terminal window
432 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
433 break;
434
435 case 'a':
436 launch_info.GetArchitecture().SetTriple (option_arg,
437 m_interpreter.GetPlatform(true).get());
438 break;
439
440 case 'A':
441 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
442 break;
443
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000444 case 'c':
445 launch_info.GetFlags().Set (eLaunchFlagLaunchInShell);
446 break;
447
Greg Claytonb72d0f02011-04-12 05:54:46 +0000448 case 'v':
449 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
450 break;
451
452 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000453 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000454 break;
455
456 }
457 return error;
458}
459
460OptionDefinition
461ProcessLaunchCommandOptions::g_option_table[] =
462{
463{ 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."},
464{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
465{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
466{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
467{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
468{ 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."},
469
470{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
471{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
472{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
473
474{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
475
476{ 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."},
477
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000478{ LLDB_OPT_SET_4 , false, "shell", 'c', no_argument, NULL, 0, eArgTypeNone, "Run the process in a shell (not supported on all platforms)."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000479{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
480};
481
482
483
484bool
485ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000486{
487 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
488 return true;
489 const char *match_name = m_match_info.GetName();
490 if (!match_name)
491 return true;
492
493 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
494}
495
496bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000497ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000498{
499 if (!NameMatches (proc_info.GetName()))
500 return false;
501
502 if (m_match_info.ProcessIDIsValid() &&
503 m_match_info.GetProcessID() != proc_info.GetProcessID())
504 return false;
505
506 if (m_match_info.ParentProcessIDIsValid() &&
507 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
508 return false;
509
Greg Claytonb72d0f02011-04-12 05:54:46 +0000510 if (m_match_info.UserIDIsValid () &&
511 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000512 return false;
513
Greg Claytonb72d0f02011-04-12 05:54:46 +0000514 if (m_match_info.GroupIDIsValid () &&
515 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000516 return false;
517
518 if (m_match_info.EffectiveUserIDIsValid () &&
519 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
520 return false;
521
522 if (m_match_info.EffectiveGroupIDIsValid () &&
523 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
524 return false;
525
526 if (m_match_info.GetArchitecture().IsValid() &&
527 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
528 return false;
529 return true;
530}
531
532bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000533ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000534{
535 if (m_name_match_type != eNameMatchIgnore)
536 return false;
537
538 if (m_match_info.ProcessIDIsValid())
539 return false;
540
541 if (m_match_info.ParentProcessIDIsValid())
542 return false;
543
Greg Claytonb72d0f02011-04-12 05:54:46 +0000544 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000545 return false;
546
Greg Claytonb72d0f02011-04-12 05:54:46 +0000547 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000548 return false;
549
550 if (m_match_info.EffectiveUserIDIsValid ())
551 return false;
552
553 if (m_match_info.EffectiveGroupIDIsValid ())
554 return false;
555
556 if (m_match_info.GetArchitecture().IsValid())
557 return false;
558
559 if (m_match_all_users)
560 return false;
561
562 return true;
563
564}
565
566void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000567ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000568{
569 m_match_info.Clear();
570 m_name_match_type = eNameMatchIgnore;
571 m_match_all_users = false;
572}
Greg Claytonfd119992011-01-07 06:08:19 +0000573
Chris Lattner24943d22010-06-08 16:52:24 +0000574Process*
575Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
576{
577 ProcessCreateInstance create_callback = NULL;
578 if (plugin_name)
579 {
580 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
581 if (create_callback)
582 {
583 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton8d2ea282011-07-17 20:36:25 +0000584 if (debugger_ap->CanDebug(target, true))
Chris Lattner24943d22010-06-08 16:52:24 +0000585 return debugger_ap.release();
586 }
587 }
588 else
589 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000590 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000591 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000592 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton8d2ea282011-07-17 20:36:25 +0000593 if (debugger_ap->CanDebug(target, false))
Greg Clayton54e7afa2010-07-09 20:39:50 +0000594 return debugger_ap.release();
Chris Lattner24943d22010-06-08 16:52:24 +0000595 }
596 }
597 return NULL;
598}
599
600
601//----------------------------------------------------------------------
602// Process constructor
603//----------------------------------------------------------------------
604Process::Process(Target &target, Listener &listener) :
605 UserID (LLDB_INVALID_PROCESS_ID),
Greg Clayton49ce6822010-10-31 03:01:06 +0000606 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +0000607 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000608 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000609 m_public_state (eStateUnloaded),
610 m_private_state (eStateUnloaded),
611 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
612 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
613 m_private_state_listener ("lldb.process.internal_state_listener"),
614 m_private_state_control_wait(),
615 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000616 m_mod_id (),
Chris Lattner24943d22010-06-08 16:52:24 +0000617 m_thread_index_id (0),
618 m_exit_status (-1),
619 m_exit_string (),
620 m_thread_list (this),
621 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000622 m_image_tokens (),
623 m_listener (listener),
624 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000625 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000626 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000627 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000628 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000629 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000630 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000631 m_stdout_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000632 m_memory_cache (*this),
633 m_allocated_memory_cache (*this),
Jim Inghamc0c53242011-09-15 21:36:42 +0000634 m_attached_to_process (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000635 m_next_event_action_ap(),
636 m_can_jit(eCanJITYes)
Chris Lattner24943d22010-06-08 16:52:24 +0000637{
Caroline Tice1ebef442010-09-27 00:30:10 +0000638 UpdateInstanceName();
639
Greg Claytone005f2c2010-11-06 01:53:30 +0000640 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000641 if (log)
642 log->Printf ("%p Process::Process()", this);
643
Greg Clayton49ce6822010-10-31 03:01:06 +0000644 SetEventName (eBroadcastBitStateChanged, "state-changed");
645 SetEventName (eBroadcastBitInterrupt, "interrupt");
646 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
647 SetEventName (eBroadcastBitSTDERR, "stderr-available");
648
Chris Lattner24943d22010-06-08 16:52:24 +0000649 listener.StartListeningForEvents (this,
650 eBroadcastBitStateChanged |
651 eBroadcastBitInterrupt |
652 eBroadcastBitSTDOUT |
653 eBroadcastBitSTDERR);
654
655 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
656 eBroadcastBitStateChanged);
657
658 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
659 eBroadcastInternalStateControlStop |
660 eBroadcastInternalStateControlPause |
661 eBroadcastInternalStateControlResume);
662}
663
664//----------------------------------------------------------------------
665// Destructor
666//----------------------------------------------------------------------
667Process::~Process()
668{
Greg Claytone005f2c2010-11-06 01:53:30 +0000669 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000670 if (log)
671 log->Printf ("%p Process::~Process()", this);
672 StopPrivateStateThread();
673}
674
675void
676Process::Finalize()
677{
Greg Clayton2f57db02011-10-01 00:45:15 +0000678 // Clear our broadcaster before we proceed with destroying
679 Broadcaster::Clear();
680
Chris Lattner24943d22010-06-08 16:52:24 +0000681 // Do any cleanup needed prior to being destructed... Subclasses
682 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000683
684 // We need to destroy the loader before the derived Process class gets destroyed
685 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton37f962e2011-08-22 02:49:39 +0000686 m_dyld_ap.reset();
687 m_os_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000688}
689
690void
691Process::RegisterNotificationCallbacks (const Notifications& callbacks)
692{
693 m_notifications.push_back(callbacks);
694 if (callbacks.initialize != NULL)
695 callbacks.initialize (callbacks.baton, this);
696}
697
698bool
699Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
700{
701 std::vector<Notifications>::iterator pos, end = m_notifications.end();
702 for (pos = m_notifications.begin(); pos != end; ++pos)
703 {
704 if (pos->baton == callbacks.baton &&
705 pos->initialize == callbacks.initialize &&
706 pos->process_state_changed == callbacks.process_state_changed)
707 {
708 m_notifications.erase(pos);
709 return true;
710 }
711 }
712 return false;
713}
714
715void
716Process::SynchronouslyNotifyStateChanged (StateType state)
717{
718 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
719 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
720 {
721 if (notification_pos->process_state_changed)
722 notification_pos->process_state_changed (notification_pos->baton, this, state);
723 }
724}
725
726// FIXME: We need to do some work on events before the general Listener sees them.
727// For instance if we are continuing from a breakpoint, we need to ensure that we do
728// the little "insert real insn, step & stop" trick. But we can't do that when the
729// event is delivered by the broadcaster - since that is done on the thread that is
730// waiting for new events, so if we needed more than one event for our handling, we would
731// stall. So instead we do it when we fetch the event off of the queue.
732//
733
734StateType
735Process::GetNextEvent (EventSP &event_sp)
736{
737 StateType state = eStateInvalid;
738
739 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
740 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
741
742 return state;
743}
744
745
746StateType
747Process::WaitForProcessToStop (const TimeValue *timeout)
748{
Jim Ingham21f37ad2011-08-09 02:12:22 +0000749 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
750 // We have to actually check each event, and in the case of a stopped event check the restarted flag
751 // on the event.
752 EventSP event_sp;
753 StateType state = GetState();
754 // If we are exited or detached, we won't ever get back to any
755 // other valid state...
756 if (state == eStateDetached || state == eStateExited)
757 return state;
758
759 while (state != eStateInvalid)
760 {
761 state = WaitForStateChangedEvents (timeout, event_sp);
762 switch (state)
763 {
764 case eStateCrashed:
765 case eStateDetached:
766 case eStateExited:
767 case eStateUnloaded:
768 return state;
769 case eStateStopped:
770 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
771 continue;
772 else
773 return state;
774 default:
775 continue;
776 }
777 }
778 return state;
Chris Lattner24943d22010-06-08 16:52:24 +0000779}
780
781
782StateType
783Process::WaitForState
784(
785 const TimeValue *timeout,
786 const StateType *match_states, const uint32_t num_match_states
787)
788{
789 EventSP event_sp;
790 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000791 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000792 while (state != eStateInvalid)
793 {
Greg Claytond8c62532010-10-07 04:19:01 +0000794 // If we are exited or detached, we won't ever get back to any
795 // other valid state...
796 if (state == eStateDetached || state == eStateExited)
797 return state;
798
Chris Lattner24943d22010-06-08 16:52:24 +0000799 state = WaitForStateChangedEvents (timeout, event_sp);
800
801 for (i=0; i<num_match_states; ++i)
802 {
803 if (match_states[i] == state)
804 return state;
805 }
806 }
807 return state;
808}
809
Jim Ingham63e24d72010-10-11 23:53:14 +0000810bool
811Process::HijackProcessEvents (Listener *listener)
812{
813 if (listener != NULL)
814 {
815 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
816 }
817 else
818 return false;
819}
820
821void
822Process::RestoreProcessEvents ()
823{
824 RestoreBroadcaster();
825}
826
Jim Inghamf9f40c22011-02-08 05:20:59 +0000827bool
828Process::HijackPrivateProcessEvents (Listener *listener)
829{
830 if (listener != NULL)
831 {
832 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
833 }
834 else
835 return false;
836}
837
838void
839Process::RestorePrivateProcessEvents ()
840{
841 m_private_state_broadcaster.RestoreBroadcaster();
842}
843
Chris Lattner24943d22010-06-08 16:52:24 +0000844StateType
845Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
846{
Greg Claytone005f2c2010-11-06 01:53:30 +0000847 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000848
849 if (log)
850 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
851
852 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000853 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
854 this,
855 eBroadcastBitStateChanged,
856 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000857 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
858
859 if (log)
860 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
861 __FUNCTION__,
862 timeout,
863 StateAsCString(state));
864 return state;
865}
866
867Event *
868Process::PeekAtStateChangedEvents ()
869{
Greg Claytone005f2c2010-11-06 01:53:30 +0000870 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000871
872 if (log)
873 log->Printf ("Process::%s...", __FUNCTION__);
874
875 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000876 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
877 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +0000878 if (log)
879 {
880 if (event_ptr)
881 {
882 log->Printf ("Process::%s (event_ptr) => %s",
883 __FUNCTION__,
884 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
885 }
886 else
887 {
888 log->Printf ("Process::%s no events found",
889 __FUNCTION__);
890 }
891 }
892 return event_ptr;
893}
894
895StateType
896Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
897{
Greg Claytone005f2c2010-11-06 01:53:30 +0000898 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000899
900 if (log)
901 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
902
903 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +0000904 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
905 &m_private_state_broadcaster,
906 eBroadcastBitStateChanged,
907 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000908 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
909
910 // This is a bit of a hack, but when we wait here we could very well return
911 // to the command-line, and that could disable the log, which would render the
912 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +0000913 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +0000914 {
915 if (state == eStateInvalid)
916 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
917 else
918 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
919 }
Chris Lattner24943d22010-06-08 16:52:24 +0000920 return state;
921}
922
923bool
924Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
925{
Greg Claytone005f2c2010-11-06 01:53:30 +0000926 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000927
928 if (log)
929 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
930
931 if (control_only)
932 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
933 else
934 return m_private_state_listener.WaitForEvent(timeout, event_sp);
935}
936
937bool
938Process::IsRunning () const
939{
940 return StateIsRunningState (m_public_state.GetValue());
941}
942
943int
944Process::GetExitStatus ()
945{
946 if (m_public_state.GetValue() == eStateExited)
947 return m_exit_status;
948 return -1;
949}
950
Greg Clayton638351a2010-12-04 00:10:17 +0000951
952void
953Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
954{
955 if (m_inherit_host_env && !m_got_host_env)
956 {
957 m_got_host_env = true;
958 StringList host_env;
959 const size_t host_env_count = Host::GetEnvironment (host_env);
960 for (size_t idx=0; idx<host_env_count; idx++)
961 {
962 const char *env_entry = host_env.GetStringAtIndex (idx);
963 if (env_entry)
964 {
Greg Clayton1f3dd642010-12-15 20:52:40 +0000965 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton638351a2010-12-04 00:10:17 +0000966 if (equal_pos)
967 {
968 std::string key (env_entry, equal_pos - env_entry);
969 std::string value (equal_pos + 1);
970 if (m_env_vars.find (key) == m_env_vars.end())
971 m_env_vars[key] = value;
972 }
973 }
974 }
975 }
976}
977
978
979size_t
980Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
981{
982 GetHostEnvironmentIfNeeded ();
983
984 dictionary::const_iterator pos, end = m_env_vars.end();
985 for (pos = m_env_vars.begin(); pos != end; ++pos)
986 {
987 std::string env_var_equal_value (pos->first);
988 env_var_equal_value.append(1, '=');
989 env_var_equal_value.append (pos->second);
990 env.AppendArgument (env_var_equal_value.c_str());
991 }
992 return env.GetArgumentCount();
993}
994
995
Chris Lattner24943d22010-06-08 16:52:24 +0000996const char *
997Process::GetExitDescription ()
998{
999 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1000 return m_exit_string.c_str();
1001 return NULL;
1002}
1003
Greg Clayton72e1c782011-01-22 23:43:18 +00001004bool
Chris Lattner24943d22010-06-08 16:52:24 +00001005Process::SetExitStatus (int status, const char *cstr)
1006{
Greg Clayton68ca8232011-01-25 02:58:48 +00001007 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1008 if (log)
1009 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1010 status, status,
1011 cstr ? "\"" : "",
1012 cstr ? cstr : "NULL",
1013 cstr ? "\"" : "");
1014
Greg Clayton72e1c782011-01-22 23:43:18 +00001015 // We were already in the exited state
1016 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001017 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001018 if (log)
1019 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001020 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001021 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001022
1023 m_exit_status = status;
1024 if (cstr)
1025 m_exit_string = cstr;
1026 else
1027 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001028
Greg Clayton72e1c782011-01-22 23:43:18 +00001029 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001030
Greg Clayton72e1c782011-01-22 23:43:18 +00001031 SetPrivateState (eStateExited);
1032 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001033}
1034
1035// This static callback can be used to watch for local child processes on
1036// the current host. The the child process exits, the process will be
1037// found in the global target list (we want to be completely sure that the
1038// lldb_private::Process doesn't go away before we can deliver the signal.
1039bool
1040Process::SetProcessExitStatus
1041(
1042 void *callback_baton,
1043 lldb::pid_t pid,
1044 int signo, // Zero for no signal
1045 int exit_status // Exit value of process if signal is zero
1046)
1047{
1048 if (signo == 0 || exit_status)
1049 {
Greg Clayton63094e02010-06-23 01:19:29 +00001050 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001051 if (target_sp)
1052 {
1053 ProcessSP process_sp (target_sp->GetProcessSP());
1054 if (process_sp)
1055 {
1056 const char *signal_cstr = NULL;
1057 if (signo)
1058 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1059
1060 process_sp->SetExitStatus (exit_status, signal_cstr);
1061 }
1062 }
1063 return true;
1064 }
1065 return false;
1066}
1067
1068
Greg Clayton37f962e2011-08-22 02:49:39 +00001069void
1070Process::UpdateThreadListIfNeeded ()
1071{
1072 const uint32_t stop_id = GetStopID();
1073 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1074 {
1075 Mutex::Locker locker (m_thread_list.GetMutex ());
1076 ThreadList new_thread_list(this);
1077 // Always update the thread list with the protocol specific
1078 // thread list
1079 UpdateThreadList (m_thread_list, new_thread_list);
1080 OperatingSystem *os = GetOperatingSystem ();
1081 if (os)
1082 os->UpdateThreadList (m_thread_list, new_thread_list);
1083 m_thread_list.Update (new_thread_list);
1084 m_thread_list.SetStopID (stop_id);
1085 }
1086}
1087
Chris Lattner24943d22010-06-08 16:52:24 +00001088uint32_t
1089Process::GetNextThreadIndexID ()
1090{
1091 return ++m_thread_index_id;
1092}
1093
1094StateType
1095Process::GetState()
1096{
1097 // If any other threads access this we will need a mutex for it
1098 return m_public_state.GetValue ();
1099}
1100
1101void
1102Process::SetPublicState (StateType new_state)
1103{
Greg Clayton68ca8232011-01-25 02:58:48 +00001104 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001105 if (log)
1106 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1107 m_public_state.SetValue (new_state);
1108}
1109
1110StateType
1111Process::GetPrivateState ()
1112{
1113 return m_private_state.GetValue();
1114}
1115
1116void
1117Process::SetPrivateState (StateType new_state)
1118{
Greg Clayton68ca8232011-01-25 02:58:48 +00001119 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001120 bool state_changed = false;
1121
1122 if (log)
1123 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1124
1125 Mutex::Locker locker(m_private_state.GetMutex());
1126
1127 const StateType old_state = m_private_state.GetValueNoLock ();
1128 state_changed = old_state != new_state;
1129 if (state_changed)
1130 {
1131 m_private_state.SetValueNoLock (new_state);
1132 if (StateIsStoppedState(new_state))
1133 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001134 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001135 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001136 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001137 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001138 }
1139 // Use our target to get a shared pointer to ourselves...
1140 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1141 }
1142 else
1143 {
1144 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001145 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001146 }
1147}
1148
Chris Lattner24943d22010-06-08 16:52:24 +00001149addr_t
1150Process::GetImageInfoAddress()
1151{
1152 return LLDB_INVALID_ADDRESS;
1153}
1154
Greg Clayton0baa3942010-11-04 01:54:29 +00001155//----------------------------------------------------------------------
1156// LoadImage
1157//
1158// This function provides a default implementation that works for most
1159// unix variants. Any Process subclasses that need to do shared library
1160// loading differently should override LoadImage and UnloadImage and
1161// do what is needed.
1162//----------------------------------------------------------------------
1163uint32_t
1164Process::LoadImage (const FileSpec &image_spec, Error &error)
1165{
1166 DynamicLoader *loader = GetDynamicLoader();
1167 if (loader)
1168 {
1169 error = loader->CanLoadImage();
1170 if (error.Fail())
1171 return LLDB_INVALID_IMAGE_TOKEN;
1172 }
1173
1174 if (error.Success())
1175 {
1176 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001177
1178 if (thread_sp)
1179 {
1180 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1181
1182 if (frame_sp)
1183 {
1184 ExecutionContext exe_ctx;
1185 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001186 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001187 StreamString expr;
1188 char path[PATH_MAX];
1189 image_spec.GetPath(path, sizeof(path));
1190 expr.Printf("dlopen (\"%s\", 2)", path);
1191 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001192 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan5b658cc2011-11-07 23:35:40 +00001193 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chenb14ec342011-09-09 00:01:43 +00001194 error = result_valobj_sp->GetError();
1195 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001196 {
1197 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001198 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001199 {
1200 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1201 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1202 {
1203 uint32_t image_token = m_image_tokens.size();
1204 m_image_tokens.push_back (image_ptr);
1205 return image_token;
1206 }
1207 }
1208 }
1209 }
1210 }
1211 }
1212 return LLDB_INVALID_IMAGE_TOKEN;
1213}
1214
1215//----------------------------------------------------------------------
1216// UnloadImage
1217//
1218// This function provides a default implementation that works for most
1219// unix variants. Any Process subclasses that need to do shared library
1220// loading differently should override LoadImage and UnloadImage and
1221// do what is needed.
1222//----------------------------------------------------------------------
1223Error
1224Process::UnloadImage (uint32_t image_token)
1225{
1226 Error error;
1227 if (image_token < m_image_tokens.size())
1228 {
1229 const addr_t image_addr = m_image_tokens[image_token];
1230 if (image_addr == LLDB_INVALID_ADDRESS)
1231 {
1232 error.SetErrorString("image already unloaded");
1233 }
1234 else
1235 {
1236 DynamicLoader *loader = GetDynamicLoader();
1237 if (loader)
1238 error = loader->CanLoadImage();
1239
1240 if (error.Success())
1241 {
1242 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001243
1244 if (thread_sp)
1245 {
1246 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1247
1248 if (frame_sp)
1249 {
1250 ExecutionContext exe_ctx;
1251 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001252 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001253 StreamString expr;
1254 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1255 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001256 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan5b658cc2011-11-07 23:35:40 +00001257 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +00001258 if (result_valobj_sp->GetError().Success())
1259 {
1260 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001261 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001262 {
1263 if (scalar.UInt(1))
1264 {
1265 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1266 }
1267 else
1268 {
1269 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1270 }
1271 }
1272 }
1273 else
1274 {
1275 error = result_valobj_sp->GetError();
1276 }
1277 }
1278 }
1279 }
1280 }
1281 }
1282 else
1283 {
1284 error.SetErrorString("invalid image token");
1285 }
1286 return error;
1287}
1288
Greg Clayton75906e42011-05-11 18:39:18 +00001289const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001290Process::GetABI()
1291{
Greg Clayton75906e42011-05-11 18:39:18 +00001292 if (!m_abi_sp)
1293 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1294 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001295}
1296
Jim Ingham642036f2010-09-23 02:01:19 +00001297LanguageRuntime *
1298Process::GetLanguageRuntime(lldb::LanguageType language)
1299{
1300 LanguageRuntimeCollection::iterator pos;
1301 pos = m_language_runtimes.find (language);
1302 if (pos == m_language_runtimes.end())
1303 {
1304 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1305
1306 m_language_runtimes[language]
1307 = runtime;
1308 return runtime.get();
1309 }
1310 else
1311 return (*pos).second.get();
1312}
1313
1314CPPLanguageRuntime *
1315Process::GetCPPLanguageRuntime ()
1316{
1317 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1318 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1319 return static_cast<CPPLanguageRuntime *> (runtime);
1320 return NULL;
1321}
1322
1323ObjCLanguageRuntime *
1324Process::GetObjCLanguageRuntime ()
1325{
1326 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1327 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1328 return static_cast<ObjCLanguageRuntime *> (runtime);
1329 return NULL;
1330}
1331
Chris Lattner24943d22010-06-08 16:52:24 +00001332BreakpointSiteList &
1333Process::GetBreakpointSiteList()
1334{
1335 return m_breakpoint_site_list;
1336}
1337
1338const BreakpointSiteList &
1339Process::GetBreakpointSiteList() const
1340{
1341 return m_breakpoint_site_list;
1342}
1343
1344
1345void
1346Process::DisableAllBreakpointSites ()
1347{
1348 m_breakpoint_site_list.SetEnabledForAll (false);
1349}
1350
1351Error
1352Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1353{
1354 Error error (DisableBreakpointSiteByID (break_id));
1355
1356 if (error.Success())
1357 m_breakpoint_site_list.Remove(break_id);
1358
1359 return error;
1360}
1361
1362Error
1363Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1364{
1365 Error error;
1366 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1367 if (bp_site_sp)
1368 {
1369 if (bp_site_sp->IsEnabled())
1370 error = DisableBreakpoint (bp_site_sp.get());
1371 }
1372 else
1373 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001374 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001375 }
1376
1377 return error;
1378}
1379
1380Error
1381Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1382{
1383 Error error;
1384 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1385 if (bp_site_sp)
1386 {
1387 if (!bp_site_sp->IsEnabled())
1388 error = EnableBreakpoint (bp_site_sp.get());
1389 }
1390 else
1391 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001392 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001393 }
1394 return error;
1395}
1396
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001397lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +00001398Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1399{
Greg Clayton265ab332011-05-19 18:17:41 +00001400 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001401 if (load_addr != LLDB_INVALID_ADDRESS)
1402 {
1403 BreakpointSiteSP bp_site_sp;
1404
1405 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1406 // create a new breakpoint site and add it.
1407
1408 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1409
1410 if (bp_site_sp)
1411 {
1412 bp_site_sp->AddOwner (owner);
1413 owner->SetBreakpointSite (bp_site_sp);
1414 return bp_site_sp->GetID();
1415 }
1416 else
1417 {
1418 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1419 if (bp_site_sp)
1420 {
1421 if (EnableBreakpoint (bp_site_sp.get()).Success())
1422 {
1423 owner->SetBreakpointSite (bp_site_sp);
1424 return m_breakpoint_site_list.Add (bp_site_sp);
1425 }
1426 }
1427 }
1428 }
1429 // We failed to enable the breakpoint
1430 return LLDB_INVALID_BREAK_ID;
1431
1432}
1433
1434void
1435Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1436{
1437 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1438 if (num_owners == 0)
1439 {
1440 DisableBreakpoint(bp_site_sp.get());
1441 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1442 }
1443}
1444
1445
1446size_t
1447Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1448{
1449 size_t bytes_removed = 0;
1450 addr_t intersect_addr;
1451 size_t intersect_size;
1452 size_t opcode_offset;
1453 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001454 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001455 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001456
Jim Ingham82820f92011-06-29 19:42:28 +00001457 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001458 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001459 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001460 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001461 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001462 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001463 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001464 {
1465 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1466 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001467 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001468 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001469 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001470 }
Chris Lattner24943d22010-06-08 16:52:24 +00001471 }
1472 }
1473 }
1474 return bytes_removed;
1475}
1476
1477
Greg Claytonb1888f22011-03-19 01:12:21 +00001478
1479size_t
1480Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1481{
1482 PlatformSP platform_sp (m_target.GetPlatform());
1483 if (platform_sp)
1484 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1485 return 0;
1486}
1487
Chris Lattner24943d22010-06-08 16:52:24 +00001488Error
1489Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1490{
1491 Error error;
1492 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001493 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001494 const addr_t bp_addr = bp_site->GetLoadAddress();
1495 if (log)
1496 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1497 if (bp_site->IsEnabled())
1498 {
1499 if (log)
1500 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1501 return error;
1502 }
1503
1504 if (bp_addr == LLDB_INVALID_ADDRESS)
1505 {
1506 error.SetErrorString("BreakpointSite contains an invalid load address.");
1507 return error;
1508 }
1509 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1510 // trap for the breakpoint site
1511 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1512
1513 if (bp_opcode_size == 0)
1514 {
Greg Clayton9c236732011-10-26 00:56:27 +00001515 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001516 }
1517 else
1518 {
1519 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1520
1521 if (bp_opcode_bytes == NULL)
1522 {
1523 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1524 return error;
1525 }
1526
1527 // Save the original opcode by reading it
1528 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1529 {
1530 // Write a software breakpoint in place of the original opcode
1531 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1532 {
1533 uint8_t verify_bp_opcode_bytes[64];
1534 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1535 {
1536 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1537 {
1538 bp_site->SetEnabled(true);
1539 bp_site->SetType (BreakpointSite::eSoftware);
1540 if (log)
1541 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1542 bp_site->GetID(),
1543 (uint64_t)bp_addr);
1544 }
1545 else
Greg Clayton9c236732011-10-26 00:56:27 +00001546 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00001547 }
1548 else
1549 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1550 }
1551 else
1552 error.SetErrorString("Unable to write breakpoint trap to memory.");
1553 }
1554 else
1555 error.SetErrorString("Unable to read memory at breakpoint address.");
1556 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001557 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001558 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1559 bp_site->GetID(),
1560 (uint64_t)bp_addr,
1561 error.AsCString());
1562 return error;
1563}
1564
1565Error
1566Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1567{
1568 Error error;
1569 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001570 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001571 addr_t bp_addr = bp_site->GetLoadAddress();
1572 lldb::user_id_t breakID = bp_site->GetID();
1573 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001574 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001575
1576 if (bp_site->IsHardware())
1577 {
1578 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1579 }
1580 else if (bp_site->IsEnabled())
1581 {
1582 const size_t break_op_size = bp_site->GetByteSize();
1583 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1584 if (break_op_size > 0)
1585 {
1586 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001587 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001588 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001589 bool break_op_found = false;
1590
1591 // Read the breakpoint opcode
1592 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1593 {
1594 bool verify = false;
1595 // Make sure we have the a breakpoint opcode exists at this address
1596 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1597 {
1598 break_op_found = true;
1599 // We found a valid breakpoint opcode at this address, now restore
1600 // the saved opcode.
1601 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1602 {
1603 verify = true;
1604 }
1605 else
1606 error.SetErrorString("Memory write failed when restoring original opcode.");
1607 }
1608 else
1609 {
1610 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1611 // Set verify to true and so we can check if the original opcode has already been restored
1612 verify = true;
1613 }
1614
1615 if (verify)
1616 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001617 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001618 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001619 // Verify that our original opcode made it back to the inferior
1620 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1621 {
1622 // compare the memory we just read with the original opcode
1623 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1624 {
1625 // SUCCESS
1626 bp_site->SetEnabled(false);
1627 if (log)
1628 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1629 return error;
1630 }
1631 else
1632 {
1633 if (break_op_found)
1634 error.SetErrorString("Failed to restore original opcode.");
1635 }
1636 }
1637 else
1638 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1639 }
1640 }
1641 else
1642 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1643 }
1644 }
1645 else
1646 {
1647 if (log)
1648 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1649 return error;
1650 }
1651
1652 if (log)
1653 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1654 bp_site->GetID(),
1655 (uint64_t)bp_addr,
1656 error.AsCString());
1657 return error;
1658
1659}
1660
Greg Claytonfd119992011-01-07 06:08:19 +00001661// Comment out line below to disable memory caching
1662#define ENABLE_MEMORY_CACHING
1663// Uncomment to verify memory caching works after making changes to caching code
1664//#define VERIFY_MEMORY_READS
1665
1666#if defined (ENABLE_MEMORY_CACHING)
1667
1668#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001669
1670size_t
1671Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1672{
Greg Claytonfd119992011-01-07 06:08:19 +00001673 // Memory caching is enabled, with debug verification
1674 if (buf && size)
1675 {
1676 // Uncomment the line below to make sure memory caching is working.
1677 // I ran this through the test suite and got no assertions, so I am
1678 // pretty confident this is working well. If any changes are made to
1679 // memory caching, uncomment the line below and test your changes!
1680
1681 // Verify all memory reads by using the cache first, then redundantly
1682 // reading the same memory from the inferior and comparing to make sure
1683 // everything is exactly the same.
1684 std::string verify_buf (size, '\0');
1685 assert (verify_buf.size() == size);
1686 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1687 Error verify_error;
1688 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1689 assert (cache_bytes_read == verify_bytes_read);
1690 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1691 assert (verify_error.Success() == error.Success());
1692 return cache_bytes_read;
1693 }
1694 return 0;
1695}
1696
1697#else // #if defined (VERIFY_MEMORY_READS)
1698
1699size_t
1700Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1701{
1702 // Memory caching enabled, no verification
Greg Clayton613b8732011-05-17 03:37:42 +00001703 return m_memory_cache.Read (addr, buf, size, error);
Greg Claytonfd119992011-01-07 06:08:19 +00001704}
1705
1706#endif // #else for #if defined (VERIFY_MEMORY_READS)
1707
1708#else // #if defined (ENABLE_MEMORY_CACHING)
1709
1710size_t
1711Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1712{
1713 // Memory caching is disabled
1714 return ReadMemoryFromInferior (addr, buf, size, error);
1715}
1716
1717#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1718
1719
1720size_t
Greg Claytonb72d0f02011-04-12 05:54:46 +00001721Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1722{
1723 size_t total_cstr_len = 0;
1724 if (dst && dst_max_len)
1725 {
1726 // NULL out everything just to be safe
1727 memset (dst, 0, dst_max_len);
1728 Error error;
1729 addr_t curr_addr = addr;
1730 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1731 size_t bytes_left = dst_max_len - 1;
1732 char *curr_dst = dst;
1733
1734 while (bytes_left > 0)
1735 {
1736 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1737 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1738 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1739
1740 if (bytes_read == 0)
1741 {
1742 dst[total_cstr_len] = '\0';
1743 break;
1744 }
1745 const size_t len = strlen(curr_dst);
1746
1747 total_cstr_len += len;
1748
1749 if (len < bytes_to_read)
1750 break;
1751
1752 curr_dst += bytes_read;
1753 curr_addr += bytes_read;
1754 bytes_left -= bytes_read;
1755 }
1756 }
1757 return total_cstr_len;
1758}
1759
1760size_t
Greg Claytonfd119992011-01-07 06:08:19 +00001761Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1762{
Chris Lattner24943d22010-06-08 16:52:24 +00001763 if (buf == NULL || size == 0)
1764 return 0;
1765
1766 size_t bytes_read = 0;
1767 uint8_t *bytes = (uint8_t *)buf;
1768
1769 while (bytes_read < size)
1770 {
1771 const size_t curr_size = size - bytes_read;
1772 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1773 bytes + bytes_read,
1774 curr_size,
1775 error);
1776 bytes_read += curr_bytes_read;
1777 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1778 break;
1779 }
1780
1781 // Replace any software breakpoint opcodes that fall into this range back
1782 // into "buf" before we return
1783 if (bytes_read > 0)
1784 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1785 return bytes_read;
1786}
1787
Greg Claytonf72fdee2010-12-16 20:01:20 +00001788uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00001789Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00001790{
Greg Claytonc0fa5332011-05-22 22:46:53 +00001791 Scalar scalar;
1792 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1793 return scalar.ULongLong(fail_value);
1794 return fail_value;
1795}
1796
1797addr_t
1798Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1799{
1800 Scalar scalar;
1801 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1802 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1803 return LLDB_INVALID_ADDRESS;
1804}
1805
1806
1807bool
1808Process::WritePointerToMemory (lldb::addr_t vm_addr,
1809 lldb::addr_t ptr_value,
1810 Error &error)
1811{
1812 Scalar scalar;
1813 const uint32_t addr_byte_size = GetAddressByteSize();
1814 if (addr_byte_size <= 4)
1815 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001816 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00001817 scalar = ptr_value;
1818 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001819}
1820
Chris Lattner24943d22010-06-08 16:52:24 +00001821size_t
1822Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1823{
1824 size_t bytes_written = 0;
1825 const uint8_t *bytes = (const uint8_t *)buf;
1826
1827 while (bytes_written < size)
1828 {
1829 const size_t curr_size = size - bytes_written;
1830 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1831 bytes + bytes_written,
1832 curr_size,
1833 error);
1834 bytes_written += curr_bytes_written;
1835 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1836 break;
1837 }
1838 return bytes_written;
1839}
1840
1841size_t
1842Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1843{
Greg Claytonfd119992011-01-07 06:08:19 +00001844#if defined (ENABLE_MEMORY_CACHING)
1845 m_memory_cache.Flush (addr, size);
1846#endif
1847
Chris Lattner24943d22010-06-08 16:52:24 +00001848 if (buf == NULL || size == 0)
1849 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00001850
Jim Ingham21f37ad2011-08-09 02:12:22 +00001851 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00001852
Chris Lattner24943d22010-06-08 16:52:24 +00001853 // We need to write any data that would go where any current software traps
1854 // (enabled software breakpoints) any software traps (breakpoints) that we
1855 // may have placed in our tasks memory.
1856
1857 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1858 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1859
1860 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001861 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00001862
1863 BreakpointSiteList::collection::const_iterator pos;
1864 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001865 addr_t intersect_addr = 0;
1866 size_t intersect_size = 0;
1867 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001868 const uint8_t *ubuf = (const uint8_t *)buf;
1869
1870 for (pos = iter; pos != end; ++pos)
1871 {
1872 BreakpointSiteSP bp;
1873 bp = pos->second;
1874
1875 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1876 assert(addr <= intersect_addr && intersect_addr < addr + size);
1877 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1878 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1879
1880 // Check for bytes before this breakpoint
1881 const addr_t curr_addr = addr + bytes_written;
1882 if (intersect_addr > curr_addr)
1883 {
1884 // There are some bytes before this breakpoint that we need to
1885 // just write to memory
1886 size_t curr_size = intersect_addr - curr_addr;
1887 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1888 ubuf + bytes_written,
1889 curr_size,
1890 error);
1891 bytes_written += curr_bytes_written;
1892 if (curr_bytes_written != curr_size)
1893 {
1894 // We weren't able to write all of the requested bytes, we
1895 // are done looping and will return the number of bytes that
1896 // we have written so far.
1897 break;
1898 }
1899 }
1900
1901 // Now write any bytes that would cover up any software breakpoints
1902 // directly into the breakpoint opcode buffer
1903 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1904 bytes_written += intersect_size;
1905 }
1906
1907 // Write any remaining bytes after the last breakpoint if we have any left
1908 if (bytes_written < size)
1909 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1910 ubuf + bytes_written,
1911 size - bytes_written,
1912 error);
Jim Inghame41494a2011-04-16 00:01:13 +00001913
Chris Lattner24943d22010-06-08 16:52:24 +00001914 return bytes_written;
1915}
Greg Claytonc0fa5332011-05-22 22:46:53 +00001916
1917size_t
1918Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
1919{
1920 if (byte_size == UINT32_MAX)
1921 byte_size = scalar.GetByteSize();
1922 if (byte_size > 0)
1923 {
1924 uint8_t buf[32];
1925 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
1926 if (mem_size > 0)
1927 return WriteMemory(addr, buf, mem_size, error);
1928 else
1929 error.SetErrorString ("failed to get scalar as memory data");
1930 }
1931 else
1932 {
1933 error.SetErrorString ("invalid scalar value");
1934 }
1935 return 0;
1936}
1937
1938size_t
1939Process::ReadScalarIntegerFromMemory (addr_t addr,
1940 uint32_t byte_size,
1941 bool is_signed,
1942 Scalar &scalar,
1943 Error &error)
1944{
1945 uint64_t uval;
1946
1947 if (byte_size <= sizeof(uval))
1948 {
1949 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
1950 if (bytes_read == byte_size)
1951 {
1952 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
1953 uint32_t offset = 0;
1954 if (byte_size <= 4)
1955 scalar = data.GetMaxU32 (&offset, byte_size);
1956 else
1957 scalar = data.GetMaxU64 (&offset, byte_size);
1958
1959 if (is_signed)
1960 scalar.SignExtend(byte_size * 8);
1961 return bytes_read;
1962 }
1963 }
1964 else
1965 {
1966 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1967 }
1968 return 0;
1969}
1970
Greg Clayton613b8732011-05-17 03:37:42 +00001971#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00001972addr_t
1973Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1974{
Jim Inghame6bd1422011-06-20 17:32:44 +00001975 if (GetPrivateState() != eStateStopped)
1976 return LLDB_INVALID_ADDRESS;
1977
Greg Clayton613b8732011-05-17 03:37:42 +00001978#if defined (USE_ALLOCATE_MEMORY_CACHE)
1979 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
1980#else
Greg Clayton2860ba92011-01-23 19:58:49 +00001981 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1982 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1983 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001984 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00001985 size,
Greg Clayton613b8732011-05-17 03:37:42 +00001986 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00001987 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00001988 m_mod_id.GetStopID(),
1989 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00001990 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00001991#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001992}
1993
Sean Callanan6cf6c472011-09-20 23:01:51 +00001994bool
1995Process::CanJIT ()
1996{
1997 return m_can_jit == eCanJITYes;
1998}
1999
2000void
2001Process::SetCanJIT (bool can_jit)
2002{
2003 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2004}
2005
Chris Lattner24943d22010-06-08 16:52:24 +00002006Error
2007Process::DeallocateMemory (addr_t ptr)
2008{
Greg Clayton613b8732011-05-17 03:37:42 +00002009 Error error;
2010#if defined (USE_ALLOCATE_MEMORY_CACHE)
2011 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2012 {
2013 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2014 }
2015#else
2016 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002017
2018 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2019 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002020 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002021 ptr,
2022 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002023 m_mod_id.GetStopID(),
2024 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002025#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002026 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002027}
2028
2029
2030Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002031Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002032{
2033 Error error;
2034 error.SetErrorString("watchpoints are not supported");
2035 return error;
2036}
2037
2038Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002039Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002040{
2041 Error error;
2042 error.SetErrorString("watchpoints are not supported");
2043 return error;
2044}
2045
2046StateType
2047Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2048{
2049 StateType state;
2050 // Now wait for the process to launch and return control to us, and then
2051 // call DidLaunch:
2052 while (1)
2053 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002054 event_sp.reset();
2055 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2056
2057 if (StateIsStoppedState(state))
Chris Lattner24943d22010-06-08 16:52:24 +00002058 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002059
2060 // If state is invalid, then we timed out
2061 if (state == eStateInvalid)
2062 break;
2063
2064 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002065 HandlePrivateEvent (event_sp);
2066 }
2067 return state;
2068}
2069
2070Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002071Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002072{
2073 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002074 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002075 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002076 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002077 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002078
Greg Clayton5beb99d2011-08-11 02:48:45 +00002079 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002080 if (exe_module)
2081 {
Greg Clayton180546b2011-04-30 01:09:13 +00002082 char local_exec_file_path[PATH_MAX];
2083 char platform_exec_file_path[PATH_MAX];
2084 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2085 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002086 if (exe_module->GetFileSpec().Exists())
2087 {
Greg Claytona2f74232011-02-24 22:24:29 +00002088 if (PrivateStateThreadIsValid ())
2089 PausePrivateStateThread ();
2090
Chris Lattner24943d22010-06-08 16:52:24 +00002091 error = WillLaunch (exe_module);
2092 if (error.Success())
2093 {
Greg Claytond8c62532010-10-07 04:19:01 +00002094 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00002095
2096 // Now launch using these arguments.
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002097 error = DoLaunch (exe_module, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +00002098
2099 if (error.Fail())
2100 {
2101 if (GetID() != LLDB_INVALID_PROCESS_ID)
2102 {
2103 SetID (LLDB_INVALID_PROCESS_ID);
2104 const char *error_string = error.AsCString();
2105 if (error_string == NULL)
2106 error_string = "launch failed";
2107 SetExitStatus (-1, error_string);
2108 }
2109 }
2110 else
2111 {
2112 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002113 TimeValue timeout_time;
2114 timeout_time = TimeValue::Now();
2115 timeout_time.OffsetWithSeconds(10);
2116 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002117
Greg Clayton49859592011-06-22 01:42:17 +00002118 if (state == eStateInvalid || event_sp.get() == NULL)
2119 {
2120 // We were able to launch the process, but we failed to
2121 // catch the initial stop.
2122 SetExitStatus (0, "failed to catch stop after launch");
2123 Destroy();
2124 }
2125 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002126 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002127
Chris Lattner24943d22010-06-08 16:52:24 +00002128 DidLaunch ();
2129
Greg Clayton37f962e2011-08-22 02:49:39 +00002130 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002131 if (m_dyld_ap.get())
2132 m_dyld_ap->DidLaunch();
2133
Greg Clayton37f962e2011-08-22 02:49:39 +00002134 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002135 // This delays passing the stopped event to listeners till DidLaunch gets
2136 // a chance to complete...
2137 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002138
2139 if (PrivateStateThreadIsValid ())
2140 ResumePrivateStateThread ();
2141 else
2142 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002143 }
2144 else if (state == eStateExited)
2145 {
2146 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2147 // not likely to work, and return an invalid pid.
2148 HandlePrivateEvent (event_sp);
2149 }
2150 }
2151 }
2152 }
2153 else
2154 {
Greg Clayton9c236732011-10-26 00:56:27 +00002155 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002156 }
2157 }
2158 return error;
2159}
2160
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002161Process::NextEventAction::EventActionResult
2162Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002163{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002164 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2165 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002166 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002167 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002168 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002169 return eEventActionRetry;
2170
2171 case eStateStopped:
2172 case eStateCrashed:
Jim Ingham7508e732010-08-09 23:31:02 +00002173 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002174 // During attach, prior to sending the eStateStopped event,
2175 // lldb_private::Process subclasses must set the process must set
2176 // the new process ID.
2177 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton75c703d2011-02-16 04:46:07 +00002178 m_process->CompleteAttach ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002179 return eEventActionSuccess;
Jim Ingham7508e732010-08-09 23:31:02 +00002180 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002181
2182
2183 break;
2184 default:
2185 case eStateExited:
2186 case eStateInvalid:
2187 m_exit_string.assign ("No valid Process");
2188 return eEventActionExit;
2189 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002190 }
2191}
Chris Lattner24943d22010-06-08 16:52:24 +00002192
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002193Process::NextEventAction::EventActionResult
2194Process::AttachCompletionHandler::HandleBeingInterrupted()
2195{
2196 return eEventActionSuccess;
2197}
2198
2199const char *
2200Process::AttachCompletionHandler::GetExitString ()
2201{
2202 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002203}
2204
2205Error
2206Process::Attach (lldb::pid_t attach_pid)
2207{
2208
Chris Lattner24943d22010-06-08 16:52:24 +00002209 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002210 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002211
Greg Clayton75c703d2011-02-16 04:46:07 +00002212 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002213 m_os_ap.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002214
Greg Clayton54e7afa2010-07-09 20:39:50 +00002215 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00002216 if (error.Success())
2217 {
Greg Claytond8c62532010-10-07 04:19:01 +00002218 SetPublicState (eStateAttaching);
2219
Greg Clayton54e7afa2010-07-09 20:39:50 +00002220 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00002221 if (error.Success())
2222 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002223 SetNextEventAction(new Process::AttachCompletionHandler(this));
2224 StartPrivateStateThread();
Chris Lattner24943d22010-06-08 16:52:24 +00002225 }
2226 else
2227 {
2228 if (GetID() != LLDB_INVALID_PROCESS_ID)
2229 {
2230 SetID (LLDB_INVALID_PROCESS_ID);
2231 const char *error_string = error.AsCString();
2232 if (error_string == NULL)
2233 error_string = "attach failed";
2234
2235 SetExitStatus(-1, error_string);
2236 }
2237 }
2238 }
2239 return error;
2240}
2241
2242Error
2243Process::Attach (const char *process_name, bool wait_for_launch)
2244{
Chris Lattner24943d22010-06-08 16:52:24 +00002245 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002246 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002247
2248 // Find the process and its architecture. Make sure it matches the architecture
2249 // of the current Target, and if not adjust it.
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002250 Error error;
Jim Ingham7508e732010-08-09 23:31:02 +00002251
Jim Inghamea294182010-08-17 21:54:19 +00002252 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00002253 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002254 ProcessInstanceInfoList process_infos;
Jim Ingham0d7f7772011-09-15 01:10:17 +00002255 PlatformSP platform_sp (m_target.GetPlatform ());
2256 assert (platform_sp.get());
2257
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002258 if (platform_sp)
Jim Inghamea294182010-08-17 21:54:19 +00002259 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002260 ProcessInstanceInfoMatch match_info;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002261 match_info.GetProcessInfo().SetName(process_name);
2262 match_info.SetNameMatchType (eNameMatchEquals);
2263 platform_sp->FindProcesses (match_info, process_infos);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002264 if (process_infos.GetSize() > 1)
Chris Lattner24943d22010-06-08 16:52:24 +00002265 {
Greg Clayton9c236732011-10-26 00:56:27 +00002266 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002267 }
2268 else if (process_infos.GetSize() == 0)
2269 {
Greg Clayton9c236732011-10-26 00:56:27 +00002270 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002271 }
Chris Lattner24943d22010-06-08 16:52:24 +00002272 }
2273 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002274 {
Greg Clayton9c236732011-10-26 00:56:27 +00002275 error.SetErrorString ("invalid platform");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002276 }
2277 }
2278
2279 if (error.Success())
2280 {
2281 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002282 m_os_ap.reset();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002283
2284 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2285 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002286 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002287 SetPublicState (eStateAttaching);
2288 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2289 if (error.Fail())
2290 {
2291 if (GetID() != LLDB_INVALID_PROCESS_ID)
2292 {
2293 SetID (LLDB_INVALID_PROCESS_ID);
2294 const char *error_string = error.AsCString();
2295 if (error_string == NULL)
2296 error_string = "attach failed";
2297
2298 SetExitStatus(-1, error_string);
2299 }
2300 }
2301 else
2302 {
2303 SetNextEventAction(new Process::AttachCompletionHandler(this));
2304 StartPrivateStateThread();
2305 }
Chris Lattner24943d22010-06-08 16:52:24 +00002306 }
2307 }
2308 return error;
2309}
2310
Greg Clayton75c703d2011-02-16 04:46:07 +00002311void
2312Process::CompleteAttach ()
2313{
2314 // Let the process subclass figure out at much as it can about the process
2315 // before we go looking for a dynamic loader plug-in.
Jim Inghamc0c53242011-09-15 21:36:42 +00002316 m_attached_to_process = true;
Greg Clayton75c703d2011-02-16 04:46:07 +00002317 DidAttach();
2318
Jim Ingham0d7f7772011-09-15 01:10:17 +00002319 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2320 // the same as the one we've already set, switch architectures.
2321 PlatformSP platform_sp (m_target.GetPlatform ());
2322 assert (platform_sp.get());
2323 if (platform_sp)
2324 {
2325 ProcessInstanceInfo process_info;
2326 platform_sp->GetProcessInfo (GetID(), process_info);
2327 const ArchSpec &process_arch = process_info.GetArchitecture();
2328 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2329 m_target.SetArchitecture (process_arch);
2330 }
2331
2332 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002333 // plug-in
Greg Clayton4fdf7602011-03-20 04:57:14 +00002334 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002335 if (m_dyld_ap.get())
2336 m_dyld_ap->DidAttach();
2337
Greg Clayton37f962e2011-08-22 02:49:39 +00002338 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002339 // Figure out which one is the executable, and set that in our target:
2340 ModuleList &modules = m_target.GetImages();
2341
2342 size_t num_modules = modules.GetSize();
2343 for (int i = 0; i < num_modules; i++)
2344 {
2345 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002346 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002347 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002348 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton75c703d2011-02-16 04:46:07 +00002349 m_target.SetExecutableModule (module_sp, false);
2350 break;
2351 }
2352 }
2353}
2354
Chris Lattner24943d22010-06-08 16:52:24 +00002355Error
Greg Claytone71e2582011-02-04 01:58:07 +00002356Process::ConnectRemote (const char *remote_url)
2357{
Greg Claytone71e2582011-02-04 01:58:07 +00002358 m_abi_sp.reset();
2359 m_process_input_reader.reset();
2360
2361 // Find the process and its architecture. Make sure it matches the architecture
2362 // of the current Target, and if not adjust it.
2363
2364 Error error (DoConnectRemote (remote_url));
2365 if (error.Success())
2366 {
Greg Claytona2f74232011-02-24 22:24:29 +00002367 if (GetID() != LLDB_INVALID_PROCESS_ID)
2368 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002369 EventSP event_sp;
2370 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2371
2372 if (state == eStateStopped || state == eStateCrashed)
2373 {
2374 // If we attached and actually have a process on the other end, then
2375 // this ended up being the equivalent of an attach.
2376 CompleteAttach ();
2377
2378 // This delays passing the stopped event to listeners till
2379 // CompleteAttach gets a chance to complete...
2380 HandlePrivateEvent (event_sp);
2381
2382 }
Greg Claytona2f74232011-02-24 22:24:29 +00002383 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002384
2385 if (PrivateStateThreadIsValid ())
2386 ResumePrivateStateThread ();
2387 else
2388 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002389 }
2390 return error;
2391}
2392
2393
2394Error
Chris Lattner24943d22010-06-08 16:52:24 +00002395Process::Resume ()
2396{
Greg Claytone005f2c2010-11-06 01:53:30 +00002397 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002398 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002399 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002400 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002401 StateAsCString(m_public_state.GetValue()),
2402 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002403
2404 Error error (WillResume());
2405 // Tell the process it is about to resume before the thread list
2406 if (error.Success())
2407 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002408 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002409 // can let all of our threads know that they are about to be
2410 // resumed. Threads will each be called with
2411 // Thread::WillResume(StateType) where StateType contains the state
2412 // that they are supposed to have when the process is resumed
2413 // (suspended/running/stepping). Threads should also check
2414 // their resume signal in lldb::Thread::GetResumeSignal()
2415 // to see if they are suppoed to start back up with a signal.
2416 if (m_thread_list.WillResume())
2417 {
2418 error = DoResume();
2419 if (error.Success())
2420 {
2421 DidResume();
2422 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00002423 if (log)
2424 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00002425 }
2426 }
2427 else
2428 {
Jim Inghamac959662011-01-24 06:34:17 +00002429 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002430 }
2431 }
Jim Inghamac959662011-01-24 06:34:17 +00002432 else if (log)
2433 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002434 return error;
2435}
2436
2437Error
2438Process::Halt ()
2439{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002440 // Pause our private state thread so we can ensure no one else eats
2441 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002442 Listener halt_listener ("lldb.process.halt_listener");
2443 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002444
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002445 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002446 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002447
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002448 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002449 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002450
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002451 bool caused_stop = false;
2452
2453 // Ask the process subclass to actually halt our process
2454 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002455 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002456 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002457 if (m_public_state.GetValue() == eStateAttaching)
2458 {
2459 SetExitStatus(SIGKILL, "Cancelled async attach.");
2460 Destroy ();
2461 }
2462 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002463 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002464 // If "caused_stop" is true, then DoHalt stopped the process. If
2465 // "caused_stop" is false, the process was already stopped.
2466 // If the DoHalt caused the process to stop, then we want to catch
2467 // this event and set the interrupted bool to true before we pass
2468 // this along so clients know that the process was interrupted by
2469 // a halt command.
2470 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002471 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002472 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002473 TimeValue timeout_time;
2474 timeout_time = TimeValue::Now();
2475 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002476 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2477 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002478
Jim Inghamf9f40c22011-02-08 05:20:59 +00002479 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002480 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002481 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002482 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002483 }
2484 else
2485 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002486 if (StateIsStoppedState (state))
2487 {
2488 // We caused the process to interrupt itself, so mark this
2489 // as such in the stop event so clients can tell an interrupted
2490 // process from a natural stop
2491 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2492 }
2493 else
2494 {
2495 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2496 if (log)
2497 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2498 error.SetErrorString ("Did not get stopped event after halt.");
2499 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002500 }
2501 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002502 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002503 }
2504 }
Chris Lattner24943d22010-06-08 16:52:24 +00002505 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002506 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002507 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002508
2509 // Post any event we might have consumed. If all goes well, we will have
2510 // stopped the process, intercepted the event and set the interrupted
2511 // bool in the event. Post it to the private event queue and that will end up
2512 // correctly setting the state.
2513 if (event_sp)
2514 m_private_state_broadcaster.BroadcastEvent(event_sp);
2515
Chris Lattner24943d22010-06-08 16:52:24 +00002516 return error;
2517}
2518
2519Error
2520Process::Detach ()
2521{
2522 Error error (WillDetach());
2523
2524 if (error.Success())
2525 {
2526 DisableAllBreakpointSites();
2527 error = DoDetach();
2528 if (error.Success())
2529 {
2530 DidDetach();
2531 StopPrivateStateThread();
2532 }
2533 }
2534 return error;
2535}
2536
2537Error
2538Process::Destroy ()
2539{
2540 Error error (WillDestroy());
2541 if (error.Success())
2542 {
2543 DisableAllBreakpointSites();
2544 error = DoDestroy();
2545 if (error.Success())
2546 {
2547 DidDestroy();
2548 StopPrivateStateThread();
2549 }
Caroline Tice861efb32010-11-16 05:07:41 +00002550 m_stdio_communication.StopReadThread();
2551 m_stdio_communication.Disconnect();
2552 if (m_process_input_reader && m_process_input_reader->IsActive())
2553 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2554 if (m_process_input_reader)
2555 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002556 }
2557 return error;
2558}
2559
2560Error
2561Process::Signal (int signal)
2562{
2563 Error error (WillSignal());
2564 if (error.Success())
2565 {
2566 error = DoSignal(signal);
2567 if (error.Success())
2568 DidSignal();
2569 }
2570 return error;
2571}
2572
Greg Clayton395fc332011-02-15 21:59:32 +00002573lldb::ByteOrder
2574Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002575{
Greg Clayton395fc332011-02-15 21:59:32 +00002576 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002577}
2578
2579uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002580Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002581{
Greg Clayton395fc332011-02-15 21:59:32 +00002582 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002583}
2584
Greg Clayton395fc332011-02-15 21:59:32 +00002585
Chris Lattner24943d22010-06-08 16:52:24 +00002586bool
2587Process::ShouldBroadcastEvent (Event *event_ptr)
2588{
2589 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2590 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002591 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002592
2593 switch (state)
2594 {
Greg Claytone71e2582011-02-04 01:58:07 +00002595 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002596 case eStateAttaching:
2597 case eStateLaunching:
2598 case eStateDetached:
2599 case eStateExited:
2600 case eStateUnloaded:
2601 // These events indicate changes in the state of the debugging session, always report them.
2602 return_value = true;
2603 break;
2604 case eStateInvalid:
2605 // We stopped for no apparent reason, don't report it.
2606 return_value = false;
2607 break;
2608 case eStateRunning:
2609 case eStateStepping:
2610 // If we've started the target running, we handle the cases where we
2611 // are already running and where there is a transition from stopped to
2612 // running differently.
2613 // running -> running: Automatically suppress extra running events
2614 // stopped -> running: Report except when there is one or more no votes
2615 // and no yes votes.
2616 SynchronouslyNotifyStateChanged (state);
2617 switch (m_public_state.GetValue())
2618 {
2619 case eStateRunning:
2620 case eStateStepping:
2621 // We always suppress multiple runnings with no PUBLIC stop in between.
2622 return_value = false;
2623 break;
2624 default:
2625 // TODO: make this work correctly. For now always report
2626 // run if we aren't running so we don't miss any runnning
2627 // events. If I run the lldb/test/thread/a.out file and
2628 // break at main.cpp:58, run and hit the breakpoints on
2629 // multiple threads, then somehow during the stepping over
2630 // of all breakpoints no run gets reported.
2631 return_value = true;
2632
2633 // This is a transition from stop to run.
2634 switch (m_thread_list.ShouldReportRun (event_ptr))
2635 {
2636 case eVoteYes:
2637 case eVoteNoOpinion:
2638 return_value = true;
2639 break;
2640 case eVoteNo:
2641 return_value = false;
2642 break;
2643 }
2644 break;
2645 }
2646 break;
2647 case eStateStopped:
2648 case eStateCrashed:
2649 case eStateSuspended:
2650 {
2651 // We've stopped. First see if we're going to restart the target.
2652 // If we are going to stop, then we always broadcast the event.
2653 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00002654 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002655 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002656 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002657 if (log)
2658 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002659 return true;
2660 }
2661 else
2662 {
Chris Lattner24943d22010-06-08 16:52:24 +00002663 RefreshStateAfterStop ();
2664
2665 if (m_thread_list.ShouldStop (event_ptr) == false)
2666 {
2667 switch (m_thread_list.ShouldReportStop (event_ptr))
2668 {
2669 case eVoteYes:
2670 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00002671 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00002672 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00002673 case eVoteNo:
2674 return_value = false;
2675 break;
2676 }
2677
2678 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002679 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002680 Resume ();
2681 }
2682 else
2683 {
2684 return_value = true;
2685 SynchronouslyNotifyStateChanged (state);
2686 }
2687 }
2688 }
2689 }
2690
2691 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002692 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00002693 return return_value;
2694}
2695
Chris Lattner24943d22010-06-08 16:52:24 +00002696
2697bool
2698Process::StartPrivateStateThread ()
2699{
Greg Claytone005f2c2010-11-06 01:53:30 +00002700 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002701
Greg Claytonb72d0f02011-04-12 05:54:46 +00002702 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00002703 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002704 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2705
2706 if (already_running)
2707 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00002708
2709 // Create a thread that watches our internal state and controls which
2710 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002711 char thread_name[1024];
Greg Clayton444e35b2011-10-19 18:09:39 +00002712 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Claytona875b642011-01-09 21:07:35 +00002713 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002714 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002715}
2716
2717void
2718Process::PausePrivateStateThread ()
2719{
2720 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2721}
2722
2723void
2724Process::ResumePrivateStateThread ()
2725{
2726 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2727}
2728
2729void
2730Process::StopPrivateStateThread ()
2731{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002732 if (PrivateStateThreadIsValid ())
2733 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner24943d22010-06-08 16:52:24 +00002734}
2735
2736void
2737Process::ControlPrivateStateThread (uint32_t signal)
2738{
Greg Claytone005f2c2010-11-06 01:53:30 +00002739 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002740
2741 assert (signal == eBroadcastInternalStateControlStop ||
2742 signal == eBroadcastInternalStateControlPause ||
2743 signal == eBroadcastInternalStateControlResume);
2744
2745 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002746 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002747
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002748 // Signal the private state thread. First we should copy this is case the
2749 // thread starts exiting since the private state thread will NULL this out
2750 // when it exits
2751 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00002752 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002753 {
2754 TimeValue timeout_time;
2755 bool timed_out;
2756
2757 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2758
2759 timeout_time = TimeValue::Now();
2760 timeout_time.OffsetWithSeconds(2);
2761 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2762 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2763
2764 if (signal == eBroadcastInternalStateControlStop)
2765 {
2766 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002767 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002768
2769 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002770 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002771 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002772 }
2773 }
2774}
2775
2776void
2777Process::HandlePrivateEvent (EventSP &event_sp)
2778{
Greg Claytone005f2c2010-11-06 01:53:30 +00002779 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002780
Greg Clayton68ca8232011-01-25 02:58:48 +00002781 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002782
2783 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00002784 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002785 {
Jim Ingham68bffc52011-01-29 04:05:41 +00002786 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002787 switch (action_result)
2788 {
2789 case NextEventAction::eEventActionSuccess:
2790 SetNextEventAction(NULL);
2791 break;
2792 case NextEventAction::eEventActionRetry:
2793 break;
2794 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00002795 // Handle Exiting Here. If we already got an exited event,
2796 // we should just propagate it. Otherwise, swallow this event,
2797 // and set our state to exit so the next event will kill us.
2798 if (new_state != eStateExited)
2799 {
2800 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00002801 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00002802 SetNextEventAction(NULL);
2803 return;
2804 }
2805 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002806 break;
2807 }
2808 }
2809
Chris Lattner24943d22010-06-08 16:52:24 +00002810 // See if we should broadcast this state to external clients?
2811 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002812
2813 if (should_broadcast)
2814 {
2815 if (log)
2816 {
Greg Clayton444e35b2011-10-19 18:09:39 +00002817 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00002818 __FUNCTION__,
2819 GetID(),
2820 StateAsCString(new_state),
2821 StateAsCString (GetState ()),
2822 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002823 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00002824 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00002825 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00002826 PushProcessInputReader ();
2827 else
2828 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00002829
Chris Lattner24943d22010-06-08 16:52:24 +00002830 BroadcastEvent (event_sp);
2831 }
2832 else
2833 {
2834 if (log)
2835 {
Greg Clayton444e35b2011-10-19 18:09:39 +00002836 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00002837 __FUNCTION__,
2838 GetID(),
2839 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002840 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00002841 }
2842 }
2843}
2844
2845void *
2846Process::PrivateStateThread (void *arg)
2847{
2848 Process *proc = static_cast<Process*> (arg);
2849 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002850 return result;
2851}
2852
2853void *
2854Process::RunPrivateStateThread ()
2855{
2856 bool control_only = false;
2857 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2858
Greg Claytone005f2c2010-11-06 01:53:30 +00002859 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002860 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002861 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002862
2863 bool exit_now = false;
2864 while (!exit_now)
2865 {
2866 EventSP event_sp;
2867 WaitForEventsPrivate (NULL, event_sp, control_only);
2868 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2869 {
2870 switch (event_sp->GetType())
2871 {
2872 case eBroadcastInternalStateControlStop:
2873 exit_now = true;
2874 continue; // Go to next loop iteration so we exit without
2875 break; // doing any internal state managment below
2876
2877 case eBroadcastInternalStateControlPause:
2878 control_only = true;
2879 break;
2880
2881 case eBroadcastInternalStateControlResume:
2882 control_only = false;
2883 break;
2884 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002885
Jim Ingham3ae449a2010-11-17 02:32:00 +00002886 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002887 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham3ae449a2010-11-17 02:32:00 +00002888
Chris Lattner24943d22010-06-08 16:52:24 +00002889 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002890 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002891 }
2892
2893
2894 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2895
2896 if (internal_state != eStateInvalid)
2897 {
2898 HandlePrivateEvent (event_sp);
2899 }
2900
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002901 if (internal_state == eStateInvalid ||
2902 internal_state == eStateExited ||
2903 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002904 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002905 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002906 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002907
Chris Lattner24943d22010-06-08 16:52:24 +00002908 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002909 }
Chris Lattner24943d22010-06-08 16:52:24 +00002910 }
2911
Caroline Tice926060e2010-10-29 21:48:37 +00002912 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002913 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002914 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002915
Greg Claytona4881d02011-01-22 07:12:45 +00002916 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2917 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002918 return NULL;
2919}
2920
Chris Lattner24943d22010-06-08 16:52:24 +00002921//------------------------------------------------------------------
2922// Process Event Data
2923//------------------------------------------------------------------
2924
2925Process::ProcessEventData::ProcessEventData () :
2926 EventData (),
2927 m_process_sp (),
2928 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002929 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002930 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002931 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002932{
2933}
2934
2935Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2936 EventData (),
2937 m_process_sp (process_sp),
2938 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002939 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002940 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002941 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002942{
2943}
2944
2945Process::ProcessEventData::~ProcessEventData()
2946{
2947}
2948
2949const ConstString &
2950Process::ProcessEventData::GetFlavorString ()
2951{
2952 static ConstString g_flavor ("Process::ProcessEventData");
2953 return g_flavor;
2954}
2955
2956const ConstString &
2957Process::ProcessEventData::GetFlavor () const
2958{
2959 return ProcessEventData::GetFlavorString ();
2960}
2961
Chris Lattner24943d22010-06-08 16:52:24 +00002962void
2963Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2964{
2965 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002966 // off of the private process event queue, and then any number of times, first when it gets pulled off of
2967 // the public event queue, then other times when we're pretending that this is where we stopped at the
2968 // end of expression evaluation. m_update_state is used to distinguish these
2969 // three cases; it is 0 when we're just pulling it off for private handling,
2970 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00002971
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002972 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00002973 return;
2974
2975 m_process_sp->SetPublicState (m_state);
2976
2977 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2978 if (m_state == eStateStopped && ! m_restarted)
2979 {
2980 int num_threads = m_process_sp->GetThreadList().GetSize();
2981 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002982
Jim Ingham21f37ad2011-08-09 02:12:22 +00002983 // The actions might change one of the thread's stop_info's opinions about whether we should
2984 // stop the process, so we need to query that as we go.
2985 bool still_should_stop = true;
2986
Chris Lattner24943d22010-06-08 16:52:24 +00002987 for (idx = 0; idx < num_threads; ++idx)
2988 {
2989 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2990
Jim Ingham6297a3a2010-10-20 00:39:53 +00002991 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2992 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002993 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00002994 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00002995 // The stop action might restart the target. If it does, then we want to mark that in the
2996 // event so that whoever is receiving it will know to wait for the running event and reflect
2997 // that state appropriately.
2998 // We also need to stop processing actions, since they aren't expecting the target to be running.
2999 if (m_process_sp->GetPrivateState() == eStateRunning)
3000 {
3001 SetRestarted (true);
3002 break;
3003 }
3004 else if (!stop_info_sp->ShouldStop(event_ptr))
3005 {
3006 still_should_stop = false;
3007 }
Chris Lattner24943d22010-06-08 16:52:24 +00003008 }
3009 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003010
Jim Ingham21f37ad2011-08-09 02:12:22 +00003011
3012 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003013 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003014 if (!still_should_stop)
3015 {
3016 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003017 SetRestarted(true);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003018 m_process_sp->Resume();
3019 }
3020 else
3021 {
3022 // If we didn't restart, run the Stop Hooks here:
3023 // They might also restart the target, so watch for that.
3024 m_process_sp->GetTarget().RunStopHooks();
3025 if (m_process_sp->GetPrivateState() == eStateRunning)
3026 SetRestarted(true);
3027 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003028 }
3029
Chris Lattner24943d22010-06-08 16:52:24 +00003030 }
3031}
3032
3033void
3034Process::ProcessEventData::Dump (Stream *s) const
3035{
3036 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003037 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003038
Greg Claytonb72d0f02011-04-12 05:54:46 +00003039 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003040}
3041
3042const Process::ProcessEventData *
3043Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3044{
3045 if (event_ptr)
3046 {
3047 const EventData *event_data = event_ptr->GetData();
3048 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3049 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3050 }
3051 return NULL;
3052}
3053
3054ProcessSP
3055Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3056{
3057 ProcessSP process_sp;
3058 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3059 if (data)
3060 process_sp = data->GetProcessSP();
3061 return process_sp;
3062}
3063
3064StateType
3065Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3066{
3067 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3068 if (data == NULL)
3069 return eStateInvalid;
3070 else
3071 return data->GetState();
3072}
3073
3074bool
3075Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3076{
3077 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3078 if (data == NULL)
3079 return false;
3080 else
3081 return data->GetRestarted();
3082}
3083
3084void
3085Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3086{
3087 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3088 if (data != NULL)
3089 data->SetRestarted(new_value);
3090}
3091
3092bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003093Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3094{
3095 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3096 if (data == NULL)
3097 return false;
3098 else
3099 return data->GetInterrupted ();
3100}
3101
3102void
3103Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3104{
3105 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3106 if (data != NULL)
3107 data->SetInterrupted(new_value);
3108}
3109
3110bool
Chris Lattner24943d22010-06-08 16:52:24 +00003111Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3112{
3113 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3114 if (data)
3115 {
3116 data->SetUpdateStateOnRemoval();
3117 return true;
3118 }
3119 return false;
3120}
3121
Chris Lattner24943d22010-06-08 16:52:24 +00003122void
Greg Claytona830adb2010-10-04 01:05:56 +00003123Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003124{
Greg Clayton567e7f32011-09-22 04:58:26 +00003125 exe_ctx.SetTargetPtr (&m_target);
3126 exe_ctx.SetProcessPtr (this);
3127 exe_ctx.SetThreadPtr(NULL);
3128 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003129}
3130
3131lldb::ProcessSP
3132Process::GetSP ()
3133{
3134 return GetTarget().GetProcessSP();
3135}
3136
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003137//uint32_t
3138//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3139//{
3140// return 0;
3141//}
3142//
3143//ArchSpec
3144//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3145//{
3146// return Host::GetArchSpecForExistingProcess (pid);
3147//}
3148//
3149//ArchSpec
3150//Process::GetArchSpecForExistingProcess (const char *process_name)
3151//{
3152// return Host::GetArchSpecForExistingProcess (process_name);
3153//}
3154//
Caroline Tice861efb32010-11-16 05:07:41 +00003155void
3156Process::AppendSTDOUT (const char * s, size_t len)
3157{
Greg Clayton20d338f2010-11-18 05:57:03 +00003158 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003159 m_stdout_data.append (s, len);
3160
Greg Claytonb3781332010-12-05 19:16:56 +00003161 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003162}
3163
3164void
3165Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3166{
3167 Process *process = (Process *) baton;
3168 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3169}
3170
3171size_t
3172Process::ProcessInputReaderCallback (void *baton,
3173 InputReader &reader,
3174 lldb::InputReaderAction notification,
3175 const char *bytes,
3176 size_t bytes_len)
3177{
3178 Process *process = (Process *) baton;
3179
3180 switch (notification)
3181 {
3182 case eInputReaderActivate:
3183 break;
3184
3185 case eInputReaderDeactivate:
3186 break;
3187
3188 case eInputReaderReactivate:
3189 break;
3190
Caroline Tice4a348082011-05-02 20:41:46 +00003191 case eInputReaderAsynchronousOutputWritten:
3192 break;
3193
Caroline Tice861efb32010-11-16 05:07:41 +00003194 case eInputReaderGotToken:
3195 {
3196 Error error;
3197 process->PutSTDIN (bytes, bytes_len, error);
3198 }
3199 break;
3200
Caroline Ticec4f55fe2010-11-19 20:47:54 +00003201 case eInputReaderInterrupt:
3202 process->Halt ();
3203 break;
3204
3205 case eInputReaderEndOfFile:
3206 process->AppendSTDOUT ("^D", 2);
3207 break;
3208
Caroline Tice861efb32010-11-16 05:07:41 +00003209 case eInputReaderDone:
3210 break;
3211
3212 }
3213
3214 return bytes_len;
3215}
3216
3217void
3218Process::ResetProcessInputReader ()
3219{
3220 m_process_input_reader.reset();
3221}
3222
3223void
3224Process::SetUpProcessInputReader (int file_descriptor)
3225{
3226 // First set up the Read Thread for reading/handling process I/O
3227
3228 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3229
3230 if (conn_ap.get())
3231 {
3232 m_stdio_communication.SetConnection (conn_ap.release());
3233 if (m_stdio_communication.IsConnected())
3234 {
3235 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3236 m_stdio_communication.StartReadThread();
3237
3238 // Now read thread is set up, set up input reader.
3239
3240 if (!m_process_input_reader.get())
3241 {
3242 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3243 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3244 this,
3245 eInputReaderGranularityByte,
3246 NULL,
3247 NULL,
3248 false));
3249
3250 if (err.Fail())
3251 m_process_input_reader.reset();
3252 }
3253 }
3254 }
3255}
3256
3257void
3258Process::PushProcessInputReader ()
3259{
3260 if (m_process_input_reader && !m_process_input_reader->IsActive())
3261 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3262}
3263
3264void
3265Process::PopProcessInputReader ()
3266{
3267 if (m_process_input_reader && m_process_input_reader->IsActive())
3268 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3269}
3270
Greg Claytond284b662011-02-18 01:44:25 +00003271// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00003272void
Caroline Tice2a456812011-03-10 22:14:10 +00003273Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003274{
Greg Claytonb3448432011-03-24 21:19:54 +00003275 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00003276
3277 int i=0;
3278 const char *name;
3279 OptionEnumValueElement option_enum;
3280 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3281 {
3282 if (name)
3283 {
3284 option_enum.value = i;
3285 option_enum.string_value = name;
3286 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3287 g_plugins.push_back (option_enum);
3288 }
3289 ++i;
3290 }
3291 option_enum.value = 0;
3292 option_enum.string_value = NULL;
3293 option_enum.usage = NULL;
3294 g_plugins.push_back (option_enum);
3295
3296 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3297 {
3298 if (::strcmp (name, "plugin") == 0)
3299 {
3300 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3301 break;
3302 }
3303 }
Greg Clayton990de7b2010-11-18 23:32:35 +00003304 UserSettingsControllerSP &usc = GetSettingsController();
3305 usc.reset (new SettingsController);
3306 UserSettingsController::InitializeSettingsController (usc,
3307 SettingsController::global_settings_table,
3308 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00003309
3310 // Now call SettingsInitialize() for each 'child' of Process settings
3311 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00003312}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003313
Greg Clayton990de7b2010-11-18 23:32:35 +00003314void
Caroline Tice2a456812011-03-10 22:14:10 +00003315Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00003316{
Caroline Tice2a456812011-03-10 22:14:10 +00003317 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3318
3319 Thread::SettingsTerminate ();
3320
3321 // Now terminate Process Settings.
3322
Greg Clayton990de7b2010-11-18 23:32:35 +00003323 UserSettingsControllerSP &usc = GetSettingsController();
3324 UserSettingsController::FinalizeSettingsController (usc);
3325 usc.reset();
3326}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003327
Greg Clayton990de7b2010-11-18 23:32:35 +00003328UserSettingsControllerSP &
3329Process::GetSettingsController ()
3330{
3331 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003332 return g_settings_controller;
3333}
3334
Caroline Tice1ebef442010-09-27 00:30:10 +00003335void
3336Process::UpdateInstanceName ()
3337{
Greg Clayton5beb99d2011-08-11 02:48:45 +00003338 Module *module = GetTarget().GetExecutableModulePointer();
3339 if (module)
Caroline Tice1ebef442010-09-27 00:30:10 +00003340 {
3341 StreamString sstr;
Greg Clayton5beb99d2011-08-11 02:48:45 +00003342 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1ebef442010-09-27 00:30:10 +00003343
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003344 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytonb72d0f02011-04-12 05:54:46 +00003345 sstr.GetData());
Caroline Tice1ebef442010-09-27 00:30:10 +00003346 }
3347}
3348
Greg Clayton427f2902010-12-14 02:59:59 +00003349ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00003350Process::RunThreadPlan (ExecutionContext &exe_ctx,
3351 lldb::ThreadPlanSP &thread_plan_sp,
3352 bool stop_others,
3353 bool try_all_threads,
3354 bool discard_on_error,
3355 uint32_t single_thread_timeout_usec,
3356 Stream &errors)
3357{
3358 ExecutionResults return_value = eExecutionSetupError;
3359
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003360 if (thread_plan_sp.get() == NULL)
3361 {
3362 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00003363 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003364 }
Greg Clayton567e7f32011-09-22 04:58:26 +00003365
3366 if (exe_ctx.GetProcessPtr() != this)
3367 {
3368 errors.Printf("RunThreadPlan called on wrong process.");
3369 return eExecutionSetupError;
3370 }
3371
3372 Thread *thread = exe_ctx.GetThreadPtr();
3373 if (thread == NULL)
3374 {
3375 errors.Printf("RunThreadPlan called with invalid thread.");
3376 return eExecutionSetupError;
3377 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003378
Jim Ingham5ab7fba2011-05-17 22:24:54 +00003379 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3380 // For that to be true the plan can't be private - since private plans suppress themselves in the
3381 // GetCompletedPlan call.
3382
3383 bool orig_plan_private = thread_plan_sp->GetPrivate();
3384 thread_plan_sp->SetPrivate(false);
3385
Jim Inghamac959662011-01-24 06:34:17 +00003386 if (m_private_state.GetValue() != eStateStopped)
3387 {
3388 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00003389 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00003390 }
3391
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003392 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00003393 const uint32_t thread_idx_id = thread->GetIndexID();
3394 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003395
3396 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3397 // so we should arrange to reset them as well.
3398
Greg Clayton567e7f32011-09-22 04:58:26 +00003399 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00003400
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003401 uint32_t selected_tid;
3402 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00003403 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00003404 {
3405 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003406 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003407 }
3408 else
3409 {
3410 selected_tid = LLDB_INVALID_THREAD_ID;
3411 }
3412
Greg Clayton567e7f32011-09-22 04:58:26 +00003413 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Ingham360f53f2010-11-30 02:22:11 +00003414
Jim Ingham6ae318c2011-01-23 21:14:08 +00003415 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003416
3417 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3418 // restored on exit to the function.
3419
3420 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00003421
Jim Ingham6ae318c2011-01-23 21:14:08 +00003422 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003423 if (log)
3424 {
3425 StreamString s;
3426 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton444e35b2011-10-19 18:09:39 +00003427 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Clayton567e7f32011-09-22 04:58:26 +00003428 thread->GetIndexID(),
3429 thread->GetID(),
Jim Inghamf9f40c22011-02-08 05:20:59 +00003430 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003431 }
3432
Jim Inghamf9f40c22011-02-08 05:20:59 +00003433 bool got_event;
3434 lldb::EventSP event_sp;
3435 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00003436
3437 TimeValue* timeout_ptr = NULL;
3438 TimeValue real_timeout;
3439
Jim Inghamf9f40c22011-02-08 05:20:59 +00003440 bool first_timeout = true;
3441 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00003442
Jim Ingham360f53f2010-11-30 02:22:11 +00003443 while (1)
3444 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003445 // We usually want to resume the process if we get to the top of the loop.
3446 // The only exception is if we get two running events with no intervening
3447 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00003448
Jim Inghamf9f40c22011-02-08 05:20:59 +00003449 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00003450 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003451 // Do the initial resume and wait for the running event before going further.
3452
Greg Clayton567e7f32011-09-22 04:58:26 +00003453 Error resume_error = Resume ();
Jim Inghamf9f40c22011-02-08 05:20:59 +00003454 if (!resume_error.Success())
3455 {
3456 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00003457 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003458 break;
3459 }
3460
3461 real_timeout = TimeValue::Now();
3462 real_timeout.OffsetWithMicroSeconds(500000);
3463 timeout_ptr = &real_timeout;
3464
3465 got_event = listener.WaitForEvent(NULL, event_sp);
3466 if (!got_event)
3467 {
3468 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003469 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003470
3471 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003472 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003473 break;
3474 }
3475
3476 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3477 if (stop_state != eStateRunning)
3478 {
3479 if (log)
3480 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3481
3482 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003483 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003484 break;
3485 }
3486
3487 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003488 log->PutCString ("Resuming succeeded.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003489 // We need to call the function synchronously, so spin waiting for it to return.
3490 // If we get interrupted while executing, we're going to lose our context, and
3491 // won't be able to gather the result at this point.
3492 // We set the timeout AFTER the resume, since the resume takes some time and we
3493 // don't want to charge that to the timeout.
3494
3495 if (single_thread_timeout_usec != 0)
3496 {
3497 real_timeout = TimeValue::Now();
3498 if (first_timeout)
3499 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3500 else
3501 real_timeout.OffsetWithSeconds(10);
3502
3503 timeout_ptr = &real_timeout;
3504 }
3505 }
3506 else
3507 {
3508 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003509 log->PutCString ("Handled an extra running event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003510 do_resume = true;
3511 }
3512
3513 // Now wait for the process to stop again:
3514 stop_state = lldb::eStateInvalid;
3515 event_sp.reset();
3516 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3517
3518 if (got_event)
3519 {
3520 if (event_sp.get())
3521 {
3522 bool keep_going = false;
3523 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3524 if (log)
3525 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3526
3527 switch (stop_state)
3528 {
3529 case lldb::eStateStopped:
Jim Ingham2370a972011-05-17 01:10:11 +00003530 {
Greg Clayton43994462011-06-03 22:12:42 +00003531 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Clayton567e7f32011-09-22 04:58:26 +00003532 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton43994462011-06-03 22:12:42 +00003533 if (!thread_sp)
Jim Ingham2370a972011-05-17 01:10:11 +00003534 {
Greg Clayton43994462011-06-03 22:12:42 +00003535 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham2370a972011-05-17 01:10:11 +00003536 if (log)
Greg Clayton43994462011-06-03 22:12:42 +00003537 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3538 return_value = eExecutionInterrupted;
Jim Ingham2370a972011-05-17 01:10:11 +00003539 }
3540 else
3541 {
Greg Clayton43994462011-06-03 22:12:42 +00003542 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3543 StopReason stop_reason = eStopReasonInvalid;
3544 if (stop_info_sp)
3545 stop_reason = stop_info_sp->GetStopReason();
3546 if (stop_reason == eStopReasonPlanComplete)
3547 {
3548 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003549 log->PutCString ("Execution completed successfully.");
Greg Clayton43994462011-06-03 22:12:42 +00003550 // Now mark this plan as private so it doesn't get reported as the stop reason
3551 // after this point.
3552 if (thread_plan_sp)
3553 thread_plan_sp->SetPrivate (orig_plan_private);
3554 return_value = eExecutionCompleted;
3555 }
3556 else
3557 {
3558 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003559 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton43994462011-06-03 22:12:42 +00003560
3561 return_value = eExecutionInterrupted;
3562 }
Jim Ingham2370a972011-05-17 01:10:11 +00003563 }
Greg Clayton43994462011-06-03 22:12:42 +00003564 }
3565 break;
3566
Jim Inghamf9f40c22011-02-08 05:20:59 +00003567 case lldb::eStateCrashed:
3568 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003569 log->PutCString ("Execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003570 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003571 break;
Greg Clayton43994462011-06-03 22:12:42 +00003572
Jim Inghamf9f40c22011-02-08 05:20:59 +00003573 case lldb::eStateRunning:
3574 do_resume = false;
3575 keep_going = true;
3576 break;
Greg Clayton43994462011-06-03 22:12:42 +00003577
Jim Inghamf9f40c22011-02-08 05:20:59 +00003578 default:
3579 if (log)
3580 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham2370a972011-05-17 01:10:11 +00003581
3582 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytonb3448432011-03-24 21:19:54 +00003583 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003584 break;
3585 }
3586 if (keep_going)
3587 continue;
3588 else
3589 break;
3590 }
3591 else
3592 {
3593 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003594 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00003595 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003596 break;
3597 }
3598 }
3599 else
3600 {
3601 // If we didn't get an event that means we've timed out...
3602 // We will interrupt the process here. Depending on what we were asked to do we will
3603 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00003604 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003605
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003606 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00003607 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003608 {
3609 if (first_timeout)
3610 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3611 "trying with all threads enabled.",
3612 single_thread_timeout_usec);
3613 else
3614 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3615 "and timeout: %d timed out.",
3616 single_thread_timeout_usec);
3617 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003618 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00003619 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3620 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00003621 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003622 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003623
Greg Clayton567e7f32011-09-22 04:58:26 +00003624 Error halt_error = Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00003625 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00003626 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003627 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003628 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003629
Jim Inghamf9f40c22011-02-08 05:20:59 +00003630 // If halt succeeds, it always produces a stopped event. Wait for that:
3631
3632 real_timeout = TimeValue::Now();
3633 real_timeout.OffsetWithMicroSeconds(500000);
3634
3635 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00003636
3637 if (got_event)
3638 {
3639 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3640 if (log)
3641 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003642 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00003643 if (stop_state == lldb::eStateStopped
3644 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf6d3d792011-08-09 22:24:33 +00003645 log->PutCString (" Event was the Halt interruption event.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003646 }
3647
Jim Inghamf9f40c22011-02-08 05:20:59 +00003648 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00003649 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003650 // Between the time we initiated the Halt and the time we delivered it, the process could have
3651 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00003652
Greg Clayton567e7f32011-09-22 04:58:26 +00003653 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00003654 {
3655 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003656 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003657 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003658 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003659 break;
3660 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003661
Jim Inghamf9f40c22011-02-08 05:20:59 +00003662 if (!try_all_threads)
3663 {
3664 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003665 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003666 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003667 break;
3668 }
3669
3670 if (first_timeout)
3671 {
3672 // Set all the other threads to run, and return to the top of the loop, which will continue;
3673 first_timeout = false;
3674 thread_plan_sp->SetStopOthers (false);
3675 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003676 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003677
3678 continue;
3679 }
3680 else
3681 {
3682 // Running all threads failed, so return Interrupted.
3683 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003684 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003685 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003686 break;
3687 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003688 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003689 }
3690 else
3691 { if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003692 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003693 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00003694 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003695 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00003696 }
3697 }
Jim Inghamc556b462011-01-22 01:30:53 +00003698 else
3699 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003700 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3701 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00003702 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003703 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.",
3704 halt_error.AsCString());
3705 real_timeout = TimeValue::Now();
3706 real_timeout.OffsetWithMicroSeconds(500000);
3707 timeout_ptr = &real_timeout;
3708 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3709 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00003710 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003711 // This is not going anywhere, bag out.
3712 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003713 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003714 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003715 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00003716 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003717 else
3718 {
3719 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3720 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003721 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003722 if (stop_state == lldb::eStateStopped)
3723 {
3724 // Between the time we initiated the Halt and the time we delivered it, the process could have
3725 // already finished its job. Check that here:
3726
Greg Clayton567e7f32011-09-22 04:58:26 +00003727 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00003728 {
3729 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003730 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003731 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003732 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003733 break;
3734 }
3735
3736 if (first_timeout)
3737 {
3738 // Set all the other threads to run, and return to the top of the loop, which will continue;
3739 first_timeout = false;
3740 thread_plan_sp->SetStopOthers (false);
3741 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003742 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003743
3744 continue;
3745 }
3746 else
3747 {
3748 // Running all threads failed, so return Interrupted.
3749 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003750 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003751 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003752 break;
3753 }
3754 }
3755 else
3756 {
Sean Callananed3f86b2011-08-09 22:07:08 +00003757 if (log)
3758 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3759 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003760 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003761 break;
3762 }
3763 }
Jim Inghamc556b462011-01-22 01:30:53 +00003764 }
3765
Jim Ingham360f53f2010-11-30 02:22:11 +00003766 }
3767
Jim Inghamf9f40c22011-02-08 05:20:59 +00003768 } // END WAIT LOOP
3769
3770 // Now do some processing on the results of the run:
3771 if (return_value == eExecutionInterrupted)
3772 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003773 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003774 {
3775 StreamString s;
3776 if (event_sp)
3777 event_sp->Dump (&s);
3778 else
3779 {
Jim Inghamf6d3d792011-08-09 22:24:33 +00003780 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003781 }
3782
3783 StreamString ts;
3784
Jim Inghamf6d3d792011-08-09 22:24:33 +00003785 const char *event_explanation = NULL;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003786
3787 do
3788 {
3789 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3790
3791 if (!event_data)
3792 {
3793 event_explanation = "<no event data>";
3794 break;
3795 }
3796
3797 Process *process = event_data->GetProcessSP().get();
3798
3799 if (!process)
3800 {
3801 event_explanation = "<no process>";
3802 break;
3803 }
3804
3805 ThreadList &thread_list = process->GetThreadList();
3806
3807 uint32_t num_threads = thread_list.GetSize();
3808 uint32_t thread_index;
3809
3810 ts.Printf("<%u threads> ", num_threads);
3811
3812 for (thread_index = 0;
3813 thread_index < num_threads;
3814 ++thread_index)
3815 {
3816 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3817
3818 if (!thread)
3819 {
3820 ts.Printf("<?> ");
3821 continue;
3822 }
3823
Greg Clayton444e35b2011-10-19 18:09:39 +00003824 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Inghamf9f40c22011-02-08 05:20:59 +00003825 RegisterContext *register_context = thread->GetRegisterContext().get();
3826
3827 if (register_context)
3828 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3829 else
3830 ts.Printf("[ip unknown] ");
3831
3832 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3833 if (stop_info_sp)
3834 {
3835 const char *stop_desc = stop_info_sp->GetDescription();
3836 if (stop_desc)
3837 ts.PutCString (stop_desc);
3838 }
3839 ts.Printf(">");
3840 }
3841
3842 event_explanation = ts.GetData();
3843 } while (0);
3844
3845 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003846 {
3847 if (event_explanation)
3848 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3849 else
3850 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
3851 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003852
3853 if (discard_on_error && thread_plan_sp)
3854 {
Greg Clayton567e7f32011-09-22 04:58:26 +00003855 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003856 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003857 }
3858 }
3859 }
3860 else if (return_value == eExecutionSetupError)
3861 {
3862 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003863 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003864
3865 if (discard_on_error && thread_plan_sp)
3866 {
Greg Clayton567e7f32011-09-22 04:58:26 +00003867 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003868 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003869 }
3870 }
3871 else
3872 {
Greg Clayton567e7f32011-09-22 04:58:26 +00003873 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00003874 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003875 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003876 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00003877 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00003878 }
Greg Clayton567e7f32011-09-22 04:58:26 +00003879 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00003880 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003881 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003882 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00003883 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00003884 }
3885 else
3886 {
3887 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003888 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00003889 if (discard_on_error && thread_plan_sp)
3890 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003891 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003892 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Clayton567e7f32011-09-22 04:58:26 +00003893 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003894 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham360f53f2010-11-30 02:22:11 +00003895 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003896 }
3897 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003898
Jim Ingham360f53f2010-11-30 02:22:11 +00003899 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003900 // Check that it's still there, and if it is put it back in the context. Also restore the
3901 // frame in the context if it is still present.
Greg Clayton567e7f32011-09-22 04:58:26 +00003902 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
3903 if (thread)
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003904 {
Greg Clayton567e7f32011-09-22 04:58:26 +00003905 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003906 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003907
3908 // Also restore the current process'es selected frame & thread, since this function calling may
3909 // be done behind the user's back.
3910
3911 if (selected_tid != LLDB_INVALID_THREAD_ID)
3912 {
Greg Clayton567e7f32011-09-22 04:58:26 +00003913 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Ingham360f53f2010-11-30 02:22:11 +00003914 {
3915 // We were able to restore the selected thread, now restore the frame:
Greg Clayton567e7f32011-09-22 04:58:26 +00003916 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003917 if (old_frame_sp)
Greg Clayton567e7f32011-09-22 04:58:26 +00003918 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00003919 }
3920 }
3921
3922 return return_value;
3923}
3924
3925const char *
3926Process::ExecutionResultAsCString (ExecutionResults result)
3927{
3928 const char *result_name;
3929
3930 switch (result)
3931 {
Greg Claytonb3448432011-03-24 21:19:54 +00003932 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003933 result_name = "eExecutionCompleted";
3934 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003935 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00003936 result_name = "eExecutionDiscarded";
3937 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003938 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003939 result_name = "eExecutionInterrupted";
3940 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003941 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00003942 result_name = "eExecutionSetupError";
3943 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003944 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00003945 result_name = "eExecutionTimedOut";
3946 break;
3947 }
3948 return result_name;
3949}
3950
Greg Claytonabe0fed2011-04-18 08:33:37 +00003951void
3952Process::GetStatus (Stream &strm)
3953{
3954 const StateType state = GetState();
3955 if (StateIsStoppedState(state))
3956 {
3957 if (state == eStateExited)
3958 {
3959 int exit_status = GetExitStatus();
3960 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00003961 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00003962 GetID(),
3963 exit_status,
3964 exit_status,
3965 exit_description ? exit_description : "");
3966 }
3967 else
3968 {
3969 if (state == eStateConnected)
3970 strm.Printf ("Connected to remote target.\n");
3971 else
Greg Clayton444e35b2011-10-19 18:09:39 +00003972 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00003973 }
3974 }
3975 else
3976 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003977 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00003978 }
3979}
3980
3981size_t
3982Process::GetThreadStatus (Stream &strm,
3983 bool only_threads_with_stop_reason,
3984 uint32_t start_frame,
3985 uint32_t num_frames,
3986 uint32_t num_frames_with_source)
3987{
3988 size_t num_thread_infos_dumped = 0;
3989
3990 const size_t num_threads = GetThreadList().GetSize();
3991 for (uint32_t i = 0; i < num_threads; i++)
3992 {
3993 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
3994 if (thread)
3995 {
3996 if (only_threads_with_stop_reason)
3997 {
3998 if (thread->GetStopInfo().get() == NULL)
3999 continue;
4000 }
4001 thread->GetStatus (strm,
4002 start_frame,
4003 num_frames,
4004 num_frames_with_source);
4005 ++num_thread_infos_dumped;
4006 }
4007 }
4008 return num_thread_infos_dumped;
4009}
4010
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004011//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004012// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004013//--------------------------------------------------------------
4014
Greg Claytond0a5a232010-09-19 02:33:57 +00004015Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00004016 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004017{
Greg Clayton638351a2010-12-04 00:10:17 +00004018 m_default_settings.reset (new ProcessInstanceSettings (*this,
4019 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00004020 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004021}
4022
Greg Claytond0a5a232010-09-19 02:33:57 +00004023Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004024{
4025}
4026
4027lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00004028Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004029{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00004030 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4031 false,
4032 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004033 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4034 return new_settings_sp;
4035}
4036
4037//--------------------------------------------------------------
4038// class ProcessInstanceSettings
4039//--------------------------------------------------------------
4040
Greg Clayton638351a2010-12-04 00:10:17 +00004041ProcessInstanceSettings::ProcessInstanceSettings
4042(
4043 UserSettingsController &owner,
4044 bool live_instance,
4045 const char *name
4046) :
4047 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004048 m_run_args (),
4049 m_env_vars (),
4050 m_input_path (),
4051 m_output_path (),
4052 m_error_path (),
Caroline Ticebd666012010-12-03 18:46:09 +00004053 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00004054 m_disable_stdio (false),
4055 m_inherit_host_env (true),
4056 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004057{
Caroline Tice396704b2010-09-09 18:26:37 +00004058 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4059 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4060 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00004061 // This is true for CreateInstanceName() too.
4062
4063 if (GetInstanceName () == InstanceSettings::InvalidName())
4064 {
4065 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4066 m_owner.RegisterInstanceSettings (this);
4067 }
Caroline Tice396704b2010-09-09 18:26:37 +00004068
4069 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004070 {
4071 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4072 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00004073 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004074 }
4075}
4076
4077ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00004078 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004079 m_run_args (rhs.m_run_args),
4080 m_env_vars (rhs.m_env_vars),
4081 m_input_path (rhs.m_input_path),
4082 m_output_path (rhs.m_output_path),
4083 m_error_path (rhs.m_error_path),
Caroline Ticebd666012010-12-03 18:46:09 +00004084 m_disable_aslr (rhs.m_disable_aslr),
4085 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004086{
4087 if (m_instance_name != InstanceSettings::GetDefaultName())
4088 {
4089 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4090 CopyInstanceSettings (pending_settings,false);
4091 m_owner.RemovePendingSettings (m_instance_name);
4092 }
4093}
4094
4095ProcessInstanceSettings::~ProcessInstanceSettings ()
4096{
4097}
4098
4099ProcessInstanceSettings&
4100ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4101{
4102 if (this != &rhs)
4103 {
4104 m_run_args = rhs.m_run_args;
4105 m_env_vars = rhs.m_env_vars;
4106 m_input_path = rhs.m_input_path;
4107 m_output_path = rhs.m_output_path;
4108 m_error_path = rhs.m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004109 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00004110 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00004111 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004112 }
4113
4114 return *this;
4115}
4116
4117
4118void
4119ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4120 const char *index_value,
4121 const char *value,
4122 const ConstString &instance_name,
4123 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00004124 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004125 Error &err,
4126 bool pending)
4127{
4128 if (var_name == RunArgsVarName())
4129 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
4130 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00004131 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00004132 // This is nice for local debugging, but it is isn't correct for
4133 // remote debugging. We need to stop process.env-vars from being
4134 // populated with the host environment and add this as a launch option
4135 // and get the correct environment from the Target's platform.
4136 // GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004137 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00004138 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004139 else if (var_name == InputPathVarName())
4140 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
4141 else if (var_name == OutputPathVarName())
4142 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
4143 else if (var_name == ErrorPathVarName())
4144 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004145 else if (var_name == DisableASLRVarName())
Greg Clayton17cd9952011-04-22 03:55:06 +00004146 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, true, err);
Caroline Ticebd666012010-12-03 18:46:09 +00004147 else if (var_name == DisableSTDIOVarName ())
Greg Clayton17cd9952011-04-22 03:55:06 +00004148 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, false, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004149}
4150
4151void
4152ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4153 bool pending)
4154{
4155 if (new_settings.get() == NULL)
4156 return;
4157
4158 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
4159
4160 m_run_args = new_process_settings->m_run_args;
4161 m_env_vars = new_process_settings->m_env_vars;
4162 m_input_path = new_process_settings->m_input_path;
4163 m_output_path = new_process_settings->m_output_path;
4164 m_error_path = new_process_settings->m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004165 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00004166 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004167}
4168
Caroline Ticebcb5b452010-09-20 21:37:42 +00004169bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004170ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4171 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00004172 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00004173 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004174{
4175 if (var_name == RunArgsVarName())
4176 {
4177 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00004178 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004179 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
4180 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00004181 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004182 }
4183 else if (var_name == EnvVarsVarName())
4184 {
Greg Clayton638351a2010-12-04 00:10:17 +00004185 GetHostEnvironmentIfNeeded ();
4186
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004187 if (m_env_vars.size() > 0)
4188 {
4189 std::map<std::string, std::string>::iterator pos;
4190 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
4191 {
4192 StreamString value_str;
4193 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
4194 value.AppendString (value_str.GetData());
4195 }
4196 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004197 }
4198 else if (var_name == InputPathVarName())
4199 {
4200 value.AppendString (m_input_path.c_str());
4201 }
4202 else if (var_name == OutputPathVarName())
4203 {
4204 value.AppendString (m_output_path.c_str());
4205 }
4206 else if (var_name == ErrorPathVarName())
4207 {
4208 value.AppendString (m_error_path.c_str());
4209 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00004210 else if (var_name == InheritHostEnvVarName())
4211 {
4212 if (m_inherit_host_env)
4213 value.AppendString ("true");
4214 else
4215 value.AppendString ("false");
4216 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004217 else if (var_name == DisableASLRVarName())
4218 {
4219 if (m_disable_aslr)
4220 value.AppendString ("true");
4221 else
4222 value.AppendString ("false");
4223 }
Caroline Ticebd666012010-12-03 18:46:09 +00004224 else if (var_name == DisableSTDIOVarName())
4225 {
4226 if (m_disable_stdio)
4227 value.AppendString ("true");
4228 else
4229 value.AppendString ("false");
4230 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004231 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00004232 {
4233 if (err)
4234 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4235 return false;
4236 }
4237 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004238}
4239
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004240const ConstString
4241ProcessInstanceSettings::CreateInstanceName ()
4242{
4243 static int instance_count = 1;
4244 StreamString sstr;
4245
4246 sstr.Printf ("process_%d", instance_count);
4247 ++instance_count;
4248
4249 const ConstString ret_val (sstr.GetData());
4250 return ret_val;
4251}
4252
4253const ConstString &
4254ProcessInstanceSettings::RunArgsVarName ()
4255{
4256 static ConstString run_args_var_name ("run-args");
4257
4258 return run_args_var_name;
4259}
4260
4261const ConstString &
4262ProcessInstanceSettings::EnvVarsVarName ()
4263{
4264 static ConstString env_vars_var_name ("env-vars");
4265
4266 return env_vars_var_name;
4267}
4268
4269const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00004270ProcessInstanceSettings::InheritHostEnvVarName ()
4271{
4272 static ConstString g_name ("inherit-env");
4273
4274 return g_name;
4275}
4276
4277const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004278ProcessInstanceSettings::InputPathVarName ()
4279{
4280 static ConstString input_path_var_name ("input-path");
4281
4282 return input_path_var_name;
4283}
4284
4285const ConstString &
4286ProcessInstanceSettings::OutputPathVarName ()
4287{
Caroline Tice87097232010-09-07 18:35:40 +00004288 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004289
4290 return output_path_var_name;
4291}
4292
4293const ConstString &
4294ProcessInstanceSettings::ErrorPathVarName ()
4295{
Caroline Tice87097232010-09-07 18:35:40 +00004296 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004297
4298 return error_path_var_name;
4299}
4300
4301const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004302ProcessInstanceSettings::DisableASLRVarName ()
4303{
4304 static ConstString disable_aslr_var_name ("disable-aslr");
4305
4306 return disable_aslr_var_name;
4307}
4308
Caroline Ticebd666012010-12-03 18:46:09 +00004309const ConstString &
4310ProcessInstanceSettings::DisableSTDIOVarName ()
4311{
4312 static ConstString disable_stdio_var_name ("disable-stdio");
4313
4314 return disable_stdio_var_name;
4315}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004316
4317//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004318// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004319//--------------------------------------------------
4320
4321SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004322Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004323{
4324 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4325 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4326};
4327
4328
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004329SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004330Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004331{
Greg Clayton638351a2010-12-04 00:10:17 +00004332 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
4333 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
4334 { "env-vars", eSetVarTypeDictionary, NULL, NULL, false, false, "A list of all the environment variables to be passed to the executable's environment, and their values." },
4335 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonde915be2011-01-23 05:56:20 +00004336 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
4337 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
4338 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
Greg Claytond284b662011-02-18 01:44:25 +00004339 { "plugin", eSetVarTypeEnum, NULL, NULL, false, false, "The plugin to be used to run the process." },
Greg Clayton638351a2010-12-04 00:10:17 +00004340 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
4341 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
4342 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004343};
4344
4345
Jim Ingham7508e732010-08-09 23:31:02 +00004346