blob: 5f6b7c273a6593f1525dfd2da31e696232eb0d0b [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 Claytonee95ed52011-11-17 22:14:31 +0000254ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
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
Greg Claytonee95ed52011-11-17 22:14:31 +0000273 const char *in_path = NULL;
274 const char *out_path = NULL;
275 const char *err_path = NULL;
Greg Clayton1d885962011-11-08 02:43:13 +0000276 if (target)
277 {
Greg Claytonee95ed52011-11-17 22:14:31 +0000278 in_path = target->GetStandardErrorPath();
279 out_path = target->GetStandardInputPath();
280 err_path = target->GetStandardOutputPath();
281 }
282
283 if (default_to_use_pty && (!in_path && !out_path && !err_path))
284 {
285 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Clayton1d885962011-11-08 02:43:13 +0000286 {
Greg Claytonee95ed52011-11-17 22:14:31 +0000287 in_path = out_path = err_path = m_pty.GetSlaveName (NULL, 0);
Greg Clayton1d885962011-11-08 02:43:13 +0000288 }
289 }
290
Greg Claytonee95ed52011-11-17 22:14:31 +0000291 if (in_path)
292 AppendOpenFileAction(STDERR_FILENO, in_path, true, true);
293
294 if (out_path)
295 AppendOpenFileAction(STDIN_FILENO, out_path, true, false);
296
297 if (err_path)
298 AppendOpenFileAction(STDOUT_FILENO, err_path, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000299 }
300 }
301}
302
Greg Clayton144f3a92011-11-15 03:53:30 +0000303
304bool
305ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error, bool localhost)
306{
307 error.Clear();
308
309 if (GetFlags().Test (eLaunchFlagLaunchInShell))
310 {
311 const char *shell_executable = GetShell();
312 if (shell_executable)
313 {
314 char shell_resolved_path[PATH_MAX];
315
316 if (localhost)
317 {
318 FileSpec shell_filespec (shell_executable, true);
319
320 if (!shell_filespec.Exists())
321 {
322 // Resolve the path in case we just got "bash", "sh" or "tcsh"
323 if (!shell_filespec.ResolveExecutableLocation ())
324 {
325 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
326 return false;
327 }
328 }
329 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
330 shell_executable = shell_resolved_path;
331 }
332
333 Args shell_arguments;
334 std::string safe_arg;
335 shell_arguments.AppendArgument (shell_executable);
336 StreamString shell_command;
337 shell_arguments.AppendArgument ("-c");
338 shell_command.PutCString ("exec");
339 if (GetArchitecture().IsValid())
340 {
341 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
342 // Set the resume count to 2:
343 // 1 - stop in shell
344 // 2 - stop in /usr/bin/arch
345 // 3 - then we will stop in our program
346 SetResumeCount(2);
347 }
348 else
349 {
350 // Set the resume count to 1:
351 // 1 - stop in shell
352 // 2 - then we will stop in our program
353 SetResumeCount(1);
354 }
355
356 const char **argv = GetArguments().GetConstArgumentVector ();
357 if (argv)
358 {
359 for (size_t i=0; argv[i] != NULL; ++i)
360 {
361 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
362 shell_command.Printf(" %s", arg);
363 }
364 }
365 shell_arguments.AppendArgument (shell_command.GetString().c_str());
366
367 m_executable.SetFile(shell_executable, false);
368 m_arguments = shell_arguments;
369 return true;
370 }
371 else
372 {
373 error.SetErrorString ("invalid shell path");
374 }
375 }
376 else
377 {
378 error.SetErrorString ("not launching in shell");
379 }
380 return false;
381}
382
383
Greg Clayton32e0a752011-03-30 18:16:51 +0000384bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000385ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
386{
387 if ((read || write) && fd >= 0 && path && path[0])
388 {
389 m_action = eFileActionOpen;
390 m_fd = fd;
391 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000392 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000393 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000394 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000395 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000396 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000397 m_path.assign (path);
398 return true;
399 }
400 else
401 {
402 Clear();
403 }
404 return false;
405}
406
407bool
408ProcessLaunchInfo::FileAction::Close (int fd)
409{
410 Clear();
411 if (fd >= 0)
412 {
413 m_action = eFileActionClose;
414 m_fd = fd;
415 }
416 return m_fd >= 0;
417}
418
419
420bool
421ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
422{
423 Clear();
424 if (fd >= 0 && dup_fd >= 0)
425 {
426 m_action = eFileActionDuplicate;
427 m_fd = fd;
428 m_arg = dup_fd;
429 }
430 return m_fd >= 0;
431}
432
433
434
435bool
436ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
437 const FileAction *info,
438 Log *log,
439 Error& error)
440{
441 if (info == NULL)
442 return false;
443
444 switch (info->m_action)
445 {
446 case eFileActionNone:
447 error.Clear();
448 break;
449
450 case eFileActionClose:
451 if (info->m_fd == -1)
452 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
453 else
454 {
455 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
456 eErrorTypePOSIX);
457 if (log && (error.Fail() || log))
458 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
459 file_actions, info->m_fd);
460 }
461 break;
462
463 case eFileActionDuplicate:
464 if (info->m_fd == -1)
465 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
466 else if (info->m_arg == -1)
467 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
468 else
469 {
470 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
471 eErrorTypePOSIX);
472 if (log && (error.Fail() || log))
473 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
474 file_actions, info->m_fd, info->m_arg);
475 }
476 break;
477
478 case eFileActionOpen:
479 if (info->m_fd == -1)
480 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
481 else
482 {
483 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000484
Greg Clayton8b82f082011-04-12 05:54:46 +0000485 mode_t mode = 0;
486
Greg Clayton144f3a92011-11-15 03:53:30 +0000487 if (oflag & O_CREAT)
488 mode = 0640;
489
Greg Clayton8b82f082011-04-12 05:54:46 +0000490 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
491 info->m_fd,
492 info->m_path.c_str(),
493 oflag,
494 mode),
495 eErrorTypePOSIX);
496 if (error.Fail() || log)
497 error.PutToLog(log,
498 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
499 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
500 }
501 break;
502
503 default:
504 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
505 break;
506 }
507 return error.Success();
508}
509
510Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000511ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000512{
513 Error error;
514 char short_option = (char) m_getopt_table[option_idx].val;
515
516 switch (short_option)
517 {
518 case 's': // Stop at program entry point
519 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
520 break;
521
522 case 'e': // STDERR for read + write
523 {
524 ProcessLaunchInfo::FileAction action;
525 if (action.Open(STDERR_FILENO, option_arg, true, true))
526 launch_info.AppendFileAction (action);
527 }
528 break;
529
530 case 'i': // STDIN for read only
531 {
532 ProcessLaunchInfo::FileAction action;
533 if (action.Open(STDIN_FILENO, option_arg, true, false))
534 launch_info.AppendFileAction (action);
535 }
536 break;
537
538 case 'o': // Open STDOUT for write only
539 {
540 ProcessLaunchInfo::FileAction action;
541 if (action.Open(STDOUT_FILENO, option_arg, false, true))
542 launch_info.AppendFileAction (action);
543 }
544 break;
545
546 case 'p': // Process plug-in name
547 launch_info.SetProcessPluginName (option_arg);
548 break;
549
550 case 'n': // Disable STDIO
551 {
552 ProcessLaunchInfo::FileAction action;
553 if (action.Open(STDERR_FILENO, "/dev/null", true, true))
554 launch_info.AppendFileAction (action);
555 if (action.Open(STDOUT_FILENO, "/dev/null", false, true))
556 launch_info.AppendFileAction (action);
557 if (action.Open(STDIN_FILENO, "/dev/null", true, false))
558 launch_info.AppendFileAction (action);
559 }
560 break;
561
562 case 'w':
563 launch_info.SetWorkingDirectory (option_arg);
564 break;
565
566 case 't': // Open process in new terminal window
567 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
568 break;
569
570 case 'a':
571 launch_info.GetArchitecture().SetTriple (option_arg,
572 m_interpreter.GetPlatform(true).get());
573 break;
574
575 case 'A':
576 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
577 break;
578
Greg Clayton982c9762011-11-03 21:22:33 +0000579 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000580 if (option_arg && option_arg[0])
581 launch_info.SetShell (option_arg);
582 else
583 launch_info.SetShell ("/bin/bash");
Greg Clayton982c9762011-11-03 21:22:33 +0000584 break;
585
Greg Clayton8b82f082011-04-12 05:54:46 +0000586 case 'v':
587 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
588 break;
589
590 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000591 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000592 break;
593
594 }
595 return error;
596}
597
598OptionDefinition
599ProcessLaunchCommandOptions::g_option_table[] =
600{
601{ 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."},
602{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
603{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
604{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
605{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
606{ 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 +0000607{ 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 +0000608
609{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
610{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
611{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
612
613{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
614
615{ 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."},
616
617{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
618};
619
620
621
622bool
623ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000624{
625 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
626 return true;
627 const char *match_name = m_match_info.GetName();
628 if (!match_name)
629 return true;
630
631 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
632}
633
634bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000635ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000636{
637 if (!NameMatches (proc_info.GetName()))
638 return false;
639
640 if (m_match_info.ProcessIDIsValid() &&
641 m_match_info.GetProcessID() != proc_info.GetProcessID())
642 return false;
643
644 if (m_match_info.ParentProcessIDIsValid() &&
645 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
646 return false;
647
Greg Clayton8b82f082011-04-12 05:54:46 +0000648 if (m_match_info.UserIDIsValid () &&
649 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000650 return false;
651
Greg Clayton8b82f082011-04-12 05:54:46 +0000652 if (m_match_info.GroupIDIsValid () &&
653 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000654 return false;
655
656 if (m_match_info.EffectiveUserIDIsValid () &&
657 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
658 return false;
659
660 if (m_match_info.EffectiveGroupIDIsValid () &&
661 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
662 return false;
663
664 if (m_match_info.GetArchitecture().IsValid() &&
665 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
666 return false;
667 return true;
668}
669
670bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000671ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000672{
673 if (m_name_match_type != eNameMatchIgnore)
674 return false;
675
676 if (m_match_info.ProcessIDIsValid())
677 return false;
678
679 if (m_match_info.ParentProcessIDIsValid())
680 return false;
681
Greg Clayton8b82f082011-04-12 05:54:46 +0000682 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000683 return false;
684
Greg Clayton8b82f082011-04-12 05:54:46 +0000685 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000686 return false;
687
688 if (m_match_info.EffectiveUserIDIsValid ())
689 return false;
690
691 if (m_match_info.EffectiveGroupIDIsValid ())
692 return false;
693
694 if (m_match_info.GetArchitecture().IsValid())
695 return false;
696
697 if (m_match_all_users)
698 return false;
699
700 return true;
701
702}
703
704void
Greg Clayton8b82f082011-04-12 05:54:46 +0000705ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000706{
707 m_match_info.Clear();
708 m_name_match_type = eNameMatchIgnore;
709 m_match_all_users = false;
710}
Greg Clayton58be07b2011-01-07 06:08:19 +0000711
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000712Process*
713Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
714{
715 ProcessCreateInstance create_callback = NULL;
716 if (plugin_name)
717 {
718 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
719 if (create_callback)
720 {
721 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000722 if (debugger_ap->CanDebug(target, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000723 return debugger_ap.release();
724 }
725 }
726 else
727 {
Greg Claytonc982c762010-07-09 20:39:50 +0000728 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729 {
Greg Claytonc982c762010-07-09 20:39:50 +0000730 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000731 if (debugger_ap->CanDebug(target, false))
Greg Claytonc982c762010-07-09 20:39:50 +0000732 return debugger_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733 }
734 }
735 return NULL;
736}
737
738
739//----------------------------------------------------------------------
740// Process constructor
741//----------------------------------------------------------------------
742Process::Process(Target &target, Listener &listener) :
743 UserID (LLDB_INVALID_PROCESS_ID),
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000744 Broadcaster ("lldb.process"),
Greg Claytondbe54502010-11-19 03:46:01 +0000745 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000747 m_public_state (eStateUnloaded),
748 m_private_state (eStateUnloaded),
749 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
750 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
751 m_private_state_listener ("lldb.process.internal_state_listener"),
752 m_private_state_control_wait(),
753 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000754 m_mod_id (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000755 m_thread_index_id (0),
756 m_exit_status (-1),
757 m_exit_string (),
758 m_thread_list (this),
759 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000760 m_image_tokens (),
761 m_listener (listener),
762 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000763 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000764 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000765 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000766 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000767 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000768 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000769 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000770 m_stderr_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000771 m_memory_cache (*this),
772 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000773 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000774 m_next_event_action_ap(),
775 m_can_jit(eCanJITYes)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000776{
Caroline Tice1559a462010-09-27 00:30:10 +0000777 UpdateInstanceName();
778
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000779 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000780 if (log)
781 log->Printf ("%p Process::Process()", this);
782
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000783 SetEventName (eBroadcastBitStateChanged, "state-changed");
784 SetEventName (eBroadcastBitInterrupt, "interrupt");
785 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
786 SetEventName (eBroadcastBitSTDERR, "stderr-available");
787
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000788 listener.StartListeningForEvents (this,
789 eBroadcastBitStateChanged |
790 eBroadcastBitInterrupt |
791 eBroadcastBitSTDOUT |
792 eBroadcastBitSTDERR);
793
794 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
795 eBroadcastBitStateChanged);
796
797 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
798 eBroadcastInternalStateControlStop |
799 eBroadcastInternalStateControlPause |
800 eBroadcastInternalStateControlResume);
801}
802
803//----------------------------------------------------------------------
804// Destructor
805//----------------------------------------------------------------------
806Process::~Process()
807{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000808 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000809 if (log)
810 log->Printf ("%p Process::~Process()", this);
811 StopPrivateStateThread();
812}
813
814void
815Process::Finalize()
816{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000817 switch (GetPrivateState())
818 {
819 case eStateConnected:
820 case eStateAttaching:
821 case eStateLaunching:
822 case eStateStopped:
823 case eStateRunning:
824 case eStateStepping:
825 case eStateCrashed:
826 case eStateSuspended:
827 if (GetShouldDetach())
828 Detach();
829 else
830 Destroy();
831 break;
832
833 case eStateInvalid:
834 case eStateUnloaded:
835 case eStateDetached:
836 case eStateExited:
837 break;
838 }
839
Greg Clayton1ed54f52011-10-01 00:45:15 +0000840 // Clear our broadcaster before we proceed with destroying
841 Broadcaster::Clear();
842
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000843 // Do any cleanup needed prior to being destructed... Subclasses
844 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000845
846 // We need to destroy the loader before the derived Process class gets destroyed
847 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000848 m_dyld_ap.reset();
849 m_os_ap.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000850}
851
852void
853Process::RegisterNotificationCallbacks (const Notifications& callbacks)
854{
855 m_notifications.push_back(callbacks);
856 if (callbacks.initialize != NULL)
857 callbacks.initialize (callbacks.baton, this);
858}
859
860bool
861Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
862{
863 std::vector<Notifications>::iterator pos, end = m_notifications.end();
864 for (pos = m_notifications.begin(); pos != end; ++pos)
865 {
866 if (pos->baton == callbacks.baton &&
867 pos->initialize == callbacks.initialize &&
868 pos->process_state_changed == callbacks.process_state_changed)
869 {
870 m_notifications.erase(pos);
871 return true;
872 }
873 }
874 return false;
875}
876
877void
878Process::SynchronouslyNotifyStateChanged (StateType state)
879{
880 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
881 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
882 {
883 if (notification_pos->process_state_changed)
884 notification_pos->process_state_changed (notification_pos->baton, this, state);
885 }
886}
887
888// FIXME: We need to do some work on events before the general Listener sees them.
889// For instance if we are continuing from a breakpoint, we need to ensure that we do
890// the little "insert real insn, step & stop" trick. But we can't do that when the
891// event is delivered by the broadcaster - since that is done on the thread that is
892// waiting for new events, so if we needed more than one event for our handling, we would
893// stall. So instead we do it when we fetch the event off of the queue.
894//
895
896StateType
897Process::GetNextEvent (EventSP &event_sp)
898{
899 StateType state = eStateInvalid;
900
901 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
902 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
903
904 return state;
905}
906
907
908StateType
909Process::WaitForProcessToStop (const TimeValue *timeout)
910{
Jim Ingham4b536182011-08-09 02:12:22 +0000911 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
912 // We have to actually check each event, and in the case of a stopped event check the restarted flag
913 // on the event.
914 EventSP event_sp;
915 StateType state = GetState();
916 // If we are exited or detached, we won't ever get back to any
917 // other valid state...
918 if (state == eStateDetached || state == eStateExited)
919 return state;
920
921 while (state != eStateInvalid)
922 {
923 state = WaitForStateChangedEvents (timeout, event_sp);
924 switch (state)
925 {
926 case eStateCrashed:
927 case eStateDetached:
928 case eStateExited:
929 case eStateUnloaded:
930 return state;
931 case eStateStopped:
932 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
933 continue;
934 else
935 return state;
936 default:
937 continue;
938 }
939 }
940 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000941}
942
943
944StateType
945Process::WaitForState
946(
947 const TimeValue *timeout,
948 const StateType *match_states, const uint32_t num_match_states
949)
950{
951 EventSP event_sp;
952 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000953 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000954 while (state != eStateInvalid)
955 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000956 // If we are exited or detached, we won't ever get back to any
957 // other valid state...
958 if (state == eStateDetached || state == eStateExited)
959 return state;
960
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000961 state = WaitForStateChangedEvents (timeout, event_sp);
962
963 for (i=0; i<num_match_states; ++i)
964 {
965 if (match_states[i] == state)
966 return state;
967 }
968 }
969 return state;
970}
971
Jim Ingham30f9b212010-10-11 23:53:14 +0000972bool
973Process::HijackProcessEvents (Listener *listener)
974{
975 if (listener != NULL)
976 {
977 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
978 }
979 else
980 return false;
981}
982
983void
984Process::RestoreProcessEvents ()
985{
986 RestoreBroadcaster();
987}
988
Jim Ingham0f16e732011-02-08 05:20:59 +0000989bool
990Process::HijackPrivateProcessEvents (Listener *listener)
991{
992 if (listener != NULL)
993 {
994 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
995 }
996 else
997 return false;
998}
999
1000void
1001Process::RestorePrivateProcessEvents ()
1002{
1003 m_private_state_broadcaster.RestoreBroadcaster();
1004}
1005
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006StateType
1007Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1008{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001009 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010
1011 if (log)
1012 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1013
1014 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001015 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1016 this,
1017 eBroadcastBitStateChanged,
1018 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001019 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1020
1021 if (log)
1022 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1023 __FUNCTION__,
1024 timeout,
1025 StateAsCString(state));
1026 return state;
1027}
1028
1029Event *
1030Process::PeekAtStateChangedEvents ()
1031{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001032 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001033
1034 if (log)
1035 log->Printf ("Process::%s...", __FUNCTION__);
1036
1037 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001038 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1039 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001040 if (log)
1041 {
1042 if (event_ptr)
1043 {
1044 log->Printf ("Process::%s (event_ptr) => %s",
1045 __FUNCTION__,
1046 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1047 }
1048 else
1049 {
1050 log->Printf ("Process::%s no events found",
1051 __FUNCTION__);
1052 }
1053 }
1054 return event_ptr;
1055}
1056
1057StateType
1058Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1059{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001060 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001061
1062 if (log)
1063 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1064
1065 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001066 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1067 &m_private_state_broadcaster,
1068 eBroadcastBitStateChanged,
1069 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1071
1072 // This is a bit of a hack, but when we wait here we could very well return
1073 // to the command-line, and that could disable the log, which would render the
1074 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001075 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001076 {
1077 if (state == eStateInvalid)
1078 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1079 else
1080 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1081 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001082 return state;
1083}
1084
1085bool
1086Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1087{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001088 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089
1090 if (log)
1091 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1092
1093 if (control_only)
1094 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1095 else
1096 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1097}
1098
1099bool
1100Process::IsRunning () const
1101{
1102 return StateIsRunningState (m_public_state.GetValue());
1103}
1104
1105int
1106Process::GetExitStatus ()
1107{
1108 if (m_public_state.GetValue() == eStateExited)
1109 return m_exit_status;
1110 return -1;
1111}
1112
Greg Clayton85851dd2010-12-04 00:10:17 +00001113
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114const char *
1115Process::GetExitDescription ()
1116{
1117 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1118 return m_exit_string.c_str();
1119 return NULL;
1120}
1121
Greg Clayton6779606a2011-01-22 23:43:18 +00001122bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001123Process::SetExitStatus (int status, const char *cstr)
1124{
Greg Clayton414f5d32011-01-25 02:58:48 +00001125 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1126 if (log)
1127 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1128 status, status,
1129 cstr ? "\"" : "",
1130 cstr ? cstr : "NULL",
1131 cstr ? "\"" : "");
1132
Greg Clayton6779606a2011-01-22 23:43:18 +00001133 // We were already in the exited state
1134 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001135 {
Greg Clayton385d6032011-01-26 23:47:29 +00001136 if (log)
1137 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001138 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001139 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001140
1141 m_exit_status = status;
1142 if (cstr)
1143 m_exit_string = cstr;
1144 else
1145 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146
Greg Clayton6779606a2011-01-22 23:43:18 +00001147 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001148
Greg Clayton6779606a2011-01-22 23:43:18 +00001149 SetPrivateState (eStateExited);
1150 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001151}
1152
1153// This static callback can be used to watch for local child processes on
1154// the current host. The the child process exits, the process will be
1155// found in the global target list (we want to be completely sure that the
1156// lldb_private::Process doesn't go away before we can deliver the signal.
1157bool
Greg Claytone4e45922011-11-16 05:37:56 +00001158Process::SetProcessExitStatus (void *callback_baton,
1159 lldb::pid_t pid,
1160 bool exited,
1161 int signo, // Zero for no signal
1162 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163)
1164{
Greg Claytone4e45922011-11-16 05:37:56 +00001165 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1166 if (log)
1167 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%i, exited=%i, signal=%i, exit_status=%i)\n",
1168 callback_baton,
1169 pid,
1170 exited,
1171 signo,
1172 exit_status);
1173
1174 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175 {
Greg Clayton66111032010-06-23 01:19:29 +00001176 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001177 if (target_sp)
1178 {
1179 ProcessSP process_sp (target_sp->GetProcessSP());
1180 if (process_sp)
1181 {
1182 const char *signal_cstr = NULL;
1183 if (signo)
1184 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1185
1186 process_sp->SetExitStatus (exit_status, signal_cstr);
1187 }
1188 }
1189 return true;
1190 }
1191 return false;
1192}
1193
1194
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001195void
1196Process::UpdateThreadListIfNeeded ()
1197{
1198 const uint32_t stop_id = GetStopID();
1199 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1200 {
Greg Clayton2637f822011-11-17 01:23:07 +00001201 const StateType state = GetPrivateState();
1202 if (StateIsStoppedState (state, true))
1203 {
1204 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001205 // m_thread_list does have its own mutex, but we need to
1206 // hold onto the mutex between the call to UpdateThreadList(...)
1207 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton2637f822011-11-17 01:23:07 +00001208 ThreadList new_thread_list(this);
1209 // Always update the thread list with the protocol specific
1210 // thread list
1211 UpdateThreadList (m_thread_list, new_thread_list);
1212 OperatingSystem *os = GetOperatingSystem ();
1213 if (os)
1214 os->UpdateThreadList (m_thread_list, new_thread_list);
1215 m_thread_list.Update (new_thread_list);
1216 m_thread_list.SetStopID (stop_id);
1217 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001218 }
1219}
1220
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001221uint32_t
1222Process::GetNextThreadIndexID ()
1223{
1224 return ++m_thread_index_id;
1225}
1226
1227StateType
1228Process::GetState()
1229{
1230 // If any other threads access this we will need a mutex for it
1231 return m_public_state.GetValue ();
1232}
1233
1234void
1235Process::SetPublicState (StateType new_state)
1236{
Greg Clayton414f5d32011-01-25 02:58:48 +00001237 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001238 if (log)
1239 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1240 m_public_state.SetValue (new_state);
1241}
1242
1243StateType
1244Process::GetPrivateState ()
1245{
1246 return m_private_state.GetValue();
1247}
1248
1249void
1250Process::SetPrivateState (StateType new_state)
1251{
Greg Clayton414f5d32011-01-25 02:58:48 +00001252 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001253 bool state_changed = false;
1254
1255 if (log)
1256 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1257
1258 Mutex::Locker locker(m_private_state.GetMutex());
1259
1260 const StateType old_state = m_private_state.GetValueNoLock ();
1261 state_changed = old_state != new_state;
1262 if (state_changed)
1263 {
1264 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001265 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001266 {
Jim Ingham4b536182011-08-09 02:12:22 +00001267 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001268 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001269 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001270 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001271 }
1272 // Use our target to get a shared pointer to ourselves...
1273 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1274 }
1275 else
1276 {
1277 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001278 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001279 }
1280}
1281
Jim Ingham0faa43f2011-11-08 03:00:11 +00001282void
1283Process::SetRunningUserExpression (bool on)
1284{
1285 m_mod_id.SetRunningUserExpression (on);
1286}
1287
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001288addr_t
1289Process::GetImageInfoAddress()
1290{
1291 return LLDB_INVALID_ADDRESS;
1292}
1293
Greg Clayton8f343b02010-11-04 01:54:29 +00001294//----------------------------------------------------------------------
1295// LoadImage
1296//
1297// This function provides a default implementation that works for most
1298// unix variants. Any Process subclasses that need to do shared library
1299// loading differently should override LoadImage and UnloadImage and
1300// do what is needed.
1301//----------------------------------------------------------------------
1302uint32_t
1303Process::LoadImage (const FileSpec &image_spec, Error &error)
1304{
1305 DynamicLoader *loader = GetDynamicLoader();
1306 if (loader)
1307 {
1308 error = loader->CanLoadImage();
1309 if (error.Fail())
1310 return LLDB_INVALID_IMAGE_TOKEN;
1311 }
1312
1313 if (error.Success())
1314 {
1315 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001316
1317 if (thread_sp)
1318 {
1319 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1320
1321 if (frame_sp)
1322 {
1323 ExecutionContext exe_ctx;
1324 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001325 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001326 StreamString expr;
1327 char path[PATH_MAX];
1328 image_spec.GetPath(path, sizeof(path));
1329 expr.Printf("dlopen (\"%s\", 2)", path);
1330 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001331 lldb::ValueObjectSP result_valobj_sp;
Sean Callananc7b65062011-11-07 23:35:40 +00001332 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chene92aa432011-09-09 00:01:43 +00001333 error = result_valobj_sp->GetError();
1334 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001335 {
1336 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001337 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001338 {
1339 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1340 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1341 {
1342 uint32_t image_token = m_image_tokens.size();
1343 m_image_tokens.push_back (image_ptr);
1344 return image_token;
1345 }
1346 }
1347 }
1348 }
1349 }
1350 }
1351 return LLDB_INVALID_IMAGE_TOKEN;
1352}
1353
1354//----------------------------------------------------------------------
1355// UnloadImage
1356//
1357// This function provides a default implementation that works for most
1358// unix variants. Any Process subclasses that need to do shared library
1359// loading differently should override LoadImage and UnloadImage and
1360// do what is needed.
1361//----------------------------------------------------------------------
1362Error
1363Process::UnloadImage (uint32_t image_token)
1364{
1365 Error error;
1366 if (image_token < m_image_tokens.size())
1367 {
1368 const addr_t image_addr = m_image_tokens[image_token];
1369 if (image_addr == LLDB_INVALID_ADDRESS)
1370 {
1371 error.SetErrorString("image already unloaded");
1372 }
1373 else
1374 {
1375 DynamicLoader *loader = GetDynamicLoader();
1376 if (loader)
1377 error = loader->CanLoadImage();
1378
1379 if (error.Success())
1380 {
1381 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001382
1383 if (thread_sp)
1384 {
1385 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1386
1387 if (frame_sp)
1388 {
1389 ExecutionContext exe_ctx;
1390 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001391 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001392 StreamString expr;
1393 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1394 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001395 lldb::ValueObjectSP result_valobj_sp;
Sean Callananc7b65062011-11-07 23:35:40 +00001396 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +00001397 if (result_valobj_sp->GetError().Success())
1398 {
1399 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001400 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001401 {
1402 if (scalar.UInt(1))
1403 {
1404 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1405 }
1406 else
1407 {
1408 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1409 }
1410 }
1411 }
1412 else
1413 {
1414 error = result_valobj_sp->GetError();
1415 }
1416 }
1417 }
1418 }
1419 }
1420 }
1421 else
1422 {
1423 error.SetErrorString("invalid image token");
1424 }
1425 return error;
1426}
1427
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001428const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001429Process::GetABI()
1430{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001431 if (!m_abi_sp)
1432 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1433 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001434}
1435
Jim Ingham22777012010-09-23 02:01:19 +00001436LanguageRuntime *
1437Process::GetLanguageRuntime(lldb::LanguageType language)
1438{
1439 LanguageRuntimeCollection::iterator pos;
1440 pos = m_language_runtimes.find (language);
1441 if (pos == m_language_runtimes.end())
1442 {
1443 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1444
1445 m_language_runtimes[language]
1446 = runtime;
1447 return runtime.get();
1448 }
1449 else
1450 return (*pos).second.get();
1451}
1452
1453CPPLanguageRuntime *
1454Process::GetCPPLanguageRuntime ()
1455{
1456 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1457 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1458 return static_cast<CPPLanguageRuntime *> (runtime);
1459 return NULL;
1460}
1461
1462ObjCLanguageRuntime *
1463Process::GetObjCLanguageRuntime ()
1464{
1465 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1466 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1467 return static_cast<ObjCLanguageRuntime *> (runtime);
1468 return NULL;
1469}
1470
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001471BreakpointSiteList &
1472Process::GetBreakpointSiteList()
1473{
1474 return m_breakpoint_site_list;
1475}
1476
1477const BreakpointSiteList &
1478Process::GetBreakpointSiteList() const
1479{
1480 return m_breakpoint_site_list;
1481}
1482
1483
1484void
1485Process::DisableAllBreakpointSites ()
1486{
1487 m_breakpoint_site_list.SetEnabledForAll (false);
1488}
1489
1490Error
1491Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1492{
1493 Error error (DisableBreakpointSiteByID (break_id));
1494
1495 if (error.Success())
1496 m_breakpoint_site_list.Remove(break_id);
1497
1498 return error;
1499}
1500
1501Error
1502Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1503{
1504 Error error;
1505 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1506 if (bp_site_sp)
1507 {
1508 if (bp_site_sp->IsEnabled())
1509 error = DisableBreakpoint (bp_site_sp.get());
1510 }
1511 else
1512 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001513 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001514 }
1515
1516 return error;
1517}
1518
1519Error
1520Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1521{
1522 Error error;
1523 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1524 if (bp_site_sp)
1525 {
1526 if (!bp_site_sp->IsEnabled())
1527 error = EnableBreakpoint (bp_site_sp.get());
1528 }
1529 else
1530 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001531 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001532 }
1533 return error;
1534}
1535
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001536lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001537Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1538{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001539 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001540 if (load_addr != LLDB_INVALID_ADDRESS)
1541 {
1542 BreakpointSiteSP bp_site_sp;
1543
1544 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1545 // create a new breakpoint site and add it.
1546
1547 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1548
1549 if (bp_site_sp)
1550 {
1551 bp_site_sp->AddOwner (owner);
1552 owner->SetBreakpointSite (bp_site_sp);
1553 return bp_site_sp->GetID();
1554 }
1555 else
1556 {
1557 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1558 if (bp_site_sp)
1559 {
1560 if (EnableBreakpoint (bp_site_sp.get()).Success())
1561 {
1562 owner->SetBreakpointSite (bp_site_sp);
1563 return m_breakpoint_site_list.Add (bp_site_sp);
1564 }
1565 }
1566 }
1567 }
1568 // We failed to enable the breakpoint
1569 return LLDB_INVALID_BREAK_ID;
1570
1571}
1572
1573void
1574Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1575{
1576 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1577 if (num_owners == 0)
1578 {
1579 DisableBreakpoint(bp_site_sp.get());
1580 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1581 }
1582}
1583
1584
1585size_t
1586Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1587{
1588 size_t bytes_removed = 0;
1589 addr_t intersect_addr;
1590 size_t intersect_size;
1591 size_t opcode_offset;
1592 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001593 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001594 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001595
Jim Ingham20c77192011-06-29 19:42:28 +00001596 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001597 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001598 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001599 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001600 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001601 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001602 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001603 {
1604 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1605 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001606 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001607 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001608 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001609 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001610 }
1611 }
1612 }
1613 return bytes_removed;
1614}
1615
1616
Greg Claytonded470d2011-03-19 01:12:21 +00001617
1618size_t
1619Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1620{
1621 PlatformSP platform_sp (m_target.GetPlatform());
1622 if (platform_sp)
1623 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1624 return 0;
1625}
1626
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001627Error
1628Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1629{
1630 Error error;
1631 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001632 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001633 const addr_t bp_addr = bp_site->GetLoadAddress();
1634 if (log)
1635 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1636 if (bp_site->IsEnabled())
1637 {
1638 if (log)
1639 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1640 return error;
1641 }
1642
1643 if (bp_addr == LLDB_INVALID_ADDRESS)
1644 {
1645 error.SetErrorString("BreakpointSite contains an invalid load address.");
1646 return error;
1647 }
1648 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1649 // trap for the breakpoint site
1650 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1651
1652 if (bp_opcode_size == 0)
1653 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001654 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001655 }
1656 else
1657 {
1658 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1659
1660 if (bp_opcode_bytes == NULL)
1661 {
1662 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1663 return error;
1664 }
1665
1666 // Save the original opcode by reading it
1667 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1668 {
1669 // Write a software breakpoint in place of the original opcode
1670 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1671 {
1672 uint8_t verify_bp_opcode_bytes[64];
1673 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1674 {
1675 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1676 {
1677 bp_site->SetEnabled(true);
1678 bp_site->SetType (BreakpointSite::eSoftware);
1679 if (log)
1680 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1681 bp_site->GetID(),
1682 (uint64_t)bp_addr);
1683 }
1684 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001685 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001686 }
1687 else
1688 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1689 }
1690 else
1691 error.SetErrorString("Unable to write breakpoint trap to memory.");
1692 }
1693 else
1694 error.SetErrorString("Unable to read memory at breakpoint address.");
1695 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001696 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001697 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1698 bp_site->GetID(),
1699 (uint64_t)bp_addr,
1700 error.AsCString());
1701 return error;
1702}
1703
1704Error
1705Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1706{
1707 Error error;
1708 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001709 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001710 addr_t bp_addr = bp_site->GetLoadAddress();
1711 lldb::user_id_t breakID = bp_site->GetID();
1712 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001713 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001714
1715 if (bp_site->IsHardware())
1716 {
1717 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1718 }
1719 else if (bp_site->IsEnabled())
1720 {
1721 const size_t break_op_size = bp_site->GetByteSize();
1722 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1723 if (break_op_size > 0)
1724 {
1725 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001726 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001727 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001728 bool break_op_found = false;
1729
1730 // Read the breakpoint opcode
1731 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1732 {
1733 bool verify = false;
1734 // Make sure we have the a breakpoint opcode exists at this address
1735 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1736 {
1737 break_op_found = true;
1738 // We found a valid breakpoint opcode at this address, now restore
1739 // the saved opcode.
1740 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1741 {
1742 verify = true;
1743 }
1744 else
1745 error.SetErrorString("Memory write failed when restoring original opcode.");
1746 }
1747 else
1748 {
1749 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1750 // Set verify to true and so we can check if the original opcode has already been restored
1751 verify = true;
1752 }
1753
1754 if (verify)
1755 {
Greg Claytonc982c762010-07-09 20:39:50 +00001756 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001757 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001758 // Verify that our original opcode made it back to the inferior
1759 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1760 {
1761 // compare the memory we just read with the original opcode
1762 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1763 {
1764 // SUCCESS
1765 bp_site->SetEnabled(false);
1766 if (log)
1767 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1768 return error;
1769 }
1770 else
1771 {
1772 if (break_op_found)
1773 error.SetErrorString("Failed to restore original opcode.");
1774 }
1775 }
1776 else
1777 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1778 }
1779 }
1780 else
1781 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1782 }
1783 }
1784 else
1785 {
1786 if (log)
1787 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1788 return error;
1789 }
1790
1791 if (log)
1792 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1793 bp_site->GetID(),
1794 (uint64_t)bp_addr,
1795 error.AsCString());
1796 return error;
1797
1798}
1799
Greg Clayton58be07b2011-01-07 06:08:19 +00001800// Comment out line below to disable memory caching
1801#define ENABLE_MEMORY_CACHING
1802// Uncomment to verify memory caching works after making changes to caching code
1803//#define VERIFY_MEMORY_READS
1804
1805#if defined (ENABLE_MEMORY_CACHING)
1806
1807#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001808
1809size_t
1810Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1811{
Greg Clayton58be07b2011-01-07 06:08:19 +00001812 // Memory caching is enabled, with debug verification
1813 if (buf && size)
1814 {
1815 // Uncomment the line below to make sure memory caching is working.
1816 // I ran this through the test suite and got no assertions, so I am
1817 // pretty confident this is working well. If any changes are made to
1818 // memory caching, uncomment the line below and test your changes!
1819
1820 // Verify all memory reads by using the cache first, then redundantly
1821 // reading the same memory from the inferior and comparing to make sure
1822 // everything is exactly the same.
1823 std::string verify_buf (size, '\0');
1824 assert (verify_buf.size() == size);
1825 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1826 Error verify_error;
1827 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1828 assert (cache_bytes_read == verify_bytes_read);
1829 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1830 assert (verify_error.Success() == error.Success());
1831 return cache_bytes_read;
1832 }
1833 return 0;
1834}
1835
1836#else // #if defined (VERIFY_MEMORY_READS)
1837
1838size_t
1839Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1840{
1841 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001842 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001843}
1844
1845#endif // #else for #if defined (VERIFY_MEMORY_READS)
1846
1847#else // #if defined (ENABLE_MEMORY_CACHING)
1848
1849size_t
1850Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1851{
1852 // Memory caching is disabled
1853 return ReadMemoryFromInferior (addr, buf, size, error);
1854}
1855
1856#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1857
1858
1859size_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001860Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1861{
1862 size_t total_cstr_len = 0;
1863 if (dst && dst_max_len)
1864 {
1865 // NULL out everything just to be safe
1866 memset (dst, 0, dst_max_len);
1867 Error error;
1868 addr_t curr_addr = addr;
1869 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1870 size_t bytes_left = dst_max_len - 1;
1871 char *curr_dst = dst;
1872
1873 while (bytes_left > 0)
1874 {
1875 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1876 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1877 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1878
1879 if (bytes_read == 0)
1880 {
1881 dst[total_cstr_len] = '\0';
1882 break;
1883 }
1884 const size_t len = strlen(curr_dst);
1885
1886 total_cstr_len += len;
1887
1888 if (len < bytes_to_read)
1889 break;
1890
1891 curr_dst += bytes_read;
1892 curr_addr += bytes_read;
1893 bytes_left -= bytes_read;
1894 }
1895 }
1896 return total_cstr_len;
1897}
1898
1899size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00001900Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1901{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001902 if (buf == NULL || size == 0)
1903 return 0;
1904
1905 size_t bytes_read = 0;
1906 uint8_t *bytes = (uint8_t *)buf;
1907
1908 while (bytes_read < size)
1909 {
1910 const size_t curr_size = size - bytes_read;
1911 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1912 bytes + bytes_read,
1913 curr_size,
1914 error);
1915 bytes_read += curr_bytes_read;
1916 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1917 break;
1918 }
1919
1920 // Replace any software breakpoint opcodes that fall into this range back
1921 // into "buf" before we return
1922 if (bytes_read > 0)
1923 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1924 return bytes_read;
1925}
1926
Greg Clayton58a4c462010-12-16 20:01:20 +00001927uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001928Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00001929{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001930 Scalar scalar;
1931 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1932 return scalar.ULongLong(fail_value);
1933 return fail_value;
1934}
1935
1936addr_t
1937Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1938{
1939 Scalar scalar;
1940 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1941 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1942 return LLDB_INVALID_ADDRESS;
1943}
1944
1945
1946bool
1947Process::WritePointerToMemory (lldb::addr_t vm_addr,
1948 lldb::addr_t ptr_value,
1949 Error &error)
1950{
1951 Scalar scalar;
1952 const uint32_t addr_byte_size = GetAddressByteSize();
1953 if (addr_byte_size <= 4)
1954 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00001955 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001956 scalar = ptr_value;
1957 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00001958}
1959
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001960size_t
1961Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1962{
1963 size_t bytes_written = 0;
1964 const uint8_t *bytes = (const uint8_t *)buf;
1965
1966 while (bytes_written < size)
1967 {
1968 const size_t curr_size = size - bytes_written;
1969 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1970 bytes + bytes_written,
1971 curr_size,
1972 error);
1973 bytes_written += curr_bytes_written;
1974 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1975 break;
1976 }
1977 return bytes_written;
1978}
1979
1980size_t
1981Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1982{
Greg Clayton58be07b2011-01-07 06:08:19 +00001983#if defined (ENABLE_MEMORY_CACHING)
1984 m_memory_cache.Flush (addr, size);
1985#endif
1986
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001987 if (buf == NULL || size == 0)
1988 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00001989
Jim Ingham4b536182011-08-09 02:12:22 +00001990 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00001991
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001992 // We need to write any data that would go where any current software traps
1993 // (enabled software breakpoints) any software traps (breakpoints) that we
1994 // may have placed in our tasks memory.
1995
1996 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1997 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1998
1999 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002000 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002001
2002 BreakpointSiteList::collection::const_iterator pos;
2003 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002004 addr_t intersect_addr = 0;
2005 size_t intersect_size = 0;
2006 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002007 const uint8_t *ubuf = (const uint8_t *)buf;
2008
2009 for (pos = iter; pos != end; ++pos)
2010 {
2011 BreakpointSiteSP bp;
2012 bp = pos->second;
2013
2014 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2015 assert(addr <= intersect_addr && intersect_addr < addr + size);
2016 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2017 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2018
2019 // Check for bytes before this breakpoint
2020 const addr_t curr_addr = addr + bytes_written;
2021 if (intersect_addr > curr_addr)
2022 {
2023 // There are some bytes before this breakpoint that we need to
2024 // just write to memory
2025 size_t curr_size = intersect_addr - curr_addr;
2026 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2027 ubuf + bytes_written,
2028 curr_size,
2029 error);
2030 bytes_written += curr_bytes_written;
2031 if (curr_bytes_written != curr_size)
2032 {
2033 // We weren't able to write all of the requested bytes, we
2034 // are done looping and will return the number of bytes that
2035 // we have written so far.
2036 break;
2037 }
2038 }
2039
2040 // Now write any bytes that would cover up any software breakpoints
2041 // directly into the breakpoint opcode buffer
2042 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2043 bytes_written += intersect_size;
2044 }
2045
2046 // Write any remaining bytes after the last breakpoint if we have any left
2047 if (bytes_written < size)
2048 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2049 ubuf + bytes_written,
2050 size - bytes_written,
2051 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002052
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002053 return bytes_written;
2054}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002055
2056size_t
2057Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2058{
2059 if (byte_size == UINT32_MAX)
2060 byte_size = scalar.GetByteSize();
2061 if (byte_size > 0)
2062 {
2063 uint8_t buf[32];
2064 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2065 if (mem_size > 0)
2066 return WriteMemory(addr, buf, mem_size, error);
2067 else
2068 error.SetErrorString ("failed to get scalar as memory data");
2069 }
2070 else
2071 {
2072 error.SetErrorString ("invalid scalar value");
2073 }
2074 return 0;
2075}
2076
2077size_t
2078Process::ReadScalarIntegerFromMemory (addr_t addr,
2079 uint32_t byte_size,
2080 bool is_signed,
2081 Scalar &scalar,
2082 Error &error)
2083{
2084 uint64_t uval;
2085
2086 if (byte_size <= sizeof(uval))
2087 {
2088 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2089 if (bytes_read == byte_size)
2090 {
2091 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2092 uint32_t offset = 0;
2093 if (byte_size <= 4)
2094 scalar = data.GetMaxU32 (&offset, byte_size);
2095 else
2096 scalar = data.GetMaxU64 (&offset, byte_size);
2097
2098 if (is_signed)
2099 scalar.SignExtend(byte_size * 8);
2100 return bytes_read;
2101 }
2102 }
2103 else
2104 {
2105 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2106 }
2107 return 0;
2108}
2109
Greg Claytond495c532011-05-17 03:37:42 +00002110#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002111addr_t
2112Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2113{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002114 if (GetPrivateState() != eStateStopped)
2115 return LLDB_INVALID_ADDRESS;
2116
Greg Claytond495c532011-05-17 03:37:42 +00002117#if defined (USE_ALLOCATE_MEMORY_CACHE)
2118 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2119#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002120 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2121 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2122 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002123 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 +00002124 size,
Greg Claytond495c532011-05-17 03:37:42 +00002125 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002126 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002127 m_mod_id.GetStopID(),
2128 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002129 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002130#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002131}
2132
Sean Callanan90539452011-09-20 23:01:51 +00002133bool
2134Process::CanJIT ()
2135{
2136 return m_can_jit == eCanJITYes;
2137}
2138
2139void
2140Process::SetCanJIT (bool can_jit)
2141{
2142 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2143}
2144
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002145Error
2146Process::DeallocateMemory (addr_t ptr)
2147{
Greg Claytond495c532011-05-17 03:37:42 +00002148 Error error;
2149#if defined (USE_ALLOCATE_MEMORY_CACHE)
2150 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2151 {
2152 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2153 }
2154#else
2155 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002156
2157 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2158 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002159 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 +00002160 ptr,
2161 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002162 m_mod_id.GetStopID(),
2163 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002164#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002165 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002166}
2167
2168
2169Error
Johnny Chen01a67862011-10-14 00:42:25 +00002170Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002171{
2172 Error error;
2173 error.SetErrorString("watchpoints are not supported");
2174 return error;
2175}
2176
2177Error
Johnny Chen01a67862011-10-14 00:42:25 +00002178Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002179{
2180 Error error;
2181 error.SetErrorString("watchpoints are not supported");
2182 return error;
2183}
2184
2185StateType
2186Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2187{
2188 StateType state;
2189 // Now wait for the process to launch and return control to us, and then
2190 // call DidLaunch:
2191 while (1)
2192 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002193 event_sp.reset();
2194 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2195
Greg Clayton2637f822011-11-17 01:23:07 +00002196 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002197 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002198
2199 // If state is invalid, then we timed out
2200 if (state == eStateInvalid)
2201 break;
2202
2203 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002204 HandlePrivateEvent (event_sp);
2205 }
2206 return state;
2207}
2208
2209Error
Greg Clayton982c9762011-11-03 21:22:33 +00002210Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002211{
2212 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002213 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002214 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002215 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002216 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002217
Greg Claytonaa149cb2011-08-11 02:48:45 +00002218 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002219 if (exe_module)
2220 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002221 char local_exec_file_path[PATH_MAX];
2222 char platform_exec_file_path[PATH_MAX];
2223 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2224 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002225 if (exe_module->GetFileSpec().Exists())
2226 {
Greg Clayton71337622011-02-24 22:24:29 +00002227 if (PrivateStateThreadIsValid ())
2228 PausePrivateStateThread ();
2229
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002230 error = WillLaunch (exe_module);
2231 if (error.Success())
2232 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002233 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002234 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002235
2236 // Now launch using these arguments.
Greg Clayton982c9762011-11-03 21:22:33 +00002237 error = DoLaunch (exe_module, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002238
2239 if (error.Fail())
2240 {
2241 if (GetID() != LLDB_INVALID_PROCESS_ID)
2242 {
2243 SetID (LLDB_INVALID_PROCESS_ID);
2244 const char *error_string = error.AsCString();
2245 if (error_string == NULL)
2246 error_string = "launch failed";
2247 SetExitStatus (-1, error_string);
2248 }
2249 }
2250 else
2251 {
2252 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002253 TimeValue timeout_time;
2254 timeout_time = TimeValue::Now();
2255 timeout_time.OffsetWithSeconds(10);
2256 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002257
Greg Clayton1a38ea72011-06-22 01:42:17 +00002258 if (state == eStateInvalid || event_sp.get() == NULL)
2259 {
2260 // We were able to launch the process, but we failed to
2261 // catch the initial stop.
2262 SetExitStatus (0, "failed to catch stop after launch");
2263 Destroy();
2264 }
2265 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002266 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002267
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268 DidLaunch ();
2269
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002270 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002271 if (m_dyld_ap.get())
2272 m_dyld_ap->DidLaunch();
2273
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002274 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002275 // This delays passing the stopped event to listeners till DidLaunch gets
2276 // a chance to complete...
2277 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002278
2279 if (PrivateStateThreadIsValid ())
2280 ResumePrivateStateThread ();
2281 else
2282 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283 }
2284 else if (state == eStateExited)
2285 {
2286 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2287 // not likely to work, and return an invalid pid.
2288 HandlePrivateEvent (event_sp);
2289 }
2290 }
2291 }
2292 }
2293 else
2294 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002295 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002296 }
2297 }
2298 return error;
2299}
2300
Jim Inghambb3a2832011-01-29 01:49:25 +00002301Process::NextEventAction::EventActionResult
2302Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002303{
Jim Inghambb3a2832011-01-29 01:49:25 +00002304 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2305 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002306 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002307 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002308 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002309 return eEventActionRetry;
2310
2311 case eStateStopped:
2312 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002313 {
2314 // During attach, prior to sending the eStateStopped event,
2315 // lldb_private::Process subclasses must set the process must set
2316 // the new process ID.
2317 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2318 if (m_exec_count > 0)
2319 {
2320 --m_exec_count;
2321 m_process->Resume();
2322 return eEventActionRetry;
2323 }
2324 else
2325 {
2326 m_process->CompleteAttach ();
2327 return eEventActionSuccess;
2328 }
2329 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002330 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002331
Greg Clayton513c26c2011-01-29 07:10:55 +00002332 default:
2333 case eStateExited:
2334 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002335 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002336 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002337
2338 m_exit_string.assign ("No valid Process");
2339 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002340}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002341
Jim Inghambb3a2832011-01-29 01:49:25 +00002342Process::NextEventAction::EventActionResult
2343Process::AttachCompletionHandler::HandleBeingInterrupted()
2344{
2345 return eEventActionSuccess;
2346}
2347
2348const char *
2349Process::AttachCompletionHandler::GetExitString ()
2350{
2351 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002352}
2353
2354Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002355Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002356{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002357 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002358 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002359 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002360 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002361
Greg Clayton144f3a92011-11-15 03:53:30 +00002362 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002363 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002364 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002365 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002366 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002367
Greg Clayton144f3a92011-11-15 03:53:30 +00002368 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002369 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002370 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2371
2372 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002373 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002374 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2375 if (error.Success())
2376 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002377 m_should_detach = true;
2378
Greg Clayton144f3a92011-11-15 03:53:30 +00002379 SetPublicState (eStateAttaching);
2380 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2381 if (error.Fail())
2382 {
2383 if (GetID() != LLDB_INVALID_PROCESS_ID)
2384 {
2385 SetID (LLDB_INVALID_PROCESS_ID);
2386 if (error.AsCString() == NULL)
2387 error.SetErrorString("attach failed");
2388
2389 SetExitStatus(-1, error.AsCString());
2390 }
2391 }
2392 else
2393 {
2394 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2395 StartPrivateStateThread();
2396 }
2397 return error;
2398 }
Greg Claytone996fd32011-03-08 22:40:15 +00002399 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002400 else
Greg Claytone996fd32011-03-08 22:40:15 +00002401 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002402 ProcessInstanceInfoList process_infos;
2403 PlatformSP platform_sp (m_target.GetPlatform ());
2404
2405 if (platform_sp)
2406 {
2407 ProcessInstanceInfoMatch match_info;
2408 match_info.GetProcessInfo() = attach_info;
2409 match_info.SetNameMatchType (eNameMatchEquals);
2410 platform_sp->FindProcesses (match_info, process_infos);
2411 const uint32_t num_matches = process_infos.GetSize();
2412 if (num_matches == 1)
2413 {
2414 attach_pid = process_infos.GetProcessIDAtIndex(0);
2415 // Fall through and attach using the above process ID
2416 }
2417 else
2418 {
2419 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2420 if (num_matches > 1)
2421 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2422 else
2423 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2424 }
2425 }
2426 else
2427 {
2428 error.SetErrorString ("invalid platform, can't find processes by name");
2429 return error;
2430 }
Greg Claytone996fd32011-03-08 22:40:15 +00002431 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002432 }
2433 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002434 {
2435 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002436 }
2437 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002438
2439 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002440 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002441 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002442 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002443 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002444 m_should_detach = true;
Greg Claytone996fd32011-03-08 22:40:15 +00002445 SetPublicState (eStateAttaching);
Greg Clayton144f3a92011-11-15 03:53:30 +00002446
2447 error = DoAttachToProcessWithID (attach_pid);
2448 if (error.Success())
2449 {
2450
2451 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2452 StartPrivateStateThread();
2453 }
2454 else
Greg Claytone996fd32011-03-08 22:40:15 +00002455 {
2456 if (GetID() != LLDB_INVALID_PROCESS_ID)
2457 {
2458 SetID (LLDB_INVALID_PROCESS_ID);
2459 const char *error_string = error.AsCString();
2460 if (error_string == NULL)
2461 error_string = "attach failed";
2462
2463 SetExitStatus(-1, error_string);
2464 }
2465 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002466 }
2467 }
2468 return error;
2469}
2470
Greg Clayton144f3a92011-11-15 03:53:30 +00002471//Error
2472//Process::Attach (const char *process_name, bool wait_for_launch)
2473//{
2474// m_abi_sp.reset();
2475// m_process_input_reader.reset();
2476//
2477// // Find the process and its architecture. Make sure it matches the architecture
2478// // of the current Target, and if not adjust it.
2479// Error error;
2480//
2481// if (!wait_for_launch)
2482// {
2483// ProcessInstanceInfoList process_infos;
2484// PlatformSP platform_sp (m_target.GetPlatform ());
2485// assert (platform_sp.get());
2486//
2487// if (platform_sp)
2488// {
2489// ProcessInstanceInfoMatch match_info;
2490// match_info.GetProcessInfo().SetName(process_name);
2491// match_info.SetNameMatchType (eNameMatchEquals);
2492// platform_sp->FindProcesses (match_info, process_infos);
2493// if (process_infos.GetSize() > 1)
2494// {
2495// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2496// }
2497// else if (process_infos.GetSize() == 0)
2498// {
2499// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2500// }
2501// }
2502// else
2503// {
2504// error.SetErrorString ("invalid platform");
2505// }
2506// }
2507//
2508// if (error.Success())
2509// {
2510// m_dyld_ap.reset();
2511// m_os_ap.reset();
2512//
2513// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2514// if (error.Success())
2515// {
2516// SetPublicState (eStateAttaching);
2517// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2518// if (error.Fail())
2519// {
2520// if (GetID() != LLDB_INVALID_PROCESS_ID)
2521// {
2522// SetID (LLDB_INVALID_PROCESS_ID);
2523// const char *error_string = error.AsCString();
2524// if (error_string == NULL)
2525// error_string = "attach failed";
2526//
2527// SetExitStatus(-1, error_string);
2528// }
2529// }
2530// else
2531// {
2532// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2533// StartPrivateStateThread();
2534// }
2535// }
2536// }
2537// return error;
2538//}
2539
Greg Clayton93d3c8332011-02-16 04:46:07 +00002540void
2541Process::CompleteAttach ()
2542{
2543 // Let the process subclass figure out at much as it can about the process
2544 // before we go looking for a dynamic loader plug-in.
2545 DidAttach();
2546
Jim Ingham4299fdb2011-09-15 01:10:17 +00002547 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2548 // the same as the one we've already set, switch architectures.
2549 PlatformSP platform_sp (m_target.GetPlatform ());
2550 assert (platform_sp.get());
2551 if (platform_sp)
2552 {
2553 ProcessInstanceInfo process_info;
2554 platform_sp->GetProcessInfo (GetID(), process_info);
2555 const ArchSpec &process_arch = process_info.GetArchitecture();
2556 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2557 m_target.SetArchitecture (process_arch);
2558 }
2559
2560 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002561 // plug-in
Greg Clayton7a5388b2011-03-20 04:57:14 +00002562 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002563 if (m_dyld_ap.get())
2564 m_dyld_ap->DidAttach();
2565
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002566 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002567 // Figure out which one is the executable, and set that in our target:
2568 ModuleList &modules = m_target.GetImages();
2569
2570 size_t num_modules = modules.GetSize();
2571 for (int i = 0; i < num_modules; i++)
2572 {
2573 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002574 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002575 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002576 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002577 m_target.SetExecutableModule (module_sp, false);
2578 break;
2579 }
2580 }
2581}
2582
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002583Error
Greg Claytonb766a732011-02-04 01:58:07 +00002584Process::ConnectRemote (const char *remote_url)
2585{
Greg Claytonb766a732011-02-04 01:58:07 +00002586 m_abi_sp.reset();
2587 m_process_input_reader.reset();
2588
2589 // Find the process and its architecture. Make sure it matches the architecture
2590 // of the current Target, and if not adjust it.
2591
2592 Error error (DoConnectRemote (remote_url));
2593 if (error.Success())
2594 {
Greg Clayton71337622011-02-24 22:24:29 +00002595 if (GetID() != LLDB_INVALID_PROCESS_ID)
2596 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002597 EventSP event_sp;
2598 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2599
2600 if (state == eStateStopped || state == eStateCrashed)
2601 {
2602 // If we attached and actually have a process on the other end, then
2603 // this ended up being the equivalent of an attach.
2604 CompleteAttach ();
2605
2606 // This delays passing the stopped event to listeners till
2607 // CompleteAttach gets a chance to complete...
2608 HandlePrivateEvent (event_sp);
2609
2610 }
Greg Clayton71337622011-02-24 22:24:29 +00002611 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002612
2613 if (PrivateStateThreadIsValid ())
2614 ResumePrivateStateThread ();
2615 else
2616 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002617 }
2618 return error;
2619}
2620
2621
2622Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002623Process::Resume ()
2624{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002625 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002626 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002627 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002628 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002629 StateAsCString(m_public_state.GetValue()),
2630 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002631
2632 Error error (WillResume());
2633 // Tell the process it is about to resume before the thread list
2634 if (error.Success())
2635 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002636 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002637 // can let all of our threads know that they are about to be
2638 // resumed. Threads will each be called with
2639 // Thread::WillResume(StateType) where StateType contains the state
2640 // that they are supposed to have when the process is resumed
2641 // (suspended/running/stepping). Threads should also check
2642 // their resume signal in lldb::Thread::GetResumeSignal()
2643 // to see if they are suppoed to start back up with a signal.
2644 if (m_thread_list.WillResume())
2645 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00002646 m_mod_id.BumpResumeID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002647 error = DoResume();
2648 if (error.Success())
2649 {
2650 DidResume();
2651 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00002652 if (log)
2653 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002654 }
2655 }
2656 else
2657 {
Jim Ingham444586b2011-01-24 06:34:17 +00002658 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002659 }
2660 }
Jim Ingham444586b2011-01-24 06:34:17 +00002661 else if (log)
2662 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002663 return error;
2664}
2665
2666Error
2667Process::Halt ()
2668{
Jim Inghambb3a2832011-01-29 01:49:25 +00002669 // Pause our private state thread so we can ensure no one else eats
2670 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002671 Listener halt_listener ("lldb.process.halt_listener");
2672 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002673
Jim Inghambb3a2832011-01-29 01:49:25 +00002674 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002675 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002676
Greg Clayton513c26c2011-01-29 07:10:55 +00002677 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002678 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002679
Greg Clayton513c26c2011-01-29 07:10:55 +00002680 bool caused_stop = false;
2681
2682 // Ask the process subclass to actually halt our process
2683 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002684 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002685 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002686 if (m_public_state.GetValue() == eStateAttaching)
2687 {
2688 SetExitStatus(SIGKILL, "Cancelled async attach.");
2689 Destroy ();
2690 }
2691 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002692 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002693 // If "caused_stop" is true, then DoHalt stopped the process. If
2694 // "caused_stop" is false, the process was already stopped.
2695 // If the DoHalt caused the process to stop, then we want to catch
2696 // this event and set the interrupted bool to true before we pass
2697 // this along so clients know that the process was interrupted by
2698 // a halt command.
2699 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002700 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002701 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002702 TimeValue timeout_time;
2703 timeout_time = TimeValue::Now();
2704 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002705 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2706 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002707
Jim Ingham0f16e732011-02-08 05:20:59 +00002708 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002709 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002710 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002711 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002712 }
2713 else
2714 {
Greg Clayton2637f822011-11-17 01:23:07 +00002715 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00002716 {
2717 // We caused the process to interrupt itself, so mark this
2718 // as such in the stop event so clients can tell an interrupted
2719 // process from a natural stop
2720 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2721 }
2722 else
2723 {
2724 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2725 if (log)
2726 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2727 error.SetErrorString ("Did not get stopped event after halt.");
2728 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002729 }
2730 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002731 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002732 }
2733 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002734 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002735 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002736 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002737
2738 // Post any event we might have consumed. If all goes well, we will have
2739 // stopped the process, intercepted the event and set the interrupted
2740 // bool in the event. Post it to the private event queue and that will end up
2741 // correctly setting the state.
2742 if (event_sp)
2743 m_private_state_broadcaster.BroadcastEvent(event_sp);
2744
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745 return error;
2746}
2747
2748Error
2749Process::Detach ()
2750{
2751 Error error (WillDetach());
2752
2753 if (error.Success())
2754 {
2755 DisableAllBreakpointSites();
2756 error = DoDetach();
2757 if (error.Success())
2758 {
2759 DidDetach();
2760 StopPrivateStateThread();
2761 }
2762 }
2763 return error;
2764}
2765
2766Error
2767Process::Destroy ()
2768{
2769 Error error (WillDestroy());
2770 if (error.Success())
2771 {
2772 DisableAllBreakpointSites();
2773 error = DoDestroy();
2774 if (error.Success())
2775 {
2776 DidDestroy();
2777 StopPrivateStateThread();
2778 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002779 m_stdio_communication.StopReadThread();
2780 m_stdio_communication.Disconnect();
2781 if (m_process_input_reader && m_process_input_reader->IsActive())
2782 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2783 if (m_process_input_reader)
2784 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002785 }
2786 return error;
2787}
2788
2789Error
2790Process::Signal (int signal)
2791{
2792 Error error (WillSignal());
2793 if (error.Success())
2794 {
2795 error = DoSignal(signal);
2796 if (error.Success())
2797 DidSignal();
2798 }
2799 return error;
2800}
2801
Greg Clayton514487e2011-02-15 21:59:32 +00002802lldb::ByteOrder
2803Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002804{
Greg Clayton514487e2011-02-15 21:59:32 +00002805 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002806}
2807
2808uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002809Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002810{
Greg Clayton514487e2011-02-15 21:59:32 +00002811 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002812}
2813
Greg Clayton514487e2011-02-15 21:59:32 +00002814
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002815bool
2816Process::ShouldBroadcastEvent (Event *event_ptr)
2817{
2818 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2819 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002820 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002821
2822 switch (state)
2823 {
Greg Claytonb766a732011-02-04 01:58:07 +00002824 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002825 case eStateAttaching:
2826 case eStateLaunching:
2827 case eStateDetached:
2828 case eStateExited:
2829 case eStateUnloaded:
2830 // These events indicate changes in the state of the debugging session, always report them.
2831 return_value = true;
2832 break;
2833 case eStateInvalid:
2834 // We stopped for no apparent reason, don't report it.
2835 return_value = false;
2836 break;
2837 case eStateRunning:
2838 case eStateStepping:
2839 // If we've started the target running, we handle the cases where we
2840 // are already running and where there is a transition from stopped to
2841 // running differently.
2842 // running -> running: Automatically suppress extra running events
2843 // stopped -> running: Report except when there is one or more no votes
2844 // and no yes votes.
2845 SynchronouslyNotifyStateChanged (state);
2846 switch (m_public_state.GetValue())
2847 {
2848 case eStateRunning:
2849 case eStateStepping:
2850 // We always suppress multiple runnings with no PUBLIC stop in between.
2851 return_value = false;
2852 break;
2853 default:
2854 // TODO: make this work correctly. For now always report
2855 // run if we aren't running so we don't miss any runnning
2856 // events. If I run the lldb/test/thread/a.out file and
2857 // break at main.cpp:58, run and hit the breakpoints on
2858 // multiple threads, then somehow during the stepping over
2859 // of all breakpoints no run gets reported.
2860 return_value = true;
2861
2862 // This is a transition from stop to run.
2863 switch (m_thread_list.ShouldReportRun (event_ptr))
2864 {
2865 case eVoteYes:
2866 case eVoteNoOpinion:
2867 return_value = true;
2868 break;
2869 case eVoteNo:
2870 return_value = false;
2871 break;
2872 }
2873 break;
2874 }
2875 break;
2876 case eStateStopped:
2877 case eStateCrashed:
2878 case eStateSuspended:
2879 {
2880 // We've stopped. First see if we're going to restart the target.
2881 // If we are going to stop, then we always broadcast the event.
2882 // 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 +00002883 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002884 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002885 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00002886 if (log)
2887 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002888 return true;
2889 }
2890 else
2891 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002892 RefreshStateAfterStop ();
2893
2894 if (m_thread_list.ShouldStop (event_ptr) == false)
2895 {
2896 switch (m_thread_list.ShouldReportStop (event_ptr))
2897 {
2898 case eVoteYes:
2899 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002900 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002901 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002902 case eVoteNo:
2903 return_value = false;
2904 break;
2905 }
2906
2907 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002908 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002909 Resume ();
2910 }
2911 else
2912 {
2913 return_value = true;
2914 SynchronouslyNotifyStateChanged (state);
2915 }
2916 }
2917 }
2918 }
2919
2920 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00002921 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002922 return return_value;
2923}
2924
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002925
2926bool
2927Process::StartPrivateStateThread ()
2928{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002929 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002930
Greg Clayton8b82f082011-04-12 05:54:46 +00002931 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002932 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00002933 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2934
2935 if (already_running)
2936 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002937
2938 // Create a thread that watches our internal state and controls which
2939 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002940 char thread_name[1024];
Greg Clayton81c22f62011-10-19 18:09:39 +00002941 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Clayton3e06bd92011-01-09 21:07:35 +00002942 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00002943 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002944}
2945
2946void
2947Process::PausePrivateStateThread ()
2948{
2949 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2950}
2951
2952void
2953Process::ResumePrivateStateThread ()
2954{
2955 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2956}
2957
2958void
2959Process::StopPrivateStateThread ()
2960{
Greg Clayton8b82f082011-04-12 05:54:46 +00002961 if (PrivateStateThreadIsValid ())
2962 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002963}
2964
2965void
2966Process::ControlPrivateStateThread (uint32_t signal)
2967{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002968 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002969
2970 assert (signal == eBroadcastInternalStateControlStop ||
2971 signal == eBroadcastInternalStateControlPause ||
2972 signal == eBroadcastInternalStateControlResume);
2973
2974 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002975 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002976
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002977 // Signal the private state thread. First we should copy this is case the
2978 // thread starts exiting since the private state thread will NULL this out
2979 // when it exits
2980 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00002981 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002982 {
2983 TimeValue timeout_time;
2984 bool timed_out;
2985
2986 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2987
2988 timeout_time = TimeValue::Now();
2989 timeout_time.OffsetWithSeconds(2);
2990 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2991 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2992
2993 if (signal == eBroadcastInternalStateControlStop)
2994 {
2995 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002996 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997
2998 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002999 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003000 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003001 }
3002 }
3003}
3004
3005void
3006Process::HandlePrivateEvent (EventSP &event_sp)
3007{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003008 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003009
Greg Clayton414f5d32011-01-25 02:58:48 +00003010 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003011
3012 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003013 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003014 {
Jim Ingham754ab982011-01-29 04:05:41 +00003015 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003016 switch (action_result)
3017 {
3018 case NextEventAction::eEventActionSuccess:
3019 SetNextEventAction(NULL);
3020 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003021
Jim Inghambb3a2832011-01-29 01:49:25 +00003022 case NextEventAction::eEventActionRetry:
3023 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003024
Jim Inghambb3a2832011-01-29 01:49:25 +00003025 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003026 // Handle Exiting Here. If we already got an exited event,
3027 // we should just propagate it. Otherwise, swallow this event,
3028 // and set our state to exit so the next event will kill us.
3029 if (new_state != eStateExited)
3030 {
3031 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003032 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003033 SetNextEventAction(NULL);
3034 return;
3035 }
3036 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003037 break;
3038 }
3039 }
3040
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003041 // See if we should broadcast this state to external clients?
3042 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003043
3044 if (should_broadcast)
3045 {
3046 if (log)
3047 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003048 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003049 __FUNCTION__,
3050 GetID(),
3051 StateAsCString(new_state),
3052 StateAsCString (GetState ()),
3053 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003054 }
Jim Ingham9575d842011-03-11 03:53:59 +00003055 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003056 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003057 PushProcessInputReader ();
3058 else
3059 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003060
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061 BroadcastEvent (event_sp);
3062 }
3063 else
3064 {
3065 if (log)
3066 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003067 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003068 __FUNCTION__,
3069 GetID(),
3070 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003071 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003072 }
3073 }
3074}
3075
3076void *
3077Process::PrivateStateThread (void *arg)
3078{
3079 Process *proc = static_cast<Process*> (arg);
3080 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081 return result;
3082}
3083
3084void *
3085Process::RunPrivateStateThread ()
3086{
3087 bool control_only = false;
3088 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3089
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003090 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003092 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003093
3094 bool exit_now = false;
3095 while (!exit_now)
3096 {
3097 EventSP event_sp;
3098 WaitForEventsPrivate (NULL, event_sp, control_only);
3099 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3100 {
3101 switch (event_sp->GetType())
3102 {
3103 case eBroadcastInternalStateControlStop:
3104 exit_now = true;
3105 continue; // Go to next loop iteration so we exit without
3106 break; // doing any internal state managment below
3107
3108 case eBroadcastInternalStateControlPause:
3109 control_only = true;
3110 break;
3111
3112 case eBroadcastInternalStateControlResume:
3113 control_only = false;
3114 break;
3115 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003116
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003117 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003118 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 +00003119
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003120 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003121 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122 }
3123
3124
3125 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3126
3127 if (internal_state != eStateInvalid)
3128 {
3129 HandlePrivateEvent (event_sp);
3130 }
3131
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003132 if (internal_state == eStateInvalid ||
3133 internal_state == eStateExited ||
3134 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003135 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003136 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003137 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 +00003138
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003139 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003140 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003141 }
3142
Caroline Tice20ad3c42010-10-29 21:48:37 +00003143 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003144 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003145 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003146
Greg Clayton6ed95942011-01-22 07:12:45 +00003147 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3148 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003149 return NULL;
3150}
3151
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003152//------------------------------------------------------------------
3153// Process Event Data
3154//------------------------------------------------------------------
3155
3156Process::ProcessEventData::ProcessEventData () :
3157 EventData (),
3158 m_process_sp (),
3159 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003160 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003161 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003162 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003163{
3164}
3165
3166Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3167 EventData (),
3168 m_process_sp (process_sp),
3169 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003170 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003171 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003172 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003173{
3174}
3175
3176Process::ProcessEventData::~ProcessEventData()
3177{
3178}
3179
3180const ConstString &
3181Process::ProcessEventData::GetFlavorString ()
3182{
3183 static ConstString g_flavor ("Process::ProcessEventData");
3184 return g_flavor;
3185}
3186
3187const ConstString &
3188Process::ProcessEventData::GetFlavor () const
3189{
3190 return ProcessEventData::GetFlavorString ();
3191}
3192
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003193void
3194Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3195{
3196 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003197 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3198 // the public event queue, then other times when we're pretending that this is where we stopped at the
3199 // end of expression evaluation. m_update_state is used to distinguish these
3200 // three cases; it is 0 when we're just pulling it off for private handling,
3201 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003202
Jim Inghama8604692011-05-22 21:45:01 +00003203 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003204 return;
3205
3206 m_process_sp->SetPublicState (m_state);
3207
3208 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3209 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003210 {
3211 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
3212 int num_threads = curr_thread_list.GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003213 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003214
Jim Ingham4b536182011-08-09 02:12:22 +00003215 // The actions might change one of the thread's stop_info's opinions about whether we should
3216 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003217
3218 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3219 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3220 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3221 // 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
3222 // against this list & bag out if anything differs.
3223 std::vector<lldb::tid_t> thread_index_array(num_threads);
3224 for (idx = 0; idx < num_threads; ++idx)
3225 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3226
Jim Ingham4b536182011-08-09 02:12:22 +00003227 bool still_should_stop = true;
3228
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003229 for (idx = 0; idx < num_threads; ++idx)
3230 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003231 curr_thread_list = m_process_sp->GetThreadList();
3232 if (curr_thread_list.GetSize() != num_threads)
3233 {
3234 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3235 log->Printf("Number of threads changed from %d to %d while processing event.", num_threads, curr_thread_list.GetSize());
3236 break;
3237 }
3238
3239 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3240
3241 if (thread_sp->GetIndexID() != thread_index_array[idx])
3242 {
3243 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
3244 log->Printf("The thread at position %d changed from %d to %d while processing event.",
3245 idx,
3246 thread_index_array[idx],
3247 thread_sp->GetIndexID());
3248 break;
3249 }
3250
Jim Inghamb15bfc72010-10-20 00:39:53 +00003251 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3252 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003253 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003254 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003255 // The stop action might restart the target. If it does, then we want to mark that in the
3256 // event so that whoever is receiving it will know to wait for the running event and reflect
3257 // that state appropriately.
3258 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003259
3260 // FIXME: we might have run.
3261 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003262 {
3263 SetRestarted (true);
3264 break;
3265 }
3266 else if (!stop_info_sp->ShouldStop(event_ptr))
3267 {
3268 still_should_stop = false;
3269 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003270 }
3271 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003272
Jim Ingham4b536182011-08-09 02:12:22 +00003273
3274 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003275 {
Jim Ingham4b536182011-08-09 02:12:22 +00003276 if (!still_should_stop)
3277 {
3278 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003279 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003280 m_process_sp->Resume();
3281 }
3282 else
3283 {
3284 // If we didn't restart, run the Stop Hooks here:
3285 // They might also restart the target, so watch for that.
3286 m_process_sp->GetTarget().RunStopHooks();
3287 if (m_process_sp->GetPrivateState() == eStateRunning)
3288 SetRestarted(true);
3289 }
Jim Ingham9575d842011-03-11 03:53:59 +00003290 }
3291
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003292 }
3293}
3294
3295void
3296Process::ProcessEventData::Dump (Stream *s) const
3297{
3298 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003299 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003300
Greg Clayton8b82f082011-04-12 05:54:46 +00003301 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003302}
3303
3304const Process::ProcessEventData *
3305Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3306{
3307 if (event_ptr)
3308 {
3309 const EventData *event_data = event_ptr->GetData();
3310 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3311 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3312 }
3313 return NULL;
3314}
3315
3316ProcessSP
3317Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3318{
3319 ProcessSP process_sp;
3320 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3321 if (data)
3322 process_sp = data->GetProcessSP();
3323 return process_sp;
3324}
3325
3326StateType
3327Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3328{
3329 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3330 if (data == NULL)
3331 return eStateInvalid;
3332 else
3333 return data->GetState();
3334}
3335
3336bool
3337Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3338{
3339 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3340 if (data == NULL)
3341 return false;
3342 else
3343 return data->GetRestarted();
3344}
3345
3346void
3347Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3348{
3349 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3350 if (data != NULL)
3351 data->SetRestarted(new_value);
3352}
3353
3354bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003355Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3356{
3357 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3358 if (data == NULL)
3359 return false;
3360 else
3361 return data->GetInterrupted ();
3362}
3363
3364void
3365Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3366{
3367 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3368 if (data != NULL)
3369 data->SetInterrupted(new_value);
3370}
3371
3372bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003373Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3374{
3375 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3376 if (data)
3377 {
3378 data->SetUpdateStateOnRemoval();
3379 return true;
3380 }
3381 return false;
3382}
3383
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003384void
Greg Clayton0603aa92010-10-04 01:05:56 +00003385Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003386{
Greg Claytonc14ee322011-09-22 04:58:26 +00003387 exe_ctx.SetTargetPtr (&m_target);
3388 exe_ctx.SetProcessPtr (this);
3389 exe_ctx.SetThreadPtr(NULL);
3390 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003391}
3392
3393lldb::ProcessSP
3394Process::GetSP ()
3395{
3396 return GetTarget().GetProcessSP();
3397}
3398
Greg Claytone996fd32011-03-08 22:40:15 +00003399//uint32_t
3400//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3401//{
3402// return 0;
3403//}
3404//
3405//ArchSpec
3406//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3407//{
3408// return Host::GetArchSpecForExistingProcess (pid);
3409//}
3410//
3411//ArchSpec
3412//Process::GetArchSpecForExistingProcess (const char *process_name)
3413//{
3414// return Host::GetArchSpecForExistingProcess (process_name);
3415//}
3416//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003417void
3418Process::AppendSTDOUT (const char * s, size_t len)
3419{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003420 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003421 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003422 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003423}
3424
3425void
Greg Clayton93e86192011-11-13 04:45:22 +00003426Process::AppendSTDERR (const char * s, size_t len)
3427{
3428 Mutex::Locker locker (m_stdio_communication_mutex);
3429 m_stderr_data.append (s, len);
3430 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3431}
3432
3433//------------------------------------------------------------------
3434// Process STDIO
3435//------------------------------------------------------------------
3436
3437size_t
3438Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3439{
3440 Mutex::Locker locker(m_stdio_communication_mutex);
3441 size_t bytes_available = m_stdout_data.size();
3442 if (bytes_available > 0)
3443 {
3444 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3445 if (log)
3446 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3447 if (bytes_available > buf_size)
3448 {
3449 memcpy(buf, m_stdout_data.c_str(), buf_size);
3450 m_stdout_data.erase(0, buf_size);
3451 bytes_available = buf_size;
3452 }
3453 else
3454 {
3455 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3456 m_stdout_data.clear();
3457 }
3458 }
3459 return bytes_available;
3460}
3461
3462
3463size_t
3464Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3465{
3466 Mutex::Locker locker(m_stdio_communication_mutex);
3467 size_t bytes_available = m_stderr_data.size();
3468 if (bytes_available > 0)
3469 {
3470 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3471 if (log)
3472 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3473 if (bytes_available > buf_size)
3474 {
3475 memcpy(buf, m_stderr_data.c_str(), buf_size);
3476 m_stderr_data.erase(0, buf_size);
3477 bytes_available = buf_size;
3478 }
3479 else
3480 {
3481 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3482 m_stderr_data.clear();
3483 }
3484 }
3485 return bytes_available;
3486}
3487
3488void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003489Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3490{
3491 Process *process = (Process *) baton;
3492 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3493}
3494
3495size_t
3496Process::ProcessInputReaderCallback (void *baton,
3497 InputReader &reader,
3498 lldb::InputReaderAction notification,
3499 const char *bytes,
3500 size_t bytes_len)
3501{
3502 Process *process = (Process *) baton;
3503
3504 switch (notification)
3505 {
3506 case eInputReaderActivate:
3507 break;
3508
3509 case eInputReaderDeactivate:
3510 break;
3511
3512 case eInputReaderReactivate:
3513 break;
3514
Caroline Tice969ed3d2011-05-02 20:41:46 +00003515 case eInputReaderAsynchronousOutputWritten:
3516 break;
3517
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003518 case eInputReaderGotToken:
3519 {
3520 Error error;
3521 process->PutSTDIN (bytes, bytes_len, error);
3522 }
3523 break;
3524
Caroline Ticeefed6132010-11-19 20:47:54 +00003525 case eInputReaderInterrupt:
3526 process->Halt ();
3527 break;
3528
3529 case eInputReaderEndOfFile:
3530 process->AppendSTDOUT ("^D", 2);
3531 break;
3532
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003533 case eInputReaderDone:
3534 break;
3535
3536 }
3537
3538 return bytes_len;
3539}
3540
3541void
3542Process::ResetProcessInputReader ()
3543{
3544 m_process_input_reader.reset();
3545}
3546
3547void
Greg Claytonee95ed52011-11-17 22:14:31 +00003548Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003549{
3550 // First set up the Read Thread for reading/handling process I/O
3551
3552 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3553
3554 if (conn_ap.get())
3555 {
3556 m_stdio_communication.SetConnection (conn_ap.release());
3557 if (m_stdio_communication.IsConnected())
3558 {
3559 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3560 m_stdio_communication.StartReadThread();
3561
3562 // Now read thread is set up, set up input reader.
3563
3564 if (!m_process_input_reader.get())
3565 {
3566 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3567 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3568 this,
3569 eInputReaderGranularityByte,
3570 NULL,
3571 NULL,
3572 false));
3573
3574 if (err.Fail())
3575 m_process_input_reader.reset();
3576 }
3577 }
3578 }
3579}
3580
3581void
3582Process::PushProcessInputReader ()
3583{
3584 if (m_process_input_reader && !m_process_input_reader->IsActive())
3585 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3586}
3587
3588void
3589Process::PopProcessInputReader ()
3590{
3591 if (m_process_input_reader && m_process_input_reader->IsActive())
3592 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3593}
3594
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003595// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003596void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003597Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003598{
Greg Claytone0d378b2011-03-24 21:19:54 +00003599 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003600
3601 int i=0;
3602 const char *name;
3603 OptionEnumValueElement option_enum;
3604 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3605 {
3606 if (name)
3607 {
3608 option_enum.value = i;
3609 option_enum.string_value = name;
3610 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3611 g_plugins.push_back (option_enum);
3612 }
3613 ++i;
3614 }
3615 option_enum.value = 0;
3616 option_enum.string_value = NULL;
3617 option_enum.usage = NULL;
3618 g_plugins.push_back (option_enum);
3619
3620 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3621 {
3622 if (::strcmp (name, "plugin") == 0)
3623 {
3624 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3625 break;
3626 }
3627 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003628 UserSettingsControllerSP &usc = GetSettingsController();
3629 usc.reset (new SettingsController);
3630 UserSettingsController::InitializeSettingsController (usc,
3631 SettingsController::global_settings_table,
3632 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003633
3634 // Now call SettingsInitialize() for each 'child' of Process settings
3635 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003636}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003637
Greg Clayton99d0faf2010-11-18 23:32:35 +00003638void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003639Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003640{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003641 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3642
3643 Thread::SettingsTerminate ();
3644
3645 // Now terminate Process Settings.
3646
Greg Clayton99d0faf2010-11-18 23:32:35 +00003647 UserSettingsControllerSP &usc = GetSettingsController();
3648 UserSettingsController::FinalizeSettingsController (usc);
3649 usc.reset();
3650}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003651
Greg Clayton99d0faf2010-11-18 23:32:35 +00003652UserSettingsControllerSP &
3653Process::GetSettingsController ()
3654{
3655 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003656 return g_settings_controller;
3657}
3658
Caroline Tice1559a462010-09-27 00:30:10 +00003659void
3660Process::UpdateInstanceName ()
3661{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003662 Module *module = GetTarget().GetExecutableModulePointer();
3663 if (module)
Caroline Tice1559a462010-09-27 00:30:10 +00003664 {
3665 StreamString sstr;
Greg Claytonaa149cb2011-08-11 02:48:45 +00003666 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003667
Greg Claytondbe54502010-11-19 03:46:01 +00003668 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Clayton8b82f082011-04-12 05:54:46 +00003669 sstr.GetData());
Caroline Tice1559a462010-09-27 00:30:10 +00003670 }
3671}
3672
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003673ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003674Process::RunThreadPlan (ExecutionContext &exe_ctx,
3675 lldb::ThreadPlanSP &thread_plan_sp,
3676 bool stop_others,
3677 bool try_all_threads,
3678 bool discard_on_error,
3679 uint32_t single_thread_timeout_usec,
3680 Stream &errors)
3681{
3682 ExecutionResults return_value = eExecutionSetupError;
3683
Jim Ingham77787032011-01-20 02:03:18 +00003684 if (thread_plan_sp.get() == NULL)
3685 {
3686 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003687 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003688 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003689
3690 if (exe_ctx.GetProcessPtr() != this)
3691 {
3692 errors.Printf("RunThreadPlan called on wrong process.");
3693 return eExecutionSetupError;
3694 }
3695
3696 Thread *thread = exe_ctx.GetThreadPtr();
3697 if (thread == NULL)
3698 {
3699 errors.Printf("RunThreadPlan called with invalid thread.");
3700 return eExecutionSetupError;
3701 }
Jim Ingham77787032011-01-20 02:03:18 +00003702
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003703 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3704 // For that to be true the plan can't be private - since private plans suppress themselves in the
3705 // GetCompletedPlan call.
3706
3707 bool orig_plan_private = thread_plan_sp->GetPrivate();
3708 thread_plan_sp->SetPrivate(false);
3709
Jim Ingham444586b2011-01-24 06:34:17 +00003710 if (m_private_state.GetValue() != eStateStopped)
3711 {
3712 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003713 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003714 }
3715
Jim Ingham66243842011-08-13 00:56:10 +00003716 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00003717 const uint32_t thread_idx_id = thread->GetIndexID();
3718 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003719
3720 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3721 // so we should arrange to reset them as well.
3722
Greg Claytonc14ee322011-09-22 04:58:26 +00003723 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003724
Jim Ingham66243842011-08-13 00:56:10 +00003725 uint32_t selected_tid;
3726 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00003727 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00003728 {
3729 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003730 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003731 }
3732 else
3733 {
3734 selected_tid = LLDB_INVALID_THREAD_ID;
3735 }
3736
Greg Claytonc14ee322011-09-22 04:58:26 +00003737 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Inghamf48169b2010-11-30 02:22:11 +00003738
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003739 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003740
3741 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3742 // restored on exit to the function.
3743
3744 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003745
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003746 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003747 if (log)
3748 {
3749 StreamString s;
3750 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton81c22f62011-10-19 18:09:39 +00003751 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00003752 thread->GetIndexID(),
3753 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00003754 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003755 }
3756
Jim Ingham0f16e732011-02-08 05:20:59 +00003757 bool got_event;
3758 lldb::EventSP event_sp;
3759 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003760
3761 TimeValue* timeout_ptr = NULL;
3762 TimeValue real_timeout;
3763
Jim Ingham0f16e732011-02-08 05:20:59 +00003764 bool first_timeout = true;
3765 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003766
Jim Inghamf48169b2010-11-30 02:22:11 +00003767 while (1)
3768 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003769 // We usually want to resume the process if we get to the top of the loop.
3770 // The only exception is if we get two running events with no intervening
3771 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003772
Jim Ingham0f16e732011-02-08 05:20:59 +00003773 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003774 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003775 // Do the initial resume and wait for the running event before going further.
3776
Greg Claytonc14ee322011-09-22 04:58:26 +00003777 Error resume_error = Resume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00003778 if (!resume_error.Success())
3779 {
3780 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003781 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003782 break;
3783 }
3784
3785 real_timeout = TimeValue::Now();
3786 real_timeout.OffsetWithMicroSeconds(500000);
3787 timeout_ptr = &real_timeout;
3788
3789 got_event = listener.WaitForEvent(NULL, event_sp);
3790 if (!got_event)
3791 {
3792 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003793 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003794
3795 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003796 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003797 break;
3798 }
3799
3800 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3801 if (stop_state != eStateRunning)
3802 {
3803 if (log)
3804 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3805
3806 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003807 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003808 break;
3809 }
3810
3811 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003812 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003813 // We need to call the function synchronously, so spin waiting for it to return.
3814 // If we get interrupted while executing, we're going to lose our context, and
3815 // won't be able to gather the result at this point.
3816 // We set the timeout AFTER the resume, since the resume takes some time and we
3817 // don't want to charge that to the timeout.
3818
3819 if (single_thread_timeout_usec != 0)
3820 {
3821 real_timeout = TimeValue::Now();
3822 if (first_timeout)
3823 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3824 else
3825 real_timeout.OffsetWithSeconds(10);
3826
3827 timeout_ptr = &real_timeout;
3828 }
3829 }
3830 else
3831 {
3832 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003833 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003834 do_resume = true;
3835 }
3836
3837 // Now wait for the process to stop again:
3838 stop_state = lldb::eStateInvalid;
3839 event_sp.reset();
3840 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3841
3842 if (got_event)
3843 {
3844 if (event_sp.get())
3845 {
3846 bool keep_going = false;
3847 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3848 if (log)
3849 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3850
3851 switch (stop_state)
3852 {
3853 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00003854 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003855 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00003856 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00003857 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00003858 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003859 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00003860 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00003861 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3862 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00003863 }
3864 else
3865 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003866 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3867 StopReason stop_reason = eStopReasonInvalid;
3868 if (stop_info_sp)
3869 stop_reason = stop_info_sp->GetStopReason();
3870 if (stop_reason == eStopReasonPlanComplete)
3871 {
3872 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003873 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003874 // Now mark this plan as private so it doesn't get reported as the stop reason
3875 // after this point.
3876 if (thread_plan_sp)
3877 thread_plan_sp->SetPrivate (orig_plan_private);
3878 return_value = eExecutionCompleted;
3879 }
3880 else
3881 {
3882 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003883 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003884
3885 return_value = eExecutionInterrupted;
3886 }
Jim Ingham160f78c2011-05-17 01:10:11 +00003887 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00003888 }
3889 break;
3890
Jim Ingham0f16e732011-02-08 05:20:59 +00003891 case lldb::eStateCrashed:
3892 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003893 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003894 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003895 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003896
Jim Ingham0f16e732011-02-08 05:20:59 +00003897 case lldb::eStateRunning:
3898 do_resume = false;
3899 keep_going = true;
3900 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003901
Jim Ingham0f16e732011-02-08 05:20:59 +00003902 default:
3903 if (log)
3904 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00003905
3906 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003907 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003908 break;
3909 }
3910 if (keep_going)
3911 continue;
3912 else
3913 break;
3914 }
3915 else
3916 {
3917 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003918 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00003919 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003920 break;
3921 }
3922 }
3923 else
3924 {
3925 // If we didn't get an event that means we've timed out...
3926 // We will interrupt the process here. Depending on what we were asked to do we will
3927 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00003928 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00003929
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003930 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00003931 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00003932 {
3933 if (first_timeout)
3934 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3935 "trying with all threads enabled.",
3936 single_thread_timeout_usec);
3937 else
3938 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3939 "and timeout: %d timed out.",
3940 single_thread_timeout_usec);
3941 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003942 else
Jim Ingham0f16e732011-02-08 05:20:59 +00003943 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3944 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00003945 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003946 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003947
Greg Claytonc14ee322011-09-22 04:58:26 +00003948 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00003949 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00003950 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003951 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003952 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003953
Jim Ingham0f16e732011-02-08 05:20:59 +00003954 // If halt succeeds, it always produces a stopped event. Wait for that:
3955
3956 real_timeout = TimeValue::Now();
3957 real_timeout.OffsetWithMicroSeconds(500000);
3958
3959 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00003960
3961 if (got_event)
3962 {
3963 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3964 if (log)
3965 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003966 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00003967 if (stop_state == lldb::eStateStopped
3968 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00003969 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003970 }
3971
Jim Ingham0f16e732011-02-08 05:20:59 +00003972 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00003973 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003974 // Between the time we initiated the Halt and the time we delivered it, the process could have
3975 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00003976
Greg Claytonc14ee322011-09-22 04:58:26 +00003977 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00003978 {
3979 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003980 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003981 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003982 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003983 break;
3984 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003985
Jim Ingham0f16e732011-02-08 05:20:59 +00003986 if (!try_all_threads)
3987 {
3988 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003989 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003990 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003991 break;
3992 }
3993
3994 if (first_timeout)
3995 {
3996 // Set all the other threads to run, and return to the top of the loop, which will continue;
3997 first_timeout = false;
3998 thread_plan_sp->SetStopOthers (false);
3999 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004000 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004001
4002 continue;
4003 }
4004 else
4005 {
4006 // Running all threads failed, so return Interrupted.
4007 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004008 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004009 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004010 break;
4011 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004012 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004013 }
4014 else
4015 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004016 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004017 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004018 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004019 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00004020 }
4021 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004022 else
4023 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004024 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4025 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00004026 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004027 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.",
4028 halt_error.AsCString());
4029 real_timeout = TimeValue::Now();
4030 real_timeout.OffsetWithMicroSeconds(500000);
4031 timeout_ptr = &real_timeout;
4032 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4033 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004034 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004035 // This is not going anywhere, bag out.
4036 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004037 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004038 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004039 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004040 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004041 else
4042 {
4043 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4044 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004045 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00004046 if (stop_state == lldb::eStateStopped)
4047 {
4048 // Between the time we initiated the Halt and the time we delivered it, the process could have
4049 // already finished its job. Check that here:
4050
Greg Claytonc14ee322011-09-22 04:58:26 +00004051 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004052 {
4053 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004054 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004055 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004056 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004057 break;
4058 }
4059
4060 if (first_timeout)
4061 {
4062 // Set all the other threads to run, and return to the top of the loop, which will continue;
4063 first_timeout = false;
4064 thread_plan_sp->SetStopOthers (false);
4065 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004066 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004067
4068 continue;
4069 }
4070 else
4071 {
4072 // Running all threads failed, so return Interrupted.
4073 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004074 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004075 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004076 break;
4077 }
4078 }
4079 else
4080 {
Sean Callanan39821ac2011-08-09 22:07:08 +00004081 if (log)
4082 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4083 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00004084 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004085 break;
4086 }
4087 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004088 }
4089
Jim Inghamf48169b2010-11-30 02:22:11 +00004090 }
4091
Jim Ingham0f16e732011-02-08 05:20:59 +00004092 } // END WAIT LOOP
4093
4094 // Now do some processing on the results of the run:
4095 if (return_value == eExecutionInterrupted)
4096 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004097 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004098 {
4099 StreamString s;
4100 if (event_sp)
4101 event_sp->Dump (&s);
4102 else
4103 {
Jim Ingham20829ac2011-08-09 22:24:33 +00004104 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004105 }
4106
4107 StreamString ts;
4108
Jim Ingham20829ac2011-08-09 22:24:33 +00004109 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00004110
4111 do
4112 {
4113 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4114
4115 if (!event_data)
4116 {
4117 event_explanation = "<no event data>";
4118 break;
4119 }
4120
4121 Process *process = event_data->GetProcessSP().get();
4122
4123 if (!process)
4124 {
4125 event_explanation = "<no process>";
4126 break;
4127 }
4128
4129 ThreadList &thread_list = process->GetThreadList();
4130
4131 uint32_t num_threads = thread_list.GetSize();
4132 uint32_t thread_index;
4133
4134 ts.Printf("<%u threads> ", num_threads);
4135
4136 for (thread_index = 0;
4137 thread_index < num_threads;
4138 ++thread_index)
4139 {
4140 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4141
4142 if (!thread)
4143 {
4144 ts.Printf("<?> ");
4145 continue;
4146 }
4147
Greg Clayton81c22f62011-10-19 18:09:39 +00004148 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Ingham0f16e732011-02-08 05:20:59 +00004149 RegisterContext *register_context = thread->GetRegisterContext().get();
4150
4151 if (register_context)
4152 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4153 else
4154 ts.Printf("[ip unknown] ");
4155
4156 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4157 if (stop_info_sp)
4158 {
4159 const char *stop_desc = stop_info_sp->GetDescription();
4160 if (stop_desc)
4161 ts.PutCString (stop_desc);
4162 }
4163 ts.Printf(">");
4164 }
4165
4166 event_explanation = ts.GetData();
4167 } while (0);
4168
4169 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004170 {
4171 if (event_explanation)
4172 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4173 else
4174 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4175 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004176
4177 if (discard_on_error && thread_plan_sp)
4178 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004179 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004180 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004181 }
4182 }
4183 }
4184 else if (return_value == eExecutionSetupError)
4185 {
4186 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004187 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004188
4189 if (discard_on_error && thread_plan_sp)
4190 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004191 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004192 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004193 }
4194 }
4195 else
4196 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004197 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004198 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004199 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004200 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00004201 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00004202 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004203 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004204 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004205 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004206 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00004207 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00004208 }
4209 else
4210 {
4211 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004212 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00004213 if (discard_on_error && thread_plan_sp)
4214 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004215 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004216 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00004217 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004218 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00004219 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004220 }
4221 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004222
Jim Inghamf48169b2010-11-30 02:22:11 +00004223 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00004224 // Check that it's still there, and if it is put it back in the context. Also restore the
4225 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00004226 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4227 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00004228 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004229 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00004230 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004231
4232 // Also restore the current process'es selected frame & thread, since this function calling may
4233 // be done behind the user's back.
4234
4235 if (selected_tid != LLDB_INVALID_THREAD_ID)
4236 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004237 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00004238 {
4239 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00004240 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00004241 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00004242 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004243 }
4244 }
4245
4246 return return_value;
4247}
4248
4249const char *
4250Process::ExecutionResultAsCString (ExecutionResults result)
4251{
4252 const char *result_name;
4253
4254 switch (result)
4255 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004256 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004257 result_name = "eExecutionCompleted";
4258 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004259 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004260 result_name = "eExecutionDiscarded";
4261 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004262 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004263 result_name = "eExecutionInterrupted";
4264 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004265 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004266 result_name = "eExecutionSetupError";
4267 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004268 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004269 result_name = "eExecutionTimedOut";
4270 break;
4271 }
4272 return result_name;
4273}
4274
Greg Clayton7260f622011-04-18 08:33:37 +00004275void
4276Process::GetStatus (Stream &strm)
4277{
4278 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00004279 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00004280 {
4281 if (state == eStateExited)
4282 {
4283 int exit_status = GetExitStatus();
4284 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004285 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004286 GetID(),
4287 exit_status,
4288 exit_status,
4289 exit_description ? exit_description : "");
4290 }
4291 else
4292 {
4293 if (state == eStateConnected)
4294 strm.Printf ("Connected to remote target.\n");
4295 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004296 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004297 }
4298 }
4299 else
4300 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004301 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004302 }
4303}
4304
4305size_t
4306Process::GetThreadStatus (Stream &strm,
4307 bool only_threads_with_stop_reason,
4308 uint32_t start_frame,
4309 uint32_t num_frames,
4310 uint32_t num_frames_with_source)
4311{
4312 size_t num_thread_infos_dumped = 0;
4313
4314 const size_t num_threads = GetThreadList().GetSize();
4315 for (uint32_t i = 0; i < num_threads; i++)
4316 {
4317 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4318 if (thread)
4319 {
4320 if (only_threads_with_stop_reason)
4321 {
4322 if (thread->GetStopInfo().get() == NULL)
4323 continue;
4324 }
4325 thread->GetStatus (strm,
4326 start_frame,
4327 num_frames,
4328 num_frames_with_source);
4329 ++num_thread_infos_dumped;
4330 }
4331 }
4332 return num_thread_infos_dumped;
4333}
4334
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004335//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004336// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004337//--------------------------------------------------------------
4338
Greg Clayton1b654882010-09-19 02:33:57 +00004339Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004340 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004341{
Greg Clayton85851dd2010-12-04 00:10:17 +00004342 m_default_settings.reset (new ProcessInstanceSettings (*this,
4343 false,
Caroline Tice91123da2010-09-08 17:48:55 +00004344 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004345}
4346
Greg Clayton1b654882010-09-19 02:33:57 +00004347Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004348{
4349}
4350
4351lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004352Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004353{
Greg Claytondbe54502010-11-19 03:46:01 +00004354 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4355 false,
4356 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004357 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4358 return new_settings_sp;
4359}
4360
4361//--------------------------------------------------------------
4362// class ProcessInstanceSettings
4363//--------------------------------------------------------------
4364
Greg Clayton85851dd2010-12-04 00:10:17 +00004365ProcessInstanceSettings::ProcessInstanceSettings
4366(
4367 UserSettingsController &owner,
4368 bool live_instance,
4369 const char *name
4370) :
Greg Clayton1d885962011-11-08 02:43:13 +00004371 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004372{
Caroline Ticef20e8232010-09-09 18:26:37 +00004373 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4374 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4375 // 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 +00004376 // This is true for CreateInstanceName() too.
Greg Clayton1d885962011-11-08 02:43:13 +00004377
Caroline Tice9e41c152010-09-16 19:05:55 +00004378 if (GetInstanceName () == InstanceSettings::InvalidName())
4379 {
4380 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4381 m_owner.RegisterInstanceSettings (this);
4382 }
Greg Clayton1d885962011-11-08 02:43:13 +00004383
Caroline Ticef20e8232010-09-09 18:26:37 +00004384 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004385 {
4386 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4387 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00004388 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004389 }
4390}
4391
4392ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Clayton1d885962011-11-08 02:43:13 +00004393 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004394{
4395 if (m_instance_name != InstanceSettings::GetDefaultName())
4396 {
4397 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4398 CopyInstanceSettings (pending_settings,false);
4399 m_owner.RemovePendingSettings (m_instance_name);
4400 }
4401}
4402
4403ProcessInstanceSettings::~ProcessInstanceSettings ()
4404{
4405}
4406
4407ProcessInstanceSettings&
4408ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4409{
4410 if (this != &rhs)
4411 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004412 }
4413
4414 return *this;
4415}
4416
4417
4418void
4419ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4420 const char *index_value,
4421 const char *value,
4422 const ConstString &instance_name,
4423 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004424 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004425 Error &err,
4426 bool pending)
4427{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004428}
4429
4430void
4431ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4432 bool pending)
4433{
Greg Clayton1d885962011-11-08 02:43:13 +00004434// if (new_settings.get() == NULL)
4435// return;
4436//
4437// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004438}
4439
Caroline Tice12cecd72010-09-20 21:37:42 +00004440bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004441ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4442 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004443 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004444 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004445{
Greg Clayton1d885962011-11-08 02:43:13 +00004446 if (err)
4447 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4448 return false;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004449}
4450
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004451const ConstString
4452ProcessInstanceSettings::CreateInstanceName ()
4453{
4454 static int instance_count = 1;
4455 StreamString sstr;
4456
4457 sstr.Printf ("process_%d", instance_count);
4458 ++instance_count;
4459
4460 const ConstString ret_val (sstr.GetData());
4461 return ret_val;
4462}
4463
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004464//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004465// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004466//--------------------------------------------------
4467
4468SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004469Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004470{
4471 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4472 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4473};
4474
4475
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004476SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004477Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004478{
Greg Clayton85851dd2010-12-04 00:10:17 +00004479 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton85851dd2010-12-04 00:10:17 +00004480 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004481};
4482
4483
Jim Ingham5aee1622010-08-09 23:31:02 +00004484
Greg Clayton1d885962011-11-08 02:43:13 +00004485