blob: e70788e93ac18469b33cc6a69621b56fe72f335c [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
39
40using namespace lldb;
41using namespace lldb_private;
42
Greg Clayton32e0a752011-03-30 18:16:51 +000043void
Greg Clayton8b82f082011-04-12 05:54:46 +000044ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +000045{
46 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +000047 if (m_pid != LLDB_INVALID_PROCESS_ID)
48 s.Printf (" pid = %i\n", m_pid);
49
50 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
51 s.Printf (" parent = %i\n", m_parent_pid);
52
53 if (m_executable)
54 {
55 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
56 s.PutCString (" file = ");
57 m_executable.Dump(&s);
58 s.EOL();
59 }
Greg Clayton8b82f082011-04-12 05:54:46 +000060 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +000061 if (argc > 0)
62 {
63 for (uint32_t i=0; i<argc; i++)
64 {
Greg Clayton8b82f082011-04-12 05:54:46 +000065 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000066 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +000067 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000068 else
Greg Clayton8b82f082011-04-12 05:54:46 +000069 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000070 }
71 }
Greg Clayton8b82f082011-04-12 05:54:46 +000072
73 const uint32_t envc = m_environment.GetArgumentCount();
74 if (envc > 0)
75 {
76 for (uint32_t i=0; i<envc; i++)
77 {
78 const char *env = m_environment.GetArgumentAtIndex(i);
79 if (i < 10)
80 s.Printf (" env[%u] = %s\n", i, env);
81 else
82 s.Printf ("env[%u] = %s\n", i, env);
83 }
84 }
85
Greg Clayton95bf0fd2011-04-01 00:29:43 +000086 if (m_arch.IsValid())
87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
88
Greg Clayton8b82f082011-04-12 05:54:46 +000089 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000090 {
Greg Clayton8b82f082011-04-12 05:54:46 +000091 cstr = platform->GetUserName (m_uid);
92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000093 }
Greg Clayton8b82f082011-04-12 05:54:46 +000094 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000095 {
Greg Clayton8b82f082011-04-12 05:54:46 +000096 cstr = platform->GetGroupName (m_gid);
97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000098 }
Greg Clayton8b82f082011-04-12 05:54:46 +000099 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000100 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000101 cstr = platform->GetUserName (m_euid);
102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000103 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000104 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000105 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000106 cstr = platform->GetGroupName (m_egid);
107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000108 }
109}
110
111void
Greg Clayton8b82f082011-04-12 05:54:46 +0000112ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000113{
Greg Clayton8b82f082011-04-12 05:54:46 +0000114 const char *label;
115 if (show_args || verbose)
116 label = "ARGUMENTS";
117 else
118 label = "NAME";
119
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000120 if (verbose)
121 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
124 }
125 else
126 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000127 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000128 s.PutCString ("====== ====== ========== ======= ============================\n");
129 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000130}
131
132void
Greg Clayton8b82f082011-04-12 05:54:46 +0000133ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000134{
135 if (m_pid != LLDB_INVALID_PROCESS_ID)
136 {
137 const char *cstr;
138 s.Printf ("%-6u %-6u ", m_pid, m_parent_pid);
139
Greg Clayton32e0a752011-03-30 18:16:51 +0000140
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000141 if (verbose)
142 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000143 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000144 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
145 s.Printf ("%-10s ", cstr);
146 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000147 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000148
Greg Clayton8b82f082011-04-12 05:54:46 +0000149 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000150 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
151 s.Printf ("%-10s ", cstr);
152 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000153 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000154
Greg Clayton8b82f082011-04-12 05:54:46 +0000155 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000156 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
157 s.Printf ("%-10s ", cstr);
158 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000159 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000160
Greg Clayton8b82f082011-04-12 05:54:46 +0000161 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000162 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
163 s.Printf ("%-10s ", cstr);
164 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000165 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000166 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
167 }
168 else
169 {
Jason Molendafd54b362011-09-20 21:44:10 +0000170 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000171 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000172 (int)m_arch.GetTriple().getArchName().size(),
173 m_arch.GetTriple().getArchName().data());
174 }
175
Greg Clayton8b82f082011-04-12 05:54:46 +0000176 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000177 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000178 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000179 if (argc > 0)
180 {
181 for (uint32_t i=0; i<argc; i++)
182 {
183 if (i > 0)
184 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000185 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000186 }
187 }
188 }
189 else
190 {
191 s.PutCString (GetName());
192 }
193
194 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000195 }
196}
197
Greg Clayton8b82f082011-04-12 05:54:46 +0000198
199void
Greg Clayton982c9762011-11-03 21:22:33 +0000200ProcessInfo::SetArguments (char const **argv,
201 bool first_arg_is_executable,
202 bool first_arg_is_executable_and_argument)
203{
204 m_arguments.SetArguments (argv);
205
206 // Is the first argument the executable?
207 if (first_arg_is_executable)
208 {
209 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
210 if (first_arg)
211 {
212 // Yes the first argument is an executable, set it as the executable
213 // in the launch options. Don't resolve the file path as the path
214 // could be a remote platform path
215 const bool resolve = false;
216 m_executable.SetFile(first_arg, resolve);
217
218 // If argument zero is an executable and shouldn't be included
219 // in the arguments, remove it from the front of the arguments
220 if (first_arg_is_executable_and_argument == false)
221 m_arguments.DeleteArgumentAtIndex (0);
222 }
223 }
224}
225void
226ProcessInfo::SetArguments (const Args& args,
227 bool first_arg_is_executable,
228 bool first_arg_is_executable_and_argument)
Greg Clayton8b82f082011-04-12 05:54:46 +0000229{
230 // Copy all arguments
231 m_arguments = args;
232
233 // Is the first argument the executable?
234 if (first_arg_is_executable)
235 {
Greg Clayton982c9762011-11-03 21:22:33 +0000236 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000237 if (first_arg)
238 {
239 // Yes the first argument is an executable, set it as the executable
240 // in the launch options. Don't resolve the file path as the path
241 // could be a remote platform path
242 const bool resolve = false;
243 m_executable.SetFile(first_arg, resolve);
244
245 // If argument zero is an executable and shouldn't be included
246 // in the arguments, remove it from the front of the arguments
247 if (first_arg_is_executable_and_argument == false)
248 m_arguments.DeleteArgumentAtIndex (0);
249 }
250 }
251}
252
Greg Clayton1d885962011-11-08 02:43:13 +0000253void
Greg Clayton144f3a92011-11-15 03:53:30 +0000254ProcessLaunchInfo::FinalizeFileActions (Target *target)
Greg Clayton1d885962011-11-08 02:43:13 +0000255{
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 Clayton144f3a92011-11-15 03:53:30 +0000307
308bool
309ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error, bool localhost)
310{
311 error.Clear();
312
313 if (GetFlags().Test (eLaunchFlagLaunchInShell))
314 {
315 const char *shell_executable = GetShell();
316 if (shell_executable)
317 {
318 char shell_resolved_path[PATH_MAX];
319
320 if (localhost)
321 {
322 FileSpec shell_filespec (shell_executable, true);
323
324 if (!shell_filespec.Exists())
325 {
326 // Resolve the path in case we just got "bash", "sh" or "tcsh"
327 if (!shell_filespec.ResolveExecutableLocation ())
328 {
329 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
330 return false;
331 }
332 }
333 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
334 shell_executable = shell_resolved_path;
335 }
336
337 Args shell_arguments;
338 std::string safe_arg;
339 shell_arguments.AppendArgument (shell_executable);
340 StreamString shell_command;
341 shell_arguments.AppendArgument ("-c");
342 shell_command.PutCString ("exec");
343 if (GetArchitecture().IsValid())
344 {
345 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
346 // Set the resume count to 2:
347 // 1 - stop in shell
348 // 2 - stop in /usr/bin/arch
349 // 3 - then we will stop in our program
350 SetResumeCount(2);
351 }
352 else
353 {
354 // Set the resume count to 1:
355 // 1 - stop in shell
356 // 2 - then we will stop in our program
357 SetResumeCount(1);
358 }
359
360 const char **argv = GetArguments().GetConstArgumentVector ();
361 if (argv)
362 {
363 for (size_t i=0; argv[i] != NULL; ++i)
364 {
365 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
366 shell_command.Printf(" %s", arg);
367 }
368 }
369 shell_arguments.AppendArgument (shell_command.GetString().c_str());
370
371 m_executable.SetFile(shell_executable, false);
372 m_arguments = shell_arguments;
373 return true;
374 }
375 else
376 {
377 error.SetErrorString ("invalid shell path");
378 }
379 }
380 else
381 {
382 error.SetErrorString ("not launching in shell");
383 }
384 return false;
385}
386
387
Greg Clayton32e0a752011-03-30 18:16:51 +0000388bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000389ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
390{
391 if ((read || write) && fd >= 0 && path && path[0])
392 {
393 m_action = eFileActionOpen;
394 m_fd = fd;
395 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000396 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000397 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000398 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000399 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000400 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000401 m_path.assign (path);
402 return true;
403 }
404 else
405 {
406 Clear();
407 }
408 return false;
409}
410
411bool
412ProcessLaunchInfo::FileAction::Close (int fd)
413{
414 Clear();
415 if (fd >= 0)
416 {
417 m_action = eFileActionClose;
418 m_fd = fd;
419 }
420 return m_fd >= 0;
421}
422
423
424bool
425ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
426{
427 Clear();
428 if (fd >= 0 && dup_fd >= 0)
429 {
430 m_action = eFileActionDuplicate;
431 m_fd = fd;
432 m_arg = dup_fd;
433 }
434 return m_fd >= 0;
435}
436
437
438
439bool
440ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
441 const FileAction *info,
442 Log *log,
443 Error& error)
444{
445 if (info == NULL)
446 return false;
447
448 switch (info->m_action)
449 {
450 case eFileActionNone:
451 error.Clear();
452 break;
453
454 case eFileActionClose:
455 if (info->m_fd == -1)
456 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
457 else
458 {
459 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
460 eErrorTypePOSIX);
461 if (log && (error.Fail() || log))
462 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
463 file_actions, info->m_fd);
464 }
465 break;
466
467 case eFileActionDuplicate:
468 if (info->m_fd == -1)
469 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
470 else if (info->m_arg == -1)
471 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
472 else
473 {
474 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
475 eErrorTypePOSIX);
476 if (log && (error.Fail() || log))
477 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
478 file_actions, info->m_fd, info->m_arg);
479 }
480 break;
481
482 case eFileActionOpen:
483 if (info->m_fd == -1)
484 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
485 else
486 {
487 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000488
Greg Clayton8b82f082011-04-12 05:54:46 +0000489 mode_t mode = 0;
490
Greg Clayton144f3a92011-11-15 03:53:30 +0000491 if (oflag & O_CREAT)
492 mode = 0640;
493
Greg Clayton8b82f082011-04-12 05:54:46 +0000494 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
495 info->m_fd,
496 info->m_path.c_str(),
497 oflag,
498 mode),
499 eErrorTypePOSIX);
500 if (error.Fail() || log)
501 error.PutToLog(log,
502 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
503 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
504 }
505 break;
506
507 default:
508 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
509 break;
510 }
511 return error.Success();
512}
513
514Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000515ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000516{
517 Error error;
518 char short_option = (char) m_getopt_table[option_idx].val;
519
520 switch (short_option)
521 {
522 case 's': // Stop at program entry point
523 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
524 break;
525
526 case 'e': // STDERR for read + write
527 {
528 ProcessLaunchInfo::FileAction action;
529 if (action.Open(STDERR_FILENO, option_arg, true, true))
530 launch_info.AppendFileAction (action);
531 }
532 break;
533
534 case 'i': // STDIN for read only
535 {
536 ProcessLaunchInfo::FileAction action;
537 if (action.Open(STDIN_FILENO, option_arg, true, false))
538 launch_info.AppendFileAction (action);
539 }
540 break;
541
542 case 'o': // Open STDOUT for write only
543 {
544 ProcessLaunchInfo::FileAction action;
545 if (action.Open(STDOUT_FILENO, option_arg, false, true))
546 launch_info.AppendFileAction (action);
547 }
548 break;
549
550 case 'p': // Process plug-in name
551 launch_info.SetProcessPluginName (option_arg);
552 break;
553
554 case 'n': // Disable STDIO
555 {
556 ProcessLaunchInfo::FileAction action;
557 if (action.Open(STDERR_FILENO, "/dev/null", true, true))
558 launch_info.AppendFileAction (action);
559 if (action.Open(STDOUT_FILENO, "/dev/null", false, true))
560 launch_info.AppendFileAction (action);
561 if (action.Open(STDIN_FILENO, "/dev/null", true, false))
562 launch_info.AppendFileAction (action);
563 }
564 break;
565
566 case 'w':
567 launch_info.SetWorkingDirectory (option_arg);
568 break;
569
570 case 't': // Open process in new terminal window
571 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
572 break;
573
574 case 'a':
575 launch_info.GetArchitecture().SetTriple (option_arg,
576 m_interpreter.GetPlatform(true).get());
577 break;
578
579 case 'A':
580 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
581 break;
582
Greg Clayton982c9762011-11-03 21:22:33 +0000583 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000584 if (option_arg && option_arg[0])
585 launch_info.SetShell (option_arg);
586 else
587 launch_info.SetShell ("/bin/bash");
Greg Clayton982c9762011-11-03 21:22:33 +0000588 break;
589
Greg Clayton8b82f082011-04-12 05:54:46 +0000590 case 'v':
591 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
592 break;
593
594 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000595 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000596 break;
597
598 }
599 return error;
600}
601
602OptionDefinition
603ProcessLaunchCommandOptions::g_option_table[] =
604{
605{ 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."},
606{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
607{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
608{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
609{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
610{ LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Greg Clayton144f3a92011-11-15 03:53:30 +0000611{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypePath, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000612
613{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
614{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
615{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
616
617{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
618
619{ 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."},
620
621{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
622};
623
624
625
626bool
627ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000628{
629 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
630 return true;
631 const char *match_name = m_match_info.GetName();
632 if (!match_name)
633 return true;
634
635 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
636}
637
638bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000639ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000640{
641 if (!NameMatches (proc_info.GetName()))
642 return false;
643
644 if (m_match_info.ProcessIDIsValid() &&
645 m_match_info.GetProcessID() != proc_info.GetProcessID())
646 return false;
647
648 if (m_match_info.ParentProcessIDIsValid() &&
649 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
650 return false;
651
Greg Clayton8b82f082011-04-12 05:54:46 +0000652 if (m_match_info.UserIDIsValid () &&
653 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000654 return false;
655
Greg Clayton8b82f082011-04-12 05:54:46 +0000656 if (m_match_info.GroupIDIsValid () &&
657 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000658 return false;
659
660 if (m_match_info.EffectiveUserIDIsValid () &&
661 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
662 return false;
663
664 if (m_match_info.EffectiveGroupIDIsValid () &&
665 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
666 return false;
667
668 if (m_match_info.GetArchitecture().IsValid() &&
669 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
670 return false;
671 return true;
672}
673
674bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000675ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000676{
677 if (m_name_match_type != eNameMatchIgnore)
678 return false;
679
680 if (m_match_info.ProcessIDIsValid())
681 return false;
682
683 if (m_match_info.ParentProcessIDIsValid())
684 return false;
685
Greg Clayton8b82f082011-04-12 05:54:46 +0000686 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000687 return false;
688
Greg Clayton8b82f082011-04-12 05:54:46 +0000689 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000690 return false;
691
692 if (m_match_info.EffectiveUserIDIsValid ())
693 return false;
694
695 if (m_match_info.EffectiveGroupIDIsValid ())
696 return false;
697
698 if (m_match_info.GetArchitecture().IsValid())
699 return false;
700
701 if (m_match_all_users)
702 return false;
703
704 return true;
705
706}
707
708void
Greg Clayton8b82f082011-04-12 05:54:46 +0000709ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000710{
711 m_match_info.Clear();
712 m_name_match_type = eNameMatchIgnore;
713 m_match_all_users = false;
714}
Greg Clayton58be07b2011-01-07 06:08:19 +0000715
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000716Process*
717Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
718{
719 ProcessCreateInstance create_callback = NULL;
720 if (plugin_name)
721 {
722 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
723 if (create_callback)
724 {
725 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000726 if (debugger_ap->CanDebug(target, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727 return debugger_ap.release();
728 }
729 }
730 else
731 {
Greg Claytonc982c762010-07-09 20:39:50 +0000732 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733 {
Greg Claytonc982c762010-07-09 20:39:50 +0000734 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000735 if (debugger_ap->CanDebug(target, false))
Greg Claytonc982c762010-07-09 20:39:50 +0000736 return debugger_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000737 }
738 }
739 return NULL;
740}
741
742
743//----------------------------------------------------------------------
744// Process constructor
745//----------------------------------------------------------------------
746Process::Process(Target &target, Listener &listener) :
747 UserID (LLDB_INVALID_PROCESS_ID),
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000748 Broadcaster ("lldb.process"),
Greg Claytondbe54502010-11-19 03:46:01 +0000749 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000751 m_public_state (eStateUnloaded),
752 m_private_state (eStateUnloaded),
753 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
754 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
755 m_private_state_listener ("lldb.process.internal_state_listener"),
756 m_private_state_control_wait(),
757 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000758 m_mod_id (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000759 m_thread_index_id (0),
760 m_exit_status (-1),
761 m_exit_string (),
762 m_thread_list (this),
763 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000764 m_image_tokens (),
765 m_listener (listener),
766 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000767 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000768 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000769 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000770 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000771 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000772 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000773 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000774 m_stderr_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000775 m_memory_cache (*this),
776 m_allocated_memory_cache (*this),
Jim Ingham8314c522011-09-15 21:36:42 +0000777 m_attached_to_process (false),
Sean Callanan90539452011-09-20 23:01:51 +0000778 m_next_event_action_ap(),
779 m_can_jit(eCanJITYes)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000780{
Caroline Tice1559a462010-09-27 00:30:10 +0000781 UpdateInstanceName();
782
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000783 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000784 if (log)
785 log->Printf ("%p Process::Process()", this);
786
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000787 SetEventName (eBroadcastBitStateChanged, "state-changed");
788 SetEventName (eBroadcastBitInterrupt, "interrupt");
789 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
790 SetEventName (eBroadcastBitSTDERR, "stderr-available");
791
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000792 listener.StartListeningForEvents (this,
793 eBroadcastBitStateChanged |
794 eBroadcastBitInterrupt |
795 eBroadcastBitSTDOUT |
796 eBroadcastBitSTDERR);
797
798 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
799 eBroadcastBitStateChanged);
800
801 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
802 eBroadcastInternalStateControlStop |
803 eBroadcastInternalStateControlPause |
804 eBroadcastInternalStateControlResume);
805}
806
807//----------------------------------------------------------------------
808// Destructor
809//----------------------------------------------------------------------
810Process::~Process()
811{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000812 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813 if (log)
814 log->Printf ("%p Process::~Process()", this);
815 StopPrivateStateThread();
816}
817
818void
819Process::Finalize()
820{
Greg Clayton1ed54f52011-10-01 00:45:15 +0000821 // Clear our broadcaster before we proceed with destroying
822 Broadcaster::Clear();
823
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000824 // Do any cleanup needed prior to being destructed... Subclasses
825 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000826
827 // We need to destroy the loader before the derived Process class gets destroyed
828 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000829 m_dyld_ap.reset();
830 m_os_ap.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000831}
832
833void
834Process::RegisterNotificationCallbacks (const Notifications& callbacks)
835{
836 m_notifications.push_back(callbacks);
837 if (callbacks.initialize != NULL)
838 callbacks.initialize (callbacks.baton, this);
839}
840
841bool
842Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
843{
844 std::vector<Notifications>::iterator pos, end = m_notifications.end();
845 for (pos = m_notifications.begin(); pos != end; ++pos)
846 {
847 if (pos->baton == callbacks.baton &&
848 pos->initialize == callbacks.initialize &&
849 pos->process_state_changed == callbacks.process_state_changed)
850 {
851 m_notifications.erase(pos);
852 return true;
853 }
854 }
855 return false;
856}
857
858void
859Process::SynchronouslyNotifyStateChanged (StateType state)
860{
861 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
862 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
863 {
864 if (notification_pos->process_state_changed)
865 notification_pos->process_state_changed (notification_pos->baton, this, state);
866 }
867}
868
869// FIXME: We need to do some work on events before the general Listener sees them.
870// For instance if we are continuing from a breakpoint, we need to ensure that we do
871// the little "insert real insn, step & stop" trick. But we can't do that when the
872// event is delivered by the broadcaster - since that is done on the thread that is
873// waiting for new events, so if we needed more than one event for our handling, we would
874// stall. So instead we do it when we fetch the event off of the queue.
875//
876
877StateType
878Process::GetNextEvent (EventSP &event_sp)
879{
880 StateType state = eStateInvalid;
881
882 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
883 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
884
885 return state;
886}
887
888
889StateType
890Process::WaitForProcessToStop (const TimeValue *timeout)
891{
Jim Ingham4b536182011-08-09 02:12:22 +0000892 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
893 // We have to actually check each event, and in the case of a stopped event check the restarted flag
894 // on the event.
895 EventSP event_sp;
896 StateType state = GetState();
897 // If we are exited or detached, we won't ever get back to any
898 // other valid state...
899 if (state == eStateDetached || state == eStateExited)
900 return state;
901
902 while (state != eStateInvalid)
903 {
904 state = WaitForStateChangedEvents (timeout, event_sp);
905 switch (state)
906 {
907 case eStateCrashed:
908 case eStateDetached:
909 case eStateExited:
910 case eStateUnloaded:
911 return state;
912 case eStateStopped:
913 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
914 continue;
915 else
916 return state;
917 default:
918 continue;
919 }
920 }
921 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000922}
923
924
925StateType
926Process::WaitForState
927(
928 const TimeValue *timeout,
929 const StateType *match_states, const uint32_t num_match_states
930)
931{
932 EventSP event_sp;
933 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000934 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000935 while (state != eStateInvalid)
936 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000937 // If we are exited or detached, we won't ever get back to any
938 // other valid state...
939 if (state == eStateDetached || state == eStateExited)
940 return state;
941
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000942 state = WaitForStateChangedEvents (timeout, event_sp);
943
944 for (i=0; i<num_match_states; ++i)
945 {
946 if (match_states[i] == state)
947 return state;
948 }
949 }
950 return state;
951}
952
Jim Ingham30f9b212010-10-11 23:53:14 +0000953bool
954Process::HijackProcessEvents (Listener *listener)
955{
956 if (listener != NULL)
957 {
958 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
959 }
960 else
961 return false;
962}
963
964void
965Process::RestoreProcessEvents ()
966{
967 RestoreBroadcaster();
968}
969
Jim Ingham0f16e732011-02-08 05:20:59 +0000970bool
971Process::HijackPrivateProcessEvents (Listener *listener)
972{
973 if (listener != NULL)
974 {
975 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
976 }
977 else
978 return false;
979}
980
981void
982Process::RestorePrivateProcessEvents ()
983{
984 m_private_state_broadcaster.RestoreBroadcaster();
985}
986
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000987StateType
988Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
989{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000990 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000991
992 if (log)
993 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
994
995 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000996 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
997 this,
998 eBroadcastBitStateChanged,
999 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001000 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1001
1002 if (log)
1003 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1004 __FUNCTION__,
1005 timeout,
1006 StateAsCString(state));
1007 return state;
1008}
1009
1010Event *
1011Process::PeekAtStateChangedEvents ()
1012{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001013 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001014
1015 if (log)
1016 log->Printf ("Process::%s...", __FUNCTION__);
1017
1018 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001019 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1020 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001021 if (log)
1022 {
1023 if (event_ptr)
1024 {
1025 log->Printf ("Process::%s (event_ptr) => %s",
1026 __FUNCTION__,
1027 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1028 }
1029 else
1030 {
1031 log->Printf ("Process::%s no events found",
1032 __FUNCTION__);
1033 }
1034 }
1035 return event_ptr;
1036}
1037
1038StateType
1039Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1040{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001041 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001042
1043 if (log)
1044 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1045
1046 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001047 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1048 &m_private_state_broadcaster,
1049 eBroadcastBitStateChanged,
1050 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1052
1053 // This is a bit of a hack, but when we wait here we could very well return
1054 // to the command-line, and that could disable the log, which would render the
1055 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001056 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001057 {
1058 if (state == eStateInvalid)
1059 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1060 else
1061 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1062 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001063 return state;
1064}
1065
1066bool
1067Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1068{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001069 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070
1071 if (log)
1072 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1073
1074 if (control_only)
1075 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1076 else
1077 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1078}
1079
1080bool
1081Process::IsRunning () const
1082{
1083 return StateIsRunningState (m_public_state.GetValue());
1084}
1085
1086int
1087Process::GetExitStatus ()
1088{
1089 if (m_public_state.GetValue() == eStateExited)
1090 return m_exit_status;
1091 return -1;
1092}
1093
Greg Clayton85851dd2010-12-04 00:10:17 +00001094
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001095const char *
1096Process::GetExitDescription ()
1097{
1098 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1099 return m_exit_string.c_str();
1100 return NULL;
1101}
1102
Greg Clayton6779606a2011-01-22 23:43:18 +00001103bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104Process::SetExitStatus (int status, const char *cstr)
1105{
Greg Clayton414f5d32011-01-25 02:58:48 +00001106 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1107 if (log)
1108 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1109 status, status,
1110 cstr ? "\"" : "",
1111 cstr ? cstr : "NULL",
1112 cstr ? "\"" : "");
1113
Greg Clayton6779606a2011-01-22 23:43:18 +00001114 // We were already in the exited state
1115 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001116 {
Greg Clayton385d6032011-01-26 23:47:29 +00001117 if (log)
1118 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001119 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001120 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001121
1122 m_exit_status = status;
1123 if (cstr)
1124 m_exit_string = cstr;
1125 else
1126 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001127
Greg Clayton6779606a2011-01-22 23:43:18 +00001128 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001129
Greg Clayton6779606a2011-01-22 23:43:18 +00001130 SetPrivateState (eStateExited);
1131 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001132}
1133
1134// This static callback can be used to watch for local child processes on
1135// the current host. The the child process exits, the process will be
1136// found in the global target list (we want to be completely sure that the
1137// lldb_private::Process doesn't go away before we can deliver the signal.
1138bool
1139Process::SetProcessExitStatus
1140(
1141 void *callback_baton,
1142 lldb::pid_t pid,
1143 int signo, // Zero for no signal
1144 int exit_status // Exit value of process if signal is zero
1145)
1146{
1147 if (signo == 0 || exit_status)
1148 {
Greg Clayton66111032010-06-23 01:19:29 +00001149 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150 if (target_sp)
1151 {
1152 ProcessSP process_sp (target_sp->GetProcessSP());
1153 if (process_sp)
1154 {
1155 const char *signal_cstr = NULL;
1156 if (signo)
1157 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1158
1159 process_sp->SetExitStatus (exit_status, signal_cstr);
1160 }
1161 }
1162 return true;
1163 }
1164 return false;
1165}
1166
1167
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001168void
1169Process::UpdateThreadListIfNeeded ()
1170{
1171 const uint32_t stop_id = GetStopID();
1172 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1173 {
1174 Mutex::Locker locker (m_thread_list.GetMutex ());
1175 ThreadList new_thread_list(this);
1176 // Always update the thread list with the protocol specific
1177 // thread list
1178 UpdateThreadList (m_thread_list, new_thread_list);
1179 OperatingSystem *os = GetOperatingSystem ();
1180 if (os)
1181 os->UpdateThreadList (m_thread_list, new_thread_list);
1182 m_thread_list.Update (new_thread_list);
1183 m_thread_list.SetStopID (stop_id);
1184 }
1185}
1186
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001187uint32_t
1188Process::GetNextThreadIndexID ()
1189{
1190 return ++m_thread_index_id;
1191}
1192
1193StateType
1194Process::GetState()
1195{
1196 // If any other threads access this we will need a mutex for it
1197 return m_public_state.GetValue ();
1198}
1199
1200void
1201Process::SetPublicState (StateType new_state)
1202{
Greg Clayton414f5d32011-01-25 02:58:48 +00001203 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001204 if (log)
1205 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1206 m_public_state.SetValue (new_state);
1207}
1208
1209StateType
1210Process::GetPrivateState ()
1211{
1212 return m_private_state.GetValue();
1213}
1214
1215void
1216Process::SetPrivateState (StateType new_state)
1217{
Greg Clayton414f5d32011-01-25 02:58:48 +00001218 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001219 bool state_changed = false;
1220
1221 if (log)
1222 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1223
1224 Mutex::Locker locker(m_private_state.GetMutex());
1225
1226 const StateType old_state = m_private_state.GetValueNoLock ();
1227 state_changed = old_state != new_state;
1228 if (state_changed)
1229 {
1230 m_private_state.SetValueNoLock (new_state);
1231 if (StateIsStoppedState(new_state))
1232 {
Jim Ingham4b536182011-08-09 02:12:22 +00001233 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001234 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001235 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001236 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001237 }
1238 // Use our target to get a shared pointer to ourselves...
1239 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1240 }
1241 else
1242 {
1243 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001244 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001245 }
1246}
1247
Jim Ingham0faa43f2011-11-08 03:00:11 +00001248void
1249Process::SetRunningUserExpression (bool on)
1250{
1251 m_mod_id.SetRunningUserExpression (on);
1252}
1253
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001254addr_t
1255Process::GetImageInfoAddress()
1256{
1257 return LLDB_INVALID_ADDRESS;
1258}
1259
Greg Clayton8f343b02010-11-04 01:54:29 +00001260//----------------------------------------------------------------------
1261// LoadImage
1262//
1263// This function provides a default implementation that works for most
1264// unix variants. Any Process subclasses that need to do shared library
1265// loading differently should override LoadImage and UnloadImage and
1266// do what is needed.
1267//----------------------------------------------------------------------
1268uint32_t
1269Process::LoadImage (const FileSpec &image_spec, Error &error)
1270{
1271 DynamicLoader *loader = GetDynamicLoader();
1272 if (loader)
1273 {
1274 error = loader->CanLoadImage();
1275 if (error.Fail())
1276 return LLDB_INVALID_IMAGE_TOKEN;
1277 }
1278
1279 if (error.Success())
1280 {
1281 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001282
1283 if (thread_sp)
1284 {
1285 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1286
1287 if (frame_sp)
1288 {
1289 ExecutionContext exe_ctx;
1290 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001291 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001292 StreamString expr;
1293 char path[PATH_MAX];
1294 image_spec.GetPath(path, sizeof(path));
1295 expr.Printf("dlopen (\"%s\", 2)", path);
1296 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001297 lldb::ValueObjectSP result_valobj_sp;
Sean Callananc7b65062011-11-07 23:35:40 +00001298 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chene92aa432011-09-09 00:01:43 +00001299 error = result_valobj_sp->GetError();
1300 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001301 {
1302 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001303 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001304 {
1305 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1306 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1307 {
1308 uint32_t image_token = m_image_tokens.size();
1309 m_image_tokens.push_back (image_ptr);
1310 return image_token;
1311 }
1312 }
1313 }
1314 }
1315 }
1316 }
1317 return LLDB_INVALID_IMAGE_TOKEN;
1318}
1319
1320//----------------------------------------------------------------------
1321// UnloadImage
1322//
1323// This function provides a default implementation that works for most
1324// unix variants. Any Process subclasses that need to do shared library
1325// loading differently should override LoadImage and UnloadImage and
1326// do what is needed.
1327//----------------------------------------------------------------------
1328Error
1329Process::UnloadImage (uint32_t image_token)
1330{
1331 Error error;
1332 if (image_token < m_image_tokens.size())
1333 {
1334 const addr_t image_addr = m_image_tokens[image_token];
1335 if (image_addr == LLDB_INVALID_ADDRESS)
1336 {
1337 error.SetErrorString("image already unloaded");
1338 }
1339 else
1340 {
1341 DynamicLoader *loader = GetDynamicLoader();
1342 if (loader)
1343 error = loader->CanLoadImage();
1344
1345 if (error.Success())
1346 {
1347 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001348
1349 if (thread_sp)
1350 {
1351 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1352
1353 if (frame_sp)
1354 {
1355 ExecutionContext exe_ctx;
1356 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001357 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001358 StreamString expr;
1359 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1360 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001361 lldb::ValueObjectSP result_valobj_sp;
Sean Callananc7b65062011-11-07 23:35:40 +00001362 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +00001363 if (result_valobj_sp->GetError().Success())
1364 {
1365 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001366 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001367 {
1368 if (scalar.UInt(1))
1369 {
1370 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1371 }
1372 else
1373 {
1374 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1375 }
1376 }
1377 }
1378 else
1379 {
1380 error = result_valobj_sp->GetError();
1381 }
1382 }
1383 }
1384 }
1385 }
1386 }
1387 else
1388 {
1389 error.SetErrorString("invalid image token");
1390 }
1391 return error;
1392}
1393
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001394const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001395Process::GetABI()
1396{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001397 if (!m_abi_sp)
1398 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1399 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400}
1401
Jim Ingham22777012010-09-23 02:01:19 +00001402LanguageRuntime *
1403Process::GetLanguageRuntime(lldb::LanguageType language)
1404{
1405 LanguageRuntimeCollection::iterator pos;
1406 pos = m_language_runtimes.find (language);
1407 if (pos == m_language_runtimes.end())
1408 {
1409 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1410
1411 m_language_runtimes[language]
1412 = runtime;
1413 return runtime.get();
1414 }
1415 else
1416 return (*pos).second.get();
1417}
1418
1419CPPLanguageRuntime *
1420Process::GetCPPLanguageRuntime ()
1421{
1422 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1423 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1424 return static_cast<CPPLanguageRuntime *> (runtime);
1425 return NULL;
1426}
1427
1428ObjCLanguageRuntime *
1429Process::GetObjCLanguageRuntime ()
1430{
1431 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1432 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1433 return static_cast<ObjCLanguageRuntime *> (runtime);
1434 return NULL;
1435}
1436
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001437BreakpointSiteList &
1438Process::GetBreakpointSiteList()
1439{
1440 return m_breakpoint_site_list;
1441}
1442
1443const BreakpointSiteList &
1444Process::GetBreakpointSiteList() const
1445{
1446 return m_breakpoint_site_list;
1447}
1448
1449
1450void
1451Process::DisableAllBreakpointSites ()
1452{
1453 m_breakpoint_site_list.SetEnabledForAll (false);
1454}
1455
1456Error
1457Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1458{
1459 Error error (DisableBreakpointSiteByID (break_id));
1460
1461 if (error.Success())
1462 m_breakpoint_site_list.Remove(break_id);
1463
1464 return error;
1465}
1466
1467Error
1468Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1469{
1470 Error error;
1471 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1472 if (bp_site_sp)
1473 {
1474 if (bp_site_sp->IsEnabled())
1475 error = DisableBreakpoint (bp_site_sp.get());
1476 }
1477 else
1478 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001479 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001480 }
1481
1482 return error;
1483}
1484
1485Error
1486Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1487{
1488 Error error;
1489 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1490 if (bp_site_sp)
1491 {
1492 if (!bp_site_sp->IsEnabled())
1493 error = EnableBreakpoint (bp_site_sp.get());
1494 }
1495 else
1496 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001497 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498 }
1499 return error;
1500}
1501
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001502lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001503Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1504{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001505 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001506 if (load_addr != LLDB_INVALID_ADDRESS)
1507 {
1508 BreakpointSiteSP bp_site_sp;
1509
1510 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1511 // create a new breakpoint site and add it.
1512
1513 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1514
1515 if (bp_site_sp)
1516 {
1517 bp_site_sp->AddOwner (owner);
1518 owner->SetBreakpointSite (bp_site_sp);
1519 return bp_site_sp->GetID();
1520 }
1521 else
1522 {
1523 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1524 if (bp_site_sp)
1525 {
1526 if (EnableBreakpoint (bp_site_sp.get()).Success())
1527 {
1528 owner->SetBreakpointSite (bp_site_sp);
1529 return m_breakpoint_site_list.Add (bp_site_sp);
1530 }
1531 }
1532 }
1533 }
1534 // We failed to enable the breakpoint
1535 return LLDB_INVALID_BREAK_ID;
1536
1537}
1538
1539void
1540Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1541{
1542 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1543 if (num_owners == 0)
1544 {
1545 DisableBreakpoint(bp_site_sp.get());
1546 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1547 }
1548}
1549
1550
1551size_t
1552Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1553{
1554 size_t bytes_removed = 0;
1555 addr_t intersect_addr;
1556 size_t intersect_size;
1557 size_t opcode_offset;
1558 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001559 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001560 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001561
Jim Ingham20c77192011-06-29 19:42:28 +00001562 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001563 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001564 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001565 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001566 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001567 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001568 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001569 {
1570 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1571 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001572 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001573 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001574 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001575 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001576 }
1577 }
1578 }
1579 return bytes_removed;
1580}
1581
1582
Greg Claytonded470d2011-03-19 01:12:21 +00001583
1584size_t
1585Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1586{
1587 PlatformSP platform_sp (m_target.GetPlatform());
1588 if (platform_sp)
1589 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1590 return 0;
1591}
1592
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001593Error
1594Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1595{
1596 Error error;
1597 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001598 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001599 const addr_t bp_addr = bp_site->GetLoadAddress();
1600 if (log)
1601 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1602 if (bp_site->IsEnabled())
1603 {
1604 if (log)
1605 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1606 return error;
1607 }
1608
1609 if (bp_addr == LLDB_INVALID_ADDRESS)
1610 {
1611 error.SetErrorString("BreakpointSite contains an invalid load address.");
1612 return error;
1613 }
1614 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1615 // trap for the breakpoint site
1616 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1617
1618 if (bp_opcode_size == 0)
1619 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001620 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001621 }
1622 else
1623 {
1624 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1625
1626 if (bp_opcode_bytes == NULL)
1627 {
1628 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1629 return error;
1630 }
1631
1632 // Save the original opcode by reading it
1633 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1634 {
1635 // Write a software breakpoint in place of the original opcode
1636 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1637 {
1638 uint8_t verify_bp_opcode_bytes[64];
1639 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1640 {
1641 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1642 {
1643 bp_site->SetEnabled(true);
1644 bp_site->SetType (BreakpointSite::eSoftware);
1645 if (log)
1646 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1647 bp_site->GetID(),
1648 (uint64_t)bp_addr);
1649 }
1650 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001651 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001652 }
1653 else
1654 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1655 }
1656 else
1657 error.SetErrorString("Unable to write breakpoint trap to memory.");
1658 }
1659 else
1660 error.SetErrorString("Unable to read memory at breakpoint address.");
1661 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001662 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001663 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1664 bp_site->GetID(),
1665 (uint64_t)bp_addr,
1666 error.AsCString());
1667 return error;
1668}
1669
1670Error
1671Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1672{
1673 Error error;
1674 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001675 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001676 addr_t bp_addr = bp_site->GetLoadAddress();
1677 lldb::user_id_t breakID = bp_site->GetID();
1678 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001679 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001680
1681 if (bp_site->IsHardware())
1682 {
1683 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1684 }
1685 else if (bp_site->IsEnabled())
1686 {
1687 const size_t break_op_size = bp_site->GetByteSize();
1688 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1689 if (break_op_size > 0)
1690 {
1691 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001692 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001693 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001694 bool break_op_found = false;
1695
1696 // Read the breakpoint opcode
1697 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1698 {
1699 bool verify = false;
1700 // Make sure we have the a breakpoint opcode exists at this address
1701 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1702 {
1703 break_op_found = true;
1704 // We found a valid breakpoint opcode at this address, now restore
1705 // the saved opcode.
1706 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1707 {
1708 verify = true;
1709 }
1710 else
1711 error.SetErrorString("Memory write failed when restoring original opcode.");
1712 }
1713 else
1714 {
1715 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1716 // Set verify to true and so we can check if the original opcode has already been restored
1717 verify = true;
1718 }
1719
1720 if (verify)
1721 {
Greg Claytonc982c762010-07-09 20:39:50 +00001722 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001723 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001724 // Verify that our original opcode made it back to the inferior
1725 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1726 {
1727 // compare the memory we just read with the original opcode
1728 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1729 {
1730 // SUCCESS
1731 bp_site->SetEnabled(false);
1732 if (log)
1733 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1734 return error;
1735 }
1736 else
1737 {
1738 if (break_op_found)
1739 error.SetErrorString("Failed to restore original opcode.");
1740 }
1741 }
1742 else
1743 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1744 }
1745 }
1746 else
1747 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1748 }
1749 }
1750 else
1751 {
1752 if (log)
1753 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1754 return error;
1755 }
1756
1757 if (log)
1758 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1759 bp_site->GetID(),
1760 (uint64_t)bp_addr,
1761 error.AsCString());
1762 return error;
1763
1764}
1765
Greg Clayton58be07b2011-01-07 06:08:19 +00001766// Comment out line below to disable memory caching
1767#define ENABLE_MEMORY_CACHING
1768// Uncomment to verify memory caching works after making changes to caching code
1769//#define VERIFY_MEMORY_READS
1770
1771#if defined (ENABLE_MEMORY_CACHING)
1772
1773#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001774
1775size_t
1776Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1777{
Greg Clayton58be07b2011-01-07 06:08:19 +00001778 // Memory caching is enabled, with debug verification
1779 if (buf && size)
1780 {
1781 // Uncomment the line below to make sure memory caching is working.
1782 // I ran this through the test suite and got no assertions, so I am
1783 // pretty confident this is working well. If any changes are made to
1784 // memory caching, uncomment the line below and test your changes!
1785
1786 // Verify all memory reads by using the cache first, then redundantly
1787 // reading the same memory from the inferior and comparing to make sure
1788 // everything is exactly the same.
1789 std::string verify_buf (size, '\0');
1790 assert (verify_buf.size() == size);
1791 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1792 Error verify_error;
1793 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1794 assert (cache_bytes_read == verify_bytes_read);
1795 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1796 assert (verify_error.Success() == error.Success());
1797 return cache_bytes_read;
1798 }
1799 return 0;
1800}
1801
1802#else // #if defined (VERIFY_MEMORY_READS)
1803
1804size_t
1805Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1806{
1807 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001808 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001809}
1810
1811#endif // #else for #if defined (VERIFY_MEMORY_READS)
1812
1813#else // #if defined (ENABLE_MEMORY_CACHING)
1814
1815size_t
1816Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1817{
1818 // Memory caching is disabled
1819 return ReadMemoryFromInferior (addr, buf, size, error);
1820}
1821
1822#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1823
1824
1825size_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001826Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1827{
1828 size_t total_cstr_len = 0;
1829 if (dst && dst_max_len)
1830 {
1831 // NULL out everything just to be safe
1832 memset (dst, 0, dst_max_len);
1833 Error error;
1834 addr_t curr_addr = addr;
1835 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1836 size_t bytes_left = dst_max_len - 1;
1837 char *curr_dst = dst;
1838
1839 while (bytes_left > 0)
1840 {
1841 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1842 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1843 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1844
1845 if (bytes_read == 0)
1846 {
1847 dst[total_cstr_len] = '\0';
1848 break;
1849 }
1850 const size_t len = strlen(curr_dst);
1851
1852 total_cstr_len += len;
1853
1854 if (len < bytes_to_read)
1855 break;
1856
1857 curr_dst += bytes_read;
1858 curr_addr += bytes_read;
1859 bytes_left -= bytes_read;
1860 }
1861 }
1862 return total_cstr_len;
1863}
1864
1865size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00001866Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1867{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001868 if (buf == NULL || size == 0)
1869 return 0;
1870
1871 size_t bytes_read = 0;
1872 uint8_t *bytes = (uint8_t *)buf;
1873
1874 while (bytes_read < size)
1875 {
1876 const size_t curr_size = size - bytes_read;
1877 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1878 bytes + bytes_read,
1879 curr_size,
1880 error);
1881 bytes_read += curr_bytes_read;
1882 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1883 break;
1884 }
1885
1886 // Replace any software breakpoint opcodes that fall into this range back
1887 // into "buf" before we return
1888 if (bytes_read > 0)
1889 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1890 return bytes_read;
1891}
1892
Greg Clayton58a4c462010-12-16 20:01:20 +00001893uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001894Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00001895{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001896 Scalar scalar;
1897 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1898 return scalar.ULongLong(fail_value);
1899 return fail_value;
1900}
1901
1902addr_t
1903Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1904{
1905 Scalar scalar;
1906 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1907 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1908 return LLDB_INVALID_ADDRESS;
1909}
1910
1911
1912bool
1913Process::WritePointerToMemory (lldb::addr_t vm_addr,
1914 lldb::addr_t ptr_value,
1915 Error &error)
1916{
1917 Scalar scalar;
1918 const uint32_t addr_byte_size = GetAddressByteSize();
1919 if (addr_byte_size <= 4)
1920 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00001921 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001922 scalar = ptr_value;
1923 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00001924}
1925
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001926size_t
1927Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1928{
1929 size_t bytes_written = 0;
1930 const uint8_t *bytes = (const uint8_t *)buf;
1931
1932 while (bytes_written < size)
1933 {
1934 const size_t curr_size = size - bytes_written;
1935 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1936 bytes + bytes_written,
1937 curr_size,
1938 error);
1939 bytes_written += curr_bytes_written;
1940 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1941 break;
1942 }
1943 return bytes_written;
1944}
1945
1946size_t
1947Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1948{
Greg Clayton58be07b2011-01-07 06:08:19 +00001949#if defined (ENABLE_MEMORY_CACHING)
1950 m_memory_cache.Flush (addr, size);
1951#endif
1952
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001953 if (buf == NULL || size == 0)
1954 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00001955
Jim Ingham4b536182011-08-09 02:12:22 +00001956 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00001957
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001958 // We need to write any data that would go where any current software traps
1959 // (enabled software breakpoints) any software traps (breakpoints) that we
1960 // may have placed in our tasks memory.
1961
1962 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1963 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1964
1965 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00001966 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001967
1968 BreakpointSiteList::collection::const_iterator pos;
1969 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001970 addr_t intersect_addr = 0;
1971 size_t intersect_size = 0;
1972 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001973 const uint8_t *ubuf = (const uint8_t *)buf;
1974
1975 for (pos = iter; pos != end; ++pos)
1976 {
1977 BreakpointSiteSP bp;
1978 bp = pos->second;
1979
1980 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1981 assert(addr <= intersect_addr && intersect_addr < addr + size);
1982 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1983 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1984
1985 // Check for bytes before this breakpoint
1986 const addr_t curr_addr = addr + bytes_written;
1987 if (intersect_addr > curr_addr)
1988 {
1989 // There are some bytes before this breakpoint that we need to
1990 // just write to memory
1991 size_t curr_size = intersect_addr - curr_addr;
1992 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1993 ubuf + bytes_written,
1994 curr_size,
1995 error);
1996 bytes_written += curr_bytes_written;
1997 if (curr_bytes_written != curr_size)
1998 {
1999 // We weren't able to write all of the requested bytes, we
2000 // are done looping and will return the number of bytes that
2001 // we have written so far.
2002 break;
2003 }
2004 }
2005
2006 // Now write any bytes that would cover up any software breakpoints
2007 // directly into the breakpoint opcode buffer
2008 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2009 bytes_written += intersect_size;
2010 }
2011
2012 // Write any remaining bytes after the last breakpoint if we have any left
2013 if (bytes_written < size)
2014 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2015 ubuf + bytes_written,
2016 size - bytes_written,
2017 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002018
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002019 return bytes_written;
2020}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002021
2022size_t
2023Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2024{
2025 if (byte_size == UINT32_MAX)
2026 byte_size = scalar.GetByteSize();
2027 if (byte_size > 0)
2028 {
2029 uint8_t buf[32];
2030 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2031 if (mem_size > 0)
2032 return WriteMemory(addr, buf, mem_size, error);
2033 else
2034 error.SetErrorString ("failed to get scalar as memory data");
2035 }
2036 else
2037 {
2038 error.SetErrorString ("invalid scalar value");
2039 }
2040 return 0;
2041}
2042
2043size_t
2044Process::ReadScalarIntegerFromMemory (addr_t addr,
2045 uint32_t byte_size,
2046 bool is_signed,
2047 Scalar &scalar,
2048 Error &error)
2049{
2050 uint64_t uval;
2051
2052 if (byte_size <= sizeof(uval))
2053 {
2054 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2055 if (bytes_read == byte_size)
2056 {
2057 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2058 uint32_t offset = 0;
2059 if (byte_size <= 4)
2060 scalar = data.GetMaxU32 (&offset, byte_size);
2061 else
2062 scalar = data.GetMaxU64 (&offset, byte_size);
2063
2064 if (is_signed)
2065 scalar.SignExtend(byte_size * 8);
2066 return bytes_read;
2067 }
2068 }
2069 else
2070 {
2071 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2072 }
2073 return 0;
2074}
2075
Greg Claytond495c532011-05-17 03:37:42 +00002076#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002077addr_t
2078Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2079{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002080 if (GetPrivateState() != eStateStopped)
2081 return LLDB_INVALID_ADDRESS;
2082
Greg Claytond495c532011-05-17 03:37:42 +00002083#if defined (USE_ALLOCATE_MEMORY_CACHE)
2084 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2085#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002086 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2087 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2088 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002089 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002090 size,
Greg Claytond495c532011-05-17 03:37:42 +00002091 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002092 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002093 m_mod_id.GetStopID(),
2094 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002095 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002096#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002097}
2098
Sean Callanan90539452011-09-20 23:01:51 +00002099bool
2100Process::CanJIT ()
2101{
2102 return m_can_jit == eCanJITYes;
2103}
2104
2105void
2106Process::SetCanJIT (bool can_jit)
2107{
2108 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2109}
2110
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111Error
2112Process::DeallocateMemory (addr_t ptr)
2113{
Greg Claytond495c532011-05-17 03:37:42 +00002114 Error error;
2115#if defined (USE_ALLOCATE_MEMORY_CACHE)
2116 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2117 {
2118 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2119 }
2120#else
2121 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002122
2123 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2124 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002125 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002126 ptr,
2127 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002128 m_mod_id.GetStopID(),
2129 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002130#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002131 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002132}
2133
2134
2135Error
Johnny Chen01a67862011-10-14 00:42:25 +00002136Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002137{
2138 Error error;
2139 error.SetErrorString("watchpoints are not supported");
2140 return error;
2141}
2142
2143Error
Johnny Chen01a67862011-10-14 00:42:25 +00002144Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145{
2146 Error error;
2147 error.SetErrorString("watchpoints are not supported");
2148 return error;
2149}
2150
2151StateType
2152Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2153{
2154 StateType state;
2155 // Now wait for the process to launch and return control to us, and then
2156 // call DidLaunch:
2157 while (1)
2158 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002159 event_sp.reset();
2160 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2161
2162 if (StateIsStoppedState(state))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002163 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002164
2165 // If state is invalid, then we timed out
2166 if (state == eStateInvalid)
2167 break;
2168
2169 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002170 HandlePrivateEvent (event_sp);
2171 }
2172 return state;
2173}
2174
2175Error
Greg Clayton982c9762011-11-03 21:22:33 +00002176Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002177{
2178 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002179 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002180 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002181 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002182 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002183
Greg Claytonaa149cb2011-08-11 02:48:45 +00002184 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002185 if (exe_module)
2186 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002187 char local_exec_file_path[PATH_MAX];
2188 char platform_exec_file_path[PATH_MAX];
2189 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2190 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002191 if (exe_module->GetFileSpec().Exists())
2192 {
Greg Clayton71337622011-02-24 22:24:29 +00002193 if (PrivateStateThreadIsValid ())
2194 PausePrivateStateThread ();
2195
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002196 error = WillLaunch (exe_module);
2197 if (error.Success())
2198 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002199 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002200
2201 // Now launch using these arguments.
Greg Clayton982c9762011-11-03 21:22:33 +00002202 error = DoLaunch (exe_module, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002203
2204 if (error.Fail())
2205 {
2206 if (GetID() != LLDB_INVALID_PROCESS_ID)
2207 {
2208 SetID (LLDB_INVALID_PROCESS_ID);
2209 const char *error_string = error.AsCString();
2210 if (error_string == NULL)
2211 error_string = "launch failed";
2212 SetExitStatus (-1, error_string);
2213 }
2214 }
2215 else
2216 {
2217 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002218 TimeValue timeout_time;
2219 timeout_time = TimeValue::Now();
2220 timeout_time.OffsetWithSeconds(10);
2221 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002222
Greg Clayton1a38ea72011-06-22 01:42:17 +00002223 if (state == eStateInvalid || event_sp.get() == NULL)
2224 {
2225 // We were able to launch the process, but we failed to
2226 // catch the initial stop.
2227 SetExitStatus (0, "failed to catch stop after launch");
2228 Destroy();
2229 }
2230 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002231 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002232
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002233 DidLaunch ();
2234
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002235 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002236 if (m_dyld_ap.get())
2237 m_dyld_ap->DidLaunch();
2238
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002239 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002240 // This delays passing the stopped event to listeners till DidLaunch gets
2241 // a chance to complete...
2242 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002243
2244 if (PrivateStateThreadIsValid ())
2245 ResumePrivateStateThread ();
2246 else
2247 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002248 }
2249 else if (state == eStateExited)
2250 {
2251 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2252 // not likely to work, and return an invalid pid.
2253 HandlePrivateEvent (event_sp);
2254 }
2255 }
2256 }
2257 }
2258 else
2259 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002260 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002261 }
2262 }
2263 return error;
2264}
2265
Jim Inghambb3a2832011-01-29 01:49:25 +00002266Process::NextEventAction::EventActionResult
2267Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268{
Jim Inghambb3a2832011-01-29 01:49:25 +00002269 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2270 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002271 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002272 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002273 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002274 return eEventActionRetry;
2275
2276 case eStateStopped:
2277 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002278 {
2279 // During attach, prior to sending the eStateStopped event,
2280 // lldb_private::Process subclasses must set the process must set
2281 // the new process ID.
2282 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2283 if (m_exec_count > 0)
2284 {
2285 --m_exec_count;
2286 m_process->Resume();
2287 return eEventActionRetry;
2288 }
2289 else
2290 {
2291 m_process->CompleteAttach ();
2292 return eEventActionSuccess;
2293 }
2294 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002295 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002296
Greg Clayton513c26c2011-01-29 07:10:55 +00002297 default:
2298 case eStateExited:
2299 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002300 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002301 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002302
2303 m_exit_string.assign ("No valid Process");
2304 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002305}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002306
Jim Inghambb3a2832011-01-29 01:49:25 +00002307Process::NextEventAction::EventActionResult
2308Process::AttachCompletionHandler::HandleBeingInterrupted()
2309{
2310 return eEventActionSuccess;
2311}
2312
2313const char *
2314Process::AttachCompletionHandler::GetExitString ()
2315{
2316 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002317}
2318
2319Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002320Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002322 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002323 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002324 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002325 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002326
Greg Clayton144f3a92011-11-15 03:53:30 +00002327 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002328 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002329 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002330 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002331 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002332
Greg Clayton144f3a92011-11-15 03:53:30 +00002333 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002334 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002335 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2336
2337 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002338 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002339 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2340 if (error.Success())
2341 {
2342 SetPublicState (eStateAttaching);
2343 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2344 if (error.Fail())
2345 {
2346 if (GetID() != LLDB_INVALID_PROCESS_ID)
2347 {
2348 SetID (LLDB_INVALID_PROCESS_ID);
2349 if (error.AsCString() == NULL)
2350 error.SetErrorString("attach failed");
2351
2352 SetExitStatus(-1, error.AsCString());
2353 }
2354 }
2355 else
2356 {
2357 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2358 StartPrivateStateThread();
2359 }
2360 return error;
2361 }
Greg Claytone996fd32011-03-08 22:40:15 +00002362 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002363 else
Greg Claytone996fd32011-03-08 22:40:15 +00002364 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002365 ProcessInstanceInfoList process_infos;
2366 PlatformSP platform_sp (m_target.GetPlatform ());
2367
2368 if (platform_sp)
2369 {
2370 ProcessInstanceInfoMatch match_info;
2371 match_info.GetProcessInfo() = attach_info;
2372 match_info.SetNameMatchType (eNameMatchEquals);
2373 platform_sp->FindProcesses (match_info, process_infos);
2374 const uint32_t num_matches = process_infos.GetSize();
2375 if (num_matches == 1)
2376 {
2377 attach_pid = process_infos.GetProcessIDAtIndex(0);
2378 // Fall through and attach using the above process ID
2379 }
2380 else
2381 {
2382 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2383 if (num_matches > 1)
2384 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2385 else
2386 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2387 }
2388 }
2389 else
2390 {
2391 error.SetErrorString ("invalid platform, can't find processes by name");
2392 return error;
2393 }
Greg Claytone996fd32011-03-08 22:40:15 +00002394 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002395 }
2396 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002397 {
2398 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002399 }
2400 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002401
2402 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002403 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002404 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002405 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406 {
Greg Claytone996fd32011-03-08 22:40:15 +00002407 SetPublicState (eStateAttaching);
Greg Clayton144f3a92011-11-15 03:53:30 +00002408
2409 error = DoAttachToProcessWithID (attach_pid);
2410 if (error.Success())
2411 {
2412
2413 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2414 StartPrivateStateThread();
2415 }
2416 else
Greg Claytone996fd32011-03-08 22:40:15 +00002417 {
2418 if (GetID() != LLDB_INVALID_PROCESS_ID)
2419 {
2420 SetID (LLDB_INVALID_PROCESS_ID);
2421 const char *error_string = error.AsCString();
2422 if (error_string == NULL)
2423 error_string = "attach failed";
2424
2425 SetExitStatus(-1, error_string);
2426 }
2427 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 }
2429 }
2430 return error;
2431}
2432
Greg Clayton144f3a92011-11-15 03:53:30 +00002433//Error
2434//Process::Attach (const char *process_name, bool wait_for_launch)
2435//{
2436// m_abi_sp.reset();
2437// m_process_input_reader.reset();
2438//
2439// // Find the process and its architecture. Make sure it matches the architecture
2440// // of the current Target, and if not adjust it.
2441// Error error;
2442//
2443// if (!wait_for_launch)
2444// {
2445// ProcessInstanceInfoList process_infos;
2446// PlatformSP platform_sp (m_target.GetPlatform ());
2447// assert (platform_sp.get());
2448//
2449// if (platform_sp)
2450// {
2451// ProcessInstanceInfoMatch match_info;
2452// match_info.GetProcessInfo().SetName(process_name);
2453// match_info.SetNameMatchType (eNameMatchEquals);
2454// platform_sp->FindProcesses (match_info, process_infos);
2455// if (process_infos.GetSize() > 1)
2456// {
2457// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2458// }
2459// else if (process_infos.GetSize() == 0)
2460// {
2461// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2462// }
2463// }
2464// else
2465// {
2466// error.SetErrorString ("invalid platform");
2467// }
2468// }
2469//
2470// if (error.Success())
2471// {
2472// m_dyld_ap.reset();
2473// m_os_ap.reset();
2474//
2475// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2476// if (error.Success())
2477// {
2478// SetPublicState (eStateAttaching);
2479// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2480// if (error.Fail())
2481// {
2482// if (GetID() != LLDB_INVALID_PROCESS_ID)
2483// {
2484// SetID (LLDB_INVALID_PROCESS_ID);
2485// const char *error_string = error.AsCString();
2486// if (error_string == NULL)
2487// error_string = "attach failed";
2488//
2489// SetExitStatus(-1, error_string);
2490// }
2491// }
2492// else
2493// {
2494// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2495// StartPrivateStateThread();
2496// }
2497// }
2498// }
2499// return error;
2500//}
2501
Greg Clayton93d3c8332011-02-16 04:46:07 +00002502void
2503Process::CompleteAttach ()
2504{
2505 // Let the process subclass figure out at much as it can about the process
2506 // before we go looking for a dynamic loader plug-in.
Jim Ingham8314c522011-09-15 21:36:42 +00002507 m_attached_to_process = true;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002508 DidAttach();
2509
Jim Ingham4299fdb2011-09-15 01:10:17 +00002510 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2511 // the same as the one we've already set, switch architectures.
2512 PlatformSP platform_sp (m_target.GetPlatform ());
2513 assert (platform_sp.get());
2514 if (platform_sp)
2515 {
2516 ProcessInstanceInfo process_info;
2517 platform_sp->GetProcessInfo (GetID(), process_info);
2518 const ArchSpec &process_arch = process_info.GetArchitecture();
2519 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2520 m_target.SetArchitecture (process_arch);
2521 }
2522
2523 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002524 // plug-in
Greg Clayton7a5388b2011-03-20 04:57:14 +00002525 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002526 if (m_dyld_ap.get())
2527 m_dyld_ap->DidAttach();
2528
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002529 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002530 // Figure out which one is the executable, and set that in our target:
2531 ModuleList &modules = m_target.GetImages();
2532
2533 size_t num_modules = modules.GetSize();
2534 for (int i = 0; i < num_modules; i++)
2535 {
2536 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002537 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002538 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002539 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002540 m_target.SetExecutableModule (module_sp, false);
2541 break;
2542 }
2543 }
2544}
2545
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002546Error
Greg Claytonb766a732011-02-04 01:58:07 +00002547Process::ConnectRemote (const char *remote_url)
2548{
Greg Claytonb766a732011-02-04 01:58:07 +00002549 m_abi_sp.reset();
2550 m_process_input_reader.reset();
2551
2552 // Find the process and its architecture. Make sure it matches the architecture
2553 // of the current Target, and if not adjust it.
2554
2555 Error error (DoConnectRemote (remote_url));
2556 if (error.Success())
2557 {
Greg Clayton71337622011-02-24 22:24:29 +00002558 if (GetID() != LLDB_INVALID_PROCESS_ID)
2559 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002560 EventSP event_sp;
2561 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2562
2563 if (state == eStateStopped || state == eStateCrashed)
2564 {
2565 // If we attached and actually have a process on the other end, then
2566 // this ended up being the equivalent of an attach.
2567 CompleteAttach ();
2568
2569 // This delays passing the stopped event to listeners till
2570 // CompleteAttach gets a chance to complete...
2571 HandlePrivateEvent (event_sp);
2572
2573 }
Greg Clayton71337622011-02-24 22:24:29 +00002574 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002575
2576 if (PrivateStateThreadIsValid ())
2577 ResumePrivateStateThread ();
2578 else
2579 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002580 }
2581 return error;
2582}
2583
2584
2585Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002586Process::Resume ()
2587{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002588 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002589 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002590 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002591 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002592 StateAsCString(m_public_state.GetValue()),
2593 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002594
2595 Error error (WillResume());
2596 // Tell the process it is about to resume before the thread list
2597 if (error.Success())
2598 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002599 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002600 // can let all of our threads know that they are about to be
2601 // resumed. Threads will each be called with
2602 // Thread::WillResume(StateType) where StateType contains the state
2603 // that they are supposed to have when the process is resumed
2604 // (suspended/running/stepping). Threads should also check
2605 // their resume signal in lldb::Thread::GetResumeSignal()
2606 // to see if they are suppoed to start back up with a signal.
2607 if (m_thread_list.WillResume())
2608 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00002609 m_mod_id.BumpResumeID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002610 error = DoResume();
2611 if (error.Success())
2612 {
2613 DidResume();
2614 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00002615 if (log)
2616 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002617 }
2618 }
2619 else
2620 {
Jim Ingham444586b2011-01-24 06:34:17 +00002621 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002622 }
2623 }
Jim Ingham444586b2011-01-24 06:34:17 +00002624 else if (log)
2625 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002626 return error;
2627}
2628
2629Error
2630Process::Halt ()
2631{
Jim Inghambb3a2832011-01-29 01:49:25 +00002632 // Pause our private state thread so we can ensure no one else eats
2633 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002634 Listener halt_listener ("lldb.process.halt_listener");
2635 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002636
Jim Inghambb3a2832011-01-29 01:49:25 +00002637 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002638 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002639
Greg Clayton513c26c2011-01-29 07:10:55 +00002640 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002641 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002642
Greg Clayton513c26c2011-01-29 07:10:55 +00002643 bool caused_stop = false;
2644
2645 // Ask the process subclass to actually halt our process
2646 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002647 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002648 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002649 if (m_public_state.GetValue() == eStateAttaching)
2650 {
2651 SetExitStatus(SIGKILL, "Cancelled async attach.");
2652 Destroy ();
2653 }
2654 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002655 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002656 // If "caused_stop" is true, then DoHalt stopped the process. If
2657 // "caused_stop" is false, the process was already stopped.
2658 // If the DoHalt caused the process to stop, then we want to catch
2659 // this event and set the interrupted bool to true before we pass
2660 // this along so clients know that the process was interrupted by
2661 // a halt command.
2662 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002663 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002664 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002665 TimeValue timeout_time;
2666 timeout_time = TimeValue::Now();
2667 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002668 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2669 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002670
Jim Ingham0f16e732011-02-08 05:20:59 +00002671 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002672 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002673 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002674 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002675 }
2676 else
2677 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002678 if (StateIsStoppedState (state))
2679 {
2680 // We caused the process to interrupt itself, so mark this
2681 // as such in the stop event so clients can tell an interrupted
2682 // process from a natural stop
2683 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2684 }
2685 else
2686 {
2687 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2688 if (log)
2689 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2690 error.SetErrorString ("Did not get stopped event after halt.");
2691 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002692 }
2693 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002694 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002695 }
2696 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002697 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002698 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002699 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002700
2701 // Post any event we might have consumed. If all goes well, we will have
2702 // stopped the process, intercepted the event and set the interrupted
2703 // bool in the event. Post it to the private event queue and that will end up
2704 // correctly setting the state.
2705 if (event_sp)
2706 m_private_state_broadcaster.BroadcastEvent(event_sp);
2707
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002708 return error;
2709}
2710
2711Error
2712Process::Detach ()
2713{
2714 Error error (WillDetach());
2715
2716 if (error.Success())
2717 {
2718 DisableAllBreakpointSites();
2719 error = DoDetach();
2720 if (error.Success())
2721 {
2722 DidDetach();
2723 StopPrivateStateThread();
2724 }
2725 }
2726 return error;
2727}
2728
2729Error
2730Process::Destroy ()
2731{
2732 Error error (WillDestroy());
2733 if (error.Success())
2734 {
2735 DisableAllBreakpointSites();
2736 error = DoDestroy();
2737 if (error.Success())
2738 {
2739 DidDestroy();
2740 StopPrivateStateThread();
2741 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002742 m_stdio_communication.StopReadThread();
2743 m_stdio_communication.Disconnect();
2744 if (m_process_input_reader && m_process_input_reader->IsActive())
2745 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2746 if (m_process_input_reader)
2747 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002748 }
2749 return error;
2750}
2751
2752Error
2753Process::Signal (int signal)
2754{
2755 Error error (WillSignal());
2756 if (error.Success())
2757 {
2758 error = DoSignal(signal);
2759 if (error.Success())
2760 DidSignal();
2761 }
2762 return error;
2763}
2764
Greg Clayton514487e2011-02-15 21:59:32 +00002765lldb::ByteOrder
2766Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002767{
Greg Clayton514487e2011-02-15 21:59:32 +00002768 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002769}
2770
2771uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002772Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773{
Greg Clayton514487e2011-02-15 21:59:32 +00002774 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002775}
2776
Greg Clayton514487e2011-02-15 21:59:32 +00002777
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778bool
2779Process::ShouldBroadcastEvent (Event *event_ptr)
2780{
2781 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2782 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002783 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002784
2785 switch (state)
2786 {
Greg Claytonb766a732011-02-04 01:58:07 +00002787 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002788 case eStateAttaching:
2789 case eStateLaunching:
2790 case eStateDetached:
2791 case eStateExited:
2792 case eStateUnloaded:
2793 // These events indicate changes in the state of the debugging session, always report them.
2794 return_value = true;
2795 break;
2796 case eStateInvalid:
2797 // We stopped for no apparent reason, don't report it.
2798 return_value = false;
2799 break;
2800 case eStateRunning:
2801 case eStateStepping:
2802 // If we've started the target running, we handle the cases where we
2803 // are already running and where there is a transition from stopped to
2804 // running differently.
2805 // running -> running: Automatically suppress extra running events
2806 // stopped -> running: Report except when there is one or more no votes
2807 // and no yes votes.
2808 SynchronouslyNotifyStateChanged (state);
2809 switch (m_public_state.GetValue())
2810 {
2811 case eStateRunning:
2812 case eStateStepping:
2813 // We always suppress multiple runnings with no PUBLIC stop in between.
2814 return_value = false;
2815 break;
2816 default:
2817 // TODO: make this work correctly. For now always report
2818 // run if we aren't running so we don't miss any runnning
2819 // events. If I run the lldb/test/thread/a.out file and
2820 // break at main.cpp:58, run and hit the breakpoints on
2821 // multiple threads, then somehow during the stepping over
2822 // of all breakpoints no run gets reported.
2823 return_value = true;
2824
2825 // This is a transition from stop to run.
2826 switch (m_thread_list.ShouldReportRun (event_ptr))
2827 {
2828 case eVoteYes:
2829 case eVoteNoOpinion:
2830 return_value = true;
2831 break;
2832 case eVoteNo:
2833 return_value = false;
2834 break;
2835 }
2836 break;
2837 }
2838 break;
2839 case eStateStopped:
2840 case eStateCrashed:
2841 case eStateSuspended:
2842 {
2843 // We've stopped. First see if we're going to restart the target.
2844 // If we are going to stop, then we always broadcast the event.
2845 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00002846 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002847 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002848 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00002849 if (log)
2850 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002851 return true;
2852 }
2853 else
2854 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002855 RefreshStateAfterStop ();
2856
2857 if (m_thread_list.ShouldStop (event_ptr) == false)
2858 {
2859 switch (m_thread_list.ShouldReportStop (event_ptr))
2860 {
2861 case eVoteYes:
2862 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002863 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002864 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002865 case eVoteNo:
2866 return_value = false;
2867 break;
2868 }
2869
2870 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002871 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002872 Resume ();
2873 }
2874 else
2875 {
2876 return_value = true;
2877 SynchronouslyNotifyStateChanged (state);
2878 }
2879 }
2880 }
2881 }
2882
2883 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00002884 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002885 return return_value;
2886}
2887
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002888
2889bool
2890Process::StartPrivateStateThread ()
2891{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002892 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002893
Greg Clayton8b82f082011-04-12 05:54:46 +00002894 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002895 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00002896 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2897
2898 if (already_running)
2899 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002900
2901 // Create a thread that watches our internal state and controls which
2902 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002903 char thread_name[1024];
Greg Clayton81c22f62011-10-19 18:09:39 +00002904 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Clayton3e06bd92011-01-09 21:07:35 +00002905 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00002906 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002907}
2908
2909void
2910Process::PausePrivateStateThread ()
2911{
2912 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2913}
2914
2915void
2916Process::ResumePrivateStateThread ()
2917{
2918 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2919}
2920
2921void
2922Process::StopPrivateStateThread ()
2923{
Greg Clayton8b82f082011-04-12 05:54:46 +00002924 if (PrivateStateThreadIsValid ())
2925 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002926}
2927
2928void
2929Process::ControlPrivateStateThread (uint32_t signal)
2930{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002931 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002932
2933 assert (signal == eBroadcastInternalStateControlStop ||
2934 signal == eBroadcastInternalStateControlPause ||
2935 signal == eBroadcastInternalStateControlResume);
2936
2937 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002938 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002939
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002940 // Signal the private state thread. First we should copy this is case the
2941 // thread starts exiting since the private state thread will NULL this out
2942 // when it exits
2943 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00002944 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002945 {
2946 TimeValue timeout_time;
2947 bool timed_out;
2948
2949 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2950
2951 timeout_time = TimeValue::Now();
2952 timeout_time.OffsetWithSeconds(2);
2953 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2954 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2955
2956 if (signal == eBroadcastInternalStateControlStop)
2957 {
2958 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002959 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002960
2961 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002962 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002963 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002964 }
2965 }
2966}
2967
2968void
2969Process::HandlePrivateEvent (EventSP &event_sp)
2970{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002971 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00002972
Greg Clayton414f5d32011-01-25 02:58:48 +00002973 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002974
2975 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00002976 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00002977 {
Jim Ingham754ab982011-01-29 04:05:41 +00002978 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002979 switch (action_result)
2980 {
2981 case NextEventAction::eEventActionSuccess:
2982 SetNextEventAction(NULL);
2983 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002984
Jim Inghambb3a2832011-01-29 01:49:25 +00002985 case NextEventAction::eEventActionRetry:
2986 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002987
Jim Inghambb3a2832011-01-29 01:49:25 +00002988 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002989 // Handle Exiting Here. If we already got an exited event,
2990 // we should just propagate it. Otherwise, swallow this event,
2991 // and set our state to exit so the next event will kill us.
2992 if (new_state != eStateExited)
2993 {
2994 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00002995 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002996 SetNextEventAction(NULL);
2997 return;
2998 }
2999 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003000 break;
3001 }
3002 }
3003
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003004 // See if we should broadcast this state to external clients?
3005 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003006
3007 if (should_broadcast)
3008 {
3009 if (log)
3010 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003011 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003012 __FUNCTION__,
3013 GetID(),
3014 StateAsCString(new_state),
3015 StateAsCString (GetState ()),
3016 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003017 }
Jim Ingham9575d842011-03-11 03:53:59 +00003018 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003019 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003020 PushProcessInputReader ();
3021 else
3022 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003023
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003024 BroadcastEvent (event_sp);
3025 }
3026 else
3027 {
3028 if (log)
3029 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003030 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003031 __FUNCTION__,
3032 GetID(),
3033 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003034 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003035 }
3036 }
3037}
3038
3039void *
3040Process::PrivateStateThread (void *arg)
3041{
3042 Process *proc = static_cast<Process*> (arg);
3043 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003044 return result;
3045}
3046
3047void *
3048Process::RunPrivateStateThread ()
3049{
3050 bool control_only = false;
3051 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3052
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003053 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003054 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003055 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003056
3057 bool exit_now = false;
3058 while (!exit_now)
3059 {
3060 EventSP event_sp;
3061 WaitForEventsPrivate (NULL, event_sp, control_only);
3062 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3063 {
3064 switch (event_sp->GetType())
3065 {
3066 case eBroadcastInternalStateControlStop:
3067 exit_now = true;
3068 continue; // Go to next loop iteration so we exit without
3069 break; // doing any internal state managment below
3070
3071 case eBroadcastInternalStateControlPause:
3072 control_only = true;
3073 break;
3074
3075 case eBroadcastInternalStateControlResume:
3076 control_only = false;
3077 break;
3078 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003079
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003080 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003081 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003082
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003083 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003084 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003085 }
3086
3087
3088 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3089
3090 if (internal_state != eStateInvalid)
3091 {
3092 HandlePrivateEvent (event_sp);
3093 }
3094
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003095 if (internal_state == eStateInvalid ||
3096 internal_state == eStateExited ||
3097 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003098 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003099 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003100 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003101
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003102 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003103 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003104 }
3105
Caroline Tice20ad3c42010-10-29 21:48:37 +00003106 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003107 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003108 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003109
Greg Clayton6ed95942011-01-22 07:12:45 +00003110 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3111 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003112 return NULL;
3113}
3114
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115//------------------------------------------------------------------
3116// Process Event Data
3117//------------------------------------------------------------------
3118
3119Process::ProcessEventData::ProcessEventData () :
3120 EventData (),
3121 m_process_sp (),
3122 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003123 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003124 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003125 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003126{
3127}
3128
3129Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3130 EventData (),
3131 m_process_sp (process_sp),
3132 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003133 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003134 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003135 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003136{
3137}
3138
3139Process::ProcessEventData::~ProcessEventData()
3140{
3141}
3142
3143const ConstString &
3144Process::ProcessEventData::GetFlavorString ()
3145{
3146 static ConstString g_flavor ("Process::ProcessEventData");
3147 return g_flavor;
3148}
3149
3150const ConstString &
3151Process::ProcessEventData::GetFlavor () const
3152{
3153 return ProcessEventData::GetFlavorString ();
3154}
3155
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003156void
3157Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3158{
3159 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003160 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3161 // the public event queue, then other times when we're pretending that this is where we stopped at the
3162 // end of expression evaluation. m_update_state is used to distinguish these
3163 // three cases; it is 0 when we're just pulling it off for private handling,
3164 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003165
Jim Inghama8604692011-05-22 21:45:01 +00003166 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003167 return;
3168
3169 m_process_sp->SetPublicState (m_state);
3170
3171 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3172 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003173 {
3174 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
3175 int num_threads = curr_thread_list.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003176 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003177
Jim Ingham4b536182011-08-09 02:12:22 +00003178 // The actions might change one of the thread's stop_info's opinions about whether we should
3179 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003180
3181 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3182 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3183 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3184 // 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
3185 // against this list & bag out if anything differs.
3186 std::vector<lldb::tid_t> thread_index_array(num_threads);
3187 for (idx = 0; idx < num_threads; ++idx)
3188 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3189
Jim Ingham4b536182011-08-09 02:12:22 +00003190 bool still_should_stop = true;
3191
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003192 for (idx = 0; idx < num_threads; ++idx)
3193 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003194 curr_thread_list = m_process_sp->GetThreadList();
3195 if (curr_thread_list.GetSize() != num_threads)
3196 {
3197 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3198 log->Printf("Number of threads changed from %d to %d while processing event.", num_threads, curr_thread_list.GetSize());
3199 break;
3200 }
3201
3202 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3203
3204 if (thread_sp->GetIndexID() != thread_index_array[idx])
3205 {
3206 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3207 log->Printf("The thread at position %d changed from %d to %d while processing event.",
3208 idx,
3209 thread_index_array[idx],
3210 thread_sp->GetIndexID());
3211 break;
3212 }
3213
Jim Inghamb15bfc72010-10-20 00:39:53 +00003214 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3215 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003216 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003217 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003218 // The stop action might restart the target. If it does, then we want to mark that in the
3219 // event so that whoever is receiving it will know to wait for the running event and reflect
3220 // that state appropriately.
3221 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003222
3223 // FIXME: we might have run.
3224 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003225 {
3226 SetRestarted (true);
3227 break;
3228 }
3229 else if (!stop_info_sp->ShouldStop(event_ptr))
3230 {
3231 still_should_stop = false;
3232 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233 }
3234 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003235
Jim Ingham4b536182011-08-09 02:12:22 +00003236
3237 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003238 {
Jim Ingham4b536182011-08-09 02:12:22 +00003239 if (!still_should_stop)
3240 {
3241 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003242 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003243 m_process_sp->Resume();
3244 }
3245 else
3246 {
3247 // If we didn't restart, run the Stop Hooks here:
3248 // They might also restart the target, so watch for that.
3249 m_process_sp->GetTarget().RunStopHooks();
3250 if (m_process_sp->GetPrivateState() == eStateRunning)
3251 SetRestarted(true);
3252 }
Jim Ingham9575d842011-03-11 03:53:59 +00003253 }
3254
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003255 }
3256}
3257
3258void
3259Process::ProcessEventData::Dump (Stream *s) const
3260{
3261 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003262 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003263
Greg Clayton8b82f082011-04-12 05:54:46 +00003264 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003265}
3266
3267const Process::ProcessEventData *
3268Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3269{
3270 if (event_ptr)
3271 {
3272 const EventData *event_data = event_ptr->GetData();
3273 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3274 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3275 }
3276 return NULL;
3277}
3278
3279ProcessSP
3280Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3281{
3282 ProcessSP process_sp;
3283 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3284 if (data)
3285 process_sp = data->GetProcessSP();
3286 return process_sp;
3287}
3288
3289StateType
3290Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3291{
3292 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3293 if (data == NULL)
3294 return eStateInvalid;
3295 else
3296 return data->GetState();
3297}
3298
3299bool
3300Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3301{
3302 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3303 if (data == NULL)
3304 return false;
3305 else
3306 return data->GetRestarted();
3307}
3308
3309void
3310Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3311{
3312 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3313 if (data != NULL)
3314 data->SetRestarted(new_value);
3315}
3316
3317bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003318Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3319{
3320 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3321 if (data == NULL)
3322 return false;
3323 else
3324 return data->GetInterrupted ();
3325}
3326
3327void
3328Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3329{
3330 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3331 if (data != NULL)
3332 data->SetInterrupted(new_value);
3333}
3334
3335bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003336Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3337{
3338 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3339 if (data)
3340 {
3341 data->SetUpdateStateOnRemoval();
3342 return true;
3343 }
3344 return false;
3345}
3346
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003347void
Greg Clayton0603aa92010-10-04 01:05:56 +00003348Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003349{
Greg Claytonc14ee322011-09-22 04:58:26 +00003350 exe_ctx.SetTargetPtr (&m_target);
3351 exe_ctx.SetProcessPtr (this);
3352 exe_ctx.SetThreadPtr(NULL);
3353 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003354}
3355
3356lldb::ProcessSP
3357Process::GetSP ()
3358{
3359 return GetTarget().GetProcessSP();
3360}
3361
Greg Claytone996fd32011-03-08 22:40:15 +00003362//uint32_t
3363//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3364//{
3365// return 0;
3366//}
3367//
3368//ArchSpec
3369//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3370//{
3371// return Host::GetArchSpecForExistingProcess (pid);
3372//}
3373//
3374//ArchSpec
3375//Process::GetArchSpecForExistingProcess (const char *process_name)
3376//{
3377// return Host::GetArchSpecForExistingProcess (process_name);
3378//}
3379//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003380void
3381Process::AppendSTDOUT (const char * s, size_t len)
3382{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003383 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003384 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003385 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003386}
3387
3388void
Greg Clayton93e86192011-11-13 04:45:22 +00003389Process::AppendSTDERR (const char * s, size_t len)
3390{
3391 Mutex::Locker locker (m_stdio_communication_mutex);
3392 m_stderr_data.append (s, len);
3393 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3394}
3395
3396//------------------------------------------------------------------
3397// Process STDIO
3398//------------------------------------------------------------------
3399
3400size_t
3401Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3402{
3403 Mutex::Locker locker(m_stdio_communication_mutex);
3404 size_t bytes_available = m_stdout_data.size();
3405 if (bytes_available > 0)
3406 {
3407 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3408 if (log)
3409 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3410 if (bytes_available > buf_size)
3411 {
3412 memcpy(buf, m_stdout_data.c_str(), buf_size);
3413 m_stdout_data.erase(0, buf_size);
3414 bytes_available = buf_size;
3415 }
3416 else
3417 {
3418 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3419 m_stdout_data.clear();
3420 }
3421 }
3422 return bytes_available;
3423}
3424
3425
3426size_t
3427Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3428{
3429 Mutex::Locker locker(m_stdio_communication_mutex);
3430 size_t bytes_available = m_stderr_data.size();
3431 if (bytes_available > 0)
3432 {
3433 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3434 if (log)
3435 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3436 if (bytes_available > buf_size)
3437 {
3438 memcpy(buf, m_stderr_data.c_str(), buf_size);
3439 m_stderr_data.erase(0, buf_size);
3440 bytes_available = buf_size;
3441 }
3442 else
3443 {
3444 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3445 m_stderr_data.clear();
3446 }
3447 }
3448 return bytes_available;
3449}
3450
3451void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003452Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3453{
3454 Process *process = (Process *) baton;
3455 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3456}
3457
3458size_t
3459Process::ProcessInputReaderCallback (void *baton,
3460 InputReader &reader,
3461 lldb::InputReaderAction notification,
3462 const char *bytes,
3463 size_t bytes_len)
3464{
3465 Process *process = (Process *) baton;
3466
3467 switch (notification)
3468 {
3469 case eInputReaderActivate:
3470 break;
3471
3472 case eInputReaderDeactivate:
3473 break;
3474
3475 case eInputReaderReactivate:
3476 break;
3477
Caroline Tice969ed3d2011-05-02 20:41:46 +00003478 case eInputReaderAsynchronousOutputWritten:
3479 break;
3480
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003481 case eInputReaderGotToken:
3482 {
3483 Error error;
3484 process->PutSTDIN (bytes, bytes_len, error);
3485 }
3486 break;
3487
Caroline Ticeefed6132010-11-19 20:47:54 +00003488 case eInputReaderInterrupt:
3489 process->Halt ();
3490 break;
3491
3492 case eInputReaderEndOfFile:
3493 process->AppendSTDOUT ("^D", 2);
3494 break;
3495
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003496 case eInputReaderDone:
3497 break;
3498
3499 }
3500
3501 return bytes_len;
3502}
3503
3504void
3505Process::ResetProcessInputReader ()
3506{
3507 m_process_input_reader.reset();
3508}
3509
3510void
3511Process::SetUpProcessInputReader (int file_descriptor)
3512{
3513 // First set up the Read Thread for reading/handling process I/O
3514
3515 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3516
3517 if (conn_ap.get())
3518 {
3519 m_stdio_communication.SetConnection (conn_ap.release());
3520 if (m_stdio_communication.IsConnected())
3521 {
3522 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3523 m_stdio_communication.StartReadThread();
3524
3525 // Now read thread is set up, set up input reader.
3526
3527 if (!m_process_input_reader.get())
3528 {
3529 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3530 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3531 this,
3532 eInputReaderGranularityByte,
3533 NULL,
3534 NULL,
3535 false));
3536
3537 if (err.Fail())
3538 m_process_input_reader.reset();
3539 }
3540 }
3541 }
3542}
3543
3544void
3545Process::PushProcessInputReader ()
3546{
3547 if (m_process_input_reader && !m_process_input_reader->IsActive())
3548 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3549}
3550
3551void
3552Process::PopProcessInputReader ()
3553{
3554 if (m_process_input_reader && m_process_input_reader->IsActive())
3555 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3556}
3557
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003558// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003559void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003560Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003561{
Greg Claytone0d378b2011-03-24 21:19:54 +00003562 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003563
3564 int i=0;
3565 const char *name;
3566 OptionEnumValueElement option_enum;
3567 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3568 {
3569 if (name)
3570 {
3571 option_enum.value = i;
3572 option_enum.string_value = name;
3573 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3574 g_plugins.push_back (option_enum);
3575 }
3576 ++i;
3577 }
3578 option_enum.value = 0;
3579 option_enum.string_value = NULL;
3580 option_enum.usage = NULL;
3581 g_plugins.push_back (option_enum);
3582
3583 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3584 {
3585 if (::strcmp (name, "plugin") == 0)
3586 {
3587 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3588 break;
3589 }
3590 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003591 UserSettingsControllerSP &usc = GetSettingsController();
3592 usc.reset (new SettingsController);
3593 UserSettingsController::InitializeSettingsController (usc,
3594 SettingsController::global_settings_table,
3595 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003596
3597 // Now call SettingsInitialize() for each 'child' of Process settings
3598 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003599}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003600
Greg Clayton99d0faf2010-11-18 23:32:35 +00003601void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003602Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003603{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003604 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3605
3606 Thread::SettingsTerminate ();
3607
3608 // Now terminate Process Settings.
3609
Greg Clayton99d0faf2010-11-18 23:32:35 +00003610 UserSettingsControllerSP &usc = GetSettingsController();
3611 UserSettingsController::FinalizeSettingsController (usc);
3612 usc.reset();
3613}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003614
Greg Clayton99d0faf2010-11-18 23:32:35 +00003615UserSettingsControllerSP &
3616Process::GetSettingsController ()
3617{
3618 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003619 return g_settings_controller;
3620}
3621
Caroline Tice1559a462010-09-27 00:30:10 +00003622void
3623Process::UpdateInstanceName ()
3624{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003625 Module *module = GetTarget().GetExecutableModulePointer();
3626 if (module)
Caroline Tice1559a462010-09-27 00:30:10 +00003627 {
3628 StreamString sstr;
Greg Claytonaa149cb2011-08-11 02:48:45 +00003629 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003630
Greg Claytondbe54502010-11-19 03:46:01 +00003631 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Clayton8b82f082011-04-12 05:54:46 +00003632 sstr.GetData());
Caroline Tice1559a462010-09-27 00:30:10 +00003633 }
3634}
3635
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003636ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003637Process::RunThreadPlan (ExecutionContext &exe_ctx,
3638 lldb::ThreadPlanSP &thread_plan_sp,
3639 bool stop_others,
3640 bool try_all_threads,
3641 bool discard_on_error,
3642 uint32_t single_thread_timeout_usec,
3643 Stream &errors)
3644{
3645 ExecutionResults return_value = eExecutionSetupError;
3646
Jim Ingham77787032011-01-20 02:03:18 +00003647 if (thread_plan_sp.get() == NULL)
3648 {
3649 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003650 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003651 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003652
3653 if (exe_ctx.GetProcessPtr() != this)
3654 {
3655 errors.Printf("RunThreadPlan called on wrong process.");
3656 return eExecutionSetupError;
3657 }
3658
3659 Thread *thread = exe_ctx.GetThreadPtr();
3660 if (thread == NULL)
3661 {
3662 errors.Printf("RunThreadPlan called with invalid thread.");
3663 return eExecutionSetupError;
3664 }
Jim Ingham77787032011-01-20 02:03:18 +00003665
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003666 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3667 // For that to be true the plan can't be private - since private plans suppress themselves in the
3668 // GetCompletedPlan call.
3669
3670 bool orig_plan_private = thread_plan_sp->GetPrivate();
3671 thread_plan_sp->SetPrivate(false);
3672
Jim Ingham444586b2011-01-24 06:34:17 +00003673 if (m_private_state.GetValue() != eStateStopped)
3674 {
3675 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003676 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003677 }
3678
Jim Ingham66243842011-08-13 00:56:10 +00003679 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00003680 const uint32_t thread_idx_id = thread->GetIndexID();
3681 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003682
3683 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3684 // so we should arrange to reset them as well.
3685
Greg Claytonc14ee322011-09-22 04:58:26 +00003686 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003687
Jim Ingham66243842011-08-13 00:56:10 +00003688 uint32_t selected_tid;
3689 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00003690 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00003691 {
3692 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003693 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003694 }
3695 else
3696 {
3697 selected_tid = LLDB_INVALID_THREAD_ID;
3698 }
3699
Greg Claytonc14ee322011-09-22 04:58:26 +00003700 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Inghamf48169b2010-11-30 02:22:11 +00003701
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003702 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003703
3704 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3705 // restored on exit to the function.
3706
3707 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003708
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003709 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003710 if (log)
3711 {
3712 StreamString s;
3713 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton81c22f62011-10-19 18:09:39 +00003714 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00003715 thread->GetIndexID(),
3716 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00003717 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003718 }
3719
Jim Ingham0f16e732011-02-08 05:20:59 +00003720 bool got_event;
3721 lldb::EventSP event_sp;
3722 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003723
3724 TimeValue* timeout_ptr = NULL;
3725 TimeValue real_timeout;
3726
Jim Ingham0f16e732011-02-08 05:20:59 +00003727 bool first_timeout = true;
3728 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003729
Jim Inghamf48169b2010-11-30 02:22:11 +00003730 while (1)
3731 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003732 // We usually want to resume the process if we get to the top of the loop.
3733 // The only exception is if we get two running events with no intervening
3734 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003735
Jim Ingham0f16e732011-02-08 05:20:59 +00003736 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003737 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003738 // Do the initial resume and wait for the running event before going further.
3739
Greg Claytonc14ee322011-09-22 04:58:26 +00003740 Error resume_error = Resume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00003741 if (!resume_error.Success())
3742 {
3743 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003744 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003745 break;
3746 }
3747
3748 real_timeout = TimeValue::Now();
3749 real_timeout.OffsetWithMicroSeconds(500000);
3750 timeout_ptr = &real_timeout;
3751
3752 got_event = listener.WaitForEvent(NULL, event_sp);
3753 if (!got_event)
3754 {
3755 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003756 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003757
3758 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003759 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003760 break;
3761 }
3762
3763 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3764 if (stop_state != eStateRunning)
3765 {
3766 if (log)
3767 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3768
3769 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003770 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003771 break;
3772 }
3773
3774 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003775 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003776 // We need to call the function synchronously, so spin waiting for it to return.
3777 // If we get interrupted while executing, we're going to lose our context, and
3778 // won't be able to gather the result at this point.
3779 // We set the timeout AFTER the resume, since the resume takes some time and we
3780 // don't want to charge that to the timeout.
3781
3782 if (single_thread_timeout_usec != 0)
3783 {
3784 real_timeout = TimeValue::Now();
3785 if (first_timeout)
3786 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3787 else
3788 real_timeout.OffsetWithSeconds(10);
3789
3790 timeout_ptr = &real_timeout;
3791 }
3792 }
3793 else
3794 {
3795 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003796 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003797 do_resume = true;
3798 }
3799
3800 // Now wait for the process to stop again:
3801 stop_state = lldb::eStateInvalid;
3802 event_sp.reset();
3803 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3804
3805 if (got_event)
3806 {
3807 if (event_sp.get())
3808 {
3809 bool keep_going = false;
3810 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3811 if (log)
3812 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3813
3814 switch (stop_state)
3815 {
3816 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00003817 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003818 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00003819 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00003820 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00003821 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003822 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00003823 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00003824 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3825 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00003826 }
3827 else
3828 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003829 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3830 StopReason stop_reason = eStopReasonInvalid;
3831 if (stop_info_sp)
3832 stop_reason = stop_info_sp->GetStopReason();
3833 if (stop_reason == eStopReasonPlanComplete)
3834 {
3835 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003836 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003837 // Now mark this plan as private so it doesn't get reported as the stop reason
3838 // after this point.
3839 if (thread_plan_sp)
3840 thread_plan_sp->SetPrivate (orig_plan_private);
3841 return_value = eExecutionCompleted;
3842 }
3843 else
3844 {
3845 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003846 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003847
3848 return_value = eExecutionInterrupted;
3849 }
Jim Ingham160f78c2011-05-17 01:10:11 +00003850 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00003851 }
3852 break;
3853
Jim Ingham0f16e732011-02-08 05:20:59 +00003854 case lldb::eStateCrashed:
3855 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003856 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003857 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003858 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003859
Jim Ingham0f16e732011-02-08 05:20:59 +00003860 case lldb::eStateRunning:
3861 do_resume = false;
3862 keep_going = true;
3863 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003864
Jim Ingham0f16e732011-02-08 05:20:59 +00003865 default:
3866 if (log)
3867 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00003868
3869 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003870 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003871 break;
3872 }
3873 if (keep_going)
3874 continue;
3875 else
3876 break;
3877 }
3878 else
3879 {
3880 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003881 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00003882 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003883 break;
3884 }
3885 }
3886 else
3887 {
3888 // If we didn't get an event that means we've timed out...
3889 // We will interrupt the process here. Depending on what we were asked to do we will
3890 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00003891 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00003892
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003893 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00003894 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00003895 {
3896 if (first_timeout)
3897 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3898 "trying with all threads enabled.",
3899 single_thread_timeout_usec);
3900 else
3901 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3902 "and timeout: %d timed out.",
3903 single_thread_timeout_usec);
3904 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003905 else
Jim Ingham0f16e732011-02-08 05:20:59 +00003906 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3907 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00003908 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003909 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003910
Greg Claytonc14ee322011-09-22 04:58:26 +00003911 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00003912 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00003913 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003914 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003915 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003916
Jim Ingham0f16e732011-02-08 05:20:59 +00003917 // If halt succeeds, it always produces a stopped event. Wait for that:
3918
3919 real_timeout = TimeValue::Now();
3920 real_timeout.OffsetWithMicroSeconds(500000);
3921
3922 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00003923
3924 if (got_event)
3925 {
3926 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3927 if (log)
3928 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003929 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00003930 if (stop_state == lldb::eStateStopped
3931 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00003932 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003933 }
3934
Jim Ingham0f16e732011-02-08 05:20:59 +00003935 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00003936 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003937 // Between the time we initiated the Halt and the time we delivered it, the process could have
3938 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00003939
Greg Claytonc14ee322011-09-22 04:58:26 +00003940 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00003941 {
3942 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003943 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003944 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003945 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003946 break;
3947 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003948
Jim Ingham0f16e732011-02-08 05:20:59 +00003949 if (!try_all_threads)
3950 {
3951 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003952 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003953 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003954 break;
3955 }
3956
3957 if (first_timeout)
3958 {
3959 // Set all the other threads to run, and return to the top of the loop, which will continue;
3960 first_timeout = false;
3961 thread_plan_sp->SetStopOthers (false);
3962 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003963 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003964
3965 continue;
3966 }
3967 else
3968 {
3969 // Running all threads failed, so return Interrupted.
3970 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003971 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003972 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003973 break;
3974 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003975 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003976 }
3977 else
3978 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003979 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003980 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003981 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003982 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00003983 }
3984 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003985 else
3986 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003987 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3988 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00003989 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003990 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.",
3991 halt_error.AsCString());
3992 real_timeout = TimeValue::Now();
3993 real_timeout.OffsetWithMicroSeconds(500000);
3994 timeout_ptr = &real_timeout;
3995 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3996 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003997 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003998 // This is not going anywhere, bag out.
3999 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004000 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004001 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004002 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004003 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004004 else
4005 {
4006 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4007 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004008 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00004009 if (stop_state == lldb::eStateStopped)
4010 {
4011 // Between the time we initiated the Halt and the time we delivered it, the process could have
4012 // already finished its job. Check that here:
4013
Greg Claytonc14ee322011-09-22 04:58:26 +00004014 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004015 {
4016 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004017 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004018 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004019 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004020 break;
4021 }
4022
4023 if (first_timeout)
4024 {
4025 // Set all the other threads to run, and return to the top of the loop, which will continue;
4026 first_timeout = false;
4027 thread_plan_sp->SetStopOthers (false);
4028 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004029 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004030
4031 continue;
4032 }
4033 else
4034 {
4035 // Running all threads failed, so return Interrupted.
4036 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004037 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004038 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004039 break;
4040 }
4041 }
4042 else
4043 {
Sean Callanan39821ac2011-08-09 22:07:08 +00004044 if (log)
4045 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4046 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00004047 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004048 break;
4049 }
4050 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004051 }
4052
Jim Inghamf48169b2010-11-30 02:22:11 +00004053 }
4054
Jim Ingham0f16e732011-02-08 05:20:59 +00004055 } // END WAIT LOOP
4056
4057 // Now do some processing on the results of the run:
4058 if (return_value == eExecutionInterrupted)
4059 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004060 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004061 {
4062 StreamString s;
4063 if (event_sp)
4064 event_sp->Dump (&s);
4065 else
4066 {
Jim Ingham20829ac2011-08-09 22:24:33 +00004067 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004068 }
4069
4070 StreamString ts;
4071
Jim Ingham20829ac2011-08-09 22:24:33 +00004072 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00004073
4074 do
4075 {
4076 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4077
4078 if (!event_data)
4079 {
4080 event_explanation = "<no event data>";
4081 break;
4082 }
4083
4084 Process *process = event_data->GetProcessSP().get();
4085
4086 if (!process)
4087 {
4088 event_explanation = "<no process>";
4089 break;
4090 }
4091
4092 ThreadList &thread_list = process->GetThreadList();
4093
4094 uint32_t num_threads = thread_list.GetSize();
4095 uint32_t thread_index;
4096
4097 ts.Printf("<%u threads> ", num_threads);
4098
4099 for (thread_index = 0;
4100 thread_index < num_threads;
4101 ++thread_index)
4102 {
4103 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4104
4105 if (!thread)
4106 {
4107 ts.Printf("<?> ");
4108 continue;
4109 }
4110
Greg Clayton81c22f62011-10-19 18:09:39 +00004111 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Ingham0f16e732011-02-08 05:20:59 +00004112 RegisterContext *register_context = thread->GetRegisterContext().get();
4113
4114 if (register_context)
4115 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4116 else
4117 ts.Printf("[ip unknown] ");
4118
4119 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4120 if (stop_info_sp)
4121 {
4122 const char *stop_desc = stop_info_sp->GetDescription();
4123 if (stop_desc)
4124 ts.PutCString (stop_desc);
4125 }
4126 ts.Printf(">");
4127 }
4128
4129 event_explanation = ts.GetData();
4130 } while (0);
4131
4132 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004133 {
4134 if (event_explanation)
4135 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4136 else
4137 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4138 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004139
4140 if (discard_on_error && thread_plan_sp)
4141 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004142 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004143 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004144 }
4145 }
4146 }
4147 else if (return_value == eExecutionSetupError)
4148 {
4149 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004150 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004151
4152 if (discard_on_error && thread_plan_sp)
4153 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004154 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004155 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004156 }
4157 }
4158 else
4159 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004160 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004161 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004162 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004163 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00004164 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00004165 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004166 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004167 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004168 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004169 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00004170 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00004171 }
4172 else
4173 {
4174 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004175 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00004176 if (discard_on_error && thread_plan_sp)
4177 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004178 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004179 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00004180 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004181 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00004182 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004183 }
4184 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004185
Jim Inghamf48169b2010-11-30 02:22:11 +00004186 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00004187 // Check that it's still there, and if it is put it back in the context. Also restore the
4188 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00004189 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4190 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00004191 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004192 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00004193 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004194
4195 // Also restore the current process'es selected frame & thread, since this function calling may
4196 // be done behind the user's back.
4197
4198 if (selected_tid != LLDB_INVALID_THREAD_ID)
4199 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004200 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00004201 {
4202 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00004203 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00004204 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00004205 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004206 }
4207 }
4208
4209 return return_value;
4210}
4211
4212const char *
4213Process::ExecutionResultAsCString (ExecutionResults result)
4214{
4215 const char *result_name;
4216
4217 switch (result)
4218 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004219 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004220 result_name = "eExecutionCompleted";
4221 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004222 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004223 result_name = "eExecutionDiscarded";
4224 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004225 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004226 result_name = "eExecutionInterrupted";
4227 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004228 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004229 result_name = "eExecutionSetupError";
4230 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004231 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004232 result_name = "eExecutionTimedOut";
4233 break;
4234 }
4235 return result_name;
4236}
4237
Greg Clayton7260f622011-04-18 08:33:37 +00004238void
4239Process::GetStatus (Stream &strm)
4240{
4241 const StateType state = GetState();
4242 if (StateIsStoppedState(state))
4243 {
4244 if (state == eStateExited)
4245 {
4246 int exit_status = GetExitStatus();
4247 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004248 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004249 GetID(),
4250 exit_status,
4251 exit_status,
4252 exit_description ? exit_description : "");
4253 }
4254 else
4255 {
4256 if (state == eStateConnected)
4257 strm.Printf ("Connected to remote target.\n");
4258 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004259 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004260 }
4261 }
4262 else
4263 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004264 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004265 }
4266}
4267
4268size_t
4269Process::GetThreadStatus (Stream &strm,
4270 bool only_threads_with_stop_reason,
4271 uint32_t start_frame,
4272 uint32_t num_frames,
4273 uint32_t num_frames_with_source)
4274{
4275 size_t num_thread_infos_dumped = 0;
4276
4277 const size_t num_threads = GetThreadList().GetSize();
4278 for (uint32_t i = 0; i < num_threads; i++)
4279 {
4280 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4281 if (thread)
4282 {
4283 if (only_threads_with_stop_reason)
4284 {
4285 if (thread->GetStopInfo().get() == NULL)
4286 continue;
4287 }
4288 thread->GetStatus (strm,
4289 start_frame,
4290 num_frames,
4291 num_frames_with_source);
4292 ++num_thread_infos_dumped;
4293 }
4294 }
4295 return num_thread_infos_dumped;
4296}
4297
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004298//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004299// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004300//--------------------------------------------------------------
4301
Greg Clayton1b654882010-09-19 02:33:57 +00004302Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004303 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004304{
Greg Clayton85851dd2010-12-04 00:10:17 +00004305 m_default_settings.reset (new ProcessInstanceSettings (*this,
4306 false,
Caroline Tice91123da2010-09-08 17:48:55 +00004307 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004308}
4309
Greg Clayton1b654882010-09-19 02:33:57 +00004310Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004311{
4312}
4313
4314lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004315Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004316{
Greg Claytondbe54502010-11-19 03:46:01 +00004317 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4318 false,
4319 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004320 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4321 return new_settings_sp;
4322}
4323
4324//--------------------------------------------------------------
4325// class ProcessInstanceSettings
4326//--------------------------------------------------------------
4327
Greg Clayton85851dd2010-12-04 00:10:17 +00004328ProcessInstanceSettings::ProcessInstanceSettings
4329(
4330 UserSettingsController &owner,
4331 bool live_instance,
4332 const char *name
4333) :
Greg Clayton1d885962011-11-08 02:43:13 +00004334 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004335{
Caroline Ticef20e8232010-09-09 18:26:37 +00004336 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4337 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4338 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice9e41c152010-09-16 19:05:55 +00004339 // This is true for CreateInstanceName() too.
Greg Clayton1d885962011-11-08 02:43:13 +00004340
Caroline Tice9e41c152010-09-16 19:05:55 +00004341 if (GetInstanceName () == InstanceSettings::InvalidName())
4342 {
4343 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4344 m_owner.RegisterInstanceSettings (this);
4345 }
Greg Clayton1d885962011-11-08 02:43:13 +00004346
Caroline Ticef20e8232010-09-09 18:26:37 +00004347 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004348 {
4349 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4350 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00004351 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004352 }
4353}
4354
4355ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Clayton1d885962011-11-08 02:43:13 +00004356 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004357{
4358 if (m_instance_name != InstanceSettings::GetDefaultName())
4359 {
4360 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4361 CopyInstanceSettings (pending_settings,false);
4362 m_owner.RemovePendingSettings (m_instance_name);
4363 }
4364}
4365
4366ProcessInstanceSettings::~ProcessInstanceSettings ()
4367{
4368}
4369
4370ProcessInstanceSettings&
4371ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4372{
4373 if (this != &rhs)
4374 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004375 }
4376
4377 return *this;
4378}
4379
4380
4381void
4382ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4383 const char *index_value,
4384 const char *value,
4385 const ConstString &instance_name,
4386 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004387 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004388 Error &err,
4389 bool pending)
4390{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004391}
4392
4393void
4394ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4395 bool pending)
4396{
Greg Clayton1d885962011-11-08 02:43:13 +00004397// if (new_settings.get() == NULL)
4398// return;
4399//
4400// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004401}
4402
Caroline Tice12cecd72010-09-20 21:37:42 +00004403bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004404ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4405 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004406 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004407 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004408{
Greg Clayton1d885962011-11-08 02:43:13 +00004409 if (err)
4410 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4411 return false;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004412}
4413
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004414const ConstString
4415ProcessInstanceSettings::CreateInstanceName ()
4416{
4417 static int instance_count = 1;
4418 StreamString sstr;
4419
4420 sstr.Printf ("process_%d", instance_count);
4421 ++instance_count;
4422
4423 const ConstString ret_val (sstr.GetData());
4424 return ret_val;
4425}
4426
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004427//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004428// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004429//--------------------------------------------------
4430
4431SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004432Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004433{
4434 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4435 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4436};
4437
4438
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004439SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004440Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004441{
Greg Clayton85851dd2010-12-04 00:10:17 +00004442 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton85851dd2010-12-04 00:10:17 +00004443 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004444};
4445
4446
Jim Ingham5aee1622010-08-09 23:31:02 +00004447
Greg Clayton1d885962011-11-08 02:43:13 +00004448