blob: 6ee9dbf85de5da77b23e341c9d52b7776ef02b9c [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
39
40using namespace lldb;
41using namespace lldb_private;
42
Greg Clayton32e0a752011-03-30 18:16:51 +000043void
Greg Clayton8b82f082011-04-12 05:54:46 +000044ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +000045{
46 const char *cstr;
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +000060 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +000061 if (argc > 0)
62 {
63 for (uint32_t i=0; i<argc; i++)
64 {
Greg Clayton8b82f082011-04-12 05:54:46 +000065 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000066 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +000067 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000068 else
Greg Clayton8b82f082011-04-12 05:54:46 +000069 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000070 }
71 }
Greg Clayton8b82f082011-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 Clayton95bf0fd2011-04-01 00:29:43 +000086 if (m_arch.IsValid())
87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
88
Greg Clayton8b82f082011-04-12 05:54:46 +000089 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000090 {
Greg Clayton8b82f082011-04-12 05:54:46 +000091 cstr = platform->GetUserName (m_uid);
92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000093 }
Greg Clayton8b82f082011-04-12 05:54:46 +000094 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000095 {
Greg Clayton8b82f082011-04-12 05:54:46 +000096 cstr = platform->GetGroupName (m_gid);
97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000098 }
Greg Clayton8b82f082011-04-12 05:54:46 +000099 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000100 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000101 cstr = platform->GetUserName (m_euid);
102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000103 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000104 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000105 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000106 cstr = platform->GetGroupName (m_egid);
107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000108 }
109}
110
111void
Greg Clayton8b82f082011-04-12 05:54:46 +0000112ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000113{
Greg Clayton8b82f082011-04-12 05:54:46 +0000114 const char *label;
115 if (show_args || verbose)
116 label = "ARGUMENTS";
117 else
118 label = "NAME";
119
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000120 if (verbose)
121 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
124 }
125 else
126 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000127 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000128 s.PutCString ("====== ====== ========== ======= ============================\n");
129 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000130}
131
132void
Greg Clayton8b82f082011-04-12 05:54:46 +0000133ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-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 Clayton32e0a752011-03-30 18:16:51 +0000140
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000141 if (verbose)
142 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000143 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000147 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000148
Greg Clayton8b82f082011-04-12 05:54:46 +0000149 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000153 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000154
Greg Clayton8b82f082011-04-12 05:54:46 +0000155 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000159 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000160
Greg Clayton8b82f082011-04-12 05:54:46 +0000161 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000165 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000166 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
167 }
168 else
169 {
Jason Molendafd54b362011-09-20 21:44:10 +0000170 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000171 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000172 (int)m_arch.GetTriple().getArchName().size(),
173 m_arch.GetTriple().getArchName().data());
174 }
175
Greg Clayton8b82f082011-04-12 05:54:46 +0000176 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000177 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000178 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000185 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000186 }
187 }
188 }
189 else
190 {
191 s.PutCString (GetName());
192 }
193
194 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000195 }
196}
197
Greg Clayton8b82f082011-04-12 05:54:46 +0000198
199void
Greg Clayton982c9762011-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 Clayton8b82f082011-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 Clayton982c9762011-11-03 21:22:33 +0000236 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-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 Clayton1d885962011-11-08 02:43:13 +0000253void
254ProcessLaunchInfo::FinalizeFileActions (Target *target, Process *process)
255{
256 // If notthing was specified, then check the process for any default
257 // settings that were set with "settings set"
258 if (m_file_actions.empty())
259 {
260 const char *path;
261 if (m_flags.Test(eLaunchFlagDisableSTDIO))
262 {
263 AppendSuppressFileAction (STDERR_FILENO, true , true );
264 AppendSuppressFileAction (STDIN_FILENO , true , false);
265 AppendSuppressFileAction (STDOUT_FILENO, false, true );
266 }
267 else
268 {
269 // Check for any values that might have gotten set with any of:
270 // (lldb) settings set target.input-path
271 // (lldb) settings set target.output-path
272 // (lldb) settings set target.error-path
273 if (target)
274 {
275 path = target->GetStandardErrorPath();
276 if (path)
277 {
278 const bool read = true;
279 const bool write = true;
280 AppendOpenFileAction(STDERR_FILENO, path, read, write);
281 }
282 path = target->GetStandardInputPath();
283 if (path)
284 {
285 const bool read = true;
286 const bool write = false;
287 AppendOpenFileAction(STDIN_FILENO, path, read, write);
288 }
289
290 path = target->GetStandardOutputPath();
291 if (path)
292 {
293 const bool read = false;
294 const bool write = true;
295 AppendOpenFileAction(STDOUT_FILENO, path, read, write);
296 }
297 }
298
299 // If we still don't have any actions...
300 if (m_file_actions.empty())
301 {
302 }
303 }
304 }
305}
306
Greg Clayton32e0a752011-03-30 18:16:51 +0000307bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000308ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
309{
310 if ((read || write) && fd >= 0 && path && path[0])
311 {
312 m_action = eFileActionOpen;
313 m_fd = fd;
314 if (read && write)
315 m_arg = O_RDWR;
316 else if (read)
317 m_arg = O_RDONLY;
318 else
319 m_arg = O_WRONLY;
320 m_path.assign (path);
321 return true;
322 }
323 else
324 {
325 Clear();
326 }
327 return false;
328}
329
330bool
331ProcessLaunchInfo::FileAction::Close (int fd)
332{
333 Clear();
334 if (fd >= 0)
335 {
336 m_action = eFileActionClose;
337 m_fd = fd;
338 }
339 return m_fd >= 0;
340}
341
342
343bool
344ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
345{
346 Clear();
347 if (fd >= 0 && dup_fd >= 0)
348 {
349 m_action = eFileActionDuplicate;
350 m_fd = fd;
351 m_arg = dup_fd;
352 }
353 return m_fd >= 0;
354}
355
356
357
358bool
359ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
360 const FileAction *info,
361 Log *log,
362 Error& error)
363{
364 if (info == NULL)
365 return false;
366
367 switch (info->m_action)
368 {
369 case eFileActionNone:
370 error.Clear();
371 break;
372
373 case eFileActionClose:
374 if (info->m_fd == -1)
375 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
376 else
377 {
378 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
379 eErrorTypePOSIX);
380 if (log && (error.Fail() || log))
381 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
382 file_actions, info->m_fd);
383 }
384 break;
385
386 case eFileActionDuplicate:
387 if (info->m_fd == -1)
388 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
389 else if (info->m_arg == -1)
390 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
391 else
392 {
393 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
394 eErrorTypePOSIX);
395 if (log && (error.Fail() || log))
396 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
397 file_actions, info->m_fd, info->m_arg);
398 }
399 break;
400
401 case eFileActionOpen:
402 if (info->m_fd == -1)
403 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
404 else
405 {
406 int oflag = info->m_arg;
407 mode_t mode = 0;
408
409 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
410 info->m_fd,
411 info->m_path.c_str(),
412 oflag,
413 mode),
414 eErrorTypePOSIX);
415 if (error.Fail() || log)
416 error.PutToLog(log,
417 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
418 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
419 }
420 break;
421
422 default:
423 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
424 break;
425 }
426 return error.Success();
427}
428
429Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000430ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000431{
432 Error error;
433 char short_option = (char) m_getopt_table[option_idx].val;
434
435 switch (short_option)
436 {
437 case 's': // Stop at program entry point
438 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
439 break;
440
441 case 'e': // STDERR for read + write
442 {
443 ProcessLaunchInfo::FileAction action;
444 if (action.Open(STDERR_FILENO, option_arg, true, true))
445 launch_info.AppendFileAction (action);
446 }
447 break;
448
449 case 'i': // STDIN for read only
450 {
451 ProcessLaunchInfo::FileAction action;
452 if (action.Open(STDIN_FILENO, option_arg, true, false))
453 launch_info.AppendFileAction (action);
454 }
455 break;
456
457 case 'o': // Open STDOUT for write only
458 {
459 ProcessLaunchInfo::FileAction action;
460 if (action.Open(STDOUT_FILENO, option_arg, false, true))
461 launch_info.AppendFileAction (action);
462 }
463 break;
464
465 case 'p': // Process plug-in name
466 launch_info.SetProcessPluginName (option_arg);
467 break;
468
469 case 'n': // Disable STDIO
470 {
471 ProcessLaunchInfo::FileAction action;
472 if (action.Open(STDERR_FILENO, "/dev/null", true, true))
473 launch_info.AppendFileAction (action);
474 if (action.Open(STDOUT_FILENO, "/dev/null", false, true))
475 launch_info.AppendFileAction (action);
476 if (action.Open(STDIN_FILENO, "/dev/null", true, false))
477 launch_info.AppendFileAction (action);
478 }
479 break;
480
481 case 'w':
482 launch_info.SetWorkingDirectory (option_arg);
483 break;
484
485 case 't': // Open process in new terminal window
486 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
487 break;
488
489 case 'a':
490 launch_info.GetArchitecture().SetTriple (option_arg,
491 m_interpreter.GetPlatform(true).get());
492 break;
493
494 case 'A':
495 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
496 break;
497
Greg Clayton982c9762011-11-03 21:22:33 +0000498 case 'c':
499 launch_info.GetFlags().Set (eLaunchFlagLaunchInShell);
500 break;
501
Greg Clayton8b82f082011-04-12 05:54:46 +0000502 case 'v':
503 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
504 break;
505
506 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000507 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000508 break;
509
510 }
511 return error;
512}
513
514OptionDefinition
515ProcessLaunchCommandOptions::g_option_table[] =
516{
517{ 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."},
518{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
519{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
520{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
521{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
522{ LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Greg Clayton1d885962011-11-08 02:43:13 +0000523{ LLDB_OPT_SET_ALL, false, "shell", 'c', no_argument, NULL, 0, eArgTypeNone, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000524
525{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
526{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
527{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
528
529{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
530
531{ 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."},
532
533{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
534};
535
536
537
538bool
539ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000540{
541 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
542 return true;
543 const char *match_name = m_match_info.GetName();
544 if (!match_name)
545 return true;
546
547 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
548}
549
550bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000551ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000552{
553 if (!NameMatches (proc_info.GetName()))
554 return false;
555
556 if (m_match_info.ProcessIDIsValid() &&
557 m_match_info.GetProcessID() != proc_info.GetProcessID())
558 return false;
559
560 if (m_match_info.ParentProcessIDIsValid() &&
561 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
562 return false;
563
Greg Clayton8b82f082011-04-12 05:54:46 +0000564 if (m_match_info.UserIDIsValid () &&
565 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000566 return false;
567
Greg Clayton8b82f082011-04-12 05:54:46 +0000568 if (m_match_info.GroupIDIsValid () &&
569 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000570 return false;
571
572 if (m_match_info.EffectiveUserIDIsValid () &&
573 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
574 return false;
575
576 if (m_match_info.EffectiveGroupIDIsValid () &&
577 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
578 return false;
579
580 if (m_match_info.GetArchitecture().IsValid() &&
581 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
582 return false;
583 return true;
584}
585
586bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000587ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000588{
589 if (m_name_match_type != eNameMatchIgnore)
590 return false;
591
592 if (m_match_info.ProcessIDIsValid())
593 return false;
594
595 if (m_match_info.ParentProcessIDIsValid())
596 return false;
597
Greg Clayton8b82f082011-04-12 05:54:46 +0000598 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000599 return false;
600
Greg Clayton8b82f082011-04-12 05:54:46 +0000601 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000602 return false;
603
604 if (m_match_info.EffectiveUserIDIsValid ())
605 return false;
606
607 if (m_match_info.EffectiveGroupIDIsValid ())
608 return false;
609
610 if (m_match_info.GetArchitecture().IsValid())
611 return false;
612
613 if (m_match_all_users)
614 return false;
615
616 return true;
617
618}
619
620void
Greg Clayton8b82f082011-04-12 05:54:46 +0000621ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000622{
623 m_match_info.Clear();
624 m_name_match_type = eNameMatchIgnore;
625 m_match_all_users = false;
626}
Greg Clayton58be07b2011-01-07 06:08:19 +0000627
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000628Process*
629Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
630{
631 ProcessCreateInstance create_callback = NULL;
632 if (plugin_name)
633 {
634 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
635 if (create_callback)
636 {
637 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000638 if (debugger_ap->CanDebug(target, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639 return debugger_ap.release();
640 }
641 }
642 else
643 {
Greg Claytonc982c762010-07-09 20:39:50 +0000644 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000645 {
Greg Claytonc982c762010-07-09 20:39:50 +0000646 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000647 if (debugger_ap->CanDebug(target, false))
Greg Claytonc982c762010-07-09 20:39:50 +0000648 return debugger_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000649 }
650 }
651 return NULL;
652}
653
654
655//----------------------------------------------------------------------
656// Process constructor
657//----------------------------------------------------------------------
658Process::Process(Target &target, Listener &listener) :
659 UserID (LLDB_INVALID_PROCESS_ID),
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000660 Broadcaster ("lldb.process"),
Greg Claytondbe54502010-11-19 03:46:01 +0000661 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000662 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663 m_public_state (eStateUnloaded),
664 m_private_state (eStateUnloaded),
665 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
666 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
667 m_private_state_listener ("lldb.process.internal_state_listener"),
668 m_private_state_control_wait(),
669 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000670 m_mod_id (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000671 m_thread_index_id (0),
672 m_exit_status (-1),
673 m_exit_string (),
674 m_thread_list (this),
675 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000676 m_image_tokens (),
677 m_listener (listener),
678 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000679 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000680 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000681 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000682 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000683 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000684 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000685 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000686 m_stderr_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000687 m_memory_cache (*this),
688 m_allocated_memory_cache (*this),
Jim Ingham8314c522011-09-15 21:36:42 +0000689 m_attached_to_process (false),
Sean Callanan90539452011-09-20 23:01:51 +0000690 m_next_event_action_ap(),
691 m_can_jit(eCanJITYes)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000692{
Caroline Tice1559a462010-09-27 00:30:10 +0000693 UpdateInstanceName();
694
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000695 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000696 if (log)
697 log->Printf ("%p Process::Process()", this);
698
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000699 SetEventName (eBroadcastBitStateChanged, "state-changed");
700 SetEventName (eBroadcastBitInterrupt, "interrupt");
701 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
702 SetEventName (eBroadcastBitSTDERR, "stderr-available");
703
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704 listener.StartListeningForEvents (this,
705 eBroadcastBitStateChanged |
706 eBroadcastBitInterrupt |
707 eBroadcastBitSTDOUT |
708 eBroadcastBitSTDERR);
709
710 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
711 eBroadcastBitStateChanged);
712
713 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
714 eBroadcastInternalStateControlStop |
715 eBroadcastInternalStateControlPause |
716 eBroadcastInternalStateControlResume);
717}
718
719//----------------------------------------------------------------------
720// Destructor
721//----------------------------------------------------------------------
722Process::~Process()
723{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000724 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000725 if (log)
726 log->Printf ("%p Process::~Process()", this);
727 StopPrivateStateThread();
728}
729
730void
731Process::Finalize()
732{
Greg Clayton1ed54f52011-10-01 00:45:15 +0000733 // Clear our broadcaster before we proceed with destroying
734 Broadcaster::Clear();
735
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736 // Do any cleanup needed prior to being destructed... Subclasses
737 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000738
739 // We need to destroy the loader before the derived Process class gets destroyed
740 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000741 m_dyld_ap.reset();
742 m_os_ap.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743}
744
745void
746Process::RegisterNotificationCallbacks (const Notifications& callbacks)
747{
748 m_notifications.push_back(callbacks);
749 if (callbacks.initialize != NULL)
750 callbacks.initialize (callbacks.baton, this);
751}
752
753bool
754Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
755{
756 std::vector<Notifications>::iterator pos, end = m_notifications.end();
757 for (pos = m_notifications.begin(); pos != end; ++pos)
758 {
759 if (pos->baton == callbacks.baton &&
760 pos->initialize == callbacks.initialize &&
761 pos->process_state_changed == callbacks.process_state_changed)
762 {
763 m_notifications.erase(pos);
764 return true;
765 }
766 }
767 return false;
768}
769
770void
771Process::SynchronouslyNotifyStateChanged (StateType state)
772{
773 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
774 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
775 {
776 if (notification_pos->process_state_changed)
777 notification_pos->process_state_changed (notification_pos->baton, this, state);
778 }
779}
780
781// FIXME: We need to do some work on events before the general Listener sees them.
782// For instance if we are continuing from a breakpoint, we need to ensure that we do
783// the little "insert real insn, step & stop" trick. But we can't do that when the
784// event is delivered by the broadcaster - since that is done on the thread that is
785// waiting for new events, so if we needed more than one event for our handling, we would
786// stall. So instead we do it when we fetch the event off of the queue.
787//
788
789StateType
790Process::GetNextEvent (EventSP &event_sp)
791{
792 StateType state = eStateInvalid;
793
794 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
795 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
796
797 return state;
798}
799
800
801StateType
802Process::WaitForProcessToStop (const TimeValue *timeout)
803{
Jim Ingham4b536182011-08-09 02:12:22 +0000804 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
805 // We have to actually check each event, and in the case of a stopped event check the restarted flag
806 // on the event.
807 EventSP event_sp;
808 StateType state = GetState();
809 // If we are exited or detached, we won't ever get back to any
810 // other valid state...
811 if (state == eStateDetached || state == eStateExited)
812 return state;
813
814 while (state != eStateInvalid)
815 {
816 state = WaitForStateChangedEvents (timeout, event_sp);
817 switch (state)
818 {
819 case eStateCrashed:
820 case eStateDetached:
821 case eStateExited:
822 case eStateUnloaded:
823 return state;
824 case eStateStopped:
825 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
826 continue;
827 else
828 return state;
829 default:
830 continue;
831 }
832 }
833 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000834}
835
836
837StateType
838Process::WaitForState
839(
840 const TimeValue *timeout,
841 const StateType *match_states, const uint32_t num_match_states
842)
843{
844 EventSP event_sp;
845 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000846 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000847 while (state != eStateInvalid)
848 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000849 // If we are exited or detached, we won't ever get back to any
850 // other valid state...
851 if (state == eStateDetached || state == eStateExited)
852 return state;
853
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000854 state = WaitForStateChangedEvents (timeout, event_sp);
855
856 for (i=0; i<num_match_states; ++i)
857 {
858 if (match_states[i] == state)
859 return state;
860 }
861 }
862 return state;
863}
864
Jim Ingham30f9b212010-10-11 23:53:14 +0000865bool
866Process::HijackProcessEvents (Listener *listener)
867{
868 if (listener != NULL)
869 {
870 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
871 }
872 else
873 return false;
874}
875
876void
877Process::RestoreProcessEvents ()
878{
879 RestoreBroadcaster();
880}
881
Jim Ingham0f16e732011-02-08 05:20:59 +0000882bool
883Process::HijackPrivateProcessEvents (Listener *listener)
884{
885 if (listener != NULL)
886 {
887 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
888 }
889 else
890 return false;
891}
892
893void
894Process::RestorePrivateProcessEvents ()
895{
896 m_private_state_broadcaster.RestoreBroadcaster();
897}
898
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000899StateType
900Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
901{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000902 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903
904 if (log)
905 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
906
907 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000908 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
909 this,
910 eBroadcastBitStateChanged,
911 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000912 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
913
914 if (log)
915 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
916 __FUNCTION__,
917 timeout,
918 StateAsCString(state));
919 return state;
920}
921
922Event *
923Process::PeekAtStateChangedEvents ()
924{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000925 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000926
927 if (log)
928 log->Printf ("Process::%s...", __FUNCTION__);
929
930 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000931 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
932 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000933 if (log)
934 {
935 if (event_ptr)
936 {
937 log->Printf ("Process::%s (event_ptr) => %s",
938 __FUNCTION__,
939 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
940 }
941 else
942 {
943 log->Printf ("Process::%s no events found",
944 __FUNCTION__);
945 }
946 }
947 return event_ptr;
948}
949
950StateType
951Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
952{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000953 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000954
955 if (log)
956 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
957
958 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +0000959 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
960 &m_private_state_broadcaster,
961 eBroadcastBitStateChanged,
962 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000963 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
964
965 // This is a bit of a hack, but when we wait here we could very well return
966 // to the command-line, and that could disable the log, which would render the
967 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000968 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +0000969 {
970 if (state == eStateInvalid)
971 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
972 else
973 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
974 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000975 return state;
976}
977
978bool
979Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
980{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000981 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000982
983 if (log)
984 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
985
986 if (control_only)
987 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
988 else
989 return m_private_state_listener.WaitForEvent(timeout, event_sp);
990}
991
992bool
993Process::IsRunning () const
994{
995 return StateIsRunningState (m_public_state.GetValue());
996}
997
998int
999Process::GetExitStatus ()
1000{
1001 if (m_public_state.GetValue() == eStateExited)
1002 return m_exit_status;
1003 return -1;
1004}
1005
Greg Clayton85851dd2010-12-04 00:10:17 +00001006
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001007const char *
1008Process::GetExitDescription ()
1009{
1010 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1011 return m_exit_string.c_str();
1012 return NULL;
1013}
1014
Greg Clayton6779606a2011-01-22 23:43:18 +00001015bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001016Process::SetExitStatus (int status, const char *cstr)
1017{
Greg Clayton414f5d32011-01-25 02:58:48 +00001018 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1019 if (log)
1020 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1021 status, status,
1022 cstr ? "\"" : "",
1023 cstr ? cstr : "NULL",
1024 cstr ? "\"" : "");
1025
Greg Clayton6779606a2011-01-22 23:43:18 +00001026 // We were already in the exited state
1027 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001028 {
Greg Clayton385d6032011-01-26 23:47:29 +00001029 if (log)
1030 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001031 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001032 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001033
1034 m_exit_status = status;
1035 if (cstr)
1036 m_exit_string = cstr;
1037 else
1038 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001039
Greg Clayton6779606a2011-01-22 23:43:18 +00001040 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001041
Greg Clayton6779606a2011-01-22 23:43:18 +00001042 SetPrivateState (eStateExited);
1043 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001044}
1045
1046// This static callback can be used to watch for local child processes on
1047// the current host. The the child process exits, the process will be
1048// found in the global target list (we want to be completely sure that the
1049// lldb_private::Process doesn't go away before we can deliver the signal.
1050bool
1051Process::SetProcessExitStatus
1052(
1053 void *callback_baton,
1054 lldb::pid_t pid,
1055 int signo, // Zero for no signal
1056 int exit_status // Exit value of process if signal is zero
1057)
1058{
1059 if (signo == 0 || exit_status)
1060 {
Greg Clayton66111032010-06-23 01:19:29 +00001061 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062 if (target_sp)
1063 {
1064 ProcessSP process_sp (target_sp->GetProcessSP());
1065 if (process_sp)
1066 {
1067 const char *signal_cstr = NULL;
1068 if (signo)
1069 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1070
1071 process_sp->SetExitStatus (exit_status, signal_cstr);
1072 }
1073 }
1074 return true;
1075 }
1076 return false;
1077}
1078
1079
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001080void
1081Process::UpdateThreadListIfNeeded ()
1082{
1083 const uint32_t stop_id = GetStopID();
1084 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1085 {
1086 Mutex::Locker locker (m_thread_list.GetMutex ());
1087 ThreadList new_thread_list(this);
1088 // Always update the thread list with the protocol specific
1089 // thread list
1090 UpdateThreadList (m_thread_list, new_thread_list);
1091 OperatingSystem *os = GetOperatingSystem ();
1092 if (os)
1093 os->UpdateThreadList (m_thread_list, new_thread_list);
1094 m_thread_list.Update (new_thread_list);
1095 m_thread_list.SetStopID (stop_id);
1096 }
1097}
1098
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099uint32_t
1100Process::GetNextThreadIndexID ()
1101{
1102 return ++m_thread_index_id;
1103}
1104
1105StateType
1106Process::GetState()
1107{
1108 // If any other threads access this we will need a mutex for it
1109 return m_public_state.GetValue ();
1110}
1111
1112void
1113Process::SetPublicState (StateType new_state)
1114{
Greg Clayton414f5d32011-01-25 02:58:48 +00001115 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116 if (log)
1117 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1118 m_public_state.SetValue (new_state);
1119}
1120
1121StateType
1122Process::GetPrivateState ()
1123{
1124 return m_private_state.GetValue();
1125}
1126
1127void
1128Process::SetPrivateState (StateType new_state)
1129{
Greg Clayton414f5d32011-01-25 02:58:48 +00001130 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001131 bool state_changed = false;
1132
1133 if (log)
1134 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1135
1136 Mutex::Locker locker(m_private_state.GetMutex());
1137
1138 const StateType old_state = m_private_state.GetValueNoLock ();
1139 state_changed = old_state != new_state;
1140 if (state_changed)
1141 {
1142 m_private_state.SetValueNoLock (new_state);
1143 if (StateIsStoppedState(new_state))
1144 {
Jim Ingham4b536182011-08-09 02:12:22 +00001145 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001146 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001147 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001148 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001149 }
1150 // Use our target to get a shared pointer to ourselves...
1151 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1152 }
1153 else
1154 {
1155 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001156 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157 }
1158}
1159
Jim Ingham0faa43f2011-11-08 03:00:11 +00001160void
1161Process::SetRunningUserExpression (bool on)
1162{
1163 m_mod_id.SetRunningUserExpression (on);
1164}
1165
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166addr_t
1167Process::GetImageInfoAddress()
1168{
1169 return LLDB_INVALID_ADDRESS;
1170}
1171
Greg Clayton8f343b02010-11-04 01:54:29 +00001172//----------------------------------------------------------------------
1173// LoadImage
1174//
1175// This function provides a default implementation that works for most
1176// unix variants. Any Process subclasses that need to do shared library
1177// loading differently should override LoadImage and UnloadImage and
1178// do what is needed.
1179//----------------------------------------------------------------------
1180uint32_t
1181Process::LoadImage (const FileSpec &image_spec, Error &error)
1182{
1183 DynamicLoader *loader = GetDynamicLoader();
1184 if (loader)
1185 {
1186 error = loader->CanLoadImage();
1187 if (error.Fail())
1188 return LLDB_INVALID_IMAGE_TOKEN;
1189 }
1190
1191 if (error.Success())
1192 {
1193 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001194
1195 if (thread_sp)
1196 {
1197 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1198
1199 if (frame_sp)
1200 {
1201 ExecutionContext exe_ctx;
1202 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001203 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001204 StreamString expr;
1205 char path[PATH_MAX];
1206 image_spec.GetPath(path, sizeof(path));
1207 expr.Printf("dlopen (\"%s\", 2)", path);
1208 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001209 lldb::ValueObjectSP result_valobj_sp;
Sean Callananc7b65062011-11-07 23:35:40 +00001210 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chene92aa432011-09-09 00:01:43 +00001211 error = result_valobj_sp->GetError();
1212 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001213 {
1214 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001215 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001216 {
1217 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1218 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1219 {
1220 uint32_t image_token = m_image_tokens.size();
1221 m_image_tokens.push_back (image_ptr);
1222 return image_token;
1223 }
1224 }
1225 }
1226 }
1227 }
1228 }
1229 return LLDB_INVALID_IMAGE_TOKEN;
1230}
1231
1232//----------------------------------------------------------------------
1233// UnloadImage
1234//
1235// This function provides a default implementation that works for most
1236// unix variants. Any Process subclasses that need to do shared library
1237// loading differently should override LoadImage and UnloadImage and
1238// do what is needed.
1239//----------------------------------------------------------------------
1240Error
1241Process::UnloadImage (uint32_t image_token)
1242{
1243 Error error;
1244 if (image_token < m_image_tokens.size())
1245 {
1246 const addr_t image_addr = m_image_tokens[image_token];
1247 if (image_addr == LLDB_INVALID_ADDRESS)
1248 {
1249 error.SetErrorString("image already unloaded");
1250 }
1251 else
1252 {
1253 DynamicLoader *loader = GetDynamicLoader();
1254 if (loader)
1255 error = loader->CanLoadImage();
1256
1257 if (error.Success())
1258 {
1259 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001260
1261 if (thread_sp)
1262 {
1263 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1264
1265 if (frame_sp)
1266 {
1267 ExecutionContext exe_ctx;
1268 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001269 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001270 StreamString expr;
1271 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1272 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001273 lldb::ValueObjectSP result_valobj_sp;
Sean Callananc7b65062011-11-07 23:35:40 +00001274 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +00001275 if (result_valobj_sp->GetError().Success())
1276 {
1277 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001278 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001279 {
1280 if (scalar.UInt(1))
1281 {
1282 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1283 }
1284 else
1285 {
1286 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1287 }
1288 }
1289 }
1290 else
1291 {
1292 error = result_valobj_sp->GetError();
1293 }
1294 }
1295 }
1296 }
1297 }
1298 }
1299 else
1300 {
1301 error.SetErrorString("invalid image token");
1302 }
1303 return error;
1304}
1305
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001306const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001307Process::GetABI()
1308{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001309 if (!m_abi_sp)
1310 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1311 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001312}
1313
Jim Ingham22777012010-09-23 02:01:19 +00001314LanguageRuntime *
1315Process::GetLanguageRuntime(lldb::LanguageType language)
1316{
1317 LanguageRuntimeCollection::iterator pos;
1318 pos = m_language_runtimes.find (language);
1319 if (pos == m_language_runtimes.end())
1320 {
1321 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1322
1323 m_language_runtimes[language]
1324 = runtime;
1325 return runtime.get();
1326 }
1327 else
1328 return (*pos).second.get();
1329}
1330
1331CPPLanguageRuntime *
1332Process::GetCPPLanguageRuntime ()
1333{
1334 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1335 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1336 return static_cast<CPPLanguageRuntime *> (runtime);
1337 return NULL;
1338}
1339
1340ObjCLanguageRuntime *
1341Process::GetObjCLanguageRuntime ()
1342{
1343 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1344 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1345 return static_cast<ObjCLanguageRuntime *> (runtime);
1346 return NULL;
1347}
1348
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001349BreakpointSiteList &
1350Process::GetBreakpointSiteList()
1351{
1352 return m_breakpoint_site_list;
1353}
1354
1355const BreakpointSiteList &
1356Process::GetBreakpointSiteList() const
1357{
1358 return m_breakpoint_site_list;
1359}
1360
1361
1362void
1363Process::DisableAllBreakpointSites ()
1364{
1365 m_breakpoint_site_list.SetEnabledForAll (false);
1366}
1367
1368Error
1369Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1370{
1371 Error error (DisableBreakpointSiteByID (break_id));
1372
1373 if (error.Success())
1374 m_breakpoint_site_list.Remove(break_id);
1375
1376 return error;
1377}
1378
1379Error
1380Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1381{
1382 Error error;
1383 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1384 if (bp_site_sp)
1385 {
1386 if (bp_site_sp->IsEnabled())
1387 error = DisableBreakpoint (bp_site_sp.get());
1388 }
1389 else
1390 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001391 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001392 }
1393
1394 return error;
1395}
1396
1397Error
1398Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1399{
1400 Error error;
1401 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1402 if (bp_site_sp)
1403 {
1404 if (!bp_site_sp->IsEnabled())
1405 error = EnableBreakpoint (bp_site_sp.get());
1406 }
1407 else
1408 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001409 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001410 }
1411 return error;
1412}
1413
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001414lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001415Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1416{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001417 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001418 if (load_addr != LLDB_INVALID_ADDRESS)
1419 {
1420 BreakpointSiteSP bp_site_sp;
1421
1422 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1423 // create a new breakpoint site and add it.
1424
1425 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1426
1427 if (bp_site_sp)
1428 {
1429 bp_site_sp->AddOwner (owner);
1430 owner->SetBreakpointSite (bp_site_sp);
1431 return bp_site_sp->GetID();
1432 }
1433 else
1434 {
1435 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1436 if (bp_site_sp)
1437 {
1438 if (EnableBreakpoint (bp_site_sp.get()).Success())
1439 {
1440 owner->SetBreakpointSite (bp_site_sp);
1441 return m_breakpoint_site_list.Add (bp_site_sp);
1442 }
1443 }
1444 }
1445 }
1446 // We failed to enable the breakpoint
1447 return LLDB_INVALID_BREAK_ID;
1448
1449}
1450
1451void
1452Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1453{
1454 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1455 if (num_owners == 0)
1456 {
1457 DisableBreakpoint(bp_site_sp.get());
1458 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1459 }
1460}
1461
1462
1463size_t
1464Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1465{
1466 size_t bytes_removed = 0;
1467 addr_t intersect_addr;
1468 size_t intersect_size;
1469 size_t opcode_offset;
1470 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001471 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001472 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001473
Jim Ingham20c77192011-06-29 19:42:28 +00001474 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001475 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001476 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001477 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001478 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001479 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001480 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001481 {
1482 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1483 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001484 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001485 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001486 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001487 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001488 }
1489 }
1490 }
1491 return bytes_removed;
1492}
1493
1494
Greg Claytonded470d2011-03-19 01:12:21 +00001495
1496size_t
1497Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1498{
1499 PlatformSP platform_sp (m_target.GetPlatform());
1500 if (platform_sp)
1501 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1502 return 0;
1503}
1504
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001505Error
1506Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1507{
1508 Error error;
1509 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001510 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001511 const addr_t bp_addr = bp_site->GetLoadAddress();
1512 if (log)
1513 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1514 if (bp_site->IsEnabled())
1515 {
1516 if (log)
1517 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1518 return error;
1519 }
1520
1521 if (bp_addr == LLDB_INVALID_ADDRESS)
1522 {
1523 error.SetErrorString("BreakpointSite contains an invalid load address.");
1524 return error;
1525 }
1526 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1527 // trap for the breakpoint site
1528 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1529
1530 if (bp_opcode_size == 0)
1531 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001532 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001533 }
1534 else
1535 {
1536 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1537
1538 if (bp_opcode_bytes == NULL)
1539 {
1540 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1541 return error;
1542 }
1543
1544 // Save the original opcode by reading it
1545 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1546 {
1547 // Write a software breakpoint in place of the original opcode
1548 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1549 {
1550 uint8_t verify_bp_opcode_bytes[64];
1551 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1552 {
1553 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1554 {
1555 bp_site->SetEnabled(true);
1556 bp_site->SetType (BreakpointSite::eSoftware);
1557 if (log)
1558 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1559 bp_site->GetID(),
1560 (uint64_t)bp_addr);
1561 }
1562 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001563 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001564 }
1565 else
1566 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1567 }
1568 else
1569 error.SetErrorString("Unable to write breakpoint trap to memory.");
1570 }
1571 else
1572 error.SetErrorString("Unable to read memory at breakpoint address.");
1573 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001574 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001575 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1576 bp_site->GetID(),
1577 (uint64_t)bp_addr,
1578 error.AsCString());
1579 return error;
1580}
1581
1582Error
1583Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1584{
1585 Error error;
1586 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001587 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001588 addr_t bp_addr = bp_site->GetLoadAddress();
1589 lldb::user_id_t breakID = bp_site->GetID();
1590 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001591 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001592
1593 if (bp_site->IsHardware())
1594 {
1595 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1596 }
1597 else if (bp_site->IsEnabled())
1598 {
1599 const size_t break_op_size = bp_site->GetByteSize();
1600 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1601 if (break_op_size > 0)
1602 {
1603 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001604 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001605 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001606 bool break_op_found = false;
1607
1608 // Read the breakpoint opcode
1609 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1610 {
1611 bool verify = false;
1612 // Make sure we have the a breakpoint opcode exists at this address
1613 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1614 {
1615 break_op_found = true;
1616 // We found a valid breakpoint opcode at this address, now restore
1617 // the saved opcode.
1618 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1619 {
1620 verify = true;
1621 }
1622 else
1623 error.SetErrorString("Memory write failed when restoring original opcode.");
1624 }
1625 else
1626 {
1627 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1628 // Set verify to true and so we can check if the original opcode has already been restored
1629 verify = true;
1630 }
1631
1632 if (verify)
1633 {
Greg Claytonc982c762010-07-09 20:39:50 +00001634 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001635 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001636 // Verify that our original opcode made it back to the inferior
1637 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1638 {
1639 // compare the memory we just read with the original opcode
1640 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1641 {
1642 // SUCCESS
1643 bp_site->SetEnabled(false);
1644 if (log)
1645 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1646 return error;
1647 }
1648 else
1649 {
1650 if (break_op_found)
1651 error.SetErrorString("Failed to restore original opcode.");
1652 }
1653 }
1654 else
1655 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1656 }
1657 }
1658 else
1659 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1660 }
1661 }
1662 else
1663 {
1664 if (log)
1665 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1666 return error;
1667 }
1668
1669 if (log)
1670 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1671 bp_site->GetID(),
1672 (uint64_t)bp_addr,
1673 error.AsCString());
1674 return error;
1675
1676}
1677
Greg Clayton58be07b2011-01-07 06:08:19 +00001678// Comment out line below to disable memory caching
1679#define ENABLE_MEMORY_CACHING
1680// Uncomment to verify memory caching works after making changes to caching code
1681//#define VERIFY_MEMORY_READS
1682
1683#if defined (ENABLE_MEMORY_CACHING)
1684
1685#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001686
1687size_t
1688Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1689{
Greg Clayton58be07b2011-01-07 06:08:19 +00001690 // Memory caching is enabled, with debug verification
1691 if (buf && size)
1692 {
1693 // Uncomment the line below to make sure memory caching is working.
1694 // I ran this through the test suite and got no assertions, so I am
1695 // pretty confident this is working well. If any changes are made to
1696 // memory caching, uncomment the line below and test your changes!
1697
1698 // Verify all memory reads by using the cache first, then redundantly
1699 // reading the same memory from the inferior and comparing to make sure
1700 // everything is exactly the same.
1701 std::string verify_buf (size, '\0');
1702 assert (verify_buf.size() == size);
1703 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1704 Error verify_error;
1705 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1706 assert (cache_bytes_read == verify_bytes_read);
1707 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1708 assert (verify_error.Success() == error.Success());
1709 return cache_bytes_read;
1710 }
1711 return 0;
1712}
1713
1714#else // #if defined (VERIFY_MEMORY_READS)
1715
1716size_t
1717Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1718{
1719 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001720 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001721}
1722
1723#endif // #else for #if defined (VERIFY_MEMORY_READS)
1724
1725#else // #if defined (ENABLE_MEMORY_CACHING)
1726
1727size_t
1728Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1729{
1730 // Memory caching is disabled
1731 return ReadMemoryFromInferior (addr, buf, size, error);
1732}
1733
1734#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1735
1736
1737size_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001738Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1739{
1740 size_t total_cstr_len = 0;
1741 if (dst && dst_max_len)
1742 {
1743 // NULL out everything just to be safe
1744 memset (dst, 0, dst_max_len);
1745 Error error;
1746 addr_t curr_addr = addr;
1747 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1748 size_t bytes_left = dst_max_len - 1;
1749 char *curr_dst = dst;
1750
1751 while (bytes_left > 0)
1752 {
1753 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1754 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1755 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1756
1757 if (bytes_read == 0)
1758 {
1759 dst[total_cstr_len] = '\0';
1760 break;
1761 }
1762 const size_t len = strlen(curr_dst);
1763
1764 total_cstr_len += len;
1765
1766 if (len < bytes_to_read)
1767 break;
1768
1769 curr_dst += bytes_read;
1770 curr_addr += bytes_read;
1771 bytes_left -= bytes_read;
1772 }
1773 }
1774 return total_cstr_len;
1775}
1776
1777size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00001778Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1779{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001780 if (buf == NULL || size == 0)
1781 return 0;
1782
1783 size_t bytes_read = 0;
1784 uint8_t *bytes = (uint8_t *)buf;
1785
1786 while (bytes_read < size)
1787 {
1788 const size_t curr_size = size - bytes_read;
1789 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1790 bytes + bytes_read,
1791 curr_size,
1792 error);
1793 bytes_read += curr_bytes_read;
1794 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1795 break;
1796 }
1797
1798 // Replace any software breakpoint opcodes that fall into this range back
1799 // into "buf" before we return
1800 if (bytes_read > 0)
1801 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1802 return bytes_read;
1803}
1804
Greg Clayton58a4c462010-12-16 20:01:20 +00001805uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001806Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00001807{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001808 Scalar scalar;
1809 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1810 return scalar.ULongLong(fail_value);
1811 return fail_value;
1812}
1813
1814addr_t
1815Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1816{
1817 Scalar scalar;
1818 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1819 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1820 return LLDB_INVALID_ADDRESS;
1821}
1822
1823
1824bool
1825Process::WritePointerToMemory (lldb::addr_t vm_addr,
1826 lldb::addr_t ptr_value,
1827 Error &error)
1828{
1829 Scalar scalar;
1830 const uint32_t addr_byte_size = GetAddressByteSize();
1831 if (addr_byte_size <= 4)
1832 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00001833 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001834 scalar = ptr_value;
1835 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00001836}
1837
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001838size_t
1839Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1840{
1841 size_t bytes_written = 0;
1842 const uint8_t *bytes = (const uint8_t *)buf;
1843
1844 while (bytes_written < size)
1845 {
1846 const size_t curr_size = size - bytes_written;
1847 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1848 bytes + bytes_written,
1849 curr_size,
1850 error);
1851 bytes_written += curr_bytes_written;
1852 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1853 break;
1854 }
1855 return bytes_written;
1856}
1857
1858size_t
1859Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1860{
Greg Clayton58be07b2011-01-07 06:08:19 +00001861#if defined (ENABLE_MEMORY_CACHING)
1862 m_memory_cache.Flush (addr, size);
1863#endif
1864
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865 if (buf == NULL || size == 0)
1866 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00001867
Jim Ingham4b536182011-08-09 02:12:22 +00001868 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00001869
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001870 // We need to write any data that would go where any current software traps
1871 // (enabled software breakpoints) any software traps (breakpoints) that we
1872 // may have placed in our tasks memory.
1873
1874 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1875 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1876
1877 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00001878 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001879
1880 BreakpointSiteList::collection::const_iterator pos;
1881 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001882 addr_t intersect_addr = 0;
1883 size_t intersect_size = 0;
1884 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001885 const uint8_t *ubuf = (const uint8_t *)buf;
1886
1887 for (pos = iter; pos != end; ++pos)
1888 {
1889 BreakpointSiteSP bp;
1890 bp = pos->second;
1891
1892 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1893 assert(addr <= intersect_addr && intersect_addr < addr + size);
1894 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1895 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1896
1897 // Check for bytes before this breakpoint
1898 const addr_t curr_addr = addr + bytes_written;
1899 if (intersect_addr > curr_addr)
1900 {
1901 // There are some bytes before this breakpoint that we need to
1902 // just write to memory
1903 size_t curr_size = intersect_addr - curr_addr;
1904 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1905 ubuf + bytes_written,
1906 curr_size,
1907 error);
1908 bytes_written += curr_bytes_written;
1909 if (curr_bytes_written != curr_size)
1910 {
1911 // We weren't able to write all of the requested bytes, we
1912 // are done looping and will return the number of bytes that
1913 // we have written so far.
1914 break;
1915 }
1916 }
1917
1918 // Now write any bytes that would cover up any software breakpoints
1919 // directly into the breakpoint opcode buffer
1920 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1921 bytes_written += intersect_size;
1922 }
1923
1924 // Write any remaining bytes after the last breakpoint if we have any left
1925 if (bytes_written < size)
1926 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1927 ubuf + bytes_written,
1928 size - bytes_written,
1929 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00001930
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001931 return bytes_written;
1932}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001933
1934size_t
1935Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
1936{
1937 if (byte_size == UINT32_MAX)
1938 byte_size = scalar.GetByteSize();
1939 if (byte_size > 0)
1940 {
1941 uint8_t buf[32];
1942 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
1943 if (mem_size > 0)
1944 return WriteMemory(addr, buf, mem_size, error);
1945 else
1946 error.SetErrorString ("failed to get scalar as memory data");
1947 }
1948 else
1949 {
1950 error.SetErrorString ("invalid scalar value");
1951 }
1952 return 0;
1953}
1954
1955size_t
1956Process::ReadScalarIntegerFromMemory (addr_t addr,
1957 uint32_t byte_size,
1958 bool is_signed,
1959 Scalar &scalar,
1960 Error &error)
1961{
1962 uint64_t uval;
1963
1964 if (byte_size <= sizeof(uval))
1965 {
1966 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
1967 if (bytes_read == byte_size)
1968 {
1969 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
1970 uint32_t offset = 0;
1971 if (byte_size <= 4)
1972 scalar = data.GetMaxU32 (&offset, byte_size);
1973 else
1974 scalar = data.GetMaxU64 (&offset, byte_size);
1975
1976 if (is_signed)
1977 scalar.SignExtend(byte_size * 8);
1978 return bytes_read;
1979 }
1980 }
1981 else
1982 {
1983 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1984 }
1985 return 0;
1986}
1987
Greg Claytond495c532011-05-17 03:37:42 +00001988#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001989addr_t
1990Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1991{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00001992 if (GetPrivateState() != eStateStopped)
1993 return LLDB_INVALID_ADDRESS;
1994
Greg Claytond495c532011-05-17 03:37:42 +00001995#if defined (USE_ALLOCATE_MEMORY_CACHE)
1996 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
1997#else
Greg Claytonb2daec92011-01-23 19:58:49 +00001998 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1999 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2000 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002001 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002002 size,
Greg Claytond495c532011-05-17 03:37:42 +00002003 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002004 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002005 m_mod_id.GetStopID(),
2006 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002007 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002008#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002009}
2010
Sean Callanan90539452011-09-20 23:01:51 +00002011bool
2012Process::CanJIT ()
2013{
2014 return m_can_jit == eCanJITYes;
2015}
2016
2017void
2018Process::SetCanJIT (bool can_jit)
2019{
2020 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2021}
2022
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002023Error
2024Process::DeallocateMemory (addr_t ptr)
2025{
Greg Claytond495c532011-05-17 03:37:42 +00002026 Error error;
2027#if defined (USE_ALLOCATE_MEMORY_CACHE)
2028 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2029 {
2030 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2031 }
2032#else
2033 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002034
2035 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2036 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002037 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002038 ptr,
2039 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002040 m_mod_id.GetStopID(),
2041 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002042#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002043 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002044}
2045
2046
2047Error
Johnny Chen01a67862011-10-14 00:42:25 +00002048Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002049{
2050 Error error;
2051 error.SetErrorString("watchpoints are not supported");
2052 return error;
2053}
2054
2055Error
Johnny Chen01a67862011-10-14 00:42:25 +00002056Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002057{
2058 Error error;
2059 error.SetErrorString("watchpoints are not supported");
2060 return error;
2061}
2062
2063StateType
2064Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2065{
2066 StateType state;
2067 // Now wait for the process to launch and return control to us, and then
2068 // call DidLaunch:
2069 while (1)
2070 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002071 event_sp.reset();
2072 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2073
2074 if (StateIsStoppedState(state))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002075 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002076
2077 // If state is invalid, then we timed out
2078 if (state == eStateInvalid)
2079 break;
2080
2081 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002082 HandlePrivateEvent (event_sp);
2083 }
2084 return state;
2085}
2086
2087Error
Greg Clayton982c9762011-11-03 21:22:33 +00002088Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002089{
2090 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002091 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002092 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002093 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002094 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002095
Greg Claytonaa149cb2011-08-11 02:48:45 +00002096 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002097 if (exe_module)
2098 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002099 char local_exec_file_path[PATH_MAX];
2100 char platform_exec_file_path[PATH_MAX];
2101 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2102 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002103 if (exe_module->GetFileSpec().Exists())
2104 {
Greg Clayton71337622011-02-24 22:24:29 +00002105 if (PrivateStateThreadIsValid ())
2106 PausePrivateStateThread ();
2107
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108 error = WillLaunch (exe_module);
2109 if (error.Success())
2110 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002111 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002112
2113 // Now launch using these arguments.
Greg Clayton982c9762011-11-03 21:22:33 +00002114 error = DoLaunch (exe_module, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002115
2116 if (error.Fail())
2117 {
2118 if (GetID() != LLDB_INVALID_PROCESS_ID)
2119 {
2120 SetID (LLDB_INVALID_PROCESS_ID);
2121 const char *error_string = error.AsCString();
2122 if (error_string == NULL)
2123 error_string = "launch failed";
2124 SetExitStatus (-1, error_string);
2125 }
2126 }
2127 else
2128 {
2129 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002130 TimeValue timeout_time;
2131 timeout_time = TimeValue::Now();
2132 timeout_time.OffsetWithSeconds(10);
2133 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002134
Greg Clayton1a38ea72011-06-22 01:42:17 +00002135 if (state == eStateInvalid || event_sp.get() == NULL)
2136 {
2137 // We were able to launch the process, but we failed to
2138 // catch the initial stop.
2139 SetExitStatus (0, "failed to catch stop after launch");
2140 Destroy();
2141 }
2142 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002143 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002144
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145 DidLaunch ();
2146
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002147 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002148 if (m_dyld_ap.get())
2149 m_dyld_ap->DidLaunch();
2150
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002151 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002152 // This delays passing the stopped event to listeners till DidLaunch gets
2153 // a chance to complete...
2154 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002155
2156 if (PrivateStateThreadIsValid ())
2157 ResumePrivateStateThread ();
2158 else
2159 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002160 }
2161 else if (state == eStateExited)
2162 {
2163 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2164 // not likely to work, and return an invalid pid.
2165 HandlePrivateEvent (event_sp);
2166 }
2167 }
2168 }
2169 }
2170 else
2171 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002172 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002173 }
2174 }
2175 return error;
2176}
2177
Jim Inghambb3a2832011-01-29 01:49:25 +00002178Process::NextEventAction::EventActionResult
2179Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002180{
Jim Inghambb3a2832011-01-29 01:49:25 +00002181 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2182 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002183 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002184 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002185 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002186 return eEventActionRetry;
2187
2188 case eStateStopped:
2189 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002190 {
2191 // During attach, prior to sending the eStateStopped event,
2192 // lldb_private::Process subclasses must set the process must set
2193 // the new process ID.
2194 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2195 if (m_exec_count > 0)
2196 {
2197 --m_exec_count;
2198 m_process->Resume();
2199 return eEventActionRetry;
2200 }
2201 else
2202 {
2203 m_process->CompleteAttach ();
2204 return eEventActionSuccess;
2205 }
2206 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002207 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002208
Greg Clayton513c26c2011-01-29 07:10:55 +00002209 default:
2210 case eStateExited:
2211 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002212 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002213 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002214
2215 m_exit_string.assign ("No valid Process");
2216 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002217}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002218
Jim Inghambb3a2832011-01-29 01:49:25 +00002219Process::NextEventAction::EventActionResult
2220Process::AttachCompletionHandler::HandleBeingInterrupted()
2221{
2222 return eEventActionSuccess;
2223}
2224
2225const char *
2226Process::AttachCompletionHandler::GetExitString ()
2227{
2228 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002229}
2230
2231Error
Greg Claytonc9ed4782011-11-12 02:10:56 +00002232Process::Attach (lldb::pid_t attach_pid, uint32_t exec_count)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002233{
2234
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002235 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002236 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002237
Greg Clayton93d3c8332011-02-16 04:46:07 +00002238 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002239 m_os_ap.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002240
Greg Claytonc982c762010-07-09 20:39:50 +00002241 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002242 if (error.Success())
2243 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002244 SetPublicState (eStateAttaching);
2245
Greg Claytonc982c762010-07-09 20:39:50 +00002246 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002247 if (error.Success())
2248 {
Greg Claytonc9ed4782011-11-12 02:10:56 +00002249
2250 SetNextEventAction(new Process::AttachCompletionHandler(this, exec_count));
Jim Inghambb3a2832011-01-29 01:49:25 +00002251 StartPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002252 }
2253 else
2254 {
2255 if (GetID() != LLDB_INVALID_PROCESS_ID)
2256 {
2257 SetID (LLDB_INVALID_PROCESS_ID);
2258 const char *error_string = error.AsCString();
2259 if (error_string == NULL)
2260 error_string = "attach failed";
2261
2262 SetExitStatus(-1, error_string);
2263 }
2264 }
2265 }
2266 return error;
2267}
2268
2269Error
2270Process::Attach (const char *process_name, bool wait_for_launch)
2271{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002272 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002273 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002274
2275 // Find the process and its architecture. Make sure it matches the architecture
2276 // of the current Target, and if not adjust it.
Greg Claytone996fd32011-03-08 22:40:15 +00002277 Error error;
Jim Ingham5aee1622010-08-09 23:31:02 +00002278
Jim Ingham2ecb7422010-08-17 21:54:19 +00002279 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00002280 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002281 ProcessInstanceInfoList process_infos;
Jim Ingham4299fdb2011-09-15 01:10:17 +00002282 PlatformSP platform_sp (m_target.GetPlatform ());
2283 assert (platform_sp.get());
2284
Greg Claytone996fd32011-03-08 22:40:15 +00002285 if (platform_sp)
Jim Ingham2ecb7422010-08-17 21:54:19 +00002286 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002287 ProcessInstanceInfoMatch match_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002288 match_info.GetProcessInfo().SetName(process_name);
2289 match_info.SetNameMatchType (eNameMatchEquals);
2290 platform_sp->FindProcesses (match_info, process_infos);
Greg Claytone996fd32011-03-08 22:40:15 +00002291 if (process_infos.GetSize() > 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002293 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
Greg Claytone996fd32011-03-08 22:40:15 +00002294 }
2295 else if (process_infos.GetSize() == 0)
2296 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002297 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
Greg Claytone996fd32011-03-08 22:40:15 +00002298 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299 }
2300 else
Greg Claytone996fd32011-03-08 22:40:15 +00002301 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002302 error.SetErrorString ("invalid platform");
Greg Claytone996fd32011-03-08 22:40:15 +00002303 }
2304 }
2305
2306 if (error.Success())
2307 {
2308 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002309 m_os_ap.reset();
Greg Claytone996fd32011-03-08 22:40:15 +00002310
2311 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2312 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002313 {
Greg Claytone996fd32011-03-08 22:40:15 +00002314 SetPublicState (eStateAttaching);
2315 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2316 if (error.Fail())
2317 {
2318 if (GetID() != LLDB_INVALID_PROCESS_ID)
2319 {
2320 SetID (LLDB_INVALID_PROCESS_ID);
2321 const char *error_string = error.AsCString();
2322 if (error_string == NULL)
2323 error_string = "attach failed";
2324
2325 SetExitStatus(-1, error_string);
2326 }
2327 }
2328 else
2329 {
Greg Claytonc9ed4782011-11-12 02:10:56 +00002330 SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
Greg Claytone996fd32011-03-08 22:40:15 +00002331 StartPrivateStateThread();
2332 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002333 }
2334 }
2335 return error;
2336}
2337
Greg Clayton93d3c8332011-02-16 04:46:07 +00002338void
2339Process::CompleteAttach ()
2340{
2341 // Let the process subclass figure out at much as it can about the process
2342 // before we go looking for a dynamic loader plug-in.
Jim Ingham8314c522011-09-15 21:36:42 +00002343 m_attached_to_process = true;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002344 DidAttach();
2345
Jim Ingham4299fdb2011-09-15 01:10:17 +00002346 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2347 // the same as the one we've already set, switch architectures.
2348 PlatformSP platform_sp (m_target.GetPlatform ());
2349 assert (platform_sp.get());
2350 if (platform_sp)
2351 {
2352 ProcessInstanceInfo process_info;
2353 platform_sp->GetProcessInfo (GetID(), process_info);
2354 const ArchSpec &process_arch = process_info.GetArchitecture();
2355 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2356 m_target.SetArchitecture (process_arch);
2357 }
2358
2359 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002360 // plug-in
Greg Clayton7a5388b2011-03-20 04:57:14 +00002361 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002362 if (m_dyld_ap.get())
2363 m_dyld_ap->DidAttach();
2364
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002365 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002366 // Figure out which one is the executable, and set that in our target:
2367 ModuleList &modules = m_target.GetImages();
2368
2369 size_t num_modules = modules.GetSize();
2370 for (int i = 0; i < num_modules; i++)
2371 {
2372 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002373 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002374 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002375 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002376 m_target.SetExecutableModule (module_sp, false);
2377 break;
2378 }
2379 }
2380}
2381
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002382Error
Greg Claytonb766a732011-02-04 01:58:07 +00002383Process::ConnectRemote (const char *remote_url)
2384{
Greg Claytonb766a732011-02-04 01:58:07 +00002385 m_abi_sp.reset();
2386 m_process_input_reader.reset();
2387
2388 // Find the process and its architecture. Make sure it matches the architecture
2389 // of the current Target, and if not adjust it.
2390
2391 Error error (DoConnectRemote (remote_url));
2392 if (error.Success())
2393 {
Greg Clayton71337622011-02-24 22:24:29 +00002394 if (GetID() != LLDB_INVALID_PROCESS_ID)
2395 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002396 EventSP event_sp;
2397 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2398
2399 if (state == eStateStopped || state == eStateCrashed)
2400 {
2401 // If we attached and actually have a process on the other end, then
2402 // this ended up being the equivalent of an attach.
2403 CompleteAttach ();
2404
2405 // This delays passing the stopped event to listeners till
2406 // CompleteAttach gets a chance to complete...
2407 HandlePrivateEvent (event_sp);
2408
2409 }
Greg Clayton71337622011-02-24 22:24:29 +00002410 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002411
2412 if (PrivateStateThreadIsValid ())
2413 ResumePrivateStateThread ();
2414 else
2415 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002416 }
2417 return error;
2418}
2419
2420
2421Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422Process::Resume ()
2423{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002424 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002425 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002426 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002427 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002428 StateAsCString(m_public_state.GetValue()),
2429 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002430
2431 Error error (WillResume());
2432 // Tell the process it is about to resume before the thread list
2433 if (error.Success())
2434 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002435 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002436 // can let all of our threads know that they are about to be
2437 // resumed. Threads will each be called with
2438 // Thread::WillResume(StateType) where StateType contains the state
2439 // that they are supposed to have when the process is resumed
2440 // (suspended/running/stepping). Threads should also check
2441 // their resume signal in lldb::Thread::GetResumeSignal()
2442 // to see if they are suppoed to start back up with a signal.
2443 if (m_thread_list.WillResume())
2444 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00002445 m_mod_id.BumpResumeID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002446 error = DoResume();
2447 if (error.Success())
2448 {
2449 DidResume();
2450 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00002451 if (log)
2452 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002453 }
2454 }
2455 else
2456 {
Jim Ingham444586b2011-01-24 06:34:17 +00002457 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002458 }
2459 }
Jim Ingham444586b2011-01-24 06:34:17 +00002460 else if (log)
2461 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002462 return error;
2463}
2464
2465Error
2466Process::Halt ()
2467{
Jim Inghambb3a2832011-01-29 01:49:25 +00002468 // Pause our private state thread so we can ensure no one else eats
2469 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002470 Listener halt_listener ("lldb.process.halt_listener");
2471 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002472
Jim Inghambb3a2832011-01-29 01:49:25 +00002473 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002474 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002475
Greg Clayton513c26c2011-01-29 07:10:55 +00002476 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002477 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002478
Greg Clayton513c26c2011-01-29 07:10:55 +00002479 bool caused_stop = false;
2480
2481 // Ask the process subclass to actually halt our process
2482 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002483 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002484 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002485 if (m_public_state.GetValue() == eStateAttaching)
2486 {
2487 SetExitStatus(SIGKILL, "Cancelled async attach.");
2488 Destroy ();
2489 }
2490 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002491 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002492 // If "caused_stop" is true, then DoHalt stopped the process. If
2493 // "caused_stop" is false, the process was already stopped.
2494 // If the DoHalt caused the process to stop, then we want to catch
2495 // this event and set the interrupted bool to true before we pass
2496 // this along so clients know that the process was interrupted by
2497 // a halt command.
2498 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002499 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002500 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002501 TimeValue timeout_time;
2502 timeout_time = TimeValue::Now();
2503 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002504 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2505 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002506
Jim Ingham0f16e732011-02-08 05:20:59 +00002507 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002508 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002509 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002510 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002511 }
2512 else
2513 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002514 if (StateIsStoppedState (state))
2515 {
2516 // We caused the process to interrupt itself, so mark this
2517 // as such in the stop event so clients can tell an interrupted
2518 // process from a natural stop
2519 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2520 }
2521 else
2522 {
2523 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2524 if (log)
2525 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2526 error.SetErrorString ("Did not get stopped event after halt.");
2527 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002528 }
2529 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002530 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002531 }
2532 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002533 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002534 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002535 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002536
2537 // Post any event we might have consumed. If all goes well, we will have
2538 // stopped the process, intercepted the event and set the interrupted
2539 // bool in the event. Post it to the private event queue and that will end up
2540 // correctly setting the state.
2541 if (event_sp)
2542 m_private_state_broadcaster.BroadcastEvent(event_sp);
2543
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002544 return error;
2545}
2546
2547Error
2548Process::Detach ()
2549{
2550 Error error (WillDetach());
2551
2552 if (error.Success())
2553 {
2554 DisableAllBreakpointSites();
2555 error = DoDetach();
2556 if (error.Success())
2557 {
2558 DidDetach();
2559 StopPrivateStateThread();
2560 }
2561 }
2562 return error;
2563}
2564
2565Error
2566Process::Destroy ()
2567{
2568 Error error (WillDestroy());
2569 if (error.Success())
2570 {
2571 DisableAllBreakpointSites();
2572 error = DoDestroy();
2573 if (error.Success())
2574 {
2575 DidDestroy();
2576 StopPrivateStateThread();
2577 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002578 m_stdio_communication.StopReadThread();
2579 m_stdio_communication.Disconnect();
2580 if (m_process_input_reader && m_process_input_reader->IsActive())
2581 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2582 if (m_process_input_reader)
2583 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002584 }
2585 return error;
2586}
2587
2588Error
2589Process::Signal (int signal)
2590{
2591 Error error (WillSignal());
2592 if (error.Success())
2593 {
2594 error = DoSignal(signal);
2595 if (error.Success())
2596 DidSignal();
2597 }
2598 return error;
2599}
2600
Greg Clayton514487e2011-02-15 21:59:32 +00002601lldb::ByteOrder
2602Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002603{
Greg Clayton514487e2011-02-15 21:59:32 +00002604 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002605}
2606
2607uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002608Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002609{
Greg Clayton514487e2011-02-15 21:59:32 +00002610 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002611}
2612
Greg Clayton514487e2011-02-15 21:59:32 +00002613
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002614bool
2615Process::ShouldBroadcastEvent (Event *event_ptr)
2616{
2617 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2618 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002619 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002620
2621 switch (state)
2622 {
Greg Claytonb766a732011-02-04 01:58:07 +00002623 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002624 case eStateAttaching:
2625 case eStateLaunching:
2626 case eStateDetached:
2627 case eStateExited:
2628 case eStateUnloaded:
2629 // These events indicate changes in the state of the debugging session, always report them.
2630 return_value = true;
2631 break;
2632 case eStateInvalid:
2633 // We stopped for no apparent reason, don't report it.
2634 return_value = false;
2635 break;
2636 case eStateRunning:
2637 case eStateStepping:
2638 // If we've started the target running, we handle the cases where we
2639 // are already running and where there is a transition from stopped to
2640 // running differently.
2641 // running -> running: Automatically suppress extra running events
2642 // stopped -> running: Report except when there is one or more no votes
2643 // and no yes votes.
2644 SynchronouslyNotifyStateChanged (state);
2645 switch (m_public_state.GetValue())
2646 {
2647 case eStateRunning:
2648 case eStateStepping:
2649 // We always suppress multiple runnings with no PUBLIC stop in between.
2650 return_value = false;
2651 break;
2652 default:
2653 // TODO: make this work correctly. For now always report
2654 // run if we aren't running so we don't miss any runnning
2655 // events. If I run the lldb/test/thread/a.out file and
2656 // break at main.cpp:58, run and hit the breakpoints on
2657 // multiple threads, then somehow during the stepping over
2658 // of all breakpoints no run gets reported.
2659 return_value = true;
2660
2661 // This is a transition from stop to run.
2662 switch (m_thread_list.ShouldReportRun (event_ptr))
2663 {
2664 case eVoteYes:
2665 case eVoteNoOpinion:
2666 return_value = true;
2667 break;
2668 case eVoteNo:
2669 return_value = false;
2670 break;
2671 }
2672 break;
2673 }
2674 break;
2675 case eStateStopped:
2676 case eStateCrashed:
2677 case eStateSuspended:
2678 {
2679 // We've stopped. First see if we're going to restart the target.
2680 // If we are going to stop, then we always broadcast the event.
2681 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00002682 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002683 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002684 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00002685 if (log)
2686 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002687 return true;
2688 }
2689 else
2690 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002691 RefreshStateAfterStop ();
2692
2693 if (m_thread_list.ShouldStop (event_ptr) == false)
2694 {
2695 switch (m_thread_list.ShouldReportStop (event_ptr))
2696 {
2697 case eVoteYes:
2698 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002699 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002700 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002701 case eVoteNo:
2702 return_value = false;
2703 break;
2704 }
2705
2706 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002707 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002708 Resume ();
2709 }
2710 else
2711 {
2712 return_value = true;
2713 SynchronouslyNotifyStateChanged (state);
2714 }
2715 }
2716 }
2717 }
2718
2719 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00002720 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002721 return return_value;
2722}
2723
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724
2725bool
2726Process::StartPrivateStateThread ()
2727{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002728 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002729
Greg Clayton8b82f082011-04-12 05:54:46 +00002730 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002731 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00002732 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2733
2734 if (already_running)
2735 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736
2737 // Create a thread that watches our internal state and controls which
2738 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002739 char thread_name[1024];
Greg Clayton81c22f62011-10-19 18:09:39 +00002740 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Clayton3e06bd92011-01-09 21:07:35 +00002741 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00002742 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743}
2744
2745void
2746Process::PausePrivateStateThread ()
2747{
2748 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2749}
2750
2751void
2752Process::ResumePrivateStateThread ()
2753{
2754 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2755}
2756
2757void
2758Process::StopPrivateStateThread ()
2759{
Greg Clayton8b82f082011-04-12 05:54:46 +00002760 if (PrivateStateThreadIsValid ())
2761 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762}
2763
2764void
2765Process::ControlPrivateStateThread (uint32_t signal)
2766{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002767 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002768
2769 assert (signal == eBroadcastInternalStateControlStop ||
2770 signal == eBroadcastInternalStateControlPause ||
2771 signal == eBroadcastInternalStateControlResume);
2772
2773 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002774 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002775
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002776 // Signal the private state thread. First we should copy this is case the
2777 // thread starts exiting since the private state thread will NULL this out
2778 // when it exits
2779 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00002780 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781 {
2782 TimeValue timeout_time;
2783 bool timed_out;
2784
2785 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2786
2787 timeout_time = TimeValue::Now();
2788 timeout_time.OffsetWithSeconds(2);
2789 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2790 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2791
2792 if (signal == eBroadcastInternalStateControlStop)
2793 {
2794 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002795 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002796
2797 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002798 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002799 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002800 }
2801 }
2802}
2803
2804void
2805Process::HandlePrivateEvent (EventSP &event_sp)
2806{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002807 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00002808
Greg Clayton414f5d32011-01-25 02:58:48 +00002809 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002810
2811 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00002812 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00002813 {
Jim Ingham754ab982011-01-29 04:05:41 +00002814 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002815 switch (action_result)
2816 {
2817 case NextEventAction::eEventActionSuccess:
2818 SetNextEventAction(NULL);
2819 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002820
Jim Inghambb3a2832011-01-29 01:49:25 +00002821 case NextEventAction::eEventActionRetry:
2822 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002823
Jim Inghambb3a2832011-01-29 01:49:25 +00002824 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002825 // Handle Exiting Here. If we already got an exited event,
2826 // we should just propagate it. Otherwise, swallow this event,
2827 // and set our state to exit so the next event will kill us.
2828 if (new_state != eStateExited)
2829 {
2830 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00002831 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002832 SetNextEventAction(NULL);
2833 return;
2834 }
2835 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00002836 break;
2837 }
2838 }
2839
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002840 // See if we should broadcast this state to external clients?
2841 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002842
2843 if (should_broadcast)
2844 {
2845 if (log)
2846 {
Greg Clayton81c22f62011-10-19 18:09:39 +00002847 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00002848 __FUNCTION__,
2849 GetID(),
2850 StateAsCString(new_state),
2851 StateAsCString (GetState ()),
2852 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002853 }
Jim Ingham9575d842011-03-11 03:53:59 +00002854 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00002855 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002856 PushProcessInputReader ();
2857 else
2858 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00002859
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002860 BroadcastEvent (event_sp);
2861 }
2862 else
2863 {
2864 if (log)
2865 {
Greg Clayton81c22f62011-10-19 18:09:39 +00002866 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00002867 __FUNCTION__,
2868 GetID(),
2869 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00002870 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002871 }
2872 }
2873}
2874
2875void *
2876Process::PrivateStateThread (void *arg)
2877{
2878 Process *proc = static_cast<Process*> (arg);
2879 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880 return result;
2881}
2882
2883void *
2884Process::RunPrivateStateThread ()
2885{
2886 bool control_only = false;
2887 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2888
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002889 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002890 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002891 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002892
2893 bool exit_now = false;
2894 while (!exit_now)
2895 {
2896 EventSP event_sp;
2897 WaitForEventsPrivate (NULL, event_sp, control_only);
2898 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2899 {
2900 switch (event_sp->GetType())
2901 {
2902 case eBroadcastInternalStateControlStop:
2903 exit_now = true;
2904 continue; // Go to next loop iteration so we exit without
2905 break; // doing any internal state managment below
2906
2907 case eBroadcastInternalStateControlPause:
2908 control_only = true;
2909 break;
2910
2911 case eBroadcastInternalStateControlResume:
2912 control_only = false;
2913 break;
2914 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002915
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002916 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002917 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002918
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002920 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002921 }
2922
2923
2924 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2925
2926 if (internal_state != eStateInvalid)
2927 {
2928 HandlePrivateEvent (event_sp);
2929 }
2930
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002931 if (internal_state == eStateInvalid ||
2932 internal_state == eStateExited ||
2933 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002934 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002935 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002936 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002937
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002938 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002939 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002940 }
2941
Caroline Tice20ad3c42010-10-29 21:48:37 +00002942 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002943 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002944 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002945
Greg Clayton6ed95942011-01-22 07:12:45 +00002946 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2947 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002948 return NULL;
2949}
2950
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002951//------------------------------------------------------------------
2952// Process Event Data
2953//------------------------------------------------------------------
2954
2955Process::ProcessEventData::ProcessEventData () :
2956 EventData (),
2957 m_process_sp (),
2958 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002959 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00002960 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002961 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002962{
2963}
2964
2965Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2966 EventData (),
2967 m_process_sp (process_sp),
2968 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002969 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00002970 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002971 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972{
2973}
2974
2975Process::ProcessEventData::~ProcessEventData()
2976{
2977}
2978
2979const ConstString &
2980Process::ProcessEventData::GetFlavorString ()
2981{
2982 static ConstString g_flavor ("Process::ProcessEventData");
2983 return g_flavor;
2984}
2985
2986const ConstString &
2987Process::ProcessEventData::GetFlavor () const
2988{
2989 return ProcessEventData::GetFlavorString ();
2990}
2991
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002992void
2993Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2994{
2995 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00002996 // off of the private process event queue, and then any number of times, first when it gets pulled off of
2997 // the public event queue, then other times when we're pretending that this is where we stopped at the
2998 // end of expression evaluation. m_update_state is used to distinguish these
2999 // three cases; it is 0 when we're just pulling it off for private handling,
3000 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003001
Jim Inghama8604692011-05-22 21:45:01 +00003002 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003003 return;
3004
3005 m_process_sp->SetPublicState (m_state);
3006
3007 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3008 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003009 {
3010 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
3011 int num_threads = curr_thread_list.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003012 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003013
Jim Ingham4b536182011-08-09 02:12:22 +00003014 // The actions might change one of the thread's stop_info's opinions about whether we should
3015 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003016
3017 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3018 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3019 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3020 // to also know if it has changed at all, so we make up a vector of the thread ID's and check what we get back
3021 // against this list & bag out if anything differs.
3022 std::vector<lldb::tid_t> thread_index_array(num_threads);
3023 for (idx = 0; idx < num_threads; ++idx)
3024 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3025
Jim Ingham4b536182011-08-09 02:12:22 +00003026 bool still_should_stop = true;
3027
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003028 for (idx = 0; idx < num_threads; ++idx)
3029 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003030 curr_thread_list = m_process_sp->GetThreadList();
3031 if (curr_thread_list.GetSize() != num_threads)
3032 {
3033 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3034 log->Printf("Number of threads changed from %d to %d while processing event.", num_threads, curr_thread_list.GetSize());
3035 break;
3036 }
3037
3038 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3039
3040 if (thread_sp->GetIndexID() != thread_index_array[idx])
3041 {
3042 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3043 log->Printf("The thread at position %d changed from %d to %d while processing event.",
3044 idx,
3045 thread_index_array[idx],
3046 thread_sp->GetIndexID());
3047 break;
3048 }
3049
Jim Inghamb15bfc72010-10-20 00:39:53 +00003050 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3051 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003052 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003053 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003054 // The stop action might restart the target. If it does, then we want to mark that in the
3055 // event so that whoever is receiving it will know to wait for the running event and reflect
3056 // that state appropriately.
3057 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003058
3059 // FIXME: we might have run.
3060 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003061 {
3062 SetRestarted (true);
3063 break;
3064 }
3065 else if (!stop_info_sp->ShouldStop(event_ptr))
3066 {
3067 still_should_stop = false;
3068 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003069 }
3070 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003071
Jim Ingham4b536182011-08-09 02:12:22 +00003072
3073 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003074 {
Jim Ingham4b536182011-08-09 02:12:22 +00003075 if (!still_should_stop)
3076 {
3077 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003078 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003079 m_process_sp->Resume();
3080 }
3081 else
3082 {
3083 // If we didn't restart, run the Stop Hooks here:
3084 // They might also restart the target, so watch for that.
3085 m_process_sp->GetTarget().RunStopHooks();
3086 if (m_process_sp->GetPrivateState() == eStateRunning)
3087 SetRestarted(true);
3088 }
Jim Ingham9575d842011-03-11 03:53:59 +00003089 }
3090
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091 }
3092}
3093
3094void
3095Process::ProcessEventData::Dump (Stream *s) const
3096{
3097 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003098 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003099
Greg Clayton8b82f082011-04-12 05:54:46 +00003100 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003101}
3102
3103const Process::ProcessEventData *
3104Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3105{
3106 if (event_ptr)
3107 {
3108 const EventData *event_data = event_ptr->GetData();
3109 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3110 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3111 }
3112 return NULL;
3113}
3114
3115ProcessSP
3116Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3117{
3118 ProcessSP process_sp;
3119 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3120 if (data)
3121 process_sp = data->GetProcessSP();
3122 return process_sp;
3123}
3124
3125StateType
3126Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3127{
3128 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3129 if (data == NULL)
3130 return eStateInvalid;
3131 else
3132 return data->GetState();
3133}
3134
3135bool
3136Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3137{
3138 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3139 if (data == NULL)
3140 return false;
3141 else
3142 return data->GetRestarted();
3143}
3144
3145void
3146Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3147{
3148 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3149 if (data != NULL)
3150 data->SetRestarted(new_value);
3151}
3152
3153bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003154Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3155{
3156 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3157 if (data == NULL)
3158 return false;
3159 else
3160 return data->GetInterrupted ();
3161}
3162
3163void
3164Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3165{
3166 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3167 if (data != NULL)
3168 data->SetInterrupted(new_value);
3169}
3170
3171bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003172Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3173{
3174 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3175 if (data)
3176 {
3177 data->SetUpdateStateOnRemoval();
3178 return true;
3179 }
3180 return false;
3181}
3182
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003183void
Greg Clayton0603aa92010-10-04 01:05:56 +00003184Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003185{
Greg Claytonc14ee322011-09-22 04:58:26 +00003186 exe_ctx.SetTargetPtr (&m_target);
3187 exe_ctx.SetProcessPtr (this);
3188 exe_ctx.SetThreadPtr(NULL);
3189 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003190}
3191
3192lldb::ProcessSP
3193Process::GetSP ()
3194{
3195 return GetTarget().GetProcessSP();
3196}
3197
Greg Claytone996fd32011-03-08 22:40:15 +00003198//uint32_t
3199//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3200//{
3201// return 0;
3202//}
3203//
3204//ArchSpec
3205//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3206//{
3207// return Host::GetArchSpecForExistingProcess (pid);
3208//}
3209//
3210//ArchSpec
3211//Process::GetArchSpecForExistingProcess (const char *process_name)
3212//{
3213// return Host::GetArchSpecForExistingProcess (process_name);
3214//}
3215//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003216void
3217Process::AppendSTDOUT (const char * s, size_t len)
3218{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003219 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003220 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003221 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003222}
3223
3224void
Greg Clayton93e86192011-11-13 04:45:22 +00003225Process::AppendSTDERR (const char * s, size_t len)
3226{
3227 Mutex::Locker locker (m_stdio_communication_mutex);
3228 m_stderr_data.append (s, len);
3229 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3230}
3231
3232//------------------------------------------------------------------
3233// Process STDIO
3234//------------------------------------------------------------------
3235
3236size_t
3237Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3238{
3239 Mutex::Locker locker(m_stdio_communication_mutex);
3240 size_t bytes_available = m_stdout_data.size();
3241 if (bytes_available > 0)
3242 {
3243 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3244 if (log)
3245 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3246 if (bytes_available > buf_size)
3247 {
3248 memcpy(buf, m_stdout_data.c_str(), buf_size);
3249 m_stdout_data.erase(0, buf_size);
3250 bytes_available = buf_size;
3251 }
3252 else
3253 {
3254 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3255 m_stdout_data.clear();
3256 }
3257 }
3258 return bytes_available;
3259}
3260
3261
3262size_t
3263Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3264{
3265 Mutex::Locker locker(m_stdio_communication_mutex);
3266 size_t bytes_available = m_stderr_data.size();
3267 if (bytes_available > 0)
3268 {
3269 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3270 if (log)
3271 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3272 if (bytes_available > buf_size)
3273 {
3274 memcpy(buf, m_stderr_data.c_str(), buf_size);
3275 m_stderr_data.erase(0, buf_size);
3276 bytes_available = buf_size;
3277 }
3278 else
3279 {
3280 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3281 m_stderr_data.clear();
3282 }
3283 }
3284 return bytes_available;
3285}
3286
3287void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003288Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3289{
3290 Process *process = (Process *) baton;
3291 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3292}
3293
3294size_t
3295Process::ProcessInputReaderCallback (void *baton,
3296 InputReader &reader,
3297 lldb::InputReaderAction notification,
3298 const char *bytes,
3299 size_t bytes_len)
3300{
3301 Process *process = (Process *) baton;
3302
3303 switch (notification)
3304 {
3305 case eInputReaderActivate:
3306 break;
3307
3308 case eInputReaderDeactivate:
3309 break;
3310
3311 case eInputReaderReactivate:
3312 break;
3313
Caroline Tice969ed3d2011-05-02 20:41:46 +00003314 case eInputReaderAsynchronousOutputWritten:
3315 break;
3316
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003317 case eInputReaderGotToken:
3318 {
3319 Error error;
3320 process->PutSTDIN (bytes, bytes_len, error);
3321 }
3322 break;
3323
Caroline Ticeefed6132010-11-19 20:47:54 +00003324 case eInputReaderInterrupt:
3325 process->Halt ();
3326 break;
3327
3328 case eInputReaderEndOfFile:
3329 process->AppendSTDOUT ("^D", 2);
3330 break;
3331
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003332 case eInputReaderDone:
3333 break;
3334
3335 }
3336
3337 return bytes_len;
3338}
3339
3340void
3341Process::ResetProcessInputReader ()
3342{
3343 m_process_input_reader.reset();
3344}
3345
3346void
3347Process::SetUpProcessInputReader (int file_descriptor)
3348{
3349 // First set up the Read Thread for reading/handling process I/O
3350
3351 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3352
3353 if (conn_ap.get())
3354 {
3355 m_stdio_communication.SetConnection (conn_ap.release());
3356 if (m_stdio_communication.IsConnected())
3357 {
3358 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3359 m_stdio_communication.StartReadThread();
3360
3361 // Now read thread is set up, set up input reader.
3362
3363 if (!m_process_input_reader.get())
3364 {
3365 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3366 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3367 this,
3368 eInputReaderGranularityByte,
3369 NULL,
3370 NULL,
3371 false));
3372
3373 if (err.Fail())
3374 m_process_input_reader.reset();
3375 }
3376 }
3377 }
3378}
3379
3380void
3381Process::PushProcessInputReader ()
3382{
3383 if (m_process_input_reader && !m_process_input_reader->IsActive())
3384 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3385}
3386
3387void
3388Process::PopProcessInputReader ()
3389{
3390 if (m_process_input_reader && m_process_input_reader->IsActive())
3391 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3392}
3393
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003394// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003395void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003396Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003397{
Greg Claytone0d378b2011-03-24 21:19:54 +00003398 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003399
3400 int i=0;
3401 const char *name;
3402 OptionEnumValueElement option_enum;
3403 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3404 {
3405 if (name)
3406 {
3407 option_enum.value = i;
3408 option_enum.string_value = name;
3409 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3410 g_plugins.push_back (option_enum);
3411 }
3412 ++i;
3413 }
3414 option_enum.value = 0;
3415 option_enum.string_value = NULL;
3416 option_enum.usage = NULL;
3417 g_plugins.push_back (option_enum);
3418
3419 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3420 {
3421 if (::strcmp (name, "plugin") == 0)
3422 {
3423 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3424 break;
3425 }
3426 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003427 UserSettingsControllerSP &usc = GetSettingsController();
3428 usc.reset (new SettingsController);
3429 UserSettingsController::InitializeSettingsController (usc,
3430 SettingsController::global_settings_table,
3431 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003432
3433 // Now call SettingsInitialize() for each 'child' of Process settings
3434 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003435}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003436
Greg Clayton99d0faf2010-11-18 23:32:35 +00003437void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003438Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003439{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003440 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3441
3442 Thread::SettingsTerminate ();
3443
3444 // Now terminate Process Settings.
3445
Greg Clayton99d0faf2010-11-18 23:32:35 +00003446 UserSettingsControllerSP &usc = GetSettingsController();
3447 UserSettingsController::FinalizeSettingsController (usc);
3448 usc.reset();
3449}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003450
Greg Clayton99d0faf2010-11-18 23:32:35 +00003451UserSettingsControllerSP &
3452Process::GetSettingsController ()
3453{
3454 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003455 return g_settings_controller;
3456}
3457
Caroline Tice1559a462010-09-27 00:30:10 +00003458void
3459Process::UpdateInstanceName ()
3460{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003461 Module *module = GetTarget().GetExecutableModulePointer();
3462 if (module)
Caroline Tice1559a462010-09-27 00:30:10 +00003463 {
3464 StreamString sstr;
Greg Claytonaa149cb2011-08-11 02:48:45 +00003465 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003466
Greg Claytondbe54502010-11-19 03:46:01 +00003467 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Clayton8b82f082011-04-12 05:54:46 +00003468 sstr.GetData());
Caroline Tice1559a462010-09-27 00:30:10 +00003469 }
3470}
3471
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003472ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003473Process::RunThreadPlan (ExecutionContext &exe_ctx,
3474 lldb::ThreadPlanSP &thread_plan_sp,
3475 bool stop_others,
3476 bool try_all_threads,
3477 bool discard_on_error,
3478 uint32_t single_thread_timeout_usec,
3479 Stream &errors)
3480{
3481 ExecutionResults return_value = eExecutionSetupError;
3482
Jim Ingham77787032011-01-20 02:03:18 +00003483 if (thread_plan_sp.get() == NULL)
3484 {
3485 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003486 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003487 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003488
3489 if (exe_ctx.GetProcessPtr() != this)
3490 {
3491 errors.Printf("RunThreadPlan called on wrong process.");
3492 return eExecutionSetupError;
3493 }
3494
3495 Thread *thread = exe_ctx.GetThreadPtr();
3496 if (thread == NULL)
3497 {
3498 errors.Printf("RunThreadPlan called with invalid thread.");
3499 return eExecutionSetupError;
3500 }
Jim Ingham77787032011-01-20 02:03:18 +00003501
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003502 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3503 // For that to be true the plan can't be private - since private plans suppress themselves in the
3504 // GetCompletedPlan call.
3505
3506 bool orig_plan_private = thread_plan_sp->GetPrivate();
3507 thread_plan_sp->SetPrivate(false);
3508
Jim Ingham444586b2011-01-24 06:34:17 +00003509 if (m_private_state.GetValue() != eStateStopped)
3510 {
3511 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003512 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003513 }
3514
Jim Ingham66243842011-08-13 00:56:10 +00003515 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00003516 const uint32_t thread_idx_id = thread->GetIndexID();
3517 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003518
3519 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3520 // so we should arrange to reset them as well.
3521
Greg Claytonc14ee322011-09-22 04:58:26 +00003522 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003523
Jim Ingham66243842011-08-13 00:56:10 +00003524 uint32_t selected_tid;
3525 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00003526 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00003527 {
3528 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003529 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003530 }
3531 else
3532 {
3533 selected_tid = LLDB_INVALID_THREAD_ID;
3534 }
3535
Greg Claytonc14ee322011-09-22 04:58:26 +00003536 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Inghamf48169b2010-11-30 02:22:11 +00003537
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003538 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003539
3540 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3541 // restored on exit to the function.
3542
3543 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003544
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003545 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003546 if (log)
3547 {
3548 StreamString s;
3549 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton81c22f62011-10-19 18:09:39 +00003550 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00003551 thread->GetIndexID(),
3552 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00003553 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003554 }
3555
Jim Ingham0f16e732011-02-08 05:20:59 +00003556 bool got_event;
3557 lldb::EventSP event_sp;
3558 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003559
3560 TimeValue* timeout_ptr = NULL;
3561 TimeValue real_timeout;
3562
Jim Ingham0f16e732011-02-08 05:20:59 +00003563 bool first_timeout = true;
3564 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003565
Jim Inghamf48169b2010-11-30 02:22:11 +00003566 while (1)
3567 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003568 // We usually want to resume the process if we get to the top of the loop.
3569 // The only exception is if we get two running events with no intervening
3570 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003571
Jim Ingham0f16e732011-02-08 05:20:59 +00003572 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003573 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003574 // Do the initial resume and wait for the running event before going further.
3575
Greg Claytonc14ee322011-09-22 04:58:26 +00003576 Error resume_error = Resume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00003577 if (!resume_error.Success())
3578 {
3579 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003580 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003581 break;
3582 }
3583
3584 real_timeout = TimeValue::Now();
3585 real_timeout.OffsetWithMicroSeconds(500000);
3586 timeout_ptr = &real_timeout;
3587
3588 got_event = listener.WaitForEvent(NULL, event_sp);
3589 if (!got_event)
3590 {
3591 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003592 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003593
3594 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003595 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003596 break;
3597 }
3598
3599 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3600 if (stop_state != eStateRunning)
3601 {
3602 if (log)
3603 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3604
3605 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003606 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003607 break;
3608 }
3609
3610 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003611 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003612 // We need to call the function synchronously, so spin waiting for it to return.
3613 // If we get interrupted while executing, we're going to lose our context, and
3614 // won't be able to gather the result at this point.
3615 // We set the timeout AFTER the resume, since the resume takes some time and we
3616 // don't want to charge that to the timeout.
3617
3618 if (single_thread_timeout_usec != 0)
3619 {
3620 real_timeout = TimeValue::Now();
3621 if (first_timeout)
3622 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3623 else
3624 real_timeout.OffsetWithSeconds(10);
3625
3626 timeout_ptr = &real_timeout;
3627 }
3628 }
3629 else
3630 {
3631 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003632 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003633 do_resume = true;
3634 }
3635
3636 // Now wait for the process to stop again:
3637 stop_state = lldb::eStateInvalid;
3638 event_sp.reset();
3639 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3640
3641 if (got_event)
3642 {
3643 if (event_sp.get())
3644 {
3645 bool keep_going = false;
3646 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3647 if (log)
3648 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3649
3650 switch (stop_state)
3651 {
3652 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00003653 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003654 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00003655 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00003656 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00003657 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003658 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00003659 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00003660 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3661 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00003662 }
3663 else
3664 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003665 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3666 StopReason stop_reason = eStopReasonInvalid;
3667 if (stop_info_sp)
3668 stop_reason = stop_info_sp->GetStopReason();
3669 if (stop_reason == eStopReasonPlanComplete)
3670 {
3671 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003672 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003673 // Now mark this plan as private so it doesn't get reported as the stop reason
3674 // after this point.
3675 if (thread_plan_sp)
3676 thread_plan_sp->SetPrivate (orig_plan_private);
3677 return_value = eExecutionCompleted;
3678 }
3679 else
3680 {
3681 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003682 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003683
3684 return_value = eExecutionInterrupted;
3685 }
Jim Ingham160f78c2011-05-17 01:10:11 +00003686 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00003687 }
3688 break;
3689
Jim Ingham0f16e732011-02-08 05:20:59 +00003690 case lldb::eStateCrashed:
3691 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003692 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003693 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003694 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003695
Jim Ingham0f16e732011-02-08 05:20:59 +00003696 case lldb::eStateRunning:
3697 do_resume = false;
3698 keep_going = true;
3699 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003700
Jim Ingham0f16e732011-02-08 05:20:59 +00003701 default:
3702 if (log)
3703 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00003704
3705 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003706 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003707 break;
3708 }
3709 if (keep_going)
3710 continue;
3711 else
3712 break;
3713 }
3714 else
3715 {
3716 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003717 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00003718 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003719 break;
3720 }
3721 }
3722 else
3723 {
3724 // If we didn't get an event that means we've timed out...
3725 // We will interrupt the process here. Depending on what we were asked to do we will
3726 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00003727 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00003728
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003729 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00003730 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00003731 {
3732 if (first_timeout)
3733 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3734 "trying with all threads enabled.",
3735 single_thread_timeout_usec);
3736 else
3737 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3738 "and timeout: %d timed out.",
3739 single_thread_timeout_usec);
3740 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003741 else
Jim Ingham0f16e732011-02-08 05:20:59 +00003742 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3743 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00003744 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003745 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003746
Greg Claytonc14ee322011-09-22 04:58:26 +00003747 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00003748 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00003749 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003750 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003751 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003752
Jim Ingham0f16e732011-02-08 05:20:59 +00003753 // If halt succeeds, it always produces a stopped event. Wait for that:
3754
3755 real_timeout = TimeValue::Now();
3756 real_timeout.OffsetWithMicroSeconds(500000);
3757
3758 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00003759
3760 if (got_event)
3761 {
3762 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3763 if (log)
3764 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003765 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00003766 if (stop_state == lldb::eStateStopped
3767 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00003768 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003769 }
3770
Jim Ingham0f16e732011-02-08 05:20:59 +00003771 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00003772 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003773 // Between the time we initiated the Halt and the time we delivered it, the process could have
3774 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00003775
Greg Claytonc14ee322011-09-22 04:58:26 +00003776 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00003777 {
3778 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003779 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003780 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003781 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003782 break;
3783 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003784
Jim Ingham0f16e732011-02-08 05:20:59 +00003785 if (!try_all_threads)
3786 {
3787 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003788 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003789 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003790 break;
3791 }
3792
3793 if (first_timeout)
3794 {
3795 // Set all the other threads to run, and return to the top of the loop, which will continue;
3796 first_timeout = false;
3797 thread_plan_sp->SetStopOthers (false);
3798 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003799 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003800
3801 continue;
3802 }
3803 else
3804 {
3805 // Running all threads failed, so return Interrupted.
3806 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003807 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003808 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003809 break;
3810 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003811 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003812 }
3813 else
3814 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003815 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003816 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003817 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003818 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00003819 }
3820 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003821 else
3822 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003823 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3824 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00003825 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003826 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.",
3827 halt_error.AsCString());
3828 real_timeout = TimeValue::Now();
3829 real_timeout.OffsetWithMicroSeconds(500000);
3830 timeout_ptr = &real_timeout;
3831 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3832 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003833 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003834 // This is not going anywhere, bag out.
3835 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003836 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003837 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003838 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003839 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003840 else
3841 {
3842 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3843 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003844 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00003845 if (stop_state == lldb::eStateStopped)
3846 {
3847 // Between the time we initiated the Halt and the time we delivered it, the process could have
3848 // already finished its job. Check that here:
3849
Greg Claytonc14ee322011-09-22 04:58:26 +00003850 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00003851 {
3852 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003853 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003854 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003855 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003856 break;
3857 }
3858
3859 if (first_timeout)
3860 {
3861 // Set all the other threads to run, and return to the top of the loop, which will continue;
3862 first_timeout = false;
3863 thread_plan_sp->SetStopOthers (false);
3864 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003865 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003866
3867 continue;
3868 }
3869 else
3870 {
3871 // Running all threads failed, so return Interrupted.
3872 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003873 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003874 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003875 break;
3876 }
3877 }
3878 else
3879 {
Sean Callanan39821ac2011-08-09 22:07:08 +00003880 if (log)
3881 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3882 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003883 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003884 break;
3885 }
3886 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003887 }
3888
Jim Inghamf48169b2010-11-30 02:22:11 +00003889 }
3890
Jim Ingham0f16e732011-02-08 05:20:59 +00003891 } // END WAIT LOOP
3892
3893 // Now do some processing on the results of the run:
3894 if (return_value == eExecutionInterrupted)
3895 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003896 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003897 {
3898 StreamString s;
3899 if (event_sp)
3900 event_sp->Dump (&s);
3901 else
3902 {
Jim Ingham20829ac2011-08-09 22:24:33 +00003903 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003904 }
3905
3906 StreamString ts;
3907
Jim Ingham20829ac2011-08-09 22:24:33 +00003908 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00003909
3910 do
3911 {
3912 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3913
3914 if (!event_data)
3915 {
3916 event_explanation = "<no event data>";
3917 break;
3918 }
3919
3920 Process *process = event_data->GetProcessSP().get();
3921
3922 if (!process)
3923 {
3924 event_explanation = "<no process>";
3925 break;
3926 }
3927
3928 ThreadList &thread_list = process->GetThreadList();
3929
3930 uint32_t num_threads = thread_list.GetSize();
3931 uint32_t thread_index;
3932
3933 ts.Printf("<%u threads> ", num_threads);
3934
3935 for (thread_index = 0;
3936 thread_index < num_threads;
3937 ++thread_index)
3938 {
3939 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3940
3941 if (!thread)
3942 {
3943 ts.Printf("<?> ");
3944 continue;
3945 }
3946
Greg Clayton81c22f62011-10-19 18:09:39 +00003947 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Ingham0f16e732011-02-08 05:20:59 +00003948 RegisterContext *register_context = thread->GetRegisterContext().get();
3949
3950 if (register_context)
3951 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3952 else
3953 ts.Printf("[ip unknown] ");
3954
3955 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3956 if (stop_info_sp)
3957 {
3958 const char *stop_desc = stop_info_sp->GetDescription();
3959 if (stop_desc)
3960 ts.PutCString (stop_desc);
3961 }
3962 ts.Printf(">");
3963 }
3964
3965 event_explanation = ts.GetData();
3966 } while (0);
3967
3968 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003969 {
3970 if (event_explanation)
3971 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3972 else
3973 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
3974 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003975
3976 if (discard_on_error && thread_plan_sp)
3977 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003978 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003979 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00003980 }
3981 }
3982 }
3983 else if (return_value == eExecutionSetupError)
3984 {
3985 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003986 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003987
3988 if (discard_on_error && thread_plan_sp)
3989 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003990 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003991 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00003992 }
3993 }
3994 else
3995 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003996 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00003997 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003998 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003999 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00004000 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00004001 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004002 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004003 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004004 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004005 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00004006 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00004007 }
4008 else
4009 {
4010 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004011 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00004012 if (discard_on_error && thread_plan_sp)
4013 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004014 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004015 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00004016 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004017 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00004018 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004019 }
4020 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004021
Jim Inghamf48169b2010-11-30 02:22:11 +00004022 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00004023 // Check that it's still there, and if it is put it back in the context. Also restore the
4024 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00004025 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4026 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00004027 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004028 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00004029 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004030
4031 // Also restore the current process'es selected frame & thread, since this function calling may
4032 // be done behind the user's back.
4033
4034 if (selected_tid != LLDB_INVALID_THREAD_ID)
4035 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004036 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00004037 {
4038 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00004039 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00004040 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00004041 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004042 }
4043 }
4044
4045 return return_value;
4046}
4047
4048const char *
4049Process::ExecutionResultAsCString (ExecutionResults result)
4050{
4051 const char *result_name;
4052
4053 switch (result)
4054 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004055 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004056 result_name = "eExecutionCompleted";
4057 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004058 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004059 result_name = "eExecutionDiscarded";
4060 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004061 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004062 result_name = "eExecutionInterrupted";
4063 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004064 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004065 result_name = "eExecutionSetupError";
4066 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004067 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004068 result_name = "eExecutionTimedOut";
4069 break;
4070 }
4071 return result_name;
4072}
4073
Greg Clayton7260f622011-04-18 08:33:37 +00004074void
4075Process::GetStatus (Stream &strm)
4076{
4077 const StateType state = GetState();
4078 if (StateIsStoppedState(state))
4079 {
4080 if (state == eStateExited)
4081 {
4082 int exit_status = GetExitStatus();
4083 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004084 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004085 GetID(),
4086 exit_status,
4087 exit_status,
4088 exit_description ? exit_description : "");
4089 }
4090 else
4091 {
4092 if (state == eStateConnected)
4093 strm.Printf ("Connected to remote target.\n");
4094 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004095 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004096 }
4097 }
4098 else
4099 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004100 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004101 }
4102}
4103
4104size_t
4105Process::GetThreadStatus (Stream &strm,
4106 bool only_threads_with_stop_reason,
4107 uint32_t start_frame,
4108 uint32_t num_frames,
4109 uint32_t num_frames_with_source)
4110{
4111 size_t num_thread_infos_dumped = 0;
4112
4113 const size_t num_threads = GetThreadList().GetSize();
4114 for (uint32_t i = 0; i < num_threads; i++)
4115 {
4116 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4117 if (thread)
4118 {
4119 if (only_threads_with_stop_reason)
4120 {
4121 if (thread->GetStopInfo().get() == NULL)
4122 continue;
4123 }
4124 thread->GetStatus (strm,
4125 start_frame,
4126 num_frames,
4127 num_frames_with_source);
4128 ++num_thread_infos_dumped;
4129 }
4130 }
4131 return num_thread_infos_dumped;
4132}
4133
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004134//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004135// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004136//--------------------------------------------------------------
4137
Greg Clayton1b654882010-09-19 02:33:57 +00004138Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004139 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004140{
Greg Clayton85851dd2010-12-04 00:10:17 +00004141 m_default_settings.reset (new ProcessInstanceSettings (*this,
4142 false,
Caroline Tice91123da2010-09-08 17:48:55 +00004143 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004144}
4145
Greg Clayton1b654882010-09-19 02:33:57 +00004146Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004147{
4148}
4149
4150lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004151Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004152{
Greg Claytondbe54502010-11-19 03:46:01 +00004153 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4154 false,
4155 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004156 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4157 return new_settings_sp;
4158}
4159
4160//--------------------------------------------------------------
4161// class ProcessInstanceSettings
4162//--------------------------------------------------------------
4163
Greg Clayton85851dd2010-12-04 00:10:17 +00004164ProcessInstanceSettings::ProcessInstanceSettings
4165(
4166 UserSettingsController &owner,
4167 bool live_instance,
4168 const char *name
4169) :
Greg Clayton1d885962011-11-08 02:43:13 +00004170 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004171{
Caroline Ticef20e8232010-09-09 18:26:37 +00004172 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4173 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4174 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice9e41c152010-09-16 19:05:55 +00004175 // This is true for CreateInstanceName() too.
Greg Clayton1d885962011-11-08 02:43:13 +00004176
Caroline Tice9e41c152010-09-16 19:05:55 +00004177 if (GetInstanceName () == InstanceSettings::InvalidName())
4178 {
4179 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4180 m_owner.RegisterInstanceSettings (this);
4181 }
Greg Clayton1d885962011-11-08 02:43:13 +00004182
Caroline Ticef20e8232010-09-09 18:26:37 +00004183 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004184 {
4185 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4186 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00004187 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004188 }
4189}
4190
4191ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Clayton1d885962011-11-08 02:43:13 +00004192 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004193{
4194 if (m_instance_name != InstanceSettings::GetDefaultName())
4195 {
4196 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4197 CopyInstanceSettings (pending_settings,false);
4198 m_owner.RemovePendingSettings (m_instance_name);
4199 }
4200}
4201
4202ProcessInstanceSettings::~ProcessInstanceSettings ()
4203{
4204}
4205
4206ProcessInstanceSettings&
4207ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4208{
4209 if (this != &rhs)
4210 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004211 }
4212
4213 return *this;
4214}
4215
4216
4217void
4218ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4219 const char *index_value,
4220 const char *value,
4221 const ConstString &instance_name,
4222 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004223 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004224 Error &err,
4225 bool pending)
4226{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004227}
4228
4229void
4230ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4231 bool pending)
4232{
Greg Clayton1d885962011-11-08 02:43:13 +00004233// if (new_settings.get() == NULL)
4234// return;
4235//
4236// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004237}
4238
Caroline Tice12cecd72010-09-20 21:37:42 +00004239bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004240ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4241 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004242 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004243 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004244{
Greg Clayton1d885962011-11-08 02:43:13 +00004245 if (err)
4246 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4247 return false;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004248}
4249
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004250const ConstString
4251ProcessInstanceSettings::CreateInstanceName ()
4252{
4253 static int instance_count = 1;
4254 StreamString sstr;
4255
4256 sstr.Printf ("process_%d", instance_count);
4257 ++instance_count;
4258
4259 const ConstString ret_val (sstr.GetData());
4260 return ret_val;
4261}
4262
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004263//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004264// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004265//--------------------------------------------------
4266
4267SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004268Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004269{
4270 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4271 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4272};
4273
4274
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004275SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004276Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004277{
Greg Clayton85851dd2010-12-04 00:10:17 +00004278 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton85851dd2010-12-04 00:10:17 +00004279 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004280};
4281
4282
Jim Ingham5aee1622010-08-09 23:31:02 +00004283
Greg Clayton1d885962011-11-08 02:43:13 +00004284