blob: b85679d1bc88408edd16595783cb9199120dce26 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
39
40using namespace lldb;
41using namespace lldb_private;
42
Greg Clayton24bc5d92011-03-30 18:16:51 +000043void
Greg Claytonb72d0f02011-04-12 05:54:46 +000044ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +000045{
46 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +000047 if (m_pid != LLDB_INVALID_PROCESS_ID)
48 s.Printf (" pid = %i\n", m_pid);
49
50 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
51 s.Printf (" parent = %i\n", m_parent_pid);
52
53 if (m_executable)
54 {
55 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
56 s.PutCString (" file = ");
57 m_executable.Dump(&s);
58 s.EOL();
59 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000060 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +000061 if (argc > 0)
62 {
63 for (uint32_t i=0; i<argc; i++)
64 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000065 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +000066 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +000067 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000068 else
Greg Claytonb72d0f02011-04-12 05:54:46 +000069 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000070 }
71 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000072
73 const uint32_t envc = m_environment.GetArgumentCount();
74 if (envc > 0)
75 {
76 for (uint32_t i=0; i<envc; i++)
77 {
78 const char *env = m_environment.GetArgumentAtIndex(i);
79 if (i < 10)
80 s.Printf (" env[%u] = %s\n", i, env);
81 else
82 s.Printf ("env[%u] = %s\n", i, env);
83 }
84 }
85
Greg Claytonff39f742011-04-01 00:29:43 +000086 if (m_arch.IsValid())
87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
88
Greg Claytonb72d0f02011-04-12 05:54:46 +000089 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000090 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000091 cstr = platform->GetUserName (m_uid);
92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000093 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000094 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000095 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000096 cstr = platform->GetGroupName (m_gid);
97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000098 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000099 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000100 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000101 cstr = platform->GetUserName (m_euid);
102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000103 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000104 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000105 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000106 cstr = platform->GetGroupName (m_egid);
107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000108 }
109}
110
111void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000112ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000113{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000114 const char *label;
115 if (show_args || verbose)
116 label = "ARGUMENTS";
117 else
118 label = "NAME";
119
Greg Claytonff39f742011-04-01 00:29:43 +0000120 if (verbose)
121 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
124 }
125 else
126 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000127 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000128 s.PutCString ("====== ====== ========== ======= ============================\n");
129 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000130}
131
132void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000133ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000134{
135 if (m_pid != LLDB_INVALID_PROCESS_ID)
136 {
137 const char *cstr;
138 s.Printf ("%-6u %-6u ", m_pid, m_parent_pid);
139
Greg Clayton24bc5d92011-03-30 18:16:51 +0000140
Greg Claytonff39f742011-04-01 00:29:43 +0000141 if (verbose)
142 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000143 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000144 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
145 s.Printf ("%-10s ", cstr);
146 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000147 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000148
Greg Claytonb72d0f02011-04-12 05:54:46 +0000149 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000150 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
151 s.Printf ("%-10s ", cstr);
152 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000153 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000154
Greg Claytonb72d0f02011-04-12 05:54:46 +0000155 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000156 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
157 s.Printf ("%-10s ", cstr);
158 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000159 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000160
Greg Claytonb72d0f02011-04-12 05:54:46 +0000161 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000162 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
163 s.Printf ("%-10s ", cstr);
164 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000165 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000166 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
167 }
168 else
169 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000170 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000171 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000172 (int)m_arch.GetTriple().getArchName().size(),
173 m_arch.GetTriple().getArchName().data());
174 }
175
Greg Claytonb72d0f02011-04-12 05:54:46 +0000176 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000177 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000178 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000179 if (argc > 0)
180 {
181 for (uint32_t i=0; i<argc; i++)
182 {
183 if (i > 0)
184 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000185 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000186 }
187 }
188 }
189 else
190 {
191 s.PutCString (GetName());
192 }
193
194 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000195 }
196}
197
Greg Claytonb72d0f02011-04-12 05:54:46 +0000198
199void
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000200ProcessInfo::SetArguments (char const **argv,
201 bool first_arg_is_executable,
202 bool first_arg_is_executable_and_argument)
203{
204 m_arguments.SetArguments (argv);
205
206 // Is the first argument the executable?
207 if (first_arg_is_executable)
208 {
209 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
210 if (first_arg)
211 {
212 // Yes the first argument is an executable, set it as the executable
213 // in the launch options. Don't resolve the file path as the path
214 // could be a remote platform path
215 const bool resolve = false;
216 m_executable.SetFile(first_arg, resolve);
217
218 // If argument zero is an executable and shouldn't be included
219 // in the arguments, remove it from the front of the arguments
220 if (first_arg_is_executable_and_argument == false)
221 m_arguments.DeleteArgumentAtIndex (0);
222 }
223 }
224}
225void
226ProcessInfo::SetArguments (const Args& args,
227 bool first_arg_is_executable,
228 bool first_arg_is_executable_and_argument)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000229{
230 // Copy all arguments
231 m_arguments = args;
232
233 // Is the first argument the executable?
234 if (first_arg_is_executable)
235 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000236 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000237 if (first_arg)
238 {
239 // Yes the first argument is an executable, set it as the executable
240 // in the launch options. Don't resolve the file path as the path
241 // could be a remote platform path
242 const bool resolve = false;
243 m_executable.SetFile(first_arg, resolve);
244
245 // If argument zero is an executable and shouldn't be included
246 // in the arguments, remove it from the front of the arguments
247 if (first_arg_is_executable_and_argument == false)
248 m_arguments.DeleteArgumentAtIndex (0);
249 }
250 }
251}
252
Greg Claytonabb33022011-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 Clayton24bc5d92011-03-30 18:16:51 +0000307bool
Greg Claytonb72d0f02011-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 Clayton143fcc32011-04-13 00:18:08 +0000430ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-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 Clayton36bc5ea2011-11-03 21:22:33 +0000498 case 'c':
499 launch_info.GetFlags().Set (eLaunchFlagLaunchInShell);
500 break;
501
Greg Claytonb72d0f02011-04-12 05:54:46 +0000502 case 'v':
503 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
504 break;
505
506 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000507 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-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 Claytonabb33022011-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 Claytonb72d0f02011-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 Clayton24bc5d92011-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 Claytonb72d0f02011-04-12 05:54:46 +0000551ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-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 Claytonb72d0f02011-04-12 05:54:46 +0000564 if (m_match_info.UserIDIsValid () &&
565 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000566 return false;
567
Greg Claytonb72d0f02011-04-12 05:54:46 +0000568 if (m_match_info.GroupIDIsValid () &&
569 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-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 Claytonb72d0f02011-04-12 05:54:46 +0000587ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-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 Claytonb72d0f02011-04-12 05:54:46 +0000598 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000599 return false;
600
Greg Claytonb72d0f02011-04-12 05:54:46 +0000601 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-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 Claytonb72d0f02011-04-12 05:54:46 +0000621ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-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 Claytonfd119992011-01-07 06:08:19 +0000627
Chris Lattner24943d22010-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 Clayton8d2ea282011-07-17 20:36:25 +0000638 if (debugger_ap->CanDebug(target, true))
Chris Lattner24943d22010-06-08 16:52:24 +0000639 return debugger_ap.release();
640 }
641 }
642 else
643 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000644 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000645 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000646 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton8d2ea282011-07-17 20:36:25 +0000647 if (debugger_ap->CanDebug(target, false))
Greg Clayton54e7afa2010-07-09 20:39:50 +0000648 return debugger_ap.release();
Chris Lattner24943d22010-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 Clayton49ce6822010-10-31 03:01:06 +0000660 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +0000661 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000662 m_target (target),
Chris Lattner24943d22010-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 Ingham21f37ad2011-08-09 02:12:22 +0000670 m_mod_id (),
Chris Lattner24943d22010-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 Clayton20d338f2010-11-18 05:57:03 +0000676 m_image_tokens (),
677 m_listener (listener),
678 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000679 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000680 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000681 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000682 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000683 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000684 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000685 m_stdout_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000686 m_memory_cache (*this),
687 m_allocated_memory_cache (*this),
Jim Inghamc0c53242011-09-15 21:36:42 +0000688 m_attached_to_process (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000689 m_next_event_action_ap(),
690 m_can_jit(eCanJITYes)
Chris Lattner24943d22010-06-08 16:52:24 +0000691{
Caroline Tice1ebef442010-09-27 00:30:10 +0000692 UpdateInstanceName();
693
Greg Claytone005f2c2010-11-06 01:53:30 +0000694 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000695 if (log)
696 log->Printf ("%p Process::Process()", this);
697
Greg Clayton49ce6822010-10-31 03:01:06 +0000698 SetEventName (eBroadcastBitStateChanged, "state-changed");
699 SetEventName (eBroadcastBitInterrupt, "interrupt");
700 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
701 SetEventName (eBroadcastBitSTDERR, "stderr-available");
702
Chris Lattner24943d22010-06-08 16:52:24 +0000703 listener.StartListeningForEvents (this,
704 eBroadcastBitStateChanged |
705 eBroadcastBitInterrupt |
706 eBroadcastBitSTDOUT |
707 eBroadcastBitSTDERR);
708
709 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
710 eBroadcastBitStateChanged);
711
712 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
713 eBroadcastInternalStateControlStop |
714 eBroadcastInternalStateControlPause |
715 eBroadcastInternalStateControlResume);
716}
717
718//----------------------------------------------------------------------
719// Destructor
720//----------------------------------------------------------------------
721Process::~Process()
722{
Greg Claytone005f2c2010-11-06 01:53:30 +0000723 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000724 if (log)
725 log->Printf ("%p Process::~Process()", this);
726 StopPrivateStateThread();
727}
728
729void
730Process::Finalize()
731{
Greg Clayton2f57db02011-10-01 00:45:15 +0000732 // Clear our broadcaster before we proceed with destroying
733 Broadcaster::Clear();
734
Chris Lattner24943d22010-06-08 16:52:24 +0000735 // Do any cleanup needed prior to being destructed... Subclasses
736 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000737
738 // We need to destroy the loader before the derived Process class gets destroyed
739 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton37f962e2011-08-22 02:49:39 +0000740 m_dyld_ap.reset();
741 m_os_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000742}
743
744void
745Process::RegisterNotificationCallbacks (const Notifications& callbacks)
746{
747 m_notifications.push_back(callbacks);
748 if (callbacks.initialize != NULL)
749 callbacks.initialize (callbacks.baton, this);
750}
751
752bool
753Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
754{
755 std::vector<Notifications>::iterator pos, end = m_notifications.end();
756 for (pos = m_notifications.begin(); pos != end; ++pos)
757 {
758 if (pos->baton == callbacks.baton &&
759 pos->initialize == callbacks.initialize &&
760 pos->process_state_changed == callbacks.process_state_changed)
761 {
762 m_notifications.erase(pos);
763 return true;
764 }
765 }
766 return false;
767}
768
769void
770Process::SynchronouslyNotifyStateChanged (StateType state)
771{
772 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
773 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
774 {
775 if (notification_pos->process_state_changed)
776 notification_pos->process_state_changed (notification_pos->baton, this, state);
777 }
778}
779
780// FIXME: We need to do some work on events before the general Listener sees them.
781// For instance if we are continuing from a breakpoint, we need to ensure that we do
782// the little "insert real insn, step & stop" trick. But we can't do that when the
783// event is delivered by the broadcaster - since that is done on the thread that is
784// waiting for new events, so if we needed more than one event for our handling, we would
785// stall. So instead we do it when we fetch the event off of the queue.
786//
787
788StateType
789Process::GetNextEvent (EventSP &event_sp)
790{
791 StateType state = eStateInvalid;
792
793 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
794 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
795
796 return state;
797}
798
799
800StateType
801Process::WaitForProcessToStop (const TimeValue *timeout)
802{
Jim Ingham21f37ad2011-08-09 02:12:22 +0000803 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
804 // We have to actually check each event, and in the case of a stopped event check the restarted flag
805 // on the event.
806 EventSP event_sp;
807 StateType state = GetState();
808 // If we are exited or detached, we won't ever get back to any
809 // other valid state...
810 if (state == eStateDetached || state == eStateExited)
811 return state;
812
813 while (state != eStateInvalid)
814 {
815 state = WaitForStateChangedEvents (timeout, event_sp);
816 switch (state)
817 {
818 case eStateCrashed:
819 case eStateDetached:
820 case eStateExited:
821 case eStateUnloaded:
822 return state;
823 case eStateStopped:
824 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
825 continue;
826 else
827 return state;
828 default:
829 continue;
830 }
831 }
832 return state;
Chris Lattner24943d22010-06-08 16:52:24 +0000833}
834
835
836StateType
837Process::WaitForState
838(
839 const TimeValue *timeout,
840 const StateType *match_states, const uint32_t num_match_states
841)
842{
843 EventSP event_sp;
844 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000845 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000846 while (state != eStateInvalid)
847 {
Greg Claytond8c62532010-10-07 04:19:01 +0000848 // If we are exited or detached, we won't ever get back to any
849 // other valid state...
850 if (state == eStateDetached || state == eStateExited)
851 return state;
852
Chris Lattner24943d22010-06-08 16:52:24 +0000853 state = WaitForStateChangedEvents (timeout, event_sp);
854
855 for (i=0; i<num_match_states; ++i)
856 {
857 if (match_states[i] == state)
858 return state;
859 }
860 }
861 return state;
862}
863
Jim Ingham63e24d72010-10-11 23:53:14 +0000864bool
865Process::HijackProcessEvents (Listener *listener)
866{
867 if (listener != NULL)
868 {
869 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
870 }
871 else
872 return false;
873}
874
875void
876Process::RestoreProcessEvents ()
877{
878 RestoreBroadcaster();
879}
880
Jim Inghamf9f40c22011-02-08 05:20:59 +0000881bool
882Process::HijackPrivateProcessEvents (Listener *listener)
883{
884 if (listener != NULL)
885 {
886 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
887 }
888 else
889 return false;
890}
891
892void
893Process::RestorePrivateProcessEvents ()
894{
895 m_private_state_broadcaster.RestoreBroadcaster();
896}
897
Chris Lattner24943d22010-06-08 16:52:24 +0000898StateType
899Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
900{
Greg Claytone005f2c2010-11-06 01:53:30 +0000901 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000902
903 if (log)
904 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
905
906 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000907 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
908 this,
909 eBroadcastBitStateChanged,
910 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000911 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
912
913 if (log)
914 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
915 __FUNCTION__,
916 timeout,
917 StateAsCString(state));
918 return state;
919}
920
921Event *
922Process::PeekAtStateChangedEvents ()
923{
Greg Claytone005f2c2010-11-06 01:53:30 +0000924 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000925
926 if (log)
927 log->Printf ("Process::%s...", __FUNCTION__);
928
929 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000930 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
931 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +0000932 if (log)
933 {
934 if (event_ptr)
935 {
936 log->Printf ("Process::%s (event_ptr) => %s",
937 __FUNCTION__,
938 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
939 }
940 else
941 {
942 log->Printf ("Process::%s no events found",
943 __FUNCTION__);
944 }
945 }
946 return event_ptr;
947}
948
949StateType
950Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
951{
Greg Claytone005f2c2010-11-06 01:53:30 +0000952 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000953
954 if (log)
955 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
956
957 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +0000958 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
959 &m_private_state_broadcaster,
960 eBroadcastBitStateChanged,
961 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000962 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
963
964 // This is a bit of a hack, but when we wait here we could very well return
965 // to the command-line, and that could disable the log, which would render the
966 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +0000967 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +0000968 {
969 if (state == eStateInvalid)
970 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
971 else
972 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
973 }
Chris Lattner24943d22010-06-08 16:52:24 +0000974 return state;
975}
976
977bool
978Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
979{
Greg Claytone005f2c2010-11-06 01:53:30 +0000980 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000981
982 if (log)
983 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
984
985 if (control_only)
986 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
987 else
988 return m_private_state_listener.WaitForEvent(timeout, event_sp);
989}
990
991bool
992Process::IsRunning () const
993{
994 return StateIsRunningState (m_public_state.GetValue());
995}
996
997int
998Process::GetExitStatus ()
999{
1000 if (m_public_state.GetValue() == eStateExited)
1001 return m_exit_status;
1002 return -1;
1003}
1004
Greg Clayton638351a2010-12-04 00:10:17 +00001005
Chris Lattner24943d22010-06-08 16:52:24 +00001006const char *
1007Process::GetExitDescription ()
1008{
1009 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1010 return m_exit_string.c_str();
1011 return NULL;
1012}
1013
Greg Clayton72e1c782011-01-22 23:43:18 +00001014bool
Chris Lattner24943d22010-06-08 16:52:24 +00001015Process::SetExitStatus (int status, const char *cstr)
1016{
Greg Clayton68ca8232011-01-25 02:58:48 +00001017 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1018 if (log)
1019 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1020 status, status,
1021 cstr ? "\"" : "",
1022 cstr ? cstr : "NULL",
1023 cstr ? "\"" : "");
1024
Greg Clayton72e1c782011-01-22 23:43:18 +00001025 // We were already in the exited state
1026 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001027 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001028 if (log)
1029 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001030 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001031 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001032
1033 m_exit_status = status;
1034 if (cstr)
1035 m_exit_string = cstr;
1036 else
1037 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001038
Greg Clayton72e1c782011-01-22 23:43:18 +00001039 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001040
Greg Clayton72e1c782011-01-22 23:43:18 +00001041 SetPrivateState (eStateExited);
1042 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001043}
1044
1045// This static callback can be used to watch for local child processes on
1046// the current host. The the child process exits, the process will be
1047// found in the global target list (we want to be completely sure that the
1048// lldb_private::Process doesn't go away before we can deliver the signal.
1049bool
1050Process::SetProcessExitStatus
1051(
1052 void *callback_baton,
1053 lldb::pid_t pid,
1054 int signo, // Zero for no signal
1055 int exit_status // Exit value of process if signal is zero
1056)
1057{
1058 if (signo == 0 || exit_status)
1059 {
Greg Clayton63094e02010-06-23 01:19:29 +00001060 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001061 if (target_sp)
1062 {
1063 ProcessSP process_sp (target_sp->GetProcessSP());
1064 if (process_sp)
1065 {
1066 const char *signal_cstr = NULL;
1067 if (signo)
1068 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1069
1070 process_sp->SetExitStatus (exit_status, signal_cstr);
1071 }
1072 }
1073 return true;
1074 }
1075 return false;
1076}
1077
1078
Greg Clayton37f962e2011-08-22 02:49:39 +00001079void
1080Process::UpdateThreadListIfNeeded ()
1081{
1082 const uint32_t stop_id = GetStopID();
1083 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1084 {
1085 Mutex::Locker locker (m_thread_list.GetMutex ());
1086 ThreadList new_thread_list(this);
1087 // Always update the thread list with the protocol specific
1088 // thread list
1089 UpdateThreadList (m_thread_list, new_thread_list);
1090 OperatingSystem *os = GetOperatingSystem ();
1091 if (os)
1092 os->UpdateThreadList (m_thread_list, new_thread_list);
1093 m_thread_list.Update (new_thread_list);
1094 m_thread_list.SetStopID (stop_id);
1095 }
1096}
1097
Chris Lattner24943d22010-06-08 16:52:24 +00001098uint32_t
1099Process::GetNextThreadIndexID ()
1100{
1101 return ++m_thread_index_id;
1102}
1103
1104StateType
1105Process::GetState()
1106{
1107 // If any other threads access this we will need a mutex for it
1108 return m_public_state.GetValue ();
1109}
1110
1111void
1112Process::SetPublicState (StateType new_state)
1113{
Greg Clayton68ca8232011-01-25 02:58:48 +00001114 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001115 if (log)
1116 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1117 m_public_state.SetValue (new_state);
1118}
1119
1120StateType
1121Process::GetPrivateState ()
1122{
1123 return m_private_state.GetValue();
1124}
1125
1126void
1127Process::SetPrivateState (StateType new_state)
1128{
Greg Clayton68ca8232011-01-25 02:58:48 +00001129 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001130 bool state_changed = false;
1131
1132 if (log)
1133 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1134
1135 Mutex::Locker locker(m_private_state.GetMutex());
1136
1137 const StateType old_state = m_private_state.GetValueNoLock ();
1138 state_changed = old_state != new_state;
1139 if (state_changed)
1140 {
1141 m_private_state.SetValueNoLock (new_state);
1142 if (StateIsStoppedState(new_state))
1143 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001144 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001145 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001146 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001147 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001148 }
1149 // Use our target to get a shared pointer to ourselves...
1150 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1151 }
1152 else
1153 {
1154 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001155 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001156 }
1157}
1158
Jim Ingham0296fe72011-11-08 03:00:11 +00001159void
1160Process::SetRunningUserExpression (bool on)
1161{
1162 m_mod_id.SetRunningUserExpression (on);
1163}
1164
Chris Lattner24943d22010-06-08 16:52:24 +00001165addr_t
1166Process::GetImageInfoAddress()
1167{
1168 return LLDB_INVALID_ADDRESS;
1169}
1170
Greg Clayton0baa3942010-11-04 01:54:29 +00001171//----------------------------------------------------------------------
1172// LoadImage
1173//
1174// This function provides a default implementation that works for most
1175// unix variants. Any Process subclasses that need to do shared library
1176// loading differently should override LoadImage and UnloadImage and
1177// do what is needed.
1178//----------------------------------------------------------------------
1179uint32_t
1180Process::LoadImage (const FileSpec &image_spec, Error &error)
1181{
1182 DynamicLoader *loader = GetDynamicLoader();
1183 if (loader)
1184 {
1185 error = loader->CanLoadImage();
1186 if (error.Fail())
1187 return LLDB_INVALID_IMAGE_TOKEN;
1188 }
1189
1190 if (error.Success())
1191 {
1192 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001193
1194 if (thread_sp)
1195 {
1196 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1197
1198 if (frame_sp)
1199 {
1200 ExecutionContext exe_ctx;
1201 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001202 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001203 StreamString expr;
1204 char path[PATH_MAX];
1205 image_spec.GetPath(path, sizeof(path));
1206 expr.Printf("dlopen (\"%s\", 2)", path);
1207 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001208 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan5b658cc2011-11-07 23:35:40 +00001209 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chenb14ec342011-09-09 00:01:43 +00001210 error = result_valobj_sp->GetError();
1211 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001212 {
1213 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001214 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001215 {
1216 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1217 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1218 {
1219 uint32_t image_token = m_image_tokens.size();
1220 m_image_tokens.push_back (image_ptr);
1221 return image_token;
1222 }
1223 }
1224 }
1225 }
1226 }
1227 }
1228 return LLDB_INVALID_IMAGE_TOKEN;
1229}
1230
1231//----------------------------------------------------------------------
1232// UnloadImage
1233//
1234// This function provides a default implementation that works for most
1235// unix variants. Any Process subclasses that need to do shared library
1236// loading differently should override LoadImage and UnloadImage and
1237// do what is needed.
1238//----------------------------------------------------------------------
1239Error
1240Process::UnloadImage (uint32_t image_token)
1241{
1242 Error error;
1243 if (image_token < m_image_tokens.size())
1244 {
1245 const addr_t image_addr = m_image_tokens[image_token];
1246 if (image_addr == LLDB_INVALID_ADDRESS)
1247 {
1248 error.SetErrorString("image already unloaded");
1249 }
1250 else
1251 {
1252 DynamicLoader *loader = GetDynamicLoader();
1253 if (loader)
1254 error = loader->CanLoadImage();
1255
1256 if (error.Success())
1257 {
1258 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001259
1260 if (thread_sp)
1261 {
1262 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1263
1264 if (frame_sp)
1265 {
1266 ExecutionContext exe_ctx;
1267 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001268 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001269 StreamString expr;
1270 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1271 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001272 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan5b658cc2011-11-07 23:35:40 +00001273 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +00001274 if (result_valobj_sp->GetError().Success())
1275 {
1276 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001277 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001278 {
1279 if (scalar.UInt(1))
1280 {
1281 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1282 }
1283 else
1284 {
1285 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1286 }
1287 }
1288 }
1289 else
1290 {
1291 error = result_valobj_sp->GetError();
1292 }
1293 }
1294 }
1295 }
1296 }
1297 }
1298 else
1299 {
1300 error.SetErrorString("invalid image token");
1301 }
1302 return error;
1303}
1304
Greg Clayton75906e42011-05-11 18:39:18 +00001305const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001306Process::GetABI()
1307{
Greg Clayton75906e42011-05-11 18:39:18 +00001308 if (!m_abi_sp)
1309 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1310 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001311}
1312
Jim Ingham642036f2010-09-23 02:01:19 +00001313LanguageRuntime *
1314Process::GetLanguageRuntime(lldb::LanguageType language)
1315{
1316 LanguageRuntimeCollection::iterator pos;
1317 pos = m_language_runtimes.find (language);
1318 if (pos == m_language_runtimes.end())
1319 {
1320 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1321
1322 m_language_runtimes[language]
1323 = runtime;
1324 return runtime.get();
1325 }
1326 else
1327 return (*pos).second.get();
1328}
1329
1330CPPLanguageRuntime *
1331Process::GetCPPLanguageRuntime ()
1332{
1333 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1334 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1335 return static_cast<CPPLanguageRuntime *> (runtime);
1336 return NULL;
1337}
1338
1339ObjCLanguageRuntime *
1340Process::GetObjCLanguageRuntime ()
1341{
1342 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1343 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1344 return static_cast<ObjCLanguageRuntime *> (runtime);
1345 return NULL;
1346}
1347
Chris Lattner24943d22010-06-08 16:52:24 +00001348BreakpointSiteList &
1349Process::GetBreakpointSiteList()
1350{
1351 return m_breakpoint_site_list;
1352}
1353
1354const BreakpointSiteList &
1355Process::GetBreakpointSiteList() const
1356{
1357 return m_breakpoint_site_list;
1358}
1359
1360
1361void
1362Process::DisableAllBreakpointSites ()
1363{
1364 m_breakpoint_site_list.SetEnabledForAll (false);
1365}
1366
1367Error
1368Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1369{
1370 Error error (DisableBreakpointSiteByID (break_id));
1371
1372 if (error.Success())
1373 m_breakpoint_site_list.Remove(break_id);
1374
1375 return error;
1376}
1377
1378Error
1379Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1380{
1381 Error error;
1382 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1383 if (bp_site_sp)
1384 {
1385 if (bp_site_sp->IsEnabled())
1386 error = DisableBreakpoint (bp_site_sp.get());
1387 }
1388 else
1389 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001390 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001391 }
1392
1393 return error;
1394}
1395
1396Error
1397Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1398{
1399 Error error;
1400 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1401 if (bp_site_sp)
1402 {
1403 if (!bp_site_sp->IsEnabled())
1404 error = EnableBreakpoint (bp_site_sp.get());
1405 }
1406 else
1407 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001408 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001409 }
1410 return error;
1411}
1412
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001413lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +00001414Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1415{
Greg Clayton265ab332011-05-19 18:17:41 +00001416 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001417 if (load_addr != LLDB_INVALID_ADDRESS)
1418 {
1419 BreakpointSiteSP bp_site_sp;
1420
1421 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1422 // create a new breakpoint site and add it.
1423
1424 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1425
1426 if (bp_site_sp)
1427 {
1428 bp_site_sp->AddOwner (owner);
1429 owner->SetBreakpointSite (bp_site_sp);
1430 return bp_site_sp->GetID();
1431 }
1432 else
1433 {
1434 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1435 if (bp_site_sp)
1436 {
1437 if (EnableBreakpoint (bp_site_sp.get()).Success())
1438 {
1439 owner->SetBreakpointSite (bp_site_sp);
1440 return m_breakpoint_site_list.Add (bp_site_sp);
1441 }
1442 }
1443 }
1444 }
1445 // We failed to enable the breakpoint
1446 return LLDB_INVALID_BREAK_ID;
1447
1448}
1449
1450void
1451Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1452{
1453 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1454 if (num_owners == 0)
1455 {
1456 DisableBreakpoint(bp_site_sp.get());
1457 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1458 }
1459}
1460
1461
1462size_t
1463Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1464{
1465 size_t bytes_removed = 0;
1466 addr_t intersect_addr;
1467 size_t intersect_size;
1468 size_t opcode_offset;
1469 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001470 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001471 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001472
Jim Ingham82820f92011-06-29 19:42:28 +00001473 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001474 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001475 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001476 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001477 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001478 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001479 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001480 {
1481 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1482 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001483 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001484 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001485 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001486 }
Chris Lattner24943d22010-06-08 16:52:24 +00001487 }
1488 }
1489 }
1490 return bytes_removed;
1491}
1492
1493
Greg Claytonb1888f22011-03-19 01:12:21 +00001494
1495size_t
1496Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1497{
1498 PlatformSP platform_sp (m_target.GetPlatform());
1499 if (platform_sp)
1500 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1501 return 0;
1502}
1503
Chris Lattner24943d22010-06-08 16:52:24 +00001504Error
1505Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1506{
1507 Error error;
1508 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001509 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001510 const addr_t bp_addr = bp_site->GetLoadAddress();
1511 if (log)
1512 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1513 if (bp_site->IsEnabled())
1514 {
1515 if (log)
1516 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1517 return error;
1518 }
1519
1520 if (bp_addr == LLDB_INVALID_ADDRESS)
1521 {
1522 error.SetErrorString("BreakpointSite contains an invalid load address.");
1523 return error;
1524 }
1525 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1526 // trap for the breakpoint site
1527 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1528
1529 if (bp_opcode_size == 0)
1530 {
Greg Clayton9c236732011-10-26 00:56:27 +00001531 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001532 }
1533 else
1534 {
1535 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1536
1537 if (bp_opcode_bytes == NULL)
1538 {
1539 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1540 return error;
1541 }
1542
1543 // Save the original opcode by reading it
1544 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1545 {
1546 // Write a software breakpoint in place of the original opcode
1547 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1548 {
1549 uint8_t verify_bp_opcode_bytes[64];
1550 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1551 {
1552 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1553 {
1554 bp_site->SetEnabled(true);
1555 bp_site->SetType (BreakpointSite::eSoftware);
1556 if (log)
1557 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1558 bp_site->GetID(),
1559 (uint64_t)bp_addr);
1560 }
1561 else
Greg Clayton9c236732011-10-26 00:56:27 +00001562 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00001563 }
1564 else
1565 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1566 }
1567 else
1568 error.SetErrorString("Unable to write breakpoint trap to memory.");
1569 }
1570 else
1571 error.SetErrorString("Unable to read memory at breakpoint address.");
1572 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001573 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001574 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1575 bp_site->GetID(),
1576 (uint64_t)bp_addr,
1577 error.AsCString());
1578 return error;
1579}
1580
1581Error
1582Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1583{
1584 Error error;
1585 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001586 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001587 addr_t bp_addr = bp_site->GetLoadAddress();
1588 lldb::user_id_t breakID = bp_site->GetID();
1589 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001590 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001591
1592 if (bp_site->IsHardware())
1593 {
1594 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1595 }
1596 else if (bp_site->IsEnabled())
1597 {
1598 const size_t break_op_size = bp_site->GetByteSize();
1599 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1600 if (break_op_size > 0)
1601 {
1602 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001603 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001604 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001605 bool break_op_found = false;
1606
1607 // Read the breakpoint opcode
1608 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1609 {
1610 bool verify = false;
1611 // Make sure we have the a breakpoint opcode exists at this address
1612 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1613 {
1614 break_op_found = true;
1615 // We found a valid breakpoint opcode at this address, now restore
1616 // the saved opcode.
1617 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1618 {
1619 verify = true;
1620 }
1621 else
1622 error.SetErrorString("Memory write failed when restoring original opcode.");
1623 }
1624 else
1625 {
1626 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1627 // Set verify to true and so we can check if the original opcode has already been restored
1628 verify = true;
1629 }
1630
1631 if (verify)
1632 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001633 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001634 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001635 // Verify that our original opcode made it back to the inferior
1636 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1637 {
1638 // compare the memory we just read with the original opcode
1639 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1640 {
1641 // SUCCESS
1642 bp_site->SetEnabled(false);
1643 if (log)
1644 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1645 return error;
1646 }
1647 else
1648 {
1649 if (break_op_found)
1650 error.SetErrorString("Failed to restore original opcode.");
1651 }
1652 }
1653 else
1654 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1655 }
1656 }
1657 else
1658 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1659 }
1660 }
1661 else
1662 {
1663 if (log)
1664 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1665 return error;
1666 }
1667
1668 if (log)
1669 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1670 bp_site->GetID(),
1671 (uint64_t)bp_addr,
1672 error.AsCString());
1673 return error;
1674
1675}
1676
Greg Claytonfd119992011-01-07 06:08:19 +00001677// Comment out line below to disable memory caching
1678#define ENABLE_MEMORY_CACHING
1679// Uncomment to verify memory caching works after making changes to caching code
1680//#define VERIFY_MEMORY_READS
1681
1682#if defined (ENABLE_MEMORY_CACHING)
1683
1684#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001685
1686size_t
1687Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1688{
Greg Claytonfd119992011-01-07 06:08:19 +00001689 // Memory caching is enabled, with debug verification
1690 if (buf && size)
1691 {
1692 // Uncomment the line below to make sure memory caching is working.
1693 // I ran this through the test suite and got no assertions, so I am
1694 // pretty confident this is working well. If any changes are made to
1695 // memory caching, uncomment the line below and test your changes!
1696
1697 // Verify all memory reads by using the cache first, then redundantly
1698 // reading the same memory from the inferior and comparing to make sure
1699 // everything is exactly the same.
1700 std::string verify_buf (size, '\0');
1701 assert (verify_buf.size() == size);
1702 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1703 Error verify_error;
1704 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1705 assert (cache_bytes_read == verify_bytes_read);
1706 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1707 assert (verify_error.Success() == error.Success());
1708 return cache_bytes_read;
1709 }
1710 return 0;
1711}
1712
1713#else // #if defined (VERIFY_MEMORY_READS)
1714
1715size_t
1716Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1717{
1718 // Memory caching enabled, no verification
Greg Clayton613b8732011-05-17 03:37:42 +00001719 return m_memory_cache.Read (addr, buf, size, error);
Greg Claytonfd119992011-01-07 06:08:19 +00001720}
1721
1722#endif // #else for #if defined (VERIFY_MEMORY_READS)
1723
1724#else // #if defined (ENABLE_MEMORY_CACHING)
1725
1726size_t
1727Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1728{
1729 // Memory caching is disabled
1730 return ReadMemoryFromInferior (addr, buf, size, error);
1731}
1732
1733#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1734
1735
1736size_t
Greg Claytonb72d0f02011-04-12 05:54:46 +00001737Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1738{
1739 size_t total_cstr_len = 0;
1740 if (dst && dst_max_len)
1741 {
1742 // NULL out everything just to be safe
1743 memset (dst, 0, dst_max_len);
1744 Error error;
1745 addr_t curr_addr = addr;
1746 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1747 size_t bytes_left = dst_max_len - 1;
1748 char *curr_dst = dst;
1749
1750 while (bytes_left > 0)
1751 {
1752 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1753 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1754 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1755
1756 if (bytes_read == 0)
1757 {
1758 dst[total_cstr_len] = '\0';
1759 break;
1760 }
1761 const size_t len = strlen(curr_dst);
1762
1763 total_cstr_len += len;
1764
1765 if (len < bytes_to_read)
1766 break;
1767
1768 curr_dst += bytes_read;
1769 curr_addr += bytes_read;
1770 bytes_left -= bytes_read;
1771 }
1772 }
1773 return total_cstr_len;
1774}
1775
1776size_t
Greg Claytonfd119992011-01-07 06:08:19 +00001777Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1778{
Chris Lattner24943d22010-06-08 16:52:24 +00001779 if (buf == NULL || size == 0)
1780 return 0;
1781
1782 size_t bytes_read = 0;
1783 uint8_t *bytes = (uint8_t *)buf;
1784
1785 while (bytes_read < size)
1786 {
1787 const size_t curr_size = size - bytes_read;
1788 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1789 bytes + bytes_read,
1790 curr_size,
1791 error);
1792 bytes_read += curr_bytes_read;
1793 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1794 break;
1795 }
1796
1797 // Replace any software breakpoint opcodes that fall into this range back
1798 // into "buf" before we return
1799 if (bytes_read > 0)
1800 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1801 return bytes_read;
1802}
1803
Greg Claytonf72fdee2010-12-16 20:01:20 +00001804uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00001805Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00001806{
Greg Claytonc0fa5332011-05-22 22:46:53 +00001807 Scalar scalar;
1808 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1809 return scalar.ULongLong(fail_value);
1810 return fail_value;
1811}
1812
1813addr_t
1814Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1815{
1816 Scalar scalar;
1817 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1818 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1819 return LLDB_INVALID_ADDRESS;
1820}
1821
1822
1823bool
1824Process::WritePointerToMemory (lldb::addr_t vm_addr,
1825 lldb::addr_t ptr_value,
1826 Error &error)
1827{
1828 Scalar scalar;
1829 const uint32_t addr_byte_size = GetAddressByteSize();
1830 if (addr_byte_size <= 4)
1831 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001832 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00001833 scalar = ptr_value;
1834 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001835}
1836
Chris Lattner24943d22010-06-08 16:52:24 +00001837size_t
1838Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1839{
1840 size_t bytes_written = 0;
1841 const uint8_t *bytes = (const uint8_t *)buf;
1842
1843 while (bytes_written < size)
1844 {
1845 const size_t curr_size = size - bytes_written;
1846 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1847 bytes + bytes_written,
1848 curr_size,
1849 error);
1850 bytes_written += curr_bytes_written;
1851 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1852 break;
1853 }
1854 return bytes_written;
1855}
1856
1857size_t
1858Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1859{
Greg Claytonfd119992011-01-07 06:08:19 +00001860#if defined (ENABLE_MEMORY_CACHING)
1861 m_memory_cache.Flush (addr, size);
1862#endif
1863
Chris Lattner24943d22010-06-08 16:52:24 +00001864 if (buf == NULL || size == 0)
1865 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00001866
Jim Ingham21f37ad2011-08-09 02:12:22 +00001867 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00001868
Chris Lattner24943d22010-06-08 16:52:24 +00001869 // We need to write any data that would go where any current software traps
1870 // (enabled software breakpoints) any software traps (breakpoints) that we
1871 // may have placed in our tasks memory.
1872
1873 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1874 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1875
1876 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001877 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00001878
1879 BreakpointSiteList::collection::const_iterator pos;
1880 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001881 addr_t intersect_addr = 0;
1882 size_t intersect_size = 0;
1883 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001884 const uint8_t *ubuf = (const uint8_t *)buf;
1885
1886 for (pos = iter; pos != end; ++pos)
1887 {
1888 BreakpointSiteSP bp;
1889 bp = pos->second;
1890
1891 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1892 assert(addr <= intersect_addr && intersect_addr < addr + size);
1893 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1894 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1895
1896 // Check for bytes before this breakpoint
1897 const addr_t curr_addr = addr + bytes_written;
1898 if (intersect_addr > curr_addr)
1899 {
1900 // There are some bytes before this breakpoint that we need to
1901 // just write to memory
1902 size_t curr_size = intersect_addr - curr_addr;
1903 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1904 ubuf + bytes_written,
1905 curr_size,
1906 error);
1907 bytes_written += curr_bytes_written;
1908 if (curr_bytes_written != curr_size)
1909 {
1910 // We weren't able to write all of the requested bytes, we
1911 // are done looping and will return the number of bytes that
1912 // we have written so far.
1913 break;
1914 }
1915 }
1916
1917 // Now write any bytes that would cover up any software breakpoints
1918 // directly into the breakpoint opcode buffer
1919 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1920 bytes_written += intersect_size;
1921 }
1922
1923 // Write any remaining bytes after the last breakpoint if we have any left
1924 if (bytes_written < size)
1925 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1926 ubuf + bytes_written,
1927 size - bytes_written,
1928 error);
Jim Inghame41494a2011-04-16 00:01:13 +00001929
Chris Lattner24943d22010-06-08 16:52:24 +00001930 return bytes_written;
1931}
Greg Claytonc0fa5332011-05-22 22:46:53 +00001932
1933size_t
1934Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
1935{
1936 if (byte_size == UINT32_MAX)
1937 byte_size = scalar.GetByteSize();
1938 if (byte_size > 0)
1939 {
1940 uint8_t buf[32];
1941 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
1942 if (mem_size > 0)
1943 return WriteMemory(addr, buf, mem_size, error);
1944 else
1945 error.SetErrorString ("failed to get scalar as memory data");
1946 }
1947 else
1948 {
1949 error.SetErrorString ("invalid scalar value");
1950 }
1951 return 0;
1952}
1953
1954size_t
1955Process::ReadScalarIntegerFromMemory (addr_t addr,
1956 uint32_t byte_size,
1957 bool is_signed,
1958 Scalar &scalar,
1959 Error &error)
1960{
1961 uint64_t uval;
1962
1963 if (byte_size <= sizeof(uval))
1964 {
1965 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
1966 if (bytes_read == byte_size)
1967 {
1968 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
1969 uint32_t offset = 0;
1970 if (byte_size <= 4)
1971 scalar = data.GetMaxU32 (&offset, byte_size);
1972 else
1973 scalar = data.GetMaxU64 (&offset, byte_size);
1974
1975 if (is_signed)
1976 scalar.SignExtend(byte_size * 8);
1977 return bytes_read;
1978 }
1979 }
1980 else
1981 {
1982 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1983 }
1984 return 0;
1985}
1986
Greg Clayton613b8732011-05-17 03:37:42 +00001987#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00001988addr_t
1989Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1990{
Jim Inghame6bd1422011-06-20 17:32:44 +00001991 if (GetPrivateState() != eStateStopped)
1992 return LLDB_INVALID_ADDRESS;
1993
Greg Clayton613b8732011-05-17 03:37:42 +00001994#if defined (USE_ALLOCATE_MEMORY_CACHE)
1995 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
1996#else
Greg Clayton2860ba92011-01-23 19:58:49 +00001997 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1998 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1999 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002000 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002001 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002002 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002003 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002004 m_mod_id.GetStopID(),
2005 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002006 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002007#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002008}
2009
Sean Callanan6cf6c472011-09-20 23:01:51 +00002010bool
2011Process::CanJIT ()
2012{
2013 return m_can_jit == eCanJITYes;
2014}
2015
2016void
2017Process::SetCanJIT (bool can_jit)
2018{
2019 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2020}
2021
Chris Lattner24943d22010-06-08 16:52:24 +00002022Error
2023Process::DeallocateMemory (addr_t ptr)
2024{
Greg Clayton613b8732011-05-17 03:37:42 +00002025 Error error;
2026#if defined (USE_ALLOCATE_MEMORY_CACHE)
2027 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2028 {
2029 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2030 }
2031#else
2032 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002033
2034 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2035 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002036 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002037 ptr,
2038 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002039 m_mod_id.GetStopID(),
2040 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002041#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002042 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002043}
2044
2045
2046Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002047Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002048{
2049 Error error;
2050 error.SetErrorString("watchpoints are not supported");
2051 return error;
2052}
2053
2054Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002055Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002056{
2057 Error error;
2058 error.SetErrorString("watchpoints are not supported");
2059 return error;
2060}
2061
2062StateType
2063Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2064{
2065 StateType state;
2066 // Now wait for the process to launch and return control to us, and then
2067 // call DidLaunch:
2068 while (1)
2069 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002070 event_sp.reset();
2071 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2072
2073 if (StateIsStoppedState(state))
Chris Lattner24943d22010-06-08 16:52:24 +00002074 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002075
2076 // If state is invalid, then we timed out
2077 if (state == eStateInvalid)
2078 break;
2079
2080 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002081 HandlePrivateEvent (event_sp);
2082 }
2083 return state;
2084}
2085
2086Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002087Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002088{
2089 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002090 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002091 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002092 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002093 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002094
Greg Clayton5beb99d2011-08-11 02:48:45 +00002095 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002096 if (exe_module)
2097 {
Greg Clayton180546b2011-04-30 01:09:13 +00002098 char local_exec_file_path[PATH_MAX];
2099 char platform_exec_file_path[PATH_MAX];
2100 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2101 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002102 if (exe_module->GetFileSpec().Exists())
2103 {
Greg Claytona2f74232011-02-24 22:24:29 +00002104 if (PrivateStateThreadIsValid ())
2105 PausePrivateStateThread ();
2106
Chris Lattner24943d22010-06-08 16:52:24 +00002107 error = WillLaunch (exe_module);
2108 if (error.Success())
2109 {
Greg Claytond8c62532010-10-07 04:19:01 +00002110 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00002111
2112 // Now launch using these arguments.
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002113 error = DoLaunch (exe_module, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +00002114
2115 if (error.Fail())
2116 {
2117 if (GetID() != LLDB_INVALID_PROCESS_ID)
2118 {
2119 SetID (LLDB_INVALID_PROCESS_ID);
2120 const char *error_string = error.AsCString();
2121 if (error_string == NULL)
2122 error_string = "launch failed";
2123 SetExitStatus (-1, error_string);
2124 }
2125 }
2126 else
2127 {
2128 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002129 TimeValue timeout_time;
2130 timeout_time = TimeValue::Now();
2131 timeout_time.OffsetWithSeconds(10);
2132 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002133
Greg Clayton49859592011-06-22 01:42:17 +00002134 if (state == eStateInvalid || event_sp.get() == NULL)
2135 {
2136 // We were able to launch the process, but we failed to
2137 // catch the initial stop.
2138 SetExitStatus (0, "failed to catch stop after launch");
2139 Destroy();
2140 }
2141 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002142 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002143
Chris Lattner24943d22010-06-08 16:52:24 +00002144 DidLaunch ();
2145
Greg Clayton37f962e2011-08-22 02:49:39 +00002146 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002147 if (m_dyld_ap.get())
2148 m_dyld_ap->DidLaunch();
2149
Greg Clayton37f962e2011-08-22 02:49:39 +00002150 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002151 // This delays passing the stopped event to listeners till DidLaunch gets
2152 // a chance to complete...
2153 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002154
2155 if (PrivateStateThreadIsValid ())
2156 ResumePrivateStateThread ();
2157 else
2158 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002159 }
2160 else if (state == eStateExited)
2161 {
2162 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2163 // not likely to work, and return an invalid pid.
2164 HandlePrivateEvent (event_sp);
2165 }
2166 }
2167 }
2168 }
2169 else
2170 {
Greg Clayton9c236732011-10-26 00:56:27 +00002171 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002172 }
2173 }
2174 return error;
2175}
2176
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002177Process::NextEventAction::EventActionResult
2178Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002179{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002180 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2181 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002182 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002183 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002184 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002185 return eEventActionRetry;
2186
2187 case eStateStopped:
2188 case eStateCrashed:
Jim Ingham7508e732010-08-09 23:31:02 +00002189 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002190 // During attach, prior to sending the eStateStopped event,
2191 // lldb_private::Process subclasses must set the process must set
2192 // the new process ID.
2193 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton75c703d2011-02-16 04:46:07 +00002194 m_process->CompleteAttach ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002195 return eEventActionSuccess;
Jim Ingham7508e732010-08-09 23:31:02 +00002196 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002197
2198
2199 break;
2200 default:
2201 case eStateExited:
2202 case eStateInvalid:
2203 m_exit_string.assign ("No valid Process");
2204 return eEventActionExit;
2205 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002206 }
2207}
Chris Lattner24943d22010-06-08 16:52:24 +00002208
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002209Process::NextEventAction::EventActionResult
2210Process::AttachCompletionHandler::HandleBeingInterrupted()
2211{
2212 return eEventActionSuccess;
2213}
2214
2215const char *
2216Process::AttachCompletionHandler::GetExitString ()
2217{
2218 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002219}
2220
2221Error
2222Process::Attach (lldb::pid_t attach_pid)
2223{
2224
Chris Lattner24943d22010-06-08 16:52:24 +00002225 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002226 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002227
Greg Clayton75c703d2011-02-16 04:46:07 +00002228 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002229 m_os_ap.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002230
Greg Clayton54e7afa2010-07-09 20:39:50 +00002231 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00002232 if (error.Success())
2233 {
Greg Claytond8c62532010-10-07 04:19:01 +00002234 SetPublicState (eStateAttaching);
2235
Greg Clayton54e7afa2010-07-09 20:39:50 +00002236 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00002237 if (error.Success())
2238 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002239 SetNextEventAction(new Process::AttachCompletionHandler(this));
2240 StartPrivateStateThread();
Chris Lattner24943d22010-06-08 16:52:24 +00002241 }
2242 else
2243 {
2244 if (GetID() != LLDB_INVALID_PROCESS_ID)
2245 {
2246 SetID (LLDB_INVALID_PROCESS_ID);
2247 const char *error_string = error.AsCString();
2248 if (error_string == NULL)
2249 error_string = "attach failed";
2250
2251 SetExitStatus(-1, error_string);
2252 }
2253 }
2254 }
2255 return error;
2256}
2257
2258Error
2259Process::Attach (const char *process_name, bool wait_for_launch)
2260{
Chris Lattner24943d22010-06-08 16:52:24 +00002261 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002262 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002263
2264 // Find the process and its architecture. Make sure it matches the architecture
2265 // of the current Target, and if not adjust it.
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002266 Error error;
Jim Ingham7508e732010-08-09 23:31:02 +00002267
Jim Inghamea294182010-08-17 21:54:19 +00002268 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00002269 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002270 ProcessInstanceInfoList process_infos;
Jim Ingham0d7f7772011-09-15 01:10:17 +00002271 PlatformSP platform_sp (m_target.GetPlatform ());
2272 assert (platform_sp.get());
2273
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002274 if (platform_sp)
Jim Inghamea294182010-08-17 21:54:19 +00002275 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002276 ProcessInstanceInfoMatch match_info;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002277 match_info.GetProcessInfo().SetName(process_name);
2278 match_info.SetNameMatchType (eNameMatchEquals);
2279 platform_sp->FindProcesses (match_info, process_infos);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002280 if (process_infos.GetSize() > 1)
Chris Lattner24943d22010-06-08 16:52:24 +00002281 {
Greg Clayton9c236732011-10-26 00:56:27 +00002282 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002283 }
2284 else if (process_infos.GetSize() == 0)
2285 {
Greg Clayton9c236732011-10-26 00:56:27 +00002286 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002287 }
Chris Lattner24943d22010-06-08 16:52:24 +00002288 }
2289 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002290 {
Greg Clayton9c236732011-10-26 00:56:27 +00002291 error.SetErrorString ("invalid platform");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002292 }
2293 }
2294
2295 if (error.Success())
2296 {
2297 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002298 m_os_ap.reset();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002299
2300 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2301 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002302 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002303 SetPublicState (eStateAttaching);
2304 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2305 if (error.Fail())
2306 {
2307 if (GetID() != LLDB_INVALID_PROCESS_ID)
2308 {
2309 SetID (LLDB_INVALID_PROCESS_ID);
2310 const char *error_string = error.AsCString();
2311 if (error_string == NULL)
2312 error_string = "attach failed";
2313
2314 SetExitStatus(-1, error_string);
2315 }
2316 }
2317 else
2318 {
2319 SetNextEventAction(new Process::AttachCompletionHandler(this));
2320 StartPrivateStateThread();
2321 }
Chris Lattner24943d22010-06-08 16:52:24 +00002322 }
2323 }
2324 return error;
2325}
2326
Greg Clayton75c703d2011-02-16 04:46:07 +00002327void
2328Process::CompleteAttach ()
2329{
2330 // Let the process subclass figure out at much as it can about the process
2331 // before we go looking for a dynamic loader plug-in.
Jim Inghamc0c53242011-09-15 21:36:42 +00002332 m_attached_to_process = true;
Greg Clayton75c703d2011-02-16 04:46:07 +00002333 DidAttach();
2334
Jim Ingham0d7f7772011-09-15 01:10:17 +00002335 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2336 // the same as the one we've already set, switch architectures.
2337 PlatformSP platform_sp (m_target.GetPlatform ());
2338 assert (platform_sp.get());
2339 if (platform_sp)
2340 {
2341 ProcessInstanceInfo process_info;
2342 platform_sp->GetProcessInfo (GetID(), process_info);
2343 const ArchSpec &process_arch = process_info.GetArchitecture();
2344 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2345 m_target.SetArchitecture (process_arch);
2346 }
2347
2348 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002349 // plug-in
Greg Clayton4fdf7602011-03-20 04:57:14 +00002350 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002351 if (m_dyld_ap.get())
2352 m_dyld_ap->DidAttach();
2353
Greg Clayton37f962e2011-08-22 02:49:39 +00002354 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002355 // Figure out which one is the executable, and set that in our target:
2356 ModuleList &modules = m_target.GetImages();
2357
2358 size_t num_modules = modules.GetSize();
2359 for (int i = 0; i < num_modules; i++)
2360 {
2361 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002362 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002363 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002364 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton75c703d2011-02-16 04:46:07 +00002365 m_target.SetExecutableModule (module_sp, false);
2366 break;
2367 }
2368 }
2369}
2370
Chris Lattner24943d22010-06-08 16:52:24 +00002371Error
Greg Claytone71e2582011-02-04 01:58:07 +00002372Process::ConnectRemote (const char *remote_url)
2373{
Greg Claytone71e2582011-02-04 01:58:07 +00002374 m_abi_sp.reset();
2375 m_process_input_reader.reset();
2376
2377 // Find the process and its architecture. Make sure it matches the architecture
2378 // of the current Target, and if not adjust it.
2379
2380 Error error (DoConnectRemote (remote_url));
2381 if (error.Success())
2382 {
Greg Claytona2f74232011-02-24 22:24:29 +00002383 if (GetID() != LLDB_INVALID_PROCESS_ID)
2384 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002385 EventSP event_sp;
2386 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2387
2388 if (state == eStateStopped || state == eStateCrashed)
2389 {
2390 // If we attached and actually have a process on the other end, then
2391 // this ended up being the equivalent of an attach.
2392 CompleteAttach ();
2393
2394 // This delays passing the stopped event to listeners till
2395 // CompleteAttach gets a chance to complete...
2396 HandlePrivateEvent (event_sp);
2397
2398 }
Greg Claytona2f74232011-02-24 22:24:29 +00002399 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002400
2401 if (PrivateStateThreadIsValid ())
2402 ResumePrivateStateThread ();
2403 else
2404 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002405 }
2406 return error;
2407}
2408
2409
2410Error
Chris Lattner24943d22010-06-08 16:52:24 +00002411Process::Resume ()
2412{
Greg Claytone005f2c2010-11-06 01:53:30 +00002413 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002414 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002415 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002416 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002417 StateAsCString(m_public_state.GetValue()),
2418 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002419
2420 Error error (WillResume());
2421 // Tell the process it is about to resume before the thread list
2422 if (error.Success())
2423 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002424 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002425 // can let all of our threads know that they are about to be
2426 // resumed. Threads will each be called with
2427 // Thread::WillResume(StateType) where StateType contains the state
2428 // that they are supposed to have when the process is resumed
2429 // (suspended/running/stepping). Threads should also check
2430 // their resume signal in lldb::Thread::GetResumeSignal()
2431 // to see if they are suppoed to start back up with a signal.
2432 if (m_thread_list.WillResume())
2433 {
Jim Ingham0296fe72011-11-08 03:00:11 +00002434 m_mod_id.BumpResumeID();
Chris Lattner24943d22010-06-08 16:52:24 +00002435 error = DoResume();
2436 if (error.Success())
2437 {
2438 DidResume();
2439 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00002440 if (log)
2441 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00002442 }
2443 }
2444 else
2445 {
Jim Inghamac959662011-01-24 06:34:17 +00002446 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002447 }
2448 }
Jim Inghamac959662011-01-24 06:34:17 +00002449 else if (log)
2450 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002451 return error;
2452}
2453
2454Error
2455Process::Halt ()
2456{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002457 // Pause our private state thread so we can ensure no one else eats
2458 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002459 Listener halt_listener ("lldb.process.halt_listener");
2460 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002461
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002462 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002463 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002464
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002465 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002466 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002467
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002468 bool caused_stop = false;
2469
2470 // Ask the process subclass to actually halt our process
2471 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002472 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002473 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002474 if (m_public_state.GetValue() == eStateAttaching)
2475 {
2476 SetExitStatus(SIGKILL, "Cancelled async attach.");
2477 Destroy ();
2478 }
2479 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002480 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002481 // If "caused_stop" is true, then DoHalt stopped the process. If
2482 // "caused_stop" is false, the process was already stopped.
2483 // If the DoHalt caused the process to stop, then we want to catch
2484 // this event and set the interrupted bool to true before we pass
2485 // this along so clients know that the process was interrupted by
2486 // a halt command.
2487 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002488 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002489 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002490 TimeValue timeout_time;
2491 timeout_time = TimeValue::Now();
2492 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002493 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2494 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002495
Jim Inghamf9f40c22011-02-08 05:20:59 +00002496 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002497 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002498 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002499 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002500 }
2501 else
2502 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002503 if (StateIsStoppedState (state))
2504 {
2505 // We caused the process to interrupt itself, so mark this
2506 // as such in the stop event so clients can tell an interrupted
2507 // process from a natural stop
2508 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2509 }
2510 else
2511 {
2512 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2513 if (log)
2514 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2515 error.SetErrorString ("Did not get stopped event after halt.");
2516 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002517 }
2518 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002519 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002520 }
2521 }
Chris Lattner24943d22010-06-08 16:52:24 +00002522 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002523 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002524 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002525
2526 // Post any event we might have consumed. If all goes well, we will have
2527 // stopped the process, intercepted the event and set the interrupted
2528 // bool in the event. Post it to the private event queue and that will end up
2529 // correctly setting the state.
2530 if (event_sp)
2531 m_private_state_broadcaster.BroadcastEvent(event_sp);
2532
Chris Lattner24943d22010-06-08 16:52:24 +00002533 return error;
2534}
2535
2536Error
2537Process::Detach ()
2538{
2539 Error error (WillDetach());
2540
2541 if (error.Success())
2542 {
2543 DisableAllBreakpointSites();
2544 error = DoDetach();
2545 if (error.Success())
2546 {
2547 DidDetach();
2548 StopPrivateStateThread();
2549 }
2550 }
2551 return error;
2552}
2553
2554Error
2555Process::Destroy ()
2556{
2557 Error error (WillDestroy());
2558 if (error.Success())
2559 {
2560 DisableAllBreakpointSites();
2561 error = DoDestroy();
2562 if (error.Success())
2563 {
2564 DidDestroy();
2565 StopPrivateStateThread();
2566 }
Caroline Tice861efb32010-11-16 05:07:41 +00002567 m_stdio_communication.StopReadThread();
2568 m_stdio_communication.Disconnect();
2569 if (m_process_input_reader && m_process_input_reader->IsActive())
2570 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2571 if (m_process_input_reader)
2572 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002573 }
2574 return error;
2575}
2576
2577Error
2578Process::Signal (int signal)
2579{
2580 Error error (WillSignal());
2581 if (error.Success())
2582 {
2583 error = DoSignal(signal);
2584 if (error.Success())
2585 DidSignal();
2586 }
2587 return error;
2588}
2589
Greg Clayton395fc332011-02-15 21:59:32 +00002590lldb::ByteOrder
2591Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002592{
Greg Clayton395fc332011-02-15 21:59:32 +00002593 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002594}
2595
2596uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002597Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002598{
Greg Clayton395fc332011-02-15 21:59:32 +00002599 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002600}
2601
Greg Clayton395fc332011-02-15 21:59:32 +00002602
Chris Lattner24943d22010-06-08 16:52:24 +00002603bool
2604Process::ShouldBroadcastEvent (Event *event_ptr)
2605{
2606 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2607 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002608 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002609
2610 switch (state)
2611 {
Greg Claytone71e2582011-02-04 01:58:07 +00002612 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002613 case eStateAttaching:
2614 case eStateLaunching:
2615 case eStateDetached:
2616 case eStateExited:
2617 case eStateUnloaded:
2618 // These events indicate changes in the state of the debugging session, always report them.
2619 return_value = true;
2620 break;
2621 case eStateInvalid:
2622 // We stopped for no apparent reason, don't report it.
2623 return_value = false;
2624 break;
2625 case eStateRunning:
2626 case eStateStepping:
2627 // If we've started the target running, we handle the cases where we
2628 // are already running and where there is a transition from stopped to
2629 // running differently.
2630 // running -> running: Automatically suppress extra running events
2631 // stopped -> running: Report except when there is one or more no votes
2632 // and no yes votes.
2633 SynchronouslyNotifyStateChanged (state);
2634 switch (m_public_state.GetValue())
2635 {
2636 case eStateRunning:
2637 case eStateStepping:
2638 // We always suppress multiple runnings with no PUBLIC stop in between.
2639 return_value = false;
2640 break;
2641 default:
2642 // TODO: make this work correctly. For now always report
2643 // run if we aren't running so we don't miss any runnning
2644 // events. If I run the lldb/test/thread/a.out file and
2645 // break at main.cpp:58, run and hit the breakpoints on
2646 // multiple threads, then somehow during the stepping over
2647 // of all breakpoints no run gets reported.
2648 return_value = true;
2649
2650 // This is a transition from stop to run.
2651 switch (m_thread_list.ShouldReportRun (event_ptr))
2652 {
2653 case eVoteYes:
2654 case eVoteNoOpinion:
2655 return_value = true;
2656 break;
2657 case eVoteNo:
2658 return_value = false;
2659 break;
2660 }
2661 break;
2662 }
2663 break;
2664 case eStateStopped:
2665 case eStateCrashed:
2666 case eStateSuspended:
2667 {
2668 // We've stopped. First see if we're going to restart the target.
2669 // If we are going to stop, then we always broadcast the event.
2670 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00002671 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002672 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002673 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002674 if (log)
2675 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002676 return true;
2677 }
2678 else
2679 {
Chris Lattner24943d22010-06-08 16:52:24 +00002680 RefreshStateAfterStop ();
2681
2682 if (m_thread_list.ShouldStop (event_ptr) == false)
2683 {
2684 switch (m_thread_list.ShouldReportStop (event_ptr))
2685 {
2686 case eVoteYes:
2687 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00002688 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00002689 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00002690 case eVoteNo:
2691 return_value = false;
2692 break;
2693 }
2694
2695 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002696 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002697 Resume ();
2698 }
2699 else
2700 {
2701 return_value = true;
2702 SynchronouslyNotifyStateChanged (state);
2703 }
2704 }
2705 }
2706 }
2707
2708 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002709 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00002710 return return_value;
2711}
2712
Chris Lattner24943d22010-06-08 16:52:24 +00002713
2714bool
2715Process::StartPrivateStateThread ()
2716{
Greg Claytone005f2c2010-11-06 01:53:30 +00002717 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002718
Greg Claytonb72d0f02011-04-12 05:54:46 +00002719 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00002720 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002721 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2722
2723 if (already_running)
2724 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00002725
2726 // Create a thread that watches our internal state and controls which
2727 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002728 char thread_name[1024];
Greg Clayton444e35b2011-10-19 18:09:39 +00002729 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Claytona875b642011-01-09 21:07:35 +00002730 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002731 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002732}
2733
2734void
2735Process::PausePrivateStateThread ()
2736{
2737 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2738}
2739
2740void
2741Process::ResumePrivateStateThread ()
2742{
2743 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2744}
2745
2746void
2747Process::StopPrivateStateThread ()
2748{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002749 if (PrivateStateThreadIsValid ())
2750 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner24943d22010-06-08 16:52:24 +00002751}
2752
2753void
2754Process::ControlPrivateStateThread (uint32_t signal)
2755{
Greg Claytone005f2c2010-11-06 01:53:30 +00002756 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002757
2758 assert (signal == eBroadcastInternalStateControlStop ||
2759 signal == eBroadcastInternalStateControlPause ||
2760 signal == eBroadcastInternalStateControlResume);
2761
2762 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002763 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002764
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002765 // Signal the private state thread. First we should copy this is case the
2766 // thread starts exiting since the private state thread will NULL this out
2767 // when it exits
2768 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00002769 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002770 {
2771 TimeValue timeout_time;
2772 bool timed_out;
2773
2774 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2775
2776 timeout_time = TimeValue::Now();
2777 timeout_time.OffsetWithSeconds(2);
2778 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2779 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2780
2781 if (signal == eBroadcastInternalStateControlStop)
2782 {
2783 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002784 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002785
2786 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002787 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002788 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002789 }
2790 }
2791}
2792
2793void
2794Process::HandlePrivateEvent (EventSP &event_sp)
2795{
Greg Claytone005f2c2010-11-06 01:53:30 +00002796 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002797
Greg Clayton68ca8232011-01-25 02:58:48 +00002798 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002799
2800 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00002801 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002802 {
Jim Ingham68bffc52011-01-29 04:05:41 +00002803 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002804 switch (action_result)
2805 {
2806 case NextEventAction::eEventActionSuccess:
2807 SetNextEventAction(NULL);
2808 break;
2809 case NextEventAction::eEventActionRetry:
2810 break;
2811 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00002812 // Handle Exiting Here. If we already got an exited event,
2813 // we should just propagate it. Otherwise, swallow this event,
2814 // and set our state to exit so the next event will kill us.
2815 if (new_state != eStateExited)
2816 {
2817 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00002818 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00002819 SetNextEventAction(NULL);
2820 return;
2821 }
2822 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002823 break;
2824 }
2825 }
2826
Chris Lattner24943d22010-06-08 16:52:24 +00002827 // See if we should broadcast this state to external clients?
2828 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002829
2830 if (should_broadcast)
2831 {
2832 if (log)
2833 {
Greg Clayton444e35b2011-10-19 18:09:39 +00002834 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00002835 __FUNCTION__,
2836 GetID(),
2837 StateAsCString(new_state),
2838 StateAsCString (GetState ()),
2839 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002840 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00002841 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00002842 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00002843 PushProcessInputReader ();
2844 else
2845 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00002846
Chris Lattner24943d22010-06-08 16:52:24 +00002847 BroadcastEvent (event_sp);
2848 }
2849 else
2850 {
2851 if (log)
2852 {
Greg Clayton444e35b2011-10-19 18:09:39 +00002853 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00002854 __FUNCTION__,
2855 GetID(),
2856 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002857 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00002858 }
2859 }
2860}
2861
2862void *
2863Process::PrivateStateThread (void *arg)
2864{
2865 Process *proc = static_cast<Process*> (arg);
2866 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002867 return result;
2868}
2869
2870void *
2871Process::RunPrivateStateThread ()
2872{
2873 bool control_only = false;
2874 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2875
Greg Claytone005f2c2010-11-06 01:53:30 +00002876 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002877 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002878 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002879
2880 bool exit_now = false;
2881 while (!exit_now)
2882 {
2883 EventSP event_sp;
2884 WaitForEventsPrivate (NULL, event_sp, control_only);
2885 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2886 {
2887 switch (event_sp->GetType())
2888 {
2889 case eBroadcastInternalStateControlStop:
2890 exit_now = true;
2891 continue; // Go to next loop iteration so we exit without
2892 break; // doing any internal state managment below
2893
2894 case eBroadcastInternalStateControlPause:
2895 control_only = true;
2896 break;
2897
2898 case eBroadcastInternalStateControlResume:
2899 control_only = false;
2900 break;
2901 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002902
Jim Ingham3ae449a2010-11-17 02:32:00 +00002903 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002904 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham3ae449a2010-11-17 02:32:00 +00002905
Chris Lattner24943d22010-06-08 16:52:24 +00002906 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002907 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002908 }
2909
2910
2911 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2912
2913 if (internal_state != eStateInvalid)
2914 {
2915 HandlePrivateEvent (event_sp);
2916 }
2917
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002918 if (internal_state == eStateInvalid ||
2919 internal_state == eStateExited ||
2920 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002921 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002922 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002923 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002924
Chris Lattner24943d22010-06-08 16:52:24 +00002925 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002926 }
Chris Lattner24943d22010-06-08 16:52:24 +00002927 }
2928
Caroline Tice926060e2010-10-29 21:48:37 +00002929 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002930 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00002931 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00002932
Greg Claytona4881d02011-01-22 07:12:45 +00002933 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2934 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002935 return NULL;
2936}
2937
Chris Lattner24943d22010-06-08 16:52:24 +00002938//------------------------------------------------------------------
2939// Process Event Data
2940//------------------------------------------------------------------
2941
2942Process::ProcessEventData::ProcessEventData () :
2943 EventData (),
2944 m_process_sp (),
2945 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002946 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002947 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002948 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002949{
2950}
2951
2952Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2953 EventData (),
2954 m_process_sp (process_sp),
2955 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002956 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002957 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002958 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002959{
2960}
2961
2962Process::ProcessEventData::~ProcessEventData()
2963{
2964}
2965
2966const ConstString &
2967Process::ProcessEventData::GetFlavorString ()
2968{
2969 static ConstString g_flavor ("Process::ProcessEventData");
2970 return g_flavor;
2971}
2972
2973const ConstString &
2974Process::ProcessEventData::GetFlavor () const
2975{
2976 return ProcessEventData::GetFlavorString ();
2977}
2978
Chris Lattner24943d22010-06-08 16:52:24 +00002979void
2980Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2981{
2982 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002983 // off of the private process event queue, and then any number of times, first when it gets pulled off of
2984 // the public event queue, then other times when we're pretending that this is where we stopped at the
2985 // end of expression evaluation. m_update_state is used to distinguish these
2986 // three cases; it is 0 when we're just pulling it off for private handling,
2987 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00002988
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00002989 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00002990 return;
2991
2992 m_process_sp->SetPublicState (m_state);
2993
2994 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2995 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00002996 {
2997 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
2998 int num_threads = curr_thread_list.GetSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002999 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003000
Jim Ingham21f37ad2011-08-09 02:12:22 +00003001 // The actions might change one of the thread's stop_info's opinions about whether we should
3002 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003003
3004 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3005 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3006 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3007 // 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
3008 // against this list & bag out if anything differs.
3009 std::vector<lldb::tid_t> thread_index_array(num_threads);
3010 for (idx = 0; idx < num_threads; ++idx)
3011 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3012
Jim Ingham21f37ad2011-08-09 02:12:22 +00003013 bool still_should_stop = true;
3014
Chris Lattner24943d22010-06-08 16:52:24 +00003015 for (idx = 0; idx < num_threads; ++idx)
3016 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003017 curr_thread_list = m_process_sp->GetThreadList();
3018 if (curr_thread_list.GetSize() != num_threads)
3019 {
3020 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3021 log->Printf("Number of threads changed from %d to %d while processing event.", num_threads, curr_thread_list.GetSize());
3022 break;
3023 }
3024
3025 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3026
3027 if (thread_sp->GetIndexID() != thread_index_array[idx])
3028 {
3029 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3030 log->Printf("The thread at position %d changed from %d to %d while processing event.",
3031 idx,
3032 thread_index_array[idx],
3033 thread_sp->GetIndexID());
3034 break;
3035 }
3036
Jim Ingham6297a3a2010-10-20 00:39:53 +00003037 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3038 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00003039 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003040 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003041 // The stop action might restart the target. If it does, then we want to mark that in the
3042 // event so that whoever is receiving it will know to wait for the running event and reflect
3043 // that state appropriately.
3044 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003045
3046 // FIXME: we might have run.
3047 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003048 {
3049 SetRestarted (true);
3050 break;
3051 }
3052 else if (!stop_info_sp->ShouldStop(event_ptr))
3053 {
3054 still_should_stop = false;
3055 }
Chris Lattner24943d22010-06-08 16:52:24 +00003056 }
3057 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003058
Jim Ingham21f37ad2011-08-09 02:12:22 +00003059
3060 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003061 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003062 if (!still_should_stop)
3063 {
3064 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003065 SetRestarted(true);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003066 m_process_sp->Resume();
3067 }
3068 else
3069 {
3070 // If we didn't restart, run the Stop Hooks here:
3071 // They might also restart the target, so watch for that.
3072 m_process_sp->GetTarget().RunStopHooks();
3073 if (m_process_sp->GetPrivateState() == eStateRunning)
3074 SetRestarted(true);
3075 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003076 }
3077
Chris Lattner24943d22010-06-08 16:52:24 +00003078 }
3079}
3080
3081void
3082Process::ProcessEventData::Dump (Stream *s) const
3083{
3084 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003085 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003086
Greg Claytonb72d0f02011-04-12 05:54:46 +00003087 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003088}
3089
3090const Process::ProcessEventData *
3091Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3092{
3093 if (event_ptr)
3094 {
3095 const EventData *event_data = event_ptr->GetData();
3096 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3097 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3098 }
3099 return NULL;
3100}
3101
3102ProcessSP
3103Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3104{
3105 ProcessSP process_sp;
3106 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3107 if (data)
3108 process_sp = data->GetProcessSP();
3109 return process_sp;
3110}
3111
3112StateType
3113Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3114{
3115 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3116 if (data == NULL)
3117 return eStateInvalid;
3118 else
3119 return data->GetState();
3120}
3121
3122bool
3123Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3124{
3125 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3126 if (data == NULL)
3127 return false;
3128 else
3129 return data->GetRestarted();
3130}
3131
3132void
3133Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3134{
3135 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3136 if (data != NULL)
3137 data->SetRestarted(new_value);
3138}
3139
3140bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003141Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3142{
3143 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3144 if (data == NULL)
3145 return false;
3146 else
3147 return data->GetInterrupted ();
3148}
3149
3150void
3151Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3152{
3153 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3154 if (data != NULL)
3155 data->SetInterrupted(new_value);
3156}
3157
3158bool
Chris Lattner24943d22010-06-08 16:52:24 +00003159Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3160{
3161 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3162 if (data)
3163 {
3164 data->SetUpdateStateOnRemoval();
3165 return true;
3166 }
3167 return false;
3168}
3169
Chris Lattner24943d22010-06-08 16:52:24 +00003170void
Greg Claytona830adb2010-10-04 01:05:56 +00003171Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003172{
Greg Clayton567e7f32011-09-22 04:58:26 +00003173 exe_ctx.SetTargetPtr (&m_target);
3174 exe_ctx.SetProcessPtr (this);
3175 exe_ctx.SetThreadPtr(NULL);
3176 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003177}
3178
3179lldb::ProcessSP
3180Process::GetSP ()
3181{
3182 return GetTarget().GetProcessSP();
3183}
3184
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003185//uint32_t
3186//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3187//{
3188// return 0;
3189//}
3190//
3191//ArchSpec
3192//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3193//{
3194// return Host::GetArchSpecForExistingProcess (pid);
3195//}
3196//
3197//ArchSpec
3198//Process::GetArchSpecForExistingProcess (const char *process_name)
3199//{
3200// return Host::GetArchSpecForExistingProcess (process_name);
3201//}
3202//
Caroline Tice861efb32010-11-16 05:07:41 +00003203void
3204Process::AppendSTDOUT (const char * s, size_t len)
3205{
Greg Clayton20d338f2010-11-18 05:57:03 +00003206 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003207 m_stdout_data.append (s, len);
3208
Greg Claytonb3781332010-12-05 19:16:56 +00003209 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003210}
3211
3212void
3213Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3214{
3215 Process *process = (Process *) baton;
3216 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3217}
3218
3219size_t
3220Process::ProcessInputReaderCallback (void *baton,
3221 InputReader &reader,
3222 lldb::InputReaderAction notification,
3223 const char *bytes,
3224 size_t bytes_len)
3225{
3226 Process *process = (Process *) baton;
3227
3228 switch (notification)
3229 {
3230 case eInputReaderActivate:
3231 break;
3232
3233 case eInputReaderDeactivate:
3234 break;
3235
3236 case eInputReaderReactivate:
3237 break;
3238
Caroline Tice4a348082011-05-02 20:41:46 +00003239 case eInputReaderAsynchronousOutputWritten:
3240 break;
3241
Caroline Tice861efb32010-11-16 05:07:41 +00003242 case eInputReaderGotToken:
3243 {
3244 Error error;
3245 process->PutSTDIN (bytes, bytes_len, error);
3246 }
3247 break;
3248
Caroline Ticec4f55fe2010-11-19 20:47:54 +00003249 case eInputReaderInterrupt:
3250 process->Halt ();
3251 break;
3252
3253 case eInputReaderEndOfFile:
3254 process->AppendSTDOUT ("^D", 2);
3255 break;
3256
Caroline Tice861efb32010-11-16 05:07:41 +00003257 case eInputReaderDone:
3258 break;
3259
3260 }
3261
3262 return bytes_len;
3263}
3264
3265void
3266Process::ResetProcessInputReader ()
3267{
3268 m_process_input_reader.reset();
3269}
3270
3271void
3272Process::SetUpProcessInputReader (int file_descriptor)
3273{
3274 // First set up the Read Thread for reading/handling process I/O
3275
3276 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3277
3278 if (conn_ap.get())
3279 {
3280 m_stdio_communication.SetConnection (conn_ap.release());
3281 if (m_stdio_communication.IsConnected())
3282 {
3283 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3284 m_stdio_communication.StartReadThread();
3285
3286 // Now read thread is set up, set up input reader.
3287
3288 if (!m_process_input_reader.get())
3289 {
3290 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3291 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3292 this,
3293 eInputReaderGranularityByte,
3294 NULL,
3295 NULL,
3296 false));
3297
3298 if (err.Fail())
3299 m_process_input_reader.reset();
3300 }
3301 }
3302 }
3303}
3304
3305void
3306Process::PushProcessInputReader ()
3307{
3308 if (m_process_input_reader && !m_process_input_reader->IsActive())
3309 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3310}
3311
3312void
3313Process::PopProcessInputReader ()
3314{
3315 if (m_process_input_reader && m_process_input_reader->IsActive())
3316 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3317}
3318
Greg Claytond284b662011-02-18 01:44:25 +00003319// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00003320void
Caroline Tice2a456812011-03-10 22:14:10 +00003321Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003322{
Greg Claytonb3448432011-03-24 21:19:54 +00003323 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00003324
3325 int i=0;
3326 const char *name;
3327 OptionEnumValueElement option_enum;
3328 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3329 {
3330 if (name)
3331 {
3332 option_enum.value = i;
3333 option_enum.string_value = name;
3334 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3335 g_plugins.push_back (option_enum);
3336 }
3337 ++i;
3338 }
3339 option_enum.value = 0;
3340 option_enum.string_value = NULL;
3341 option_enum.usage = NULL;
3342 g_plugins.push_back (option_enum);
3343
3344 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3345 {
3346 if (::strcmp (name, "plugin") == 0)
3347 {
3348 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3349 break;
3350 }
3351 }
Greg Clayton990de7b2010-11-18 23:32:35 +00003352 UserSettingsControllerSP &usc = GetSettingsController();
3353 usc.reset (new SettingsController);
3354 UserSettingsController::InitializeSettingsController (usc,
3355 SettingsController::global_settings_table,
3356 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00003357
3358 // Now call SettingsInitialize() for each 'child' of Process settings
3359 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00003360}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003361
Greg Clayton990de7b2010-11-18 23:32:35 +00003362void
Caroline Tice2a456812011-03-10 22:14:10 +00003363Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00003364{
Caroline Tice2a456812011-03-10 22:14:10 +00003365 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3366
3367 Thread::SettingsTerminate ();
3368
3369 // Now terminate Process Settings.
3370
Greg Clayton990de7b2010-11-18 23:32:35 +00003371 UserSettingsControllerSP &usc = GetSettingsController();
3372 UserSettingsController::FinalizeSettingsController (usc);
3373 usc.reset();
3374}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003375
Greg Clayton990de7b2010-11-18 23:32:35 +00003376UserSettingsControllerSP &
3377Process::GetSettingsController ()
3378{
3379 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003380 return g_settings_controller;
3381}
3382
Caroline Tice1ebef442010-09-27 00:30:10 +00003383void
3384Process::UpdateInstanceName ()
3385{
Greg Clayton5beb99d2011-08-11 02:48:45 +00003386 Module *module = GetTarget().GetExecutableModulePointer();
3387 if (module)
Caroline Tice1ebef442010-09-27 00:30:10 +00003388 {
3389 StreamString sstr;
Greg Clayton5beb99d2011-08-11 02:48:45 +00003390 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1ebef442010-09-27 00:30:10 +00003391
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003392 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytonb72d0f02011-04-12 05:54:46 +00003393 sstr.GetData());
Caroline Tice1ebef442010-09-27 00:30:10 +00003394 }
3395}
3396
Greg Clayton427f2902010-12-14 02:59:59 +00003397ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00003398Process::RunThreadPlan (ExecutionContext &exe_ctx,
3399 lldb::ThreadPlanSP &thread_plan_sp,
3400 bool stop_others,
3401 bool try_all_threads,
3402 bool discard_on_error,
3403 uint32_t single_thread_timeout_usec,
3404 Stream &errors)
3405{
3406 ExecutionResults return_value = eExecutionSetupError;
3407
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003408 if (thread_plan_sp.get() == NULL)
3409 {
3410 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00003411 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003412 }
Greg Clayton567e7f32011-09-22 04:58:26 +00003413
3414 if (exe_ctx.GetProcessPtr() != this)
3415 {
3416 errors.Printf("RunThreadPlan called on wrong process.");
3417 return eExecutionSetupError;
3418 }
3419
3420 Thread *thread = exe_ctx.GetThreadPtr();
3421 if (thread == NULL)
3422 {
3423 errors.Printf("RunThreadPlan called with invalid thread.");
3424 return eExecutionSetupError;
3425 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003426
Jim Ingham5ab7fba2011-05-17 22:24:54 +00003427 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3428 // For that to be true the plan can't be private - since private plans suppress themselves in the
3429 // GetCompletedPlan call.
3430
3431 bool orig_plan_private = thread_plan_sp->GetPrivate();
3432 thread_plan_sp->SetPrivate(false);
3433
Jim Inghamac959662011-01-24 06:34:17 +00003434 if (m_private_state.GetValue() != eStateStopped)
3435 {
3436 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00003437 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00003438 }
3439
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003440 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00003441 const uint32_t thread_idx_id = thread->GetIndexID();
3442 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003443
3444 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3445 // so we should arrange to reset them as well.
3446
Greg Clayton567e7f32011-09-22 04:58:26 +00003447 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00003448
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003449 uint32_t selected_tid;
3450 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00003451 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00003452 {
3453 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003454 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003455 }
3456 else
3457 {
3458 selected_tid = LLDB_INVALID_THREAD_ID;
3459 }
3460
Greg Clayton567e7f32011-09-22 04:58:26 +00003461 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Ingham360f53f2010-11-30 02:22:11 +00003462
Jim Ingham6ae318c2011-01-23 21:14:08 +00003463 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003464
3465 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3466 // restored on exit to the function.
3467
3468 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00003469
Jim Ingham6ae318c2011-01-23 21:14:08 +00003470 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003471 if (log)
3472 {
3473 StreamString s;
3474 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton444e35b2011-10-19 18:09:39 +00003475 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Clayton567e7f32011-09-22 04:58:26 +00003476 thread->GetIndexID(),
3477 thread->GetID(),
Jim Inghamf9f40c22011-02-08 05:20:59 +00003478 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003479 }
3480
Jim Inghamf9f40c22011-02-08 05:20:59 +00003481 bool got_event;
3482 lldb::EventSP event_sp;
3483 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00003484
3485 TimeValue* timeout_ptr = NULL;
3486 TimeValue real_timeout;
3487
Jim Inghamf9f40c22011-02-08 05:20:59 +00003488 bool first_timeout = true;
3489 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00003490
Jim Ingham360f53f2010-11-30 02:22:11 +00003491 while (1)
3492 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003493 // We usually want to resume the process if we get to the top of the loop.
3494 // The only exception is if we get two running events with no intervening
3495 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00003496
Jim Inghamf9f40c22011-02-08 05:20:59 +00003497 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00003498 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003499 // Do the initial resume and wait for the running event before going further.
3500
Greg Clayton567e7f32011-09-22 04:58:26 +00003501 Error resume_error = Resume ();
Jim Inghamf9f40c22011-02-08 05:20:59 +00003502 if (!resume_error.Success())
3503 {
3504 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00003505 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003506 break;
3507 }
3508
3509 real_timeout = TimeValue::Now();
3510 real_timeout.OffsetWithMicroSeconds(500000);
3511 timeout_ptr = &real_timeout;
3512
3513 got_event = listener.WaitForEvent(NULL, event_sp);
3514 if (!got_event)
3515 {
3516 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003517 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003518
3519 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003520 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003521 break;
3522 }
3523
3524 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3525 if (stop_state != eStateRunning)
3526 {
3527 if (log)
3528 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3529
3530 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003531 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003532 break;
3533 }
3534
3535 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003536 log->PutCString ("Resuming succeeded.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003537 // We need to call the function synchronously, so spin waiting for it to return.
3538 // If we get interrupted while executing, we're going to lose our context, and
3539 // won't be able to gather the result at this point.
3540 // We set the timeout AFTER the resume, since the resume takes some time and we
3541 // don't want to charge that to the timeout.
3542
3543 if (single_thread_timeout_usec != 0)
3544 {
3545 real_timeout = TimeValue::Now();
3546 if (first_timeout)
3547 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3548 else
3549 real_timeout.OffsetWithSeconds(10);
3550
3551 timeout_ptr = &real_timeout;
3552 }
3553 }
3554 else
3555 {
3556 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003557 log->PutCString ("Handled an extra running event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003558 do_resume = true;
3559 }
3560
3561 // Now wait for the process to stop again:
3562 stop_state = lldb::eStateInvalid;
3563 event_sp.reset();
3564 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3565
3566 if (got_event)
3567 {
3568 if (event_sp.get())
3569 {
3570 bool keep_going = false;
3571 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3572 if (log)
3573 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3574
3575 switch (stop_state)
3576 {
3577 case lldb::eStateStopped:
Jim Ingham2370a972011-05-17 01:10:11 +00003578 {
Greg Clayton43994462011-06-03 22:12:42 +00003579 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Clayton567e7f32011-09-22 04:58:26 +00003580 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton43994462011-06-03 22:12:42 +00003581 if (!thread_sp)
Jim Ingham2370a972011-05-17 01:10:11 +00003582 {
Greg Clayton43994462011-06-03 22:12:42 +00003583 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham2370a972011-05-17 01:10:11 +00003584 if (log)
Greg Clayton43994462011-06-03 22:12:42 +00003585 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3586 return_value = eExecutionInterrupted;
Jim Ingham2370a972011-05-17 01:10:11 +00003587 }
3588 else
3589 {
Greg Clayton43994462011-06-03 22:12:42 +00003590 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3591 StopReason stop_reason = eStopReasonInvalid;
3592 if (stop_info_sp)
3593 stop_reason = stop_info_sp->GetStopReason();
3594 if (stop_reason == eStopReasonPlanComplete)
3595 {
3596 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003597 log->PutCString ("Execution completed successfully.");
Greg Clayton43994462011-06-03 22:12:42 +00003598 // Now mark this plan as private so it doesn't get reported as the stop reason
3599 // after this point.
3600 if (thread_plan_sp)
3601 thread_plan_sp->SetPrivate (orig_plan_private);
3602 return_value = eExecutionCompleted;
3603 }
3604 else
3605 {
3606 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003607 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton43994462011-06-03 22:12:42 +00003608
3609 return_value = eExecutionInterrupted;
3610 }
Jim Ingham2370a972011-05-17 01:10:11 +00003611 }
Greg Clayton43994462011-06-03 22:12:42 +00003612 }
3613 break;
3614
Jim Inghamf9f40c22011-02-08 05:20:59 +00003615 case lldb::eStateCrashed:
3616 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003617 log->PutCString ("Execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003618 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003619 break;
Greg Clayton43994462011-06-03 22:12:42 +00003620
Jim Inghamf9f40c22011-02-08 05:20:59 +00003621 case lldb::eStateRunning:
3622 do_resume = false;
3623 keep_going = true;
3624 break;
Greg Clayton43994462011-06-03 22:12:42 +00003625
Jim Inghamf9f40c22011-02-08 05:20:59 +00003626 default:
3627 if (log)
3628 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham2370a972011-05-17 01:10:11 +00003629
3630 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytonb3448432011-03-24 21:19:54 +00003631 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003632 break;
3633 }
3634 if (keep_going)
3635 continue;
3636 else
3637 break;
3638 }
3639 else
3640 {
3641 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003642 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00003643 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003644 break;
3645 }
3646 }
3647 else
3648 {
3649 // If we didn't get an event that means we've timed out...
3650 // We will interrupt the process here. Depending on what we were asked to do we will
3651 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00003652 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003653
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003654 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00003655 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003656 {
3657 if (first_timeout)
3658 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3659 "trying with all threads enabled.",
3660 single_thread_timeout_usec);
3661 else
3662 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3663 "and timeout: %d timed out.",
3664 single_thread_timeout_usec);
3665 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003666 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00003667 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3668 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00003669 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003670 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003671
Greg Clayton567e7f32011-09-22 04:58:26 +00003672 Error halt_error = Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00003673 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00003674 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003675 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003676 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003677
Jim Inghamf9f40c22011-02-08 05:20:59 +00003678 // If halt succeeds, it always produces a stopped event. Wait for that:
3679
3680 real_timeout = TimeValue::Now();
3681 real_timeout.OffsetWithMicroSeconds(500000);
3682
3683 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00003684
3685 if (got_event)
3686 {
3687 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3688 if (log)
3689 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003690 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00003691 if (stop_state == lldb::eStateStopped
3692 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf6d3d792011-08-09 22:24:33 +00003693 log->PutCString (" Event was the Halt interruption event.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003694 }
3695
Jim Inghamf9f40c22011-02-08 05:20:59 +00003696 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00003697 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003698 // Between the time we initiated the Halt and the time we delivered it, the process could have
3699 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00003700
Greg Clayton567e7f32011-09-22 04:58:26 +00003701 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00003702 {
3703 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003704 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003705 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003706 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003707 break;
3708 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003709
Jim Inghamf9f40c22011-02-08 05:20:59 +00003710 if (!try_all_threads)
3711 {
3712 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003713 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003714 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003715 break;
3716 }
3717
3718 if (first_timeout)
3719 {
3720 // Set all the other threads to run, and return to the top of the loop, which will continue;
3721 first_timeout = false;
3722 thread_plan_sp->SetStopOthers (false);
3723 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003724 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003725
3726 continue;
3727 }
3728 else
3729 {
3730 // Running all threads failed, so return Interrupted.
3731 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003732 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003733 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003734 break;
3735 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003736 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003737 }
3738 else
3739 { if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003740 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003741 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00003742 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003743 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00003744 }
3745 }
Jim Inghamc556b462011-01-22 01:30:53 +00003746 else
3747 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003748 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3749 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00003750 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003751 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.",
3752 halt_error.AsCString());
3753 real_timeout = TimeValue::Now();
3754 real_timeout.OffsetWithMicroSeconds(500000);
3755 timeout_ptr = &real_timeout;
3756 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3757 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00003758 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003759 // This is not going anywhere, bag out.
3760 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003761 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003762 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003763 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00003764 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003765 else
3766 {
3767 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3768 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003769 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003770 if (stop_state == lldb::eStateStopped)
3771 {
3772 // Between the time we initiated the Halt and the time we delivered it, the process could have
3773 // already finished its job. Check that here:
3774
Greg Clayton567e7f32011-09-22 04:58:26 +00003775 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00003776 {
3777 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003778 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003779 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003780 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003781 break;
3782 }
3783
3784 if (first_timeout)
3785 {
3786 // Set all the other threads to run, and return to the top of the loop, which will continue;
3787 first_timeout = false;
3788 thread_plan_sp->SetStopOthers (false);
3789 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003790 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003791
3792 continue;
3793 }
3794 else
3795 {
3796 // Running all threads failed, so return Interrupted.
3797 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003798 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003799 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003800 break;
3801 }
3802 }
3803 else
3804 {
Sean Callananed3f86b2011-08-09 22:07:08 +00003805 if (log)
3806 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3807 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003808 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003809 break;
3810 }
3811 }
Jim Inghamc556b462011-01-22 01:30:53 +00003812 }
3813
Jim Ingham360f53f2010-11-30 02:22:11 +00003814 }
3815
Jim Inghamf9f40c22011-02-08 05:20:59 +00003816 } // END WAIT LOOP
3817
3818 // Now do some processing on the results of the run:
3819 if (return_value == eExecutionInterrupted)
3820 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003821 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003822 {
3823 StreamString s;
3824 if (event_sp)
3825 event_sp->Dump (&s);
3826 else
3827 {
Jim Inghamf6d3d792011-08-09 22:24:33 +00003828 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003829 }
3830
3831 StreamString ts;
3832
Jim Inghamf6d3d792011-08-09 22:24:33 +00003833 const char *event_explanation = NULL;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003834
3835 do
3836 {
3837 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3838
3839 if (!event_data)
3840 {
3841 event_explanation = "<no event data>";
3842 break;
3843 }
3844
3845 Process *process = event_data->GetProcessSP().get();
3846
3847 if (!process)
3848 {
3849 event_explanation = "<no process>";
3850 break;
3851 }
3852
3853 ThreadList &thread_list = process->GetThreadList();
3854
3855 uint32_t num_threads = thread_list.GetSize();
3856 uint32_t thread_index;
3857
3858 ts.Printf("<%u threads> ", num_threads);
3859
3860 for (thread_index = 0;
3861 thread_index < num_threads;
3862 ++thread_index)
3863 {
3864 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3865
3866 if (!thread)
3867 {
3868 ts.Printf("<?> ");
3869 continue;
3870 }
3871
Greg Clayton444e35b2011-10-19 18:09:39 +00003872 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Inghamf9f40c22011-02-08 05:20:59 +00003873 RegisterContext *register_context = thread->GetRegisterContext().get();
3874
3875 if (register_context)
3876 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3877 else
3878 ts.Printf("[ip unknown] ");
3879
3880 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3881 if (stop_info_sp)
3882 {
3883 const char *stop_desc = stop_info_sp->GetDescription();
3884 if (stop_desc)
3885 ts.PutCString (stop_desc);
3886 }
3887 ts.Printf(">");
3888 }
3889
3890 event_explanation = ts.GetData();
3891 } while (0);
3892
3893 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003894 {
3895 if (event_explanation)
3896 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3897 else
3898 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
3899 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003900
3901 if (discard_on_error && thread_plan_sp)
3902 {
Greg Clayton567e7f32011-09-22 04:58:26 +00003903 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003904 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003905 }
3906 }
3907 }
3908 else if (return_value == eExecutionSetupError)
3909 {
3910 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003911 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003912
3913 if (discard_on_error && thread_plan_sp)
3914 {
Greg Clayton567e7f32011-09-22 04:58:26 +00003915 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003916 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003917 }
3918 }
3919 else
3920 {
Greg Clayton567e7f32011-09-22 04:58:26 +00003921 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00003922 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003923 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003924 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00003925 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00003926 }
Greg Clayton567e7f32011-09-22 04:58:26 +00003927 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00003928 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003929 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003930 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00003931 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00003932 }
3933 else
3934 {
3935 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003936 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00003937 if (discard_on_error && thread_plan_sp)
3938 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003939 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003940 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Clayton567e7f32011-09-22 04:58:26 +00003941 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003942 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham360f53f2010-11-30 02:22:11 +00003943 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003944 }
3945 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003946
Jim Ingham360f53f2010-11-30 02:22:11 +00003947 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003948 // Check that it's still there, and if it is put it back in the context. Also restore the
3949 // frame in the context if it is still present.
Greg Clayton567e7f32011-09-22 04:58:26 +00003950 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
3951 if (thread)
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003952 {
Greg Clayton567e7f32011-09-22 04:58:26 +00003953 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003954 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003955
3956 // Also restore the current process'es selected frame & thread, since this function calling may
3957 // be done behind the user's back.
3958
3959 if (selected_tid != LLDB_INVALID_THREAD_ID)
3960 {
Greg Clayton567e7f32011-09-22 04:58:26 +00003961 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Ingham360f53f2010-11-30 02:22:11 +00003962 {
3963 // We were able to restore the selected thread, now restore the frame:
Greg Clayton567e7f32011-09-22 04:58:26 +00003964 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003965 if (old_frame_sp)
Greg Clayton567e7f32011-09-22 04:58:26 +00003966 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00003967 }
3968 }
3969
3970 return return_value;
3971}
3972
3973const char *
3974Process::ExecutionResultAsCString (ExecutionResults result)
3975{
3976 const char *result_name;
3977
3978 switch (result)
3979 {
Greg Claytonb3448432011-03-24 21:19:54 +00003980 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003981 result_name = "eExecutionCompleted";
3982 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003983 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00003984 result_name = "eExecutionDiscarded";
3985 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003986 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003987 result_name = "eExecutionInterrupted";
3988 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003989 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00003990 result_name = "eExecutionSetupError";
3991 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003992 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00003993 result_name = "eExecutionTimedOut";
3994 break;
3995 }
3996 return result_name;
3997}
3998
Greg Claytonabe0fed2011-04-18 08:33:37 +00003999void
4000Process::GetStatus (Stream &strm)
4001{
4002 const StateType state = GetState();
4003 if (StateIsStoppedState(state))
4004 {
4005 if (state == eStateExited)
4006 {
4007 int exit_status = GetExitStatus();
4008 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00004009 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00004010 GetID(),
4011 exit_status,
4012 exit_status,
4013 exit_description ? exit_description : "");
4014 }
4015 else
4016 {
4017 if (state == eStateConnected)
4018 strm.Printf ("Connected to remote target.\n");
4019 else
Greg Clayton444e35b2011-10-19 18:09:39 +00004020 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00004021 }
4022 }
4023 else
4024 {
Greg Clayton444e35b2011-10-19 18:09:39 +00004025 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004026 }
4027}
4028
4029size_t
4030Process::GetThreadStatus (Stream &strm,
4031 bool only_threads_with_stop_reason,
4032 uint32_t start_frame,
4033 uint32_t num_frames,
4034 uint32_t num_frames_with_source)
4035{
4036 size_t num_thread_infos_dumped = 0;
4037
4038 const size_t num_threads = GetThreadList().GetSize();
4039 for (uint32_t i = 0; i < num_threads; i++)
4040 {
4041 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4042 if (thread)
4043 {
4044 if (only_threads_with_stop_reason)
4045 {
4046 if (thread->GetStopInfo().get() == NULL)
4047 continue;
4048 }
4049 thread->GetStatus (strm,
4050 start_frame,
4051 num_frames,
4052 num_frames_with_source);
4053 ++num_thread_infos_dumped;
4054 }
4055 }
4056 return num_thread_infos_dumped;
4057}
4058
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004059//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004060// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004061//--------------------------------------------------------------
4062
Greg Claytond0a5a232010-09-19 02:33:57 +00004063Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00004064 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004065{
Greg Clayton638351a2010-12-04 00:10:17 +00004066 m_default_settings.reset (new ProcessInstanceSettings (*this,
4067 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00004068 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004069}
4070
Greg Claytond0a5a232010-09-19 02:33:57 +00004071Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004072{
4073}
4074
4075lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00004076Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004077{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00004078 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4079 false,
4080 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004081 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4082 return new_settings_sp;
4083}
4084
4085//--------------------------------------------------------------
4086// class ProcessInstanceSettings
4087//--------------------------------------------------------------
4088
Greg Clayton638351a2010-12-04 00:10:17 +00004089ProcessInstanceSettings::ProcessInstanceSettings
4090(
4091 UserSettingsController &owner,
4092 bool live_instance,
4093 const char *name
4094) :
Greg Claytonabb33022011-11-08 02:43:13 +00004095 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004096{
Caroline Tice396704b2010-09-09 18:26:37 +00004097 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4098 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4099 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00004100 // This is true for CreateInstanceName() too.
Greg Claytonabb33022011-11-08 02:43:13 +00004101
Caroline Tice75b11a32010-09-16 19:05:55 +00004102 if (GetInstanceName () == InstanceSettings::InvalidName())
4103 {
4104 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4105 m_owner.RegisterInstanceSettings (this);
4106 }
Greg Claytonabb33022011-11-08 02:43:13 +00004107
Caroline Tice396704b2010-09-09 18:26:37 +00004108 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004109 {
4110 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4111 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00004112 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004113 }
4114}
4115
4116ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonabb33022011-11-08 02:43:13 +00004117 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004118{
4119 if (m_instance_name != InstanceSettings::GetDefaultName())
4120 {
4121 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4122 CopyInstanceSettings (pending_settings,false);
4123 m_owner.RemovePendingSettings (m_instance_name);
4124 }
4125}
4126
4127ProcessInstanceSettings::~ProcessInstanceSettings ()
4128{
4129}
4130
4131ProcessInstanceSettings&
4132ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4133{
4134 if (this != &rhs)
4135 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004136 }
4137
4138 return *this;
4139}
4140
4141
4142void
4143ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4144 const char *index_value,
4145 const char *value,
4146 const ConstString &instance_name,
4147 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00004148 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004149 Error &err,
4150 bool pending)
4151{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004152}
4153
4154void
4155ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4156 bool pending)
4157{
Greg Claytonabb33022011-11-08 02:43:13 +00004158// if (new_settings.get() == NULL)
4159// return;
4160//
4161// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004162}
4163
Caroline Ticebcb5b452010-09-20 21:37:42 +00004164bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004165ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4166 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00004167 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00004168 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004169{
Greg Claytonabb33022011-11-08 02:43:13 +00004170 if (err)
4171 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4172 return false;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004173}
4174
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004175const ConstString
4176ProcessInstanceSettings::CreateInstanceName ()
4177{
4178 static int instance_count = 1;
4179 StreamString sstr;
4180
4181 sstr.Printf ("process_%d", instance_count);
4182 ++instance_count;
4183
4184 const ConstString ret_val (sstr.GetData());
4185 return ret_val;
4186}
4187
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004188//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004189// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004190//--------------------------------------------------
4191
4192SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004193Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004194{
4195 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4196 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4197};
4198
4199
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004200SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004201Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004202{
Greg Clayton638351a2010-12-04 00:10:17 +00004203 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton638351a2010-12-04 00:10:17 +00004204 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004205};
4206
4207
Jim Ingham7508e732010-08-09 23:31:02 +00004208
Greg Claytonabb33022011-11-08 02:43:13 +00004209