blob: e8016263da6da47acbf97035cd5670ad32aca332 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
39
40using namespace lldb;
41using namespace lldb_private;
42
Greg Clayton24bc5d92011-03-30 18:16:51 +000043void
Greg Claytonb72d0f02011-04-12 05:54:46 +000044ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +000045{
46 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +000047 if (m_pid != LLDB_INVALID_PROCESS_ID)
48 s.Printf (" pid = %i\n", m_pid);
49
50 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
51 s.Printf (" parent = %i\n", m_parent_pid);
52
53 if (m_executable)
54 {
55 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
56 s.PutCString (" file = ");
57 m_executable.Dump(&s);
58 s.EOL();
59 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000060 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +000061 if (argc > 0)
62 {
63 for (uint32_t i=0; i<argc; i++)
64 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000065 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +000066 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +000067 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000068 else
Greg Claytonb72d0f02011-04-12 05:54:46 +000069 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000070 }
71 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000072
73 const uint32_t envc = m_environment.GetArgumentCount();
74 if (envc > 0)
75 {
76 for (uint32_t i=0; i<envc; i++)
77 {
78 const char *env = m_environment.GetArgumentAtIndex(i);
79 if (i < 10)
80 s.Printf (" env[%u] = %s\n", i, env);
81 else
82 s.Printf ("env[%u] = %s\n", i, env);
83 }
84 }
85
Greg Claytonff39f742011-04-01 00:29:43 +000086 if (m_arch.IsValid())
87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
88
Greg Claytonb72d0f02011-04-12 05:54:46 +000089 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000090 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000091 cstr = platform->GetUserName (m_uid);
92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000093 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000094 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000095 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000096 cstr = platform->GetGroupName (m_gid);
97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000098 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000099 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000100 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000101 cstr = platform->GetUserName (m_euid);
102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000103 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000104 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000105 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000106 cstr = platform->GetGroupName (m_egid);
107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000108 }
109}
110
111void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000112ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000113{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000114 const char *label;
115 if (show_args || verbose)
116 label = "ARGUMENTS";
117 else
118 label = "NAME";
119
Greg Claytonff39f742011-04-01 00:29:43 +0000120 if (verbose)
121 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
124 }
125 else
126 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000127 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000128 s.PutCString ("====== ====== ========== ======= ============================\n");
129 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000130}
131
132void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000133ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000134{
135 if (m_pid != LLDB_INVALID_PROCESS_ID)
136 {
137 const char *cstr;
138 s.Printf ("%-6u %-6u ", m_pid, m_parent_pid);
139
Greg Clayton24bc5d92011-03-30 18:16:51 +0000140
Greg Claytonff39f742011-04-01 00:29:43 +0000141 if (verbose)
142 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000143 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000144 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
145 s.Printf ("%-10s ", cstr);
146 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000147 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000148
Greg Claytonb72d0f02011-04-12 05:54:46 +0000149 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000150 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
151 s.Printf ("%-10s ", cstr);
152 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000153 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000154
Greg Claytonb72d0f02011-04-12 05:54:46 +0000155 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000156 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
157 s.Printf ("%-10s ", cstr);
158 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000159 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000160
Greg Claytonb72d0f02011-04-12 05:54:46 +0000161 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000162 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
163 s.Printf ("%-10s ", cstr);
164 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000165 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000166 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
167 }
168 else
169 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000170 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000171 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000172 (int)m_arch.GetTriple().getArchName().size(),
173 m_arch.GetTriple().getArchName().data());
174 }
175
Greg Claytonb72d0f02011-04-12 05:54:46 +0000176 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000177 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000178 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000179 if (argc > 0)
180 {
181 for (uint32_t i=0; i<argc; i++)
182 {
183 if (i > 0)
184 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000185 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000186 }
187 }
188 }
189 else
190 {
191 s.PutCString (GetName());
192 }
193
194 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000195 }
196}
197
Greg Claytonb72d0f02011-04-12 05:54:46 +0000198
199void
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000200ProcessInfo::SetArguments (char const **argv,
201 bool first_arg_is_executable,
202 bool first_arg_is_executable_and_argument)
203{
204 m_arguments.SetArguments (argv);
205
206 // Is the first argument the executable?
207 if (first_arg_is_executable)
208 {
209 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
210 if (first_arg)
211 {
212 // Yes the first argument is an executable, set it as the executable
213 // in the launch options. Don't resolve the file path as the path
214 // could be a remote platform path
215 const bool resolve = false;
216 m_executable.SetFile(first_arg, resolve);
217
218 // If argument zero is an executable and shouldn't be included
219 // in the arguments, remove it from the front of the arguments
220 if (first_arg_is_executable_and_argument == false)
221 m_arguments.DeleteArgumentAtIndex (0);
222 }
223 }
224}
225void
226ProcessInfo::SetArguments (const Args& args,
227 bool first_arg_is_executable,
228 bool first_arg_is_executable_and_argument)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000229{
230 // Copy all arguments
231 m_arguments = args;
232
233 // Is the first argument the executable?
234 if (first_arg_is_executable)
235 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000236 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000237 if (first_arg)
238 {
239 // Yes the first argument is an executable, set it as the executable
240 // in the launch options. Don't resolve the file path as the path
241 // could be a remote platform path
242 const bool resolve = false;
243 m_executable.SetFile(first_arg, resolve);
244
245 // If argument zero is an executable and shouldn't be included
246 // in the arguments, remove it from the front of the arguments
247 if (first_arg_is_executable_and_argument == false)
248 m_arguments.DeleteArgumentAtIndex (0);
249 }
250 }
251}
252
Greg Claytonabb33022011-11-08 02:43:13 +0000253void
Greg Clayton464c6162011-11-17 22:14:31 +0000254ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-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 {
Greg Claytonabb33022011-11-08 02:43:13 +0000260 if (m_flags.Test(eLaunchFlagDisableSTDIO))
261 {
262 AppendSuppressFileAction (STDERR_FILENO, true , true );
263 AppendSuppressFileAction (STDIN_FILENO , true , false);
264 AppendSuppressFileAction (STDOUT_FILENO, false, true );
265 }
266 else
267 {
268 // Check for any values that might have gotten set with any of:
269 // (lldb) settings set target.input-path
270 // (lldb) settings set target.output-path
271 // (lldb) settings set target.error-path
Greg Clayton464c6162011-11-17 22:14:31 +0000272 const char *in_path = NULL;
273 const char *out_path = NULL;
274 const char *err_path = NULL;
Greg Claytonabb33022011-11-08 02:43:13 +0000275 if (target)
276 {
Greg Clayton464c6162011-11-17 22:14:31 +0000277 in_path = target->GetStandardErrorPath();
278 out_path = target->GetStandardInputPath();
279 err_path = target->GetStandardOutputPath();
280 }
281
282 if (default_to_use_pty && (!in_path && !out_path && !err_path))
283 {
284 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000285 {
Greg Clayton464c6162011-11-17 22:14:31 +0000286 in_path = out_path = err_path = m_pty.GetSlaveName (NULL, 0);
Greg Claytonabb33022011-11-08 02:43:13 +0000287 }
288 }
289
Greg Clayton464c6162011-11-17 22:14:31 +0000290 if (in_path)
291 AppendOpenFileAction(STDERR_FILENO, in_path, true, true);
292
293 if (out_path)
294 AppendOpenFileAction(STDIN_FILENO, out_path, true, false);
295
296 if (err_path)
297 AppendOpenFileAction(STDOUT_FILENO, err_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000298 }
299 }
300}
301
Greg Clayton527154d2011-11-15 03:53:30 +0000302
303bool
304ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error, bool localhost)
305{
306 error.Clear();
307
308 if (GetFlags().Test (eLaunchFlagLaunchInShell))
309 {
310 const char *shell_executable = GetShell();
311 if (shell_executable)
312 {
313 char shell_resolved_path[PATH_MAX];
314
315 if (localhost)
316 {
317 FileSpec shell_filespec (shell_executable, true);
318
319 if (!shell_filespec.Exists())
320 {
321 // Resolve the path in case we just got "bash", "sh" or "tcsh"
322 if (!shell_filespec.ResolveExecutableLocation ())
323 {
324 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
325 return false;
326 }
327 }
328 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
329 shell_executable = shell_resolved_path;
330 }
331
332 Args shell_arguments;
333 std::string safe_arg;
334 shell_arguments.AppendArgument (shell_executable);
335 StreamString shell_command;
336 shell_arguments.AppendArgument ("-c");
337 shell_command.PutCString ("exec");
338 if (GetArchitecture().IsValid())
339 {
340 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
341 // Set the resume count to 2:
342 // 1 - stop in shell
343 // 2 - stop in /usr/bin/arch
344 // 3 - then we will stop in our program
345 SetResumeCount(2);
346 }
347 else
348 {
349 // Set the resume count to 1:
350 // 1 - stop in shell
351 // 2 - then we will stop in our program
352 SetResumeCount(1);
353 }
354
355 const char **argv = GetArguments().GetConstArgumentVector ();
356 if (argv)
357 {
358 for (size_t i=0; argv[i] != NULL; ++i)
359 {
360 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
361 shell_command.Printf(" %s", arg);
362 }
363 }
364 shell_arguments.AppendArgument (shell_command.GetString().c_str());
365
366 m_executable.SetFile(shell_executable, false);
367 m_arguments = shell_arguments;
368 return true;
369 }
370 else
371 {
372 error.SetErrorString ("invalid shell path");
373 }
374 }
375 else
376 {
377 error.SetErrorString ("not launching in shell");
378 }
379 return false;
380}
381
382
Greg Clayton24bc5d92011-03-30 18:16:51 +0000383bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000384ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
385{
386 if ((read || write) && fd >= 0 && path && path[0])
387 {
388 m_action = eFileActionOpen;
389 m_fd = fd;
390 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000391 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000392 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000393 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000394 else
Greg Clayton527154d2011-11-15 03:53:30 +0000395 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000396 m_path.assign (path);
397 return true;
398 }
399 else
400 {
401 Clear();
402 }
403 return false;
404}
405
406bool
407ProcessLaunchInfo::FileAction::Close (int fd)
408{
409 Clear();
410 if (fd >= 0)
411 {
412 m_action = eFileActionClose;
413 m_fd = fd;
414 }
415 return m_fd >= 0;
416}
417
418
419bool
420ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
421{
422 Clear();
423 if (fd >= 0 && dup_fd >= 0)
424 {
425 m_action = eFileActionDuplicate;
426 m_fd = fd;
427 m_arg = dup_fd;
428 }
429 return m_fd >= 0;
430}
431
432
433
434bool
435ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
436 const FileAction *info,
437 Log *log,
438 Error& error)
439{
440 if (info == NULL)
441 return false;
442
443 switch (info->m_action)
444 {
445 case eFileActionNone:
446 error.Clear();
447 break;
448
449 case eFileActionClose:
450 if (info->m_fd == -1)
451 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
452 else
453 {
454 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
455 eErrorTypePOSIX);
456 if (log && (error.Fail() || log))
457 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
458 file_actions, info->m_fd);
459 }
460 break;
461
462 case eFileActionDuplicate:
463 if (info->m_fd == -1)
464 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
465 else if (info->m_arg == -1)
466 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
467 else
468 {
469 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
470 eErrorTypePOSIX);
471 if (log && (error.Fail() || log))
472 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
473 file_actions, info->m_fd, info->m_arg);
474 }
475 break;
476
477 case eFileActionOpen:
478 if (info->m_fd == -1)
479 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
480 else
481 {
482 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000483
Greg Claytonb72d0f02011-04-12 05:54:46 +0000484 mode_t mode = 0;
485
Greg Clayton527154d2011-11-15 03:53:30 +0000486 if (oflag & O_CREAT)
487 mode = 0640;
488
Greg Claytonb72d0f02011-04-12 05:54:46 +0000489 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
490 info->m_fd,
491 info->m_path.c_str(),
492 oflag,
493 mode),
494 eErrorTypePOSIX);
495 if (error.Fail() || log)
496 error.PutToLog(log,
497 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
498 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
499 }
500 break;
501
502 default:
503 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
504 break;
505 }
506 return error.Success();
507}
508
509Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000510ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000511{
512 Error error;
513 char short_option = (char) m_getopt_table[option_idx].val;
514
515 switch (short_option)
516 {
517 case 's': // Stop at program entry point
518 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
519 break;
520
521 case 'e': // STDERR for read + write
522 {
523 ProcessLaunchInfo::FileAction action;
524 if (action.Open(STDERR_FILENO, option_arg, true, true))
525 launch_info.AppendFileAction (action);
526 }
527 break;
528
529 case 'i': // STDIN for read only
530 {
531 ProcessLaunchInfo::FileAction action;
532 if (action.Open(STDIN_FILENO, option_arg, true, false))
533 launch_info.AppendFileAction (action);
534 }
535 break;
536
537 case 'o': // Open STDOUT for write only
538 {
539 ProcessLaunchInfo::FileAction action;
540 if (action.Open(STDOUT_FILENO, option_arg, false, true))
541 launch_info.AppendFileAction (action);
542 }
543 break;
544
545 case 'p': // Process plug-in name
546 launch_info.SetProcessPluginName (option_arg);
547 break;
548
549 case 'n': // Disable STDIO
550 {
551 ProcessLaunchInfo::FileAction action;
552 if (action.Open(STDERR_FILENO, "/dev/null", true, true))
553 launch_info.AppendFileAction (action);
554 if (action.Open(STDOUT_FILENO, "/dev/null", false, true))
555 launch_info.AppendFileAction (action);
556 if (action.Open(STDIN_FILENO, "/dev/null", true, false))
557 launch_info.AppendFileAction (action);
558 }
559 break;
560
561 case 'w':
562 launch_info.SetWorkingDirectory (option_arg);
563 break;
564
565 case 't': // Open process in new terminal window
566 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
567 break;
568
569 case 'a':
570 launch_info.GetArchitecture().SetTriple (option_arg,
571 m_interpreter.GetPlatform(true).get());
572 break;
573
574 case 'A':
575 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
576 break;
577
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000578 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000579 if (option_arg && option_arg[0])
580 launch_info.SetShell (option_arg);
581 else
582 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000583 break;
584
Greg Claytonb72d0f02011-04-12 05:54:46 +0000585 case 'v':
586 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
587 break;
588
589 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000590 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000591 break;
592
593 }
594 return error;
595}
596
597OptionDefinition
598ProcessLaunchCommandOptions::g_option_table[] =
599{
600{ 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."},
601{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
602{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
603{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
604{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
605{ 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 Clayton527154d2011-11-15 03:53:30 +0000606{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypePath, "Run the process in a shell (not supported on all platforms)."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000607
608{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
609{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
610{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
611
612{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
613
614{ 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."},
615
616{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
617};
618
619
620
621bool
622ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000623{
624 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
625 return true;
626 const char *match_name = m_match_info.GetName();
627 if (!match_name)
628 return true;
629
630 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
631}
632
633bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000634ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000635{
636 if (!NameMatches (proc_info.GetName()))
637 return false;
638
639 if (m_match_info.ProcessIDIsValid() &&
640 m_match_info.GetProcessID() != proc_info.GetProcessID())
641 return false;
642
643 if (m_match_info.ParentProcessIDIsValid() &&
644 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
645 return false;
646
Greg Claytonb72d0f02011-04-12 05:54:46 +0000647 if (m_match_info.UserIDIsValid () &&
648 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000649 return false;
650
Greg Claytonb72d0f02011-04-12 05:54:46 +0000651 if (m_match_info.GroupIDIsValid () &&
652 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000653 return false;
654
655 if (m_match_info.EffectiveUserIDIsValid () &&
656 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
657 return false;
658
659 if (m_match_info.EffectiveGroupIDIsValid () &&
660 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
661 return false;
662
663 if (m_match_info.GetArchitecture().IsValid() &&
664 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
665 return false;
666 return true;
667}
668
669bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000670ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000671{
672 if (m_name_match_type != eNameMatchIgnore)
673 return false;
674
675 if (m_match_info.ProcessIDIsValid())
676 return false;
677
678 if (m_match_info.ParentProcessIDIsValid())
679 return false;
680
Greg Claytonb72d0f02011-04-12 05:54:46 +0000681 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000682 return false;
683
Greg Claytonb72d0f02011-04-12 05:54:46 +0000684 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000685 return false;
686
687 if (m_match_info.EffectiveUserIDIsValid ())
688 return false;
689
690 if (m_match_info.EffectiveGroupIDIsValid ())
691 return false;
692
693 if (m_match_info.GetArchitecture().IsValid())
694 return false;
695
696 if (m_match_all_users)
697 return false;
698
699 return true;
700
701}
702
703void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000704ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000705{
706 m_match_info.Clear();
707 m_name_match_type = eNameMatchIgnore;
708 m_match_all_users = false;
709}
Greg Claytonfd119992011-01-07 06:08:19 +0000710
Chris Lattner24943d22010-06-08 16:52:24 +0000711Process*
712Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
713{
714 ProcessCreateInstance create_callback = NULL;
715 if (plugin_name)
716 {
717 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
718 if (create_callback)
719 {
720 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton8d2ea282011-07-17 20:36:25 +0000721 if (debugger_ap->CanDebug(target, true))
Chris Lattner24943d22010-06-08 16:52:24 +0000722 return debugger_ap.release();
723 }
724 }
725 else
726 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000727 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000728 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000729 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton8d2ea282011-07-17 20:36:25 +0000730 if (debugger_ap->CanDebug(target, false))
Greg Clayton54e7afa2010-07-09 20:39:50 +0000731 return debugger_ap.release();
Chris Lattner24943d22010-06-08 16:52:24 +0000732 }
733 }
734 return NULL;
735}
736
737
738//----------------------------------------------------------------------
739// Process constructor
740//----------------------------------------------------------------------
741Process::Process(Target &target, Listener &listener) :
742 UserID (LLDB_INVALID_PROCESS_ID),
Greg Clayton49ce6822010-10-31 03:01:06 +0000743 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +0000744 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000745 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000746 m_public_state (eStateUnloaded),
747 m_private_state (eStateUnloaded),
748 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
749 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
750 m_private_state_listener ("lldb.process.internal_state_listener"),
751 m_private_state_control_wait(),
752 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000753 m_mod_id (),
Chris Lattner24943d22010-06-08 16:52:24 +0000754 m_thread_index_id (0),
755 m_exit_status (-1),
756 m_exit_string (),
757 m_thread_list (this),
758 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000759 m_image_tokens (),
760 m_listener (listener),
761 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000762 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000763 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000764 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000765 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000766 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000767 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000768 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000769 m_stderr_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000770 m_memory_cache (*this),
771 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +0000772 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000773 m_next_event_action_ap(),
774 m_can_jit(eCanJITYes)
Chris Lattner24943d22010-06-08 16:52:24 +0000775{
Caroline Tice1ebef442010-09-27 00:30:10 +0000776 UpdateInstanceName();
777
Greg Claytone005f2c2010-11-06 01:53:30 +0000778 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000779 if (log)
780 log->Printf ("%p Process::Process()", this);
781
Greg Clayton49ce6822010-10-31 03:01:06 +0000782 SetEventName (eBroadcastBitStateChanged, "state-changed");
783 SetEventName (eBroadcastBitInterrupt, "interrupt");
784 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
785 SetEventName (eBroadcastBitSTDERR, "stderr-available");
786
Chris Lattner24943d22010-06-08 16:52:24 +0000787 listener.StartListeningForEvents (this,
788 eBroadcastBitStateChanged |
789 eBroadcastBitInterrupt |
790 eBroadcastBitSTDOUT |
791 eBroadcastBitSTDERR);
792
793 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
794 eBroadcastBitStateChanged);
795
796 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
797 eBroadcastInternalStateControlStop |
798 eBroadcastInternalStateControlPause |
799 eBroadcastInternalStateControlResume);
800}
801
802//----------------------------------------------------------------------
803// Destructor
804//----------------------------------------------------------------------
805Process::~Process()
806{
Greg Claytone005f2c2010-11-06 01:53:30 +0000807 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000808 if (log)
809 log->Printf ("%p Process::~Process()", this);
810 StopPrivateStateThread();
811}
812
813void
814Process::Finalize()
815{
Greg Claytonffa43a62011-11-17 04:46:02 +0000816 switch (GetPrivateState())
817 {
818 case eStateConnected:
819 case eStateAttaching:
820 case eStateLaunching:
821 case eStateStopped:
822 case eStateRunning:
823 case eStateStepping:
824 case eStateCrashed:
825 case eStateSuspended:
826 if (GetShouldDetach())
827 Detach();
828 else
829 Destroy();
830 break;
831
832 case eStateInvalid:
833 case eStateUnloaded:
834 case eStateDetached:
835 case eStateExited:
836 break;
837 }
838
Greg Clayton2f57db02011-10-01 00:45:15 +0000839 // Clear our broadcaster before we proceed with destroying
840 Broadcaster::Clear();
841
Chris Lattner24943d22010-06-08 16:52:24 +0000842 // Do any cleanup needed prior to being destructed... Subclasses
843 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000844
845 // We need to destroy the loader before the derived Process class gets destroyed
846 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton37f962e2011-08-22 02:49:39 +0000847 m_dyld_ap.reset();
848 m_os_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000849}
850
851void
852Process::RegisterNotificationCallbacks (const Notifications& callbacks)
853{
854 m_notifications.push_back(callbacks);
855 if (callbacks.initialize != NULL)
856 callbacks.initialize (callbacks.baton, this);
857}
858
859bool
860Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
861{
862 std::vector<Notifications>::iterator pos, end = m_notifications.end();
863 for (pos = m_notifications.begin(); pos != end; ++pos)
864 {
865 if (pos->baton == callbacks.baton &&
866 pos->initialize == callbacks.initialize &&
867 pos->process_state_changed == callbacks.process_state_changed)
868 {
869 m_notifications.erase(pos);
870 return true;
871 }
872 }
873 return false;
874}
875
876void
877Process::SynchronouslyNotifyStateChanged (StateType state)
878{
879 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
880 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
881 {
882 if (notification_pos->process_state_changed)
883 notification_pos->process_state_changed (notification_pos->baton, this, state);
884 }
885}
886
887// FIXME: We need to do some work on events before the general Listener sees them.
888// For instance if we are continuing from a breakpoint, we need to ensure that we do
889// the little "insert real insn, step & stop" trick. But we can't do that when the
890// event is delivered by the broadcaster - since that is done on the thread that is
891// waiting for new events, so if we needed more than one event for our handling, we would
892// stall. So instead we do it when we fetch the event off of the queue.
893//
894
895StateType
896Process::GetNextEvent (EventSP &event_sp)
897{
898 StateType state = eStateInvalid;
899
900 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
901 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
902
903 return state;
904}
905
906
907StateType
908Process::WaitForProcessToStop (const TimeValue *timeout)
909{
Jim Ingham21f37ad2011-08-09 02:12:22 +0000910 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
911 // We have to actually check each event, and in the case of a stopped event check the restarted flag
912 // on the event.
913 EventSP event_sp;
914 StateType state = GetState();
915 // If we are exited or detached, we won't ever get back to any
916 // other valid state...
917 if (state == eStateDetached || state == eStateExited)
918 return state;
919
920 while (state != eStateInvalid)
921 {
922 state = WaitForStateChangedEvents (timeout, event_sp);
923 switch (state)
924 {
925 case eStateCrashed:
926 case eStateDetached:
927 case eStateExited:
928 case eStateUnloaded:
929 return state;
930 case eStateStopped:
931 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
932 continue;
933 else
934 return state;
935 default:
936 continue;
937 }
938 }
939 return state;
Chris Lattner24943d22010-06-08 16:52:24 +0000940}
941
942
943StateType
944Process::WaitForState
945(
946 const TimeValue *timeout,
947 const StateType *match_states, const uint32_t num_match_states
948)
949{
950 EventSP event_sp;
951 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000952 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000953 while (state != eStateInvalid)
954 {
Greg Claytond8c62532010-10-07 04:19:01 +0000955 // If we are exited or detached, we won't ever get back to any
956 // other valid state...
957 if (state == eStateDetached || state == eStateExited)
958 return state;
959
Chris Lattner24943d22010-06-08 16:52:24 +0000960 state = WaitForStateChangedEvents (timeout, event_sp);
961
962 for (i=0; i<num_match_states; ++i)
963 {
964 if (match_states[i] == state)
965 return state;
966 }
967 }
968 return state;
969}
970
Jim Ingham63e24d72010-10-11 23:53:14 +0000971bool
972Process::HijackProcessEvents (Listener *listener)
973{
974 if (listener != NULL)
975 {
976 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
977 }
978 else
979 return false;
980}
981
982void
983Process::RestoreProcessEvents ()
984{
985 RestoreBroadcaster();
986}
987
Jim Inghamf9f40c22011-02-08 05:20:59 +0000988bool
989Process::HijackPrivateProcessEvents (Listener *listener)
990{
991 if (listener != NULL)
992 {
993 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
994 }
995 else
996 return false;
997}
998
999void
1000Process::RestorePrivateProcessEvents ()
1001{
1002 m_private_state_broadcaster.RestoreBroadcaster();
1003}
1004
Chris Lattner24943d22010-06-08 16:52:24 +00001005StateType
1006Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1007{
Greg Claytone005f2c2010-11-06 01:53:30 +00001008 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001009
1010 if (log)
1011 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1012
1013 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001014 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1015 this,
1016 eBroadcastBitStateChanged,
1017 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +00001018 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1019
1020 if (log)
1021 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1022 __FUNCTION__,
1023 timeout,
1024 StateAsCString(state));
1025 return state;
1026}
1027
1028Event *
1029Process::PeekAtStateChangedEvents ()
1030{
Greg Claytone005f2c2010-11-06 01:53:30 +00001031 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001032
1033 if (log)
1034 log->Printf ("Process::%s...", __FUNCTION__);
1035
1036 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001037 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1038 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001039 if (log)
1040 {
1041 if (event_ptr)
1042 {
1043 log->Printf ("Process::%s (event_ptr) => %s",
1044 __FUNCTION__,
1045 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1046 }
1047 else
1048 {
1049 log->Printf ("Process::%s no events found",
1050 __FUNCTION__);
1051 }
1052 }
1053 return event_ptr;
1054}
1055
1056StateType
1057Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1058{
Greg Claytone005f2c2010-11-06 01:53:30 +00001059 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001060
1061 if (log)
1062 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1063
1064 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001065 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1066 &m_private_state_broadcaster,
1067 eBroadcastBitStateChanged,
1068 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +00001069 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1070
1071 // This is a bit of a hack, but when we wait here we could very well return
1072 // to the command-line, and that could disable the log, which would render the
1073 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001074 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001075 {
1076 if (state == eStateInvalid)
1077 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1078 else
1079 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1080 }
Chris Lattner24943d22010-06-08 16:52:24 +00001081 return state;
1082}
1083
1084bool
1085Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1086{
Greg Claytone005f2c2010-11-06 01:53:30 +00001087 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001088
1089 if (log)
1090 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1091
1092 if (control_only)
1093 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1094 else
1095 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1096}
1097
1098bool
1099Process::IsRunning () const
1100{
1101 return StateIsRunningState (m_public_state.GetValue());
1102}
1103
1104int
1105Process::GetExitStatus ()
1106{
1107 if (m_public_state.GetValue() == eStateExited)
1108 return m_exit_status;
1109 return -1;
1110}
1111
Greg Clayton638351a2010-12-04 00:10:17 +00001112
Chris Lattner24943d22010-06-08 16:52:24 +00001113const char *
1114Process::GetExitDescription ()
1115{
1116 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1117 return m_exit_string.c_str();
1118 return NULL;
1119}
1120
Greg Clayton72e1c782011-01-22 23:43:18 +00001121bool
Chris Lattner24943d22010-06-08 16:52:24 +00001122Process::SetExitStatus (int status, const char *cstr)
1123{
Greg Clayton68ca8232011-01-25 02:58:48 +00001124 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1125 if (log)
1126 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1127 status, status,
1128 cstr ? "\"" : "",
1129 cstr ? cstr : "NULL",
1130 cstr ? "\"" : "");
1131
Greg Clayton72e1c782011-01-22 23:43:18 +00001132 // We were already in the exited state
1133 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001134 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001135 if (log)
1136 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001137 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001138 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001139
1140 m_exit_status = status;
1141 if (cstr)
1142 m_exit_string = cstr;
1143 else
1144 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001145
Greg Clayton72e1c782011-01-22 23:43:18 +00001146 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001147
Greg Clayton72e1c782011-01-22 23:43:18 +00001148 SetPrivateState (eStateExited);
1149 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001150}
1151
1152// This static callback can be used to watch for local child processes on
1153// the current host. The the child process exits, the process will be
1154// found in the global target list (we want to be completely sure that the
1155// lldb_private::Process doesn't go away before we can deliver the signal.
1156bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001157Process::SetProcessExitStatus (void *callback_baton,
1158 lldb::pid_t pid,
1159 bool exited,
1160 int signo, // Zero for no signal
1161 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001162)
1163{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001164 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1165 if (log)
1166 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%i, exited=%i, signal=%i, exit_status=%i)\n",
1167 callback_baton,
1168 pid,
1169 exited,
1170 signo,
1171 exit_status);
1172
1173 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001174 {
Greg Clayton63094e02010-06-23 01:19:29 +00001175 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001176 if (target_sp)
1177 {
1178 ProcessSP process_sp (target_sp->GetProcessSP());
1179 if (process_sp)
1180 {
1181 const char *signal_cstr = NULL;
1182 if (signo)
1183 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1184
1185 process_sp->SetExitStatus (exit_status, signal_cstr);
1186 }
1187 }
1188 return true;
1189 }
1190 return false;
1191}
1192
1193
Greg Clayton37f962e2011-08-22 02:49:39 +00001194void
1195Process::UpdateThreadListIfNeeded ()
1196{
1197 const uint32_t stop_id = GetStopID();
1198 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1199 {
Greg Clayton20206082011-11-17 01:23:07 +00001200 const StateType state = GetPrivateState();
1201 if (StateIsStoppedState (state, true))
1202 {
1203 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001204 // m_thread_list does have its own mutex, but we need to
1205 // hold onto the mutex between the call to UpdateThreadList(...)
1206 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001207 ThreadList new_thread_list(this);
1208 // Always update the thread list with the protocol specific
1209 // thread list
1210 UpdateThreadList (m_thread_list, new_thread_list);
1211 OperatingSystem *os = GetOperatingSystem ();
1212 if (os)
1213 os->UpdateThreadList (m_thread_list, new_thread_list);
1214 m_thread_list.Update (new_thread_list);
1215 m_thread_list.SetStopID (stop_id);
1216 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001217 }
1218}
1219
Chris Lattner24943d22010-06-08 16:52:24 +00001220uint32_t
1221Process::GetNextThreadIndexID ()
1222{
1223 return ++m_thread_index_id;
1224}
1225
1226StateType
1227Process::GetState()
1228{
1229 // If any other threads access this we will need a mutex for it
1230 return m_public_state.GetValue ();
1231}
1232
1233void
1234Process::SetPublicState (StateType new_state)
1235{
Greg Clayton68ca8232011-01-25 02:58:48 +00001236 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001237 if (log)
1238 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1239 m_public_state.SetValue (new_state);
1240}
1241
1242StateType
1243Process::GetPrivateState ()
1244{
1245 return m_private_state.GetValue();
1246}
1247
1248void
1249Process::SetPrivateState (StateType new_state)
1250{
Greg Clayton68ca8232011-01-25 02:58:48 +00001251 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001252 bool state_changed = false;
1253
1254 if (log)
1255 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1256
1257 Mutex::Locker locker(m_private_state.GetMutex());
1258
1259 const StateType old_state = m_private_state.GetValueNoLock ();
1260 state_changed = old_state != new_state;
1261 if (state_changed)
1262 {
1263 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001264 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001265 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001266 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001267 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001268 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001269 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001270 }
1271 // Use our target to get a shared pointer to ourselves...
1272 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1273 }
1274 else
1275 {
1276 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001277 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001278 }
1279}
1280
Jim Ingham0296fe72011-11-08 03:00:11 +00001281void
1282Process::SetRunningUserExpression (bool on)
1283{
1284 m_mod_id.SetRunningUserExpression (on);
1285}
1286
Chris Lattner24943d22010-06-08 16:52:24 +00001287addr_t
1288Process::GetImageInfoAddress()
1289{
1290 return LLDB_INVALID_ADDRESS;
1291}
1292
Greg Clayton0baa3942010-11-04 01:54:29 +00001293//----------------------------------------------------------------------
1294// LoadImage
1295//
1296// This function provides a default implementation that works for most
1297// unix variants. Any Process subclasses that need to do shared library
1298// loading differently should override LoadImage and UnloadImage and
1299// do what is needed.
1300//----------------------------------------------------------------------
1301uint32_t
1302Process::LoadImage (const FileSpec &image_spec, Error &error)
1303{
1304 DynamicLoader *loader = GetDynamicLoader();
1305 if (loader)
1306 {
1307 error = loader->CanLoadImage();
1308 if (error.Fail())
1309 return LLDB_INVALID_IMAGE_TOKEN;
1310 }
1311
1312 if (error.Success())
1313 {
1314 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001315
1316 if (thread_sp)
1317 {
1318 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1319
1320 if (frame_sp)
1321 {
1322 ExecutionContext exe_ctx;
1323 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001324 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001325 StreamString expr;
1326 char path[PATH_MAX];
1327 image_spec.GetPath(path, sizeof(path));
1328 expr.Printf("dlopen (\"%s\", 2)", path);
1329 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001330 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan5b658cc2011-11-07 23:35:40 +00001331 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chenb14ec342011-09-09 00:01:43 +00001332 error = result_valobj_sp->GetError();
1333 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001334 {
1335 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001336 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001337 {
1338 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1339 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1340 {
1341 uint32_t image_token = m_image_tokens.size();
1342 m_image_tokens.push_back (image_ptr);
1343 return image_token;
1344 }
1345 }
1346 }
1347 }
1348 }
1349 }
1350 return LLDB_INVALID_IMAGE_TOKEN;
1351}
1352
1353//----------------------------------------------------------------------
1354// UnloadImage
1355//
1356// This function provides a default implementation that works for most
1357// unix variants. Any Process subclasses that need to do shared library
1358// loading differently should override LoadImage and UnloadImage and
1359// do what is needed.
1360//----------------------------------------------------------------------
1361Error
1362Process::UnloadImage (uint32_t image_token)
1363{
1364 Error error;
1365 if (image_token < m_image_tokens.size())
1366 {
1367 const addr_t image_addr = m_image_tokens[image_token];
1368 if (image_addr == LLDB_INVALID_ADDRESS)
1369 {
1370 error.SetErrorString("image already unloaded");
1371 }
1372 else
1373 {
1374 DynamicLoader *loader = GetDynamicLoader();
1375 if (loader)
1376 error = loader->CanLoadImage();
1377
1378 if (error.Success())
1379 {
1380 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001381
1382 if (thread_sp)
1383 {
1384 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1385
1386 if (frame_sp)
1387 {
1388 ExecutionContext exe_ctx;
1389 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001390 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001391 StreamString expr;
1392 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1393 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001394 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan5b658cc2011-11-07 23:35:40 +00001395 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +00001396 if (result_valobj_sp->GetError().Success())
1397 {
1398 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001399 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001400 {
1401 if (scalar.UInt(1))
1402 {
1403 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1404 }
1405 else
1406 {
1407 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1408 }
1409 }
1410 }
1411 else
1412 {
1413 error = result_valobj_sp->GetError();
1414 }
1415 }
1416 }
1417 }
1418 }
1419 }
1420 else
1421 {
1422 error.SetErrorString("invalid image token");
1423 }
1424 return error;
1425}
1426
Greg Clayton75906e42011-05-11 18:39:18 +00001427const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001428Process::GetABI()
1429{
Greg Clayton75906e42011-05-11 18:39:18 +00001430 if (!m_abi_sp)
1431 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1432 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001433}
1434
Jim Ingham642036f2010-09-23 02:01:19 +00001435LanguageRuntime *
1436Process::GetLanguageRuntime(lldb::LanguageType language)
1437{
1438 LanguageRuntimeCollection::iterator pos;
1439 pos = m_language_runtimes.find (language);
1440 if (pos == m_language_runtimes.end())
1441 {
1442 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1443
1444 m_language_runtimes[language]
1445 = runtime;
1446 return runtime.get();
1447 }
1448 else
1449 return (*pos).second.get();
1450}
1451
1452CPPLanguageRuntime *
1453Process::GetCPPLanguageRuntime ()
1454{
1455 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1456 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1457 return static_cast<CPPLanguageRuntime *> (runtime);
1458 return NULL;
1459}
1460
1461ObjCLanguageRuntime *
1462Process::GetObjCLanguageRuntime ()
1463{
1464 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1465 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1466 return static_cast<ObjCLanguageRuntime *> (runtime);
1467 return NULL;
1468}
1469
Chris Lattner24943d22010-06-08 16:52:24 +00001470BreakpointSiteList &
1471Process::GetBreakpointSiteList()
1472{
1473 return m_breakpoint_site_list;
1474}
1475
1476const BreakpointSiteList &
1477Process::GetBreakpointSiteList() const
1478{
1479 return m_breakpoint_site_list;
1480}
1481
1482
1483void
1484Process::DisableAllBreakpointSites ()
1485{
1486 m_breakpoint_site_list.SetEnabledForAll (false);
1487}
1488
1489Error
1490Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1491{
1492 Error error (DisableBreakpointSiteByID (break_id));
1493
1494 if (error.Success())
1495 m_breakpoint_site_list.Remove(break_id);
1496
1497 return error;
1498}
1499
1500Error
1501Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1502{
1503 Error error;
1504 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1505 if (bp_site_sp)
1506 {
1507 if (bp_site_sp->IsEnabled())
1508 error = DisableBreakpoint (bp_site_sp.get());
1509 }
1510 else
1511 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001512 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001513 }
1514
1515 return error;
1516}
1517
1518Error
1519Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1520{
1521 Error error;
1522 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1523 if (bp_site_sp)
1524 {
1525 if (!bp_site_sp->IsEnabled())
1526 error = EnableBreakpoint (bp_site_sp.get());
1527 }
1528 else
1529 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001530 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001531 }
1532 return error;
1533}
1534
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001535lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +00001536Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1537{
Greg Clayton265ab332011-05-19 18:17:41 +00001538 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001539 if (load_addr != LLDB_INVALID_ADDRESS)
1540 {
1541 BreakpointSiteSP bp_site_sp;
1542
1543 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1544 // create a new breakpoint site and add it.
1545
1546 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1547
1548 if (bp_site_sp)
1549 {
1550 bp_site_sp->AddOwner (owner);
1551 owner->SetBreakpointSite (bp_site_sp);
1552 return bp_site_sp->GetID();
1553 }
1554 else
1555 {
1556 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1557 if (bp_site_sp)
1558 {
1559 if (EnableBreakpoint (bp_site_sp.get()).Success())
1560 {
1561 owner->SetBreakpointSite (bp_site_sp);
1562 return m_breakpoint_site_list.Add (bp_site_sp);
1563 }
1564 }
1565 }
1566 }
1567 // We failed to enable the breakpoint
1568 return LLDB_INVALID_BREAK_ID;
1569
1570}
1571
1572void
1573Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1574{
1575 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1576 if (num_owners == 0)
1577 {
1578 DisableBreakpoint(bp_site_sp.get());
1579 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1580 }
1581}
1582
1583
1584size_t
1585Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1586{
1587 size_t bytes_removed = 0;
1588 addr_t intersect_addr;
1589 size_t intersect_size;
1590 size_t opcode_offset;
1591 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001592 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001593 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001594
Jim Ingham82820f92011-06-29 19:42:28 +00001595 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001596 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001597 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001598 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001599 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001600 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001601 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001602 {
1603 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1604 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001605 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001606 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001607 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001608 }
Chris Lattner24943d22010-06-08 16:52:24 +00001609 }
1610 }
1611 }
1612 return bytes_removed;
1613}
1614
1615
Greg Claytonb1888f22011-03-19 01:12:21 +00001616
1617size_t
1618Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1619{
1620 PlatformSP platform_sp (m_target.GetPlatform());
1621 if (platform_sp)
1622 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1623 return 0;
1624}
1625
Chris Lattner24943d22010-06-08 16:52:24 +00001626Error
1627Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1628{
1629 Error error;
1630 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001631 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001632 const addr_t bp_addr = bp_site->GetLoadAddress();
1633 if (log)
1634 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1635 if (bp_site->IsEnabled())
1636 {
1637 if (log)
1638 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1639 return error;
1640 }
1641
1642 if (bp_addr == LLDB_INVALID_ADDRESS)
1643 {
1644 error.SetErrorString("BreakpointSite contains an invalid load address.");
1645 return error;
1646 }
1647 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1648 // trap for the breakpoint site
1649 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1650
1651 if (bp_opcode_size == 0)
1652 {
Greg Clayton9c236732011-10-26 00:56:27 +00001653 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001654 }
1655 else
1656 {
1657 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1658
1659 if (bp_opcode_bytes == NULL)
1660 {
1661 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1662 return error;
1663 }
1664
1665 // Save the original opcode by reading it
1666 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1667 {
1668 // Write a software breakpoint in place of the original opcode
1669 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1670 {
1671 uint8_t verify_bp_opcode_bytes[64];
1672 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1673 {
1674 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1675 {
1676 bp_site->SetEnabled(true);
1677 bp_site->SetType (BreakpointSite::eSoftware);
1678 if (log)
1679 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1680 bp_site->GetID(),
1681 (uint64_t)bp_addr);
1682 }
1683 else
Greg Clayton9c236732011-10-26 00:56:27 +00001684 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00001685 }
1686 else
1687 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1688 }
1689 else
1690 error.SetErrorString("Unable to write breakpoint trap to memory.");
1691 }
1692 else
1693 error.SetErrorString("Unable to read memory at breakpoint address.");
1694 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001695 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001696 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1697 bp_site->GetID(),
1698 (uint64_t)bp_addr,
1699 error.AsCString());
1700 return error;
1701}
1702
1703Error
1704Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1705{
1706 Error error;
1707 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001708 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001709 addr_t bp_addr = bp_site->GetLoadAddress();
1710 lldb::user_id_t breakID = bp_site->GetID();
1711 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001712 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001713
1714 if (bp_site->IsHardware())
1715 {
1716 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1717 }
1718 else if (bp_site->IsEnabled())
1719 {
1720 const size_t break_op_size = bp_site->GetByteSize();
1721 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1722 if (break_op_size > 0)
1723 {
1724 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001725 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001726 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001727 bool break_op_found = false;
1728
1729 // Read the breakpoint opcode
1730 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1731 {
1732 bool verify = false;
1733 // Make sure we have the a breakpoint opcode exists at this address
1734 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1735 {
1736 break_op_found = true;
1737 // We found a valid breakpoint opcode at this address, now restore
1738 // the saved opcode.
1739 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1740 {
1741 verify = true;
1742 }
1743 else
1744 error.SetErrorString("Memory write failed when restoring original opcode.");
1745 }
1746 else
1747 {
1748 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1749 // Set verify to true and so we can check if the original opcode has already been restored
1750 verify = true;
1751 }
1752
1753 if (verify)
1754 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001755 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001756 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001757 // Verify that our original opcode made it back to the inferior
1758 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1759 {
1760 // compare the memory we just read with the original opcode
1761 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1762 {
1763 // SUCCESS
1764 bp_site->SetEnabled(false);
1765 if (log)
1766 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1767 return error;
1768 }
1769 else
1770 {
1771 if (break_op_found)
1772 error.SetErrorString("Failed to restore original opcode.");
1773 }
1774 }
1775 else
1776 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1777 }
1778 }
1779 else
1780 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1781 }
1782 }
1783 else
1784 {
1785 if (log)
1786 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1787 return error;
1788 }
1789
1790 if (log)
1791 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1792 bp_site->GetID(),
1793 (uint64_t)bp_addr,
1794 error.AsCString());
1795 return error;
1796
1797}
1798
Greg Claytonfd119992011-01-07 06:08:19 +00001799// Comment out line below to disable memory caching
1800#define ENABLE_MEMORY_CACHING
1801// Uncomment to verify memory caching works after making changes to caching code
1802//#define VERIFY_MEMORY_READS
1803
1804#if defined (ENABLE_MEMORY_CACHING)
1805
1806#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001807
1808size_t
1809Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1810{
Greg Claytonfd119992011-01-07 06:08:19 +00001811 // Memory caching is enabled, with debug verification
1812 if (buf && size)
1813 {
1814 // Uncomment the line below to make sure memory caching is working.
1815 // I ran this through the test suite and got no assertions, so I am
1816 // pretty confident this is working well. If any changes are made to
1817 // memory caching, uncomment the line below and test your changes!
1818
1819 // Verify all memory reads by using the cache first, then redundantly
1820 // reading the same memory from the inferior and comparing to make sure
1821 // everything is exactly the same.
1822 std::string verify_buf (size, '\0');
1823 assert (verify_buf.size() == size);
1824 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1825 Error verify_error;
1826 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1827 assert (cache_bytes_read == verify_bytes_read);
1828 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1829 assert (verify_error.Success() == error.Success());
1830 return cache_bytes_read;
1831 }
1832 return 0;
1833}
1834
1835#else // #if defined (VERIFY_MEMORY_READS)
1836
1837size_t
1838Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1839{
1840 // Memory caching enabled, no verification
Greg Clayton613b8732011-05-17 03:37:42 +00001841 return m_memory_cache.Read (addr, buf, size, error);
Greg Claytonfd119992011-01-07 06:08:19 +00001842}
1843
1844#endif // #else for #if defined (VERIFY_MEMORY_READS)
1845
1846#else // #if defined (ENABLE_MEMORY_CACHING)
1847
1848size_t
1849Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1850{
1851 // Memory caching is disabled
1852 return ReadMemoryFromInferior (addr, buf, size, error);
1853}
1854
1855#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1856
1857
1858size_t
Greg Claytonb72d0f02011-04-12 05:54:46 +00001859Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1860{
1861 size_t total_cstr_len = 0;
1862 if (dst && dst_max_len)
1863 {
1864 // NULL out everything just to be safe
1865 memset (dst, 0, dst_max_len);
1866 Error error;
1867 addr_t curr_addr = addr;
1868 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1869 size_t bytes_left = dst_max_len - 1;
1870 char *curr_dst = dst;
1871
1872 while (bytes_left > 0)
1873 {
1874 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1875 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1876 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1877
1878 if (bytes_read == 0)
1879 {
1880 dst[total_cstr_len] = '\0';
1881 break;
1882 }
1883 const size_t len = strlen(curr_dst);
1884
1885 total_cstr_len += len;
1886
1887 if (len < bytes_to_read)
1888 break;
1889
1890 curr_dst += bytes_read;
1891 curr_addr += bytes_read;
1892 bytes_left -= bytes_read;
1893 }
1894 }
1895 return total_cstr_len;
1896}
1897
1898size_t
Greg Claytonfd119992011-01-07 06:08:19 +00001899Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1900{
Chris Lattner24943d22010-06-08 16:52:24 +00001901 if (buf == NULL || size == 0)
1902 return 0;
1903
1904 size_t bytes_read = 0;
1905 uint8_t *bytes = (uint8_t *)buf;
1906
1907 while (bytes_read < size)
1908 {
1909 const size_t curr_size = size - bytes_read;
1910 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1911 bytes + bytes_read,
1912 curr_size,
1913 error);
1914 bytes_read += curr_bytes_read;
1915 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1916 break;
1917 }
1918
1919 // Replace any software breakpoint opcodes that fall into this range back
1920 // into "buf" before we return
1921 if (bytes_read > 0)
1922 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1923 return bytes_read;
1924}
1925
Greg Claytonf72fdee2010-12-16 20:01:20 +00001926uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00001927Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00001928{
Greg Claytonc0fa5332011-05-22 22:46:53 +00001929 Scalar scalar;
1930 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1931 return scalar.ULongLong(fail_value);
1932 return fail_value;
1933}
1934
1935addr_t
1936Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1937{
1938 Scalar scalar;
1939 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1940 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1941 return LLDB_INVALID_ADDRESS;
1942}
1943
1944
1945bool
1946Process::WritePointerToMemory (lldb::addr_t vm_addr,
1947 lldb::addr_t ptr_value,
1948 Error &error)
1949{
1950 Scalar scalar;
1951 const uint32_t addr_byte_size = GetAddressByteSize();
1952 if (addr_byte_size <= 4)
1953 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001954 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00001955 scalar = ptr_value;
1956 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001957}
1958
Chris Lattner24943d22010-06-08 16:52:24 +00001959size_t
1960Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1961{
1962 size_t bytes_written = 0;
1963 const uint8_t *bytes = (const uint8_t *)buf;
1964
1965 while (bytes_written < size)
1966 {
1967 const size_t curr_size = size - bytes_written;
1968 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1969 bytes + bytes_written,
1970 curr_size,
1971 error);
1972 bytes_written += curr_bytes_written;
1973 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1974 break;
1975 }
1976 return bytes_written;
1977}
1978
1979size_t
1980Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1981{
Greg Claytonfd119992011-01-07 06:08:19 +00001982#if defined (ENABLE_MEMORY_CACHING)
1983 m_memory_cache.Flush (addr, size);
1984#endif
1985
Chris Lattner24943d22010-06-08 16:52:24 +00001986 if (buf == NULL || size == 0)
1987 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00001988
Jim Ingham21f37ad2011-08-09 02:12:22 +00001989 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00001990
Chris Lattner24943d22010-06-08 16:52:24 +00001991 // We need to write any data that would go where any current software traps
1992 // (enabled software breakpoints) any software traps (breakpoints) that we
1993 // may have placed in our tasks memory.
1994
1995 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1996 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1997
1998 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00001999 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002000
2001 BreakpointSiteList::collection::const_iterator pos;
2002 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002003 addr_t intersect_addr = 0;
2004 size_t intersect_size = 0;
2005 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002006 const uint8_t *ubuf = (const uint8_t *)buf;
2007
2008 for (pos = iter; pos != end; ++pos)
2009 {
2010 BreakpointSiteSP bp;
2011 bp = pos->second;
2012
2013 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2014 assert(addr <= intersect_addr && intersect_addr < addr + size);
2015 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2016 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2017
2018 // Check for bytes before this breakpoint
2019 const addr_t curr_addr = addr + bytes_written;
2020 if (intersect_addr > curr_addr)
2021 {
2022 // There are some bytes before this breakpoint that we need to
2023 // just write to memory
2024 size_t curr_size = intersect_addr - curr_addr;
2025 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2026 ubuf + bytes_written,
2027 curr_size,
2028 error);
2029 bytes_written += curr_bytes_written;
2030 if (curr_bytes_written != curr_size)
2031 {
2032 // We weren't able to write all of the requested bytes, we
2033 // are done looping and will return the number of bytes that
2034 // we have written so far.
2035 break;
2036 }
2037 }
2038
2039 // Now write any bytes that would cover up any software breakpoints
2040 // directly into the breakpoint opcode buffer
2041 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2042 bytes_written += intersect_size;
2043 }
2044
2045 // Write any remaining bytes after the last breakpoint if we have any left
2046 if (bytes_written < size)
2047 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2048 ubuf + bytes_written,
2049 size - bytes_written,
2050 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002051
Chris Lattner24943d22010-06-08 16:52:24 +00002052 return bytes_written;
2053}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002054
2055size_t
2056Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2057{
2058 if (byte_size == UINT32_MAX)
2059 byte_size = scalar.GetByteSize();
2060 if (byte_size > 0)
2061 {
2062 uint8_t buf[32];
2063 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2064 if (mem_size > 0)
2065 return WriteMemory(addr, buf, mem_size, error);
2066 else
2067 error.SetErrorString ("failed to get scalar as memory data");
2068 }
2069 else
2070 {
2071 error.SetErrorString ("invalid scalar value");
2072 }
2073 return 0;
2074}
2075
2076size_t
2077Process::ReadScalarIntegerFromMemory (addr_t addr,
2078 uint32_t byte_size,
2079 bool is_signed,
2080 Scalar &scalar,
2081 Error &error)
2082{
2083 uint64_t uval;
2084
2085 if (byte_size <= sizeof(uval))
2086 {
2087 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2088 if (bytes_read == byte_size)
2089 {
2090 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2091 uint32_t offset = 0;
2092 if (byte_size <= 4)
2093 scalar = data.GetMaxU32 (&offset, byte_size);
2094 else
2095 scalar = data.GetMaxU64 (&offset, byte_size);
2096
2097 if (is_signed)
2098 scalar.SignExtend(byte_size * 8);
2099 return bytes_read;
2100 }
2101 }
2102 else
2103 {
2104 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2105 }
2106 return 0;
2107}
2108
Greg Clayton613b8732011-05-17 03:37:42 +00002109#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002110addr_t
2111Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2112{
Jim Inghame6bd1422011-06-20 17:32:44 +00002113 if (GetPrivateState() != eStateStopped)
2114 return LLDB_INVALID_ADDRESS;
2115
Greg Clayton613b8732011-05-17 03:37:42 +00002116#if defined (USE_ALLOCATE_MEMORY_CACHE)
2117 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2118#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002119 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2120 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2121 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002122 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002123 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002124 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002125 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002126 m_mod_id.GetStopID(),
2127 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002128 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002129#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002130}
2131
Sean Callanan6cf6c472011-09-20 23:01:51 +00002132bool
2133Process::CanJIT ()
2134{
2135 return m_can_jit == eCanJITYes;
2136}
2137
2138void
2139Process::SetCanJIT (bool can_jit)
2140{
2141 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2142}
2143
Chris Lattner24943d22010-06-08 16:52:24 +00002144Error
2145Process::DeallocateMemory (addr_t ptr)
2146{
Greg Clayton613b8732011-05-17 03:37:42 +00002147 Error error;
2148#if defined (USE_ALLOCATE_MEMORY_CACHE)
2149 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2150 {
2151 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2152 }
2153#else
2154 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002155
2156 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2157 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002158 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002159 ptr,
2160 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002161 m_mod_id.GetStopID(),
2162 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002163#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002164 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002165}
2166
2167
2168Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002169Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002170{
2171 Error error;
2172 error.SetErrorString("watchpoints are not supported");
2173 return error;
2174}
2175
2176Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002177Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002178{
2179 Error error;
2180 error.SetErrorString("watchpoints are not supported");
2181 return error;
2182}
2183
2184StateType
2185Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2186{
2187 StateType state;
2188 // Now wait for the process to launch and return control to us, and then
2189 // call DidLaunch:
2190 while (1)
2191 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002192 event_sp.reset();
2193 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2194
Greg Clayton20206082011-11-17 01:23:07 +00002195 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002196 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002197
2198 // If state is invalid, then we timed out
2199 if (state == eStateInvalid)
2200 break;
2201
2202 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002203 HandlePrivateEvent (event_sp);
2204 }
2205 return state;
2206}
2207
2208Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002209Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002210{
2211 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002212 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002213 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002214 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002215 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002216
Greg Clayton5beb99d2011-08-11 02:48:45 +00002217 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002218 if (exe_module)
2219 {
Greg Clayton180546b2011-04-30 01:09:13 +00002220 char local_exec_file_path[PATH_MAX];
2221 char platform_exec_file_path[PATH_MAX];
2222 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2223 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002224 if (exe_module->GetFileSpec().Exists())
2225 {
Greg Claytona2f74232011-02-24 22:24:29 +00002226 if (PrivateStateThreadIsValid ())
2227 PausePrivateStateThread ();
2228
Chris Lattner24943d22010-06-08 16:52:24 +00002229 error = WillLaunch (exe_module);
2230 if (error.Success())
2231 {
Greg Claytond8c62532010-10-07 04:19:01 +00002232 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002233 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002234
2235 // Now launch using these arguments.
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002236 error = DoLaunch (exe_module, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +00002237
2238 if (error.Fail())
2239 {
2240 if (GetID() != LLDB_INVALID_PROCESS_ID)
2241 {
2242 SetID (LLDB_INVALID_PROCESS_ID);
2243 const char *error_string = error.AsCString();
2244 if (error_string == NULL)
2245 error_string = "launch failed";
2246 SetExitStatus (-1, error_string);
2247 }
2248 }
2249 else
2250 {
2251 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002252 TimeValue timeout_time;
2253 timeout_time = TimeValue::Now();
2254 timeout_time.OffsetWithSeconds(10);
2255 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002256
Greg Clayton49859592011-06-22 01:42:17 +00002257 if (state == eStateInvalid || event_sp.get() == NULL)
2258 {
2259 // We were able to launch the process, but we failed to
2260 // catch the initial stop.
2261 SetExitStatus (0, "failed to catch stop after launch");
2262 Destroy();
2263 }
2264 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002265 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002266
Chris Lattner24943d22010-06-08 16:52:24 +00002267 DidLaunch ();
2268
Greg Clayton37f962e2011-08-22 02:49:39 +00002269 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002270 if (m_dyld_ap.get())
2271 m_dyld_ap->DidLaunch();
2272
Greg Clayton37f962e2011-08-22 02:49:39 +00002273 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002274 // This delays passing the stopped event to listeners till DidLaunch gets
2275 // a chance to complete...
2276 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002277
2278 if (PrivateStateThreadIsValid ())
2279 ResumePrivateStateThread ();
2280 else
2281 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002282 }
2283 else if (state == eStateExited)
2284 {
2285 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2286 // not likely to work, and return an invalid pid.
2287 HandlePrivateEvent (event_sp);
2288 }
2289 }
2290 }
2291 }
2292 else
2293 {
Greg Clayton9c236732011-10-26 00:56:27 +00002294 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002295 }
2296 }
2297 return error;
2298}
2299
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002300Process::NextEventAction::EventActionResult
2301Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002302{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002303 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2304 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002305 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002306 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002307 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002308 return eEventActionRetry;
2309
2310 case eStateStopped:
2311 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002312 {
2313 // During attach, prior to sending the eStateStopped event,
2314 // lldb_private::Process subclasses must set the process must set
2315 // the new process ID.
2316 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2317 if (m_exec_count > 0)
2318 {
2319 --m_exec_count;
2320 m_process->Resume();
2321 return eEventActionRetry;
2322 }
2323 else
2324 {
2325 m_process->CompleteAttach ();
2326 return eEventActionSuccess;
2327 }
2328 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002329 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002330
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002331 default:
2332 case eStateExited:
2333 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002334 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002335 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002336
2337 m_exit_string.assign ("No valid Process");
2338 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002339}
Chris Lattner24943d22010-06-08 16:52:24 +00002340
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002341Process::NextEventAction::EventActionResult
2342Process::AttachCompletionHandler::HandleBeingInterrupted()
2343{
2344 return eEventActionSuccess;
2345}
2346
2347const char *
2348Process::AttachCompletionHandler::GetExitString ()
2349{
2350 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002351}
2352
2353Error
Greg Clayton527154d2011-11-15 03:53:30 +00002354Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002355{
Chris Lattner24943d22010-06-08 16:52:24 +00002356 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002357 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002358 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002359 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002360
Greg Clayton527154d2011-11-15 03:53:30 +00002361 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002362 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002363 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002364 {
Greg Clayton527154d2011-11-15 03:53:30 +00002365 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002366
Greg Clayton527154d2011-11-15 03:53:30 +00002367 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002368 {
Greg Clayton527154d2011-11-15 03:53:30 +00002369 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2370
2371 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002372 {
Greg Clayton527154d2011-11-15 03:53:30 +00002373 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2374 if (error.Success())
2375 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002376 m_should_detach = true;
2377
Greg Clayton527154d2011-11-15 03:53:30 +00002378 SetPublicState (eStateAttaching);
2379 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2380 if (error.Fail())
2381 {
2382 if (GetID() != LLDB_INVALID_PROCESS_ID)
2383 {
2384 SetID (LLDB_INVALID_PROCESS_ID);
2385 if (error.AsCString() == NULL)
2386 error.SetErrorString("attach failed");
2387
2388 SetExitStatus(-1, error.AsCString());
2389 }
2390 }
2391 else
2392 {
2393 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2394 StartPrivateStateThread();
2395 }
2396 return error;
2397 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002398 }
Greg Clayton527154d2011-11-15 03:53:30 +00002399 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002400 {
Greg Clayton527154d2011-11-15 03:53:30 +00002401 ProcessInstanceInfoList process_infos;
2402 PlatformSP platform_sp (m_target.GetPlatform ());
2403
2404 if (platform_sp)
2405 {
2406 ProcessInstanceInfoMatch match_info;
2407 match_info.GetProcessInfo() = attach_info;
2408 match_info.SetNameMatchType (eNameMatchEquals);
2409 platform_sp->FindProcesses (match_info, process_infos);
2410 const uint32_t num_matches = process_infos.GetSize();
2411 if (num_matches == 1)
2412 {
2413 attach_pid = process_infos.GetProcessIDAtIndex(0);
2414 // Fall through and attach using the above process ID
2415 }
2416 else
2417 {
2418 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2419 if (num_matches > 1)
2420 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2421 else
2422 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2423 }
2424 }
2425 else
2426 {
2427 error.SetErrorString ("invalid platform, can't find processes by name");
2428 return error;
2429 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002430 }
Chris Lattner24943d22010-06-08 16:52:24 +00002431 }
2432 else
Greg Clayton527154d2011-11-15 03:53:30 +00002433 {
2434 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002435 }
2436 }
Greg Clayton527154d2011-11-15 03:53:30 +00002437
2438 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002439 {
Greg Clayton527154d2011-11-15 03:53:30 +00002440 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002441 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002442 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002443 m_should_detach = true;
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002444 SetPublicState (eStateAttaching);
Greg Clayton527154d2011-11-15 03:53:30 +00002445
2446 error = DoAttachToProcessWithID (attach_pid);
2447 if (error.Success())
2448 {
2449
2450 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2451 StartPrivateStateThread();
2452 }
2453 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002454 {
2455 if (GetID() != LLDB_INVALID_PROCESS_ID)
2456 {
2457 SetID (LLDB_INVALID_PROCESS_ID);
2458 const char *error_string = error.AsCString();
2459 if (error_string == NULL)
2460 error_string = "attach failed";
2461
2462 SetExitStatus(-1, error_string);
2463 }
2464 }
Chris Lattner24943d22010-06-08 16:52:24 +00002465 }
2466 }
2467 return error;
2468}
2469
Greg Clayton527154d2011-11-15 03:53:30 +00002470//Error
2471//Process::Attach (const char *process_name, bool wait_for_launch)
2472//{
2473// m_abi_sp.reset();
2474// m_process_input_reader.reset();
2475//
2476// // Find the process and its architecture. Make sure it matches the architecture
2477// // of the current Target, and if not adjust it.
2478// Error error;
2479//
2480// if (!wait_for_launch)
2481// {
2482// ProcessInstanceInfoList process_infos;
2483// PlatformSP platform_sp (m_target.GetPlatform ());
2484// assert (platform_sp.get());
2485//
2486// if (platform_sp)
2487// {
2488// ProcessInstanceInfoMatch match_info;
2489// match_info.GetProcessInfo().SetName(process_name);
2490// match_info.SetNameMatchType (eNameMatchEquals);
2491// platform_sp->FindProcesses (match_info, process_infos);
2492// if (process_infos.GetSize() > 1)
2493// {
2494// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2495// }
2496// else if (process_infos.GetSize() == 0)
2497// {
2498// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2499// }
2500// }
2501// else
2502// {
2503// error.SetErrorString ("invalid platform");
2504// }
2505// }
2506//
2507// if (error.Success())
2508// {
2509// m_dyld_ap.reset();
2510// m_os_ap.reset();
2511//
2512// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2513// if (error.Success())
2514// {
2515// SetPublicState (eStateAttaching);
2516// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2517// if (error.Fail())
2518// {
2519// if (GetID() != LLDB_INVALID_PROCESS_ID)
2520// {
2521// SetID (LLDB_INVALID_PROCESS_ID);
2522// const char *error_string = error.AsCString();
2523// if (error_string == NULL)
2524// error_string = "attach failed";
2525//
2526// SetExitStatus(-1, error_string);
2527// }
2528// }
2529// else
2530// {
2531// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2532// StartPrivateStateThread();
2533// }
2534// }
2535// }
2536// return error;
2537//}
2538
Greg Clayton75c703d2011-02-16 04:46:07 +00002539void
2540Process::CompleteAttach ()
2541{
2542 // Let the process subclass figure out at much as it can about the process
2543 // before we go looking for a dynamic loader plug-in.
2544 DidAttach();
2545
Jim Ingham0d7f7772011-09-15 01:10:17 +00002546 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2547 // the same as the one we've already set, switch architectures.
2548 PlatformSP platform_sp (m_target.GetPlatform ());
2549 assert (platform_sp.get());
2550 if (platform_sp)
2551 {
2552 ProcessInstanceInfo process_info;
2553 platform_sp->GetProcessInfo (GetID(), process_info);
2554 const ArchSpec &process_arch = process_info.GetArchitecture();
2555 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2556 m_target.SetArchitecture (process_arch);
2557 }
2558
2559 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002560 // plug-in
Greg Clayton4fdf7602011-03-20 04:57:14 +00002561 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002562 if (m_dyld_ap.get())
2563 m_dyld_ap->DidAttach();
2564
Greg Clayton37f962e2011-08-22 02:49:39 +00002565 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002566 // Figure out which one is the executable, and set that in our target:
2567 ModuleList &modules = m_target.GetImages();
2568
2569 size_t num_modules = modules.GetSize();
2570 for (int i = 0; i < num_modules; i++)
2571 {
2572 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002573 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002574 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002575 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton75c703d2011-02-16 04:46:07 +00002576 m_target.SetExecutableModule (module_sp, false);
2577 break;
2578 }
2579 }
2580}
2581
Chris Lattner24943d22010-06-08 16:52:24 +00002582Error
Greg Claytone71e2582011-02-04 01:58:07 +00002583Process::ConnectRemote (const char *remote_url)
2584{
Greg Claytone71e2582011-02-04 01:58:07 +00002585 m_abi_sp.reset();
2586 m_process_input_reader.reset();
2587
2588 // Find the process and its architecture. Make sure it matches the architecture
2589 // of the current Target, and if not adjust it.
2590
2591 Error error (DoConnectRemote (remote_url));
2592 if (error.Success())
2593 {
Greg Claytona2f74232011-02-24 22:24:29 +00002594 if (GetID() != LLDB_INVALID_PROCESS_ID)
2595 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002596 EventSP event_sp;
2597 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2598
2599 if (state == eStateStopped || state == eStateCrashed)
2600 {
2601 // If we attached and actually have a process on the other end, then
2602 // this ended up being the equivalent of an attach.
2603 CompleteAttach ();
2604
2605 // This delays passing the stopped event to listeners till
2606 // CompleteAttach gets a chance to complete...
2607 HandlePrivateEvent (event_sp);
2608
2609 }
Greg Claytona2f74232011-02-24 22:24:29 +00002610 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002611
2612 if (PrivateStateThreadIsValid ())
2613 ResumePrivateStateThread ();
2614 else
2615 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002616 }
2617 return error;
2618}
2619
2620
2621Error
Chris Lattner24943d22010-06-08 16:52:24 +00002622Process::Resume ()
2623{
Greg Claytone005f2c2010-11-06 01:53:30 +00002624 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002625 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002626 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002627 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002628 StateAsCString(m_public_state.GetValue()),
2629 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002630
2631 Error error (WillResume());
2632 // Tell the process it is about to resume before the thread list
2633 if (error.Success())
2634 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002635 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002636 // can let all of our threads know that they are about to be
2637 // resumed. Threads will each be called with
2638 // Thread::WillResume(StateType) where StateType contains the state
2639 // that they are supposed to have when the process is resumed
2640 // (suspended/running/stepping). Threads should also check
2641 // their resume signal in lldb::Thread::GetResumeSignal()
2642 // to see if they are suppoed to start back up with a signal.
2643 if (m_thread_list.WillResume())
2644 {
Jim Ingham0296fe72011-11-08 03:00:11 +00002645 m_mod_id.BumpResumeID();
Chris Lattner24943d22010-06-08 16:52:24 +00002646 error = DoResume();
2647 if (error.Success())
2648 {
2649 DidResume();
2650 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00002651 if (log)
2652 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00002653 }
2654 }
2655 else
2656 {
Jim Inghamac959662011-01-24 06:34:17 +00002657 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002658 }
2659 }
Jim Inghamac959662011-01-24 06:34:17 +00002660 else if (log)
2661 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002662 return error;
2663}
2664
2665Error
2666Process::Halt ()
2667{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002668 // Pause our private state thread so we can ensure no one else eats
2669 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002670 Listener halt_listener ("lldb.process.halt_listener");
2671 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002672
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002673 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002674 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002675
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002676 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002677 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002678
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002679 bool caused_stop = false;
2680
2681 // Ask the process subclass to actually halt our process
2682 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002683 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002684 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002685 if (m_public_state.GetValue() == eStateAttaching)
2686 {
2687 SetExitStatus(SIGKILL, "Cancelled async attach.");
2688 Destroy ();
2689 }
2690 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002691 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002692 // If "caused_stop" is true, then DoHalt stopped the process. If
2693 // "caused_stop" is false, the process was already stopped.
2694 // If the DoHalt caused the process to stop, then we want to catch
2695 // this event and set the interrupted bool to true before we pass
2696 // this along so clients know that the process was interrupted by
2697 // a halt command.
2698 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002699 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002700 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002701 TimeValue timeout_time;
2702 timeout_time = TimeValue::Now();
2703 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002704 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2705 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002706
Jim Inghamf9f40c22011-02-08 05:20:59 +00002707 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002708 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002709 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002710 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002711 }
2712 else
2713 {
Greg Clayton20206082011-11-17 01:23:07 +00002714 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002715 {
2716 // We caused the process to interrupt itself, so mark this
2717 // as such in the stop event so clients can tell an interrupted
2718 // process from a natural stop
2719 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2720 }
2721 else
2722 {
2723 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2724 if (log)
2725 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2726 error.SetErrorString ("Did not get stopped event after halt.");
2727 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002728 }
2729 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002730 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002731 }
2732 }
Chris Lattner24943d22010-06-08 16:52:24 +00002733 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002734 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002735 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002736
2737 // Post any event we might have consumed. If all goes well, we will have
2738 // stopped the process, intercepted the event and set the interrupted
2739 // bool in the event. Post it to the private event queue and that will end up
2740 // correctly setting the state.
2741 if (event_sp)
2742 m_private_state_broadcaster.BroadcastEvent(event_sp);
2743
Chris Lattner24943d22010-06-08 16:52:24 +00002744 return error;
2745}
2746
2747Error
2748Process::Detach ()
2749{
2750 Error error (WillDetach());
2751
2752 if (error.Success())
2753 {
2754 DisableAllBreakpointSites();
2755 error = DoDetach();
2756 if (error.Success())
2757 {
2758 DidDetach();
2759 StopPrivateStateThread();
2760 }
2761 }
2762 return error;
2763}
2764
2765Error
2766Process::Destroy ()
2767{
2768 Error error (WillDestroy());
2769 if (error.Success())
2770 {
2771 DisableAllBreakpointSites();
2772 error = DoDestroy();
2773 if (error.Success())
2774 {
2775 DidDestroy();
2776 StopPrivateStateThread();
2777 }
Caroline Tice861efb32010-11-16 05:07:41 +00002778 m_stdio_communication.StopReadThread();
2779 m_stdio_communication.Disconnect();
2780 if (m_process_input_reader && m_process_input_reader->IsActive())
2781 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2782 if (m_process_input_reader)
2783 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002784 }
2785 return error;
2786}
2787
2788Error
2789Process::Signal (int signal)
2790{
2791 Error error (WillSignal());
2792 if (error.Success())
2793 {
2794 error = DoSignal(signal);
2795 if (error.Success())
2796 DidSignal();
2797 }
2798 return error;
2799}
2800
Greg Clayton395fc332011-02-15 21:59:32 +00002801lldb::ByteOrder
2802Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002803{
Greg Clayton395fc332011-02-15 21:59:32 +00002804 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002805}
2806
2807uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002808Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002809{
Greg Clayton395fc332011-02-15 21:59:32 +00002810 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002811}
2812
Greg Clayton395fc332011-02-15 21:59:32 +00002813
Chris Lattner24943d22010-06-08 16:52:24 +00002814bool
2815Process::ShouldBroadcastEvent (Event *event_ptr)
2816{
2817 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2818 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002819 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002820
2821 switch (state)
2822 {
Greg Claytone71e2582011-02-04 01:58:07 +00002823 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002824 case eStateAttaching:
2825 case eStateLaunching:
2826 case eStateDetached:
2827 case eStateExited:
2828 case eStateUnloaded:
2829 // These events indicate changes in the state of the debugging session, always report them.
2830 return_value = true;
2831 break;
2832 case eStateInvalid:
2833 // We stopped for no apparent reason, don't report it.
2834 return_value = false;
2835 break;
2836 case eStateRunning:
2837 case eStateStepping:
2838 // If we've started the target running, we handle the cases where we
2839 // are already running and where there is a transition from stopped to
2840 // running differently.
2841 // running -> running: Automatically suppress extra running events
2842 // stopped -> running: Report except when there is one or more no votes
2843 // and no yes votes.
2844 SynchronouslyNotifyStateChanged (state);
2845 switch (m_public_state.GetValue())
2846 {
2847 case eStateRunning:
2848 case eStateStepping:
2849 // We always suppress multiple runnings with no PUBLIC stop in between.
2850 return_value = false;
2851 break;
2852 default:
2853 // TODO: make this work correctly. For now always report
2854 // run if we aren't running so we don't miss any runnning
2855 // events. If I run the lldb/test/thread/a.out file and
2856 // break at main.cpp:58, run and hit the breakpoints on
2857 // multiple threads, then somehow during the stepping over
2858 // of all breakpoints no run gets reported.
2859 return_value = true;
2860
2861 // This is a transition from stop to run.
2862 switch (m_thread_list.ShouldReportRun (event_ptr))
2863 {
2864 case eVoteYes:
2865 case eVoteNoOpinion:
2866 return_value = true;
2867 break;
2868 case eVoteNo:
2869 return_value = false;
2870 break;
2871 }
2872 break;
2873 }
2874 break;
2875 case eStateStopped:
2876 case eStateCrashed:
2877 case eStateSuspended:
2878 {
2879 // We've stopped. First see if we're going to restart the target.
2880 // If we are going to stop, then we always broadcast the event.
2881 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00002882 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002883 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002884 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002885 if (log)
2886 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002887 return true;
2888 }
2889 else
2890 {
Chris Lattner24943d22010-06-08 16:52:24 +00002891 RefreshStateAfterStop ();
2892
2893 if (m_thread_list.ShouldStop (event_ptr) == false)
2894 {
2895 switch (m_thread_list.ShouldReportStop (event_ptr))
2896 {
2897 case eVoteYes:
2898 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00002899 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00002900 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00002901 case eVoteNo:
2902 return_value = false;
2903 break;
2904 }
2905
2906 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002907 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002908 Resume ();
2909 }
2910 else
2911 {
2912 return_value = true;
2913 SynchronouslyNotifyStateChanged (state);
2914 }
2915 }
2916 }
2917 }
2918
2919 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002920 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00002921 return return_value;
2922}
2923
Chris Lattner24943d22010-06-08 16:52:24 +00002924
2925bool
2926Process::StartPrivateStateThread ()
2927{
Greg Claytone005f2c2010-11-06 01:53:30 +00002928 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002929
Greg Claytonb72d0f02011-04-12 05:54:46 +00002930 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00002931 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002932 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2933
2934 if (already_running)
2935 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00002936
2937 // Create a thread that watches our internal state and controls which
2938 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002939 char thread_name[1024];
Greg Clayton444e35b2011-10-19 18:09:39 +00002940 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Claytona875b642011-01-09 21:07:35 +00002941 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002942 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002943}
2944
2945void
2946Process::PausePrivateStateThread ()
2947{
2948 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2949}
2950
2951void
2952Process::ResumePrivateStateThread ()
2953{
2954 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2955}
2956
2957void
2958Process::StopPrivateStateThread ()
2959{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002960 if (PrivateStateThreadIsValid ())
2961 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner24943d22010-06-08 16:52:24 +00002962}
2963
2964void
2965Process::ControlPrivateStateThread (uint32_t signal)
2966{
Greg Claytone005f2c2010-11-06 01:53:30 +00002967 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002968
2969 assert (signal == eBroadcastInternalStateControlStop ||
2970 signal == eBroadcastInternalStateControlPause ||
2971 signal == eBroadcastInternalStateControlResume);
2972
2973 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002974 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002975
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002976 // Signal the private state thread. First we should copy this is case the
2977 // thread starts exiting since the private state thread will NULL this out
2978 // when it exits
2979 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00002980 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002981 {
2982 TimeValue timeout_time;
2983 bool timed_out;
2984
2985 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2986
2987 timeout_time = TimeValue::Now();
2988 timeout_time.OffsetWithSeconds(2);
2989 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2990 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2991
2992 if (signal == eBroadcastInternalStateControlStop)
2993 {
2994 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002995 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002996
2997 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002998 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002999 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003000 }
3001 }
3002}
3003
3004void
3005Process::HandlePrivateEvent (EventSP &event_sp)
3006{
Greg Claytone005f2c2010-11-06 01:53:30 +00003007 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003008
Greg Clayton68ca8232011-01-25 02:58:48 +00003009 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003010
3011 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003012 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003013 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003014 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003015 switch (action_result)
3016 {
3017 case NextEventAction::eEventActionSuccess:
3018 SetNextEventAction(NULL);
3019 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003020
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003021 case NextEventAction::eEventActionRetry:
3022 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003023
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003024 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003025 // Handle Exiting Here. If we already got an exited event,
3026 // we should just propagate it. Otherwise, swallow this event,
3027 // and set our state to exit so the next event will kill us.
3028 if (new_state != eStateExited)
3029 {
3030 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003031 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003032 SetNextEventAction(NULL);
3033 return;
3034 }
3035 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003036 break;
3037 }
3038 }
3039
Chris Lattner24943d22010-06-08 16:52:24 +00003040 // See if we should broadcast this state to external clients?
3041 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003042
3043 if (should_broadcast)
3044 {
3045 if (log)
3046 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003047 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003048 __FUNCTION__,
3049 GetID(),
3050 StateAsCString(new_state),
3051 StateAsCString (GetState ()),
3052 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003053 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003054 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003055 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003056 PushProcessInputReader ();
3057 else
3058 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003059
Chris Lattner24943d22010-06-08 16:52:24 +00003060 BroadcastEvent (event_sp);
3061 }
3062 else
3063 {
3064 if (log)
3065 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003066 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003067 __FUNCTION__,
3068 GetID(),
3069 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003070 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003071 }
3072 }
3073}
3074
3075void *
3076Process::PrivateStateThread (void *arg)
3077{
3078 Process *proc = static_cast<Process*> (arg);
3079 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003080 return result;
3081}
3082
3083void *
3084Process::RunPrivateStateThread ()
3085{
3086 bool control_only = false;
3087 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3088
Greg Claytone005f2c2010-11-06 01:53:30 +00003089 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003090 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003091 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003092
3093 bool exit_now = false;
3094 while (!exit_now)
3095 {
3096 EventSP event_sp;
3097 WaitForEventsPrivate (NULL, event_sp, control_only);
3098 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3099 {
3100 switch (event_sp->GetType())
3101 {
3102 case eBroadcastInternalStateControlStop:
3103 exit_now = true;
3104 continue; // Go to next loop iteration so we exit without
3105 break; // doing any internal state managment below
3106
3107 case eBroadcastInternalStateControlPause:
3108 control_only = true;
3109 break;
3110
3111 case eBroadcastInternalStateControlResume:
3112 control_only = false;
3113 break;
3114 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003115
Jim Ingham3ae449a2010-11-17 02:32:00 +00003116 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003117 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham3ae449a2010-11-17 02:32:00 +00003118
Chris Lattner24943d22010-06-08 16:52:24 +00003119 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003120 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003121 }
3122
3123
3124 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3125
3126 if (internal_state != eStateInvalid)
3127 {
3128 HandlePrivateEvent (event_sp);
3129 }
3130
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003131 if (internal_state == eStateInvalid ||
3132 internal_state == eStateExited ||
3133 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003134 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003135 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003136 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003137
Chris Lattner24943d22010-06-08 16:52:24 +00003138 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003139 }
Chris Lattner24943d22010-06-08 16:52:24 +00003140 }
3141
Caroline Tice926060e2010-10-29 21:48:37 +00003142 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003143 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003144 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003145
Greg Claytona4881d02011-01-22 07:12:45 +00003146 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3147 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003148 return NULL;
3149}
3150
Chris Lattner24943d22010-06-08 16:52:24 +00003151//------------------------------------------------------------------
3152// Process Event Data
3153//------------------------------------------------------------------
3154
3155Process::ProcessEventData::ProcessEventData () :
3156 EventData (),
3157 m_process_sp (),
3158 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003159 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003160 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003161 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003162{
3163}
3164
3165Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3166 EventData (),
3167 m_process_sp (process_sp),
3168 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003169 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003170 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003171 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003172{
3173}
3174
3175Process::ProcessEventData::~ProcessEventData()
3176{
3177}
3178
3179const ConstString &
3180Process::ProcessEventData::GetFlavorString ()
3181{
3182 static ConstString g_flavor ("Process::ProcessEventData");
3183 return g_flavor;
3184}
3185
3186const ConstString &
3187Process::ProcessEventData::GetFlavor () const
3188{
3189 return ProcessEventData::GetFlavorString ();
3190}
3191
Chris Lattner24943d22010-06-08 16:52:24 +00003192void
3193Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3194{
3195 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003196 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3197 // the public event queue, then other times when we're pretending that this is where we stopped at the
3198 // end of expression evaluation. m_update_state is used to distinguish these
3199 // three cases; it is 0 when we're just pulling it off for private handling,
3200 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003201
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003202 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003203 return;
3204
3205 m_process_sp->SetPublicState (m_state);
3206
3207 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3208 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003209 {
3210 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
3211 int num_threads = curr_thread_list.GetSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003212 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003213
Jim Ingham21f37ad2011-08-09 02:12:22 +00003214 // The actions might change one of the thread's stop_info's opinions about whether we should
3215 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003216
3217 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3218 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3219 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3220 // 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
3221 // against this list & bag out if anything differs.
3222 std::vector<lldb::tid_t> thread_index_array(num_threads);
3223 for (idx = 0; idx < num_threads; ++idx)
3224 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3225
Jim Ingham21f37ad2011-08-09 02:12:22 +00003226 bool still_should_stop = true;
3227
Chris Lattner24943d22010-06-08 16:52:24 +00003228 for (idx = 0; idx < num_threads; ++idx)
3229 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003230 curr_thread_list = m_process_sp->GetThreadList();
3231 if (curr_thread_list.GetSize() != num_threads)
3232 {
3233 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003234 if (log)
3235 log->Printf("Number of threads changed from %d to %d while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0296fe72011-11-08 03:00:11 +00003236 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));
Jim Ingham60526c42011-12-01 20:26:15 +00003244 if (log)
3245 log->Printf("The thread at position %d changed from %d to %d while processing event.",
3246 idx,
3247 thread_index_array[idx],
3248 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003249 break;
3250 }
3251
Jim Ingham6297a3a2010-10-20 00:39:53 +00003252 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3253 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00003254 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003255 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003256 // The stop action might restart the target. If it does, then we want to mark that in the
3257 // event so that whoever is receiving it will know to wait for the running event and reflect
3258 // that state appropriately.
3259 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003260
3261 // FIXME: we might have run.
3262 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003263 {
3264 SetRestarted (true);
3265 break;
3266 }
3267 else if (!stop_info_sp->ShouldStop(event_ptr))
3268 {
3269 still_should_stop = false;
3270 }
Chris Lattner24943d22010-06-08 16:52:24 +00003271 }
3272 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003273
Jim Ingham21f37ad2011-08-09 02:12:22 +00003274
3275 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003276 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003277 if (!still_should_stop)
3278 {
3279 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003280 SetRestarted(true);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003281 m_process_sp->Resume();
3282 }
3283 else
3284 {
3285 // If we didn't restart, run the Stop Hooks here:
3286 // They might also restart the target, so watch for that.
3287 m_process_sp->GetTarget().RunStopHooks();
3288 if (m_process_sp->GetPrivateState() == eStateRunning)
3289 SetRestarted(true);
3290 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003291 }
3292
Chris Lattner24943d22010-06-08 16:52:24 +00003293 }
3294}
3295
3296void
3297Process::ProcessEventData::Dump (Stream *s) const
3298{
3299 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003300 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003301
Greg Claytonb72d0f02011-04-12 05:54:46 +00003302 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003303}
3304
3305const Process::ProcessEventData *
3306Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3307{
3308 if (event_ptr)
3309 {
3310 const EventData *event_data = event_ptr->GetData();
3311 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3312 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3313 }
3314 return NULL;
3315}
3316
3317ProcessSP
3318Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3319{
3320 ProcessSP process_sp;
3321 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3322 if (data)
3323 process_sp = data->GetProcessSP();
3324 return process_sp;
3325}
3326
3327StateType
3328Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3329{
3330 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3331 if (data == NULL)
3332 return eStateInvalid;
3333 else
3334 return data->GetState();
3335}
3336
3337bool
3338Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3339{
3340 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3341 if (data == NULL)
3342 return false;
3343 else
3344 return data->GetRestarted();
3345}
3346
3347void
3348Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3349{
3350 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3351 if (data != NULL)
3352 data->SetRestarted(new_value);
3353}
3354
3355bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003356Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3357{
3358 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3359 if (data == NULL)
3360 return false;
3361 else
3362 return data->GetInterrupted ();
3363}
3364
3365void
3366Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3367{
3368 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3369 if (data != NULL)
3370 data->SetInterrupted(new_value);
3371}
3372
3373bool
Chris Lattner24943d22010-06-08 16:52:24 +00003374Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3375{
3376 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3377 if (data)
3378 {
3379 data->SetUpdateStateOnRemoval();
3380 return true;
3381 }
3382 return false;
3383}
3384
Chris Lattner24943d22010-06-08 16:52:24 +00003385void
Greg Claytona830adb2010-10-04 01:05:56 +00003386Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003387{
Greg Clayton567e7f32011-09-22 04:58:26 +00003388 exe_ctx.SetTargetPtr (&m_target);
3389 exe_ctx.SetProcessPtr (this);
3390 exe_ctx.SetThreadPtr(NULL);
3391 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003392}
3393
3394lldb::ProcessSP
3395Process::GetSP ()
3396{
3397 return GetTarget().GetProcessSP();
3398}
3399
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003400//uint32_t
3401//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3402//{
3403// return 0;
3404//}
3405//
3406//ArchSpec
3407//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3408//{
3409// return Host::GetArchSpecForExistingProcess (pid);
3410//}
3411//
3412//ArchSpec
3413//Process::GetArchSpecForExistingProcess (const char *process_name)
3414//{
3415// return Host::GetArchSpecForExistingProcess (process_name);
3416//}
3417//
Caroline Tice861efb32010-11-16 05:07:41 +00003418void
3419Process::AppendSTDOUT (const char * s, size_t len)
3420{
Greg Clayton20d338f2010-11-18 05:57:03 +00003421 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003422 m_stdout_data.append (s, len);
Greg Claytonb3781332010-12-05 19:16:56 +00003423 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003424}
3425
3426void
Greg Claytonbd06ff42011-11-13 04:45:22 +00003427Process::AppendSTDERR (const char * s, size_t len)
3428{
3429 Mutex::Locker locker (m_stdio_communication_mutex);
3430 m_stderr_data.append (s, len);
3431 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3432}
3433
3434//------------------------------------------------------------------
3435// Process STDIO
3436//------------------------------------------------------------------
3437
3438size_t
3439Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3440{
3441 Mutex::Locker locker(m_stdio_communication_mutex);
3442 size_t bytes_available = m_stdout_data.size();
3443 if (bytes_available > 0)
3444 {
3445 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3446 if (log)
3447 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3448 if (bytes_available > buf_size)
3449 {
3450 memcpy(buf, m_stdout_data.c_str(), buf_size);
3451 m_stdout_data.erase(0, buf_size);
3452 bytes_available = buf_size;
3453 }
3454 else
3455 {
3456 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3457 m_stdout_data.clear();
3458 }
3459 }
3460 return bytes_available;
3461}
3462
3463
3464size_t
3465Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3466{
3467 Mutex::Locker locker(m_stdio_communication_mutex);
3468 size_t bytes_available = m_stderr_data.size();
3469 if (bytes_available > 0)
3470 {
3471 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3472 if (log)
3473 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3474 if (bytes_available > buf_size)
3475 {
3476 memcpy(buf, m_stderr_data.c_str(), buf_size);
3477 m_stderr_data.erase(0, buf_size);
3478 bytes_available = buf_size;
3479 }
3480 else
3481 {
3482 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3483 m_stderr_data.clear();
3484 }
3485 }
3486 return bytes_available;
3487}
3488
3489void
Caroline Tice861efb32010-11-16 05:07:41 +00003490Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3491{
3492 Process *process = (Process *) baton;
3493 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3494}
3495
3496size_t
3497Process::ProcessInputReaderCallback (void *baton,
3498 InputReader &reader,
3499 lldb::InputReaderAction notification,
3500 const char *bytes,
3501 size_t bytes_len)
3502{
3503 Process *process = (Process *) baton;
3504
3505 switch (notification)
3506 {
3507 case eInputReaderActivate:
3508 break;
3509
3510 case eInputReaderDeactivate:
3511 break;
3512
3513 case eInputReaderReactivate:
3514 break;
3515
Caroline Tice4a348082011-05-02 20:41:46 +00003516 case eInputReaderAsynchronousOutputWritten:
3517 break;
3518
Caroline Tice861efb32010-11-16 05:07:41 +00003519 case eInputReaderGotToken:
3520 {
3521 Error error;
3522 process->PutSTDIN (bytes, bytes_len, error);
3523 }
3524 break;
3525
Caroline Ticec4f55fe2010-11-19 20:47:54 +00003526 case eInputReaderInterrupt:
3527 process->Halt ();
3528 break;
3529
3530 case eInputReaderEndOfFile:
3531 process->AppendSTDOUT ("^D", 2);
3532 break;
3533
Caroline Tice861efb32010-11-16 05:07:41 +00003534 case eInputReaderDone:
3535 break;
3536
3537 }
3538
3539 return bytes_len;
3540}
3541
3542void
3543Process::ResetProcessInputReader ()
3544{
3545 m_process_input_reader.reset();
3546}
3547
3548void
Greg Clayton464c6162011-11-17 22:14:31 +00003549Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00003550{
3551 // First set up the Read Thread for reading/handling process I/O
3552
3553 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3554
3555 if (conn_ap.get())
3556 {
3557 m_stdio_communication.SetConnection (conn_ap.release());
3558 if (m_stdio_communication.IsConnected())
3559 {
3560 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3561 m_stdio_communication.StartReadThread();
3562
3563 // Now read thread is set up, set up input reader.
3564
3565 if (!m_process_input_reader.get())
3566 {
3567 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3568 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3569 this,
3570 eInputReaderGranularityByte,
3571 NULL,
3572 NULL,
3573 false));
3574
3575 if (err.Fail())
3576 m_process_input_reader.reset();
3577 }
3578 }
3579 }
3580}
3581
3582void
3583Process::PushProcessInputReader ()
3584{
3585 if (m_process_input_reader && !m_process_input_reader->IsActive())
3586 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3587}
3588
3589void
3590Process::PopProcessInputReader ()
3591{
3592 if (m_process_input_reader && m_process_input_reader->IsActive())
3593 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3594}
3595
Greg Claytond284b662011-02-18 01:44:25 +00003596// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00003597void
Caroline Tice2a456812011-03-10 22:14:10 +00003598Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003599{
Greg Claytonb3448432011-03-24 21:19:54 +00003600 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00003601
3602 int i=0;
3603 const char *name;
3604 OptionEnumValueElement option_enum;
3605 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3606 {
3607 if (name)
3608 {
3609 option_enum.value = i;
3610 option_enum.string_value = name;
3611 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3612 g_plugins.push_back (option_enum);
3613 }
3614 ++i;
3615 }
3616 option_enum.value = 0;
3617 option_enum.string_value = NULL;
3618 option_enum.usage = NULL;
3619 g_plugins.push_back (option_enum);
3620
3621 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3622 {
3623 if (::strcmp (name, "plugin") == 0)
3624 {
3625 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3626 break;
3627 }
3628 }
Greg Clayton990de7b2010-11-18 23:32:35 +00003629 UserSettingsControllerSP &usc = GetSettingsController();
3630 usc.reset (new SettingsController);
3631 UserSettingsController::InitializeSettingsController (usc,
3632 SettingsController::global_settings_table,
3633 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00003634
3635 // Now call SettingsInitialize() for each 'child' of Process settings
3636 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00003637}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003638
Greg Clayton990de7b2010-11-18 23:32:35 +00003639void
Caroline Tice2a456812011-03-10 22:14:10 +00003640Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00003641{
Caroline Tice2a456812011-03-10 22:14:10 +00003642 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3643
3644 Thread::SettingsTerminate ();
3645
3646 // Now terminate Process Settings.
3647
Greg Clayton990de7b2010-11-18 23:32:35 +00003648 UserSettingsControllerSP &usc = GetSettingsController();
3649 UserSettingsController::FinalizeSettingsController (usc);
3650 usc.reset();
3651}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003652
Greg Clayton990de7b2010-11-18 23:32:35 +00003653UserSettingsControllerSP &
3654Process::GetSettingsController ()
3655{
3656 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003657 return g_settings_controller;
3658}
3659
Caroline Tice1ebef442010-09-27 00:30:10 +00003660void
3661Process::UpdateInstanceName ()
3662{
Greg Clayton5beb99d2011-08-11 02:48:45 +00003663 Module *module = GetTarget().GetExecutableModulePointer();
3664 if (module)
Caroline Tice1ebef442010-09-27 00:30:10 +00003665 {
3666 StreamString sstr;
Greg Clayton5beb99d2011-08-11 02:48:45 +00003667 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1ebef442010-09-27 00:30:10 +00003668
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003669 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytonb72d0f02011-04-12 05:54:46 +00003670 sstr.GetData());
Caroline Tice1ebef442010-09-27 00:30:10 +00003671 }
3672}
3673
Greg Clayton427f2902010-12-14 02:59:59 +00003674ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00003675Process::RunThreadPlan (ExecutionContext &exe_ctx,
3676 lldb::ThreadPlanSP &thread_plan_sp,
3677 bool stop_others,
3678 bool try_all_threads,
3679 bool discard_on_error,
3680 uint32_t single_thread_timeout_usec,
3681 Stream &errors)
3682{
3683 ExecutionResults return_value = eExecutionSetupError;
3684
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003685 if (thread_plan_sp.get() == NULL)
3686 {
3687 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00003688 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003689 }
Greg Clayton567e7f32011-09-22 04:58:26 +00003690
3691 if (exe_ctx.GetProcessPtr() != this)
3692 {
3693 errors.Printf("RunThreadPlan called on wrong process.");
3694 return eExecutionSetupError;
3695 }
3696
3697 Thread *thread = exe_ctx.GetThreadPtr();
3698 if (thread == NULL)
3699 {
3700 errors.Printf("RunThreadPlan called with invalid thread.");
3701 return eExecutionSetupError;
3702 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003703
Jim Ingham5ab7fba2011-05-17 22:24:54 +00003704 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3705 // For that to be true the plan can't be private - since private plans suppress themselves in the
3706 // GetCompletedPlan call.
3707
3708 bool orig_plan_private = thread_plan_sp->GetPrivate();
3709 thread_plan_sp->SetPrivate(false);
3710
Jim Inghamac959662011-01-24 06:34:17 +00003711 if (m_private_state.GetValue() != eStateStopped)
3712 {
3713 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00003714 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00003715 }
3716
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003717 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00003718 const uint32_t thread_idx_id = thread->GetIndexID();
3719 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003720
3721 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3722 // so we should arrange to reset them as well.
3723
Greg Clayton567e7f32011-09-22 04:58:26 +00003724 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00003725
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003726 uint32_t selected_tid;
3727 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00003728 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00003729 {
3730 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003731 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003732 }
3733 else
3734 {
3735 selected_tid = LLDB_INVALID_THREAD_ID;
3736 }
3737
Greg Clayton567e7f32011-09-22 04:58:26 +00003738 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Ingham360f53f2010-11-30 02:22:11 +00003739
Jim Ingham6ae318c2011-01-23 21:14:08 +00003740 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003741
3742 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3743 // restored on exit to the function.
3744
3745 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00003746
Jim Ingham6ae318c2011-01-23 21:14:08 +00003747 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003748 if (log)
3749 {
3750 StreamString s;
3751 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton444e35b2011-10-19 18:09:39 +00003752 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Clayton567e7f32011-09-22 04:58:26 +00003753 thread->GetIndexID(),
3754 thread->GetID(),
Jim Inghamf9f40c22011-02-08 05:20:59 +00003755 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003756 }
3757
Jim Inghamf9f40c22011-02-08 05:20:59 +00003758 bool got_event;
3759 lldb::EventSP event_sp;
3760 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00003761
3762 TimeValue* timeout_ptr = NULL;
3763 TimeValue real_timeout;
3764
Jim Inghamf9f40c22011-02-08 05:20:59 +00003765 bool first_timeout = true;
3766 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00003767
Jim Ingham360f53f2010-11-30 02:22:11 +00003768 while (1)
3769 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003770 // We usually want to resume the process if we get to the top of the loop.
3771 // The only exception is if we get two running events with no intervening
3772 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00003773
Jim Inghamf9f40c22011-02-08 05:20:59 +00003774 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00003775 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003776 // Do the initial resume and wait for the running event before going further.
3777
Greg Clayton567e7f32011-09-22 04:58:26 +00003778 Error resume_error = Resume ();
Jim Inghamf9f40c22011-02-08 05:20:59 +00003779 if (!resume_error.Success())
3780 {
3781 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00003782 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003783 break;
3784 }
3785
3786 real_timeout = TimeValue::Now();
3787 real_timeout.OffsetWithMicroSeconds(500000);
3788 timeout_ptr = &real_timeout;
3789
3790 got_event = listener.WaitForEvent(NULL, event_sp);
3791 if (!got_event)
3792 {
3793 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003794 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003795
3796 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003797 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003798 break;
3799 }
3800
3801 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3802 if (stop_state != eStateRunning)
3803 {
3804 if (log)
3805 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3806
3807 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003808 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003809 break;
3810 }
3811
3812 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003813 log->PutCString ("Resuming succeeded.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003814 // We need to call the function synchronously, so spin waiting for it to return.
3815 // If we get interrupted while executing, we're going to lose our context, and
3816 // won't be able to gather the result at this point.
3817 // We set the timeout AFTER the resume, since the resume takes some time and we
3818 // don't want to charge that to the timeout.
3819
3820 if (single_thread_timeout_usec != 0)
3821 {
3822 real_timeout = TimeValue::Now();
3823 if (first_timeout)
3824 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3825 else
3826 real_timeout.OffsetWithSeconds(10);
3827
3828 timeout_ptr = &real_timeout;
3829 }
3830 }
3831 else
3832 {
3833 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003834 log->PutCString ("Handled an extra running event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003835 do_resume = true;
3836 }
3837
3838 // Now wait for the process to stop again:
3839 stop_state = lldb::eStateInvalid;
3840 event_sp.reset();
3841 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3842
3843 if (got_event)
3844 {
3845 if (event_sp.get())
3846 {
3847 bool keep_going = false;
3848 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3849 if (log)
3850 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3851
3852 switch (stop_state)
3853 {
3854 case lldb::eStateStopped:
Jim Ingham2370a972011-05-17 01:10:11 +00003855 {
Greg Clayton43994462011-06-03 22:12:42 +00003856 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Clayton567e7f32011-09-22 04:58:26 +00003857 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton43994462011-06-03 22:12:42 +00003858 if (!thread_sp)
Jim Ingham2370a972011-05-17 01:10:11 +00003859 {
Greg Clayton43994462011-06-03 22:12:42 +00003860 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham2370a972011-05-17 01:10:11 +00003861 if (log)
Greg Clayton43994462011-06-03 22:12:42 +00003862 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3863 return_value = eExecutionInterrupted;
Jim Ingham2370a972011-05-17 01:10:11 +00003864 }
3865 else
3866 {
Greg Clayton43994462011-06-03 22:12:42 +00003867 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3868 StopReason stop_reason = eStopReasonInvalid;
3869 if (stop_info_sp)
3870 stop_reason = stop_info_sp->GetStopReason();
3871 if (stop_reason == eStopReasonPlanComplete)
3872 {
3873 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003874 log->PutCString ("Execution completed successfully.");
Greg Clayton43994462011-06-03 22:12:42 +00003875 // Now mark this plan as private so it doesn't get reported as the stop reason
3876 // after this point.
3877 if (thread_plan_sp)
3878 thread_plan_sp->SetPrivate (orig_plan_private);
3879 return_value = eExecutionCompleted;
3880 }
3881 else
3882 {
3883 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003884 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton43994462011-06-03 22:12:42 +00003885
3886 return_value = eExecutionInterrupted;
3887 }
Jim Ingham2370a972011-05-17 01:10:11 +00003888 }
Greg Clayton43994462011-06-03 22:12:42 +00003889 }
3890 break;
3891
Jim Inghamf9f40c22011-02-08 05:20:59 +00003892 case lldb::eStateCrashed:
3893 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003894 log->PutCString ("Execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003895 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003896 break;
Greg Clayton43994462011-06-03 22:12:42 +00003897
Jim Inghamf9f40c22011-02-08 05:20:59 +00003898 case lldb::eStateRunning:
3899 do_resume = false;
3900 keep_going = true;
3901 break;
Greg Clayton43994462011-06-03 22:12:42 +00003902
Jim Inghamf9f40c22011-02-08 05:20:59 +00003903 default:
3904 if (log)
3905 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham2370a972011-05-17 01:10:11 +00003906
3907 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytonb3448432011-03-24 21:19:54 +00003908 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003909 break;
3910 }
3911 if (keep_going)
3912 continue;
3913 else
3914 break;
3915 }
3916 else
3917 {
3918 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003919 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00003920 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003921 break;
3922 }
3923 }
3924 else
3925 {
3926 // If we didn't get an event that means we've timed out...
3927 // We will interrupt the process here. Depending on what we were asked to do we will
3928 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00003929 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003930
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003931 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00003932 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003933 {
3934 if (first_timeout)
3935 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3936 "trying with all threads enabled.",
3937 single_thread_timeout_usec);
3938 else
3939 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3940 "and timeout: %d timed out.",
3941 single_thread_timeout_usec);
3942 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003943 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00003944 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3945 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00003946 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003947 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003948
Greg Clayton567e7f32011-09-22 04:58:26 +00003949 Error halt_error = Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00003950 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00003951 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003952 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003953 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003954
Jim Inghamf9f40c22011-02-08 05:20:59 +00003955 // If halt succeeds, it always produces a stopped event. Wait for that:
3956
3957 real_timeout = TimeValue::Now();
3958 real_timeout.OffsetWithMicroSeconds(500000);
3959
3960 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00003961
3962 if (got_event)
3963 {
3964 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3965 if (log)
3966 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003967 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00003968 if (stop_state == lldb::eStateStopped
3969 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf6d3d792011-08-09 22:24:33 +00003970 log->PutCString (" Event was the Halt interruption event.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003971 }
3972
Jim Inghamf9f40c22011-02-08 05:20:59 +00003973 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00003974 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003975 // Between the time we initiated the Halt and the time we delivered it, the process could have
3976 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00003977
Greg Clayton567e7f32011-09-22 04:58:26 +00003978 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00003979 {
3980 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003981 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003982 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003983 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003984 break;
3985 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003986
Jim Inghamf9f40c22011-02-08 05:20:59 +00003987 if (!try_all_threads)
3988 {
3989 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003990 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003991 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003992 break;
3993 }
3994
3995 if (first_timeout)
3996 {
3997 // Set all the other threads to run, and return to the top of the loop, which will continue;
3998 first_timeout = false;
3999 thread_plan_sp->SetStopOthers (false);
4000 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004001 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004002
4003 continue;
4004 }
4005 else
4006 {
4007 // Running all threads failed, so return Interrupted.
4008 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004009 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00004010 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004011 break;
4012 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004013 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004014 }
4015 else
4016 { if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004017 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004018 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00004019 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004020 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00004021 }
4022 }
Jim Inghamc556b462011-01-22 01:30:53 +00004023 else
4024 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004025 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4026 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00004027 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004028 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.",
4029 halt_error.AsCString());
4030 real_timeout = TimeValue::Now();
4031 real_timeout.OffsetWithMicroSeconds(500000);
4032 timeout_ptr = &real_timeout;
4033 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4034 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00004035 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004036 // This is not going anywhere, bag out.
4037 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004038 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00004039 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004040 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00004041 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004042 else
4043 {
4044 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4045 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004046 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004047 if (stop_state == lldb::eStateStopped)
4048 {
4049 // Between the time we initiated the Halt and the time we delivered it, the process could have
4050 // already finished its job. Check that here:
4051
Greg Clayton567e7f32011-09-22 04:58:26 +00004052 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00004053 {
4054 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004055 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004056 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00004057 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004058 break;
4059 }
4060
4061 if (first_timeout)
4062 {
4063 // Set all the other threads to run, and return to the top of the loop, which will continue;
4064 first_timeout = false;
4065 thread_plan_sp->SetStopOthers (false);
4066 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004067 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004068
4069 continue;
4070 }
4071 else
4072 {
4073 // Running all threads failed, so return Interrupted.
4074 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004075 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00004076 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004077 break;
4078 }
4079 }
4080 else
4081 {
Sean Callananed3f86b2011-08-09 22:07:08 +00004082 if (log)
4083 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4084 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00004085 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004086 break;
4087 }
4088 }
Jim Inghamc556b462011-01-22 01:30:53 +00004089 }
4090
Jim Ingham360f53f2010-11-30 02:22:11 +00004091 }
4092
Jim Inghamf9f40c22011-02-08 05:20:59 +00004093 } // END WAIT LOOP
4094
4095 // Now do some processing on the results of the run:
4096 if (return_value == eExecutionInterrupted)
4097 {
Jim Ingham360f53f2010-11-30 02:22:11 +00004098 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004099 {
4100 StreamString s;
4101 if (event_sp)
4102 event_sp->Dump (&s);
4103 else
4104 {
Jim Inghamf6d3d792011-08-09 22:24:33 +00004105 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004106 }
4107
4108 StreamString ts;
4109
Jim Inghamf6d3d792011-08-09 22:24:33 +00004110 const char *event_explanation = NULL;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004111
4112 do
4113 {
4114 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4115
4116 if (!event_data)
4117 {
4118 event_explanation = "<no event data>";
4119 break;
4120 }
4121
4122 Process *process = event_data->GetProcessSP().get();
4123
4124 if (!process)
4125 {
4126 event_explanation = "<no process>";
4127 break;
4128 }
4129
4130 ThreadList &thread_list = process->GetThreadList();
4131
4132 uint32_t num_threads = thread_list.GetSize();
4133 uint32_t thread_index;
4134
4135 ts.Printf("<%u threads> ", num_threads);
4136
4137 for (thread_index = 0;
4138 thread_index < num_threads;
4139 ++thread_index)
4140 {
4141 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4142
4143 if (!thread)
4144 {
4145 ts.Printf("<?> ");
4146 continue;
4147 }
4148
Greg Clayton444e35b2011-10-19 18:09:39 +00004149 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Inghamf9f40c22011-02-08 05:20:59 +00004150 RegisterContext *register_context = thread->GetRegisterContext().get();
4151
4152 if (register_context)
4153 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4154 else
4155 ts.Printf("[ip unknown] ");
4156
4157 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4158 if (stop_info_sp)
4159 {
4160 const char *stop_desc = stop_info_sp->GetDescription();
4161 if (stop_desc)
4162 ts.PutCString (stop_desc);
4163 }
4164 ts.Printf(">");
4165 }
4166
4167 event_explanation = ts.GetData();
4168 } while (0);
4169
4170 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004171 {
4172 if (event_explanation)
4173 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4174 else
4175 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4176 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004177
4178 if (discard_on_error && thread_plan_sp)
4179 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004180 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004181 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004182 }
4183 }
4184 }
4185 else if (return_value == eExecutionSetupError)
4186 {
4187 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004188 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004189
4190 if (discard_on_error && thread_plan_sp)
4191 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004192 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004193 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004194 }
4195 }
4196 else
4197 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004198 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004199 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004200 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004201 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00004202 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00004203 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004204 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004205 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004206 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004207 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00004208 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00004209 }
4210 else
4211 {
4212 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004213 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00004214 if (discard_on_error && thread_plan_sp)
4215 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004216 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004217 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Clayton567e7f32011-09-22 04:58:26 +00004218 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004219 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham360f53f2010-11-30 02:22:11 +00004220 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004221 }
4222 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004223
Jim Ingham360f53f2010-11-30 02:22:11 +00004224 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004225 // Check that it's still there, and if it is put it back in the context. Also restore the
4226 // frame in the context if it is still present.
Greg Clayton567e7f32011-09-22 04:58:26 +00004227 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4228 if (thread)
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004229 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004230 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004231 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004232
4233 // Also restore the current process'es selected frame & thread, since this function calling may
4234 // be done behind the user's back.
4235
4236 if (selected_tid != LLDB_INVALID_THREAD_ID)
4237 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004238 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Ingham360f53f2010-11-30 02:22:11 +00004239 {
4240 // We were able to restore the selected thread, now restore the frame:
Greg Clayton567e7f32011-09-22 04:58:26 +00004241 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004242 if (old_frame_sp)
Greg Clayton567e7f32011-09-22 04:58:26 +00004243 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00004244 }
4245 }
4246
4247 return return_value;
4248}
4249
4250const char *
4251Process::ExecutionResultAsCString (ExecutionResults result)
4252{
4253 const char *result_name;
4254
4255 switch (result)
4256 {
Greg Claytonb3448432011-03-24 21:19:54 +00004257 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004258 result_name = "eExecutionCompleted";
4259 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004260 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00004261 result_name = "eExecutionDiscarded";
4262 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004263 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004264 result_name = "eExecutionInterrupted";
4265 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004266 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00004267 result_name = "eExecutionSetupError";
4268 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004269 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00004270 result_name = "eExecutionTimedOut";
4271 break;
4272 }
4273 return result_name;
4274}
4275
Greg Claytonabe0fed2011-04-18 08:33:37 +00004276void
4277Process::GetStatus (Stream &strm)
4278{
4279 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00004280 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00004281 {
4282 if (state == eStateExited)
4283 {
4284 int exit_status = GetExitStatus();
4285 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00004286 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00004287 GetID(),
4288 exit_status,
4289 exit_status,
4290 exit_description ? exit_description : "");
4291 }
4292 else
4293 {
4294 if (state == eStateConnected)
4295 strm.Printf ("Connected to remote target.\n");
4296 else
Greg Clayton444e35b2011-10-19 18:09:39 +00004297 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00004298 }
4299 }
4300 else
4301 {
Greg Clayton444e35b2011-10-19 18:09:39 +00004302 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004303 }
4304}
4305
4306size_t
4307Process::GetThreadStatus (Stream &strm,
4308 bool only_threads_with_stop_reason,
4309 uint32_t start_frame,
4310 uint32_t num_frames,
4311 uint32_t num_frames_with_source)
4312{
4313 size_t num_thread_infos_dumped = 0;
4314
4315 const size_t num_threads = GetThreadList().GetSize();
4316 for (uint32_t i = 0; i < num_threads; i++)
4317 {
4318 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4319 if (thread)
4320 {
4321 if (only_threads_with_stop_reason)
4322 {
4323 if (thread->GetStopInfo().get() == NULL)
4324 continue;
4325 }
4326 thread->GetStatus (strm,
4327 start_frame,
4328 num_frames,
4329 num_frames_with_source);
4330 ++num_thread_infos_dumped;
4331 }
4332 }
4333 return num_thread_infos_dumped;
4334}
4335
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004336//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004337// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004338//--------------------------------------------------------------
4339
Greg Claytond0a5a232010-09-19 02:33:57 +00004340Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00004341 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004342{
Greg Clayton638351a2010-12-04 00:10:17 +00004343 m_default_settings.reset (new ProcessInstanceSettings (*this,
4344 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00004345 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004346}
4347
Greg Claytond0a5a232010-09-19 02:33:57 +00004348Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004349{
4350}
4351
4352lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00004353Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004354{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00004355 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4356 false,
4357 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004358 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4359 return new_settings_sp;
4360}
4361
4362//--------------------------------------------------------------
4363// class ProcessInstanceSettings
4364//--------------------------------------------------------------
4365
Greg Clayton638351a2010-12-04 00:10:17 +00004366ProcessInstanceSettings::ProcessInstanceSettings
4367(
4368 UserSettingsController &owner,
4369 bool live_instance,
4370 const char *name
4371) :
Greg Claytonabb33022011-11-08 02:43:13 +00004372 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004373{
Caroline Tice396704b2010-09-09 18:26:37 +00004374 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4375 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4376 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00004377 // This is true for CreateInstanceName() too.
Greg Claytonabb33022011-11-08 02:43:13 +00004378
Caroline Tice75b11a32010-09-16 19:05:55 +00004379 if (GetInstanceName () == InstanceSettings::InvalidName())
4380 {
4381 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4382 m_owner.RegisterInstanceSettings (this);
4383 }
Greg Claytonabb33022011-11-08 02:43:13 +00004384
Caroline Tice396704b2010-09-09 18:26:37 +00004385 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004386 {
4387 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4388 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00004389 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004390 }
4391}
4392
4393ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonabb33022011-11-08 02:43:13 +00004394 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004395{
4396 if (m_instance_name != InstanceSettings::GetDefaultName())
4397 {
4398 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4399 CopyInstanceSettings (pending_settings,false);
4400 m_owner.RemovePendingSettings (m_instance_name);
4401 }
4402}
4403
4404ProcessInstanceSettings::~ProcessInstanceSettings ()
4405{
4406}
4407
4408ProcessInstanceSettings&
4409ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4410{
4411 if (this != &rhs)
4412 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004413 }
4414
4415 return *this;
4416}
4417
4418
4419void
4420ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4421 const char *index_value,
4422 const char *value,
4423 const ConstString &instance_name,
4424 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00004425 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004426 Error &err,
4427 bool pending)
4428{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004429}
4430
4431void
4432ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4433 bool pending)
4434{
Greg Claytonabb33022011-11-08 02:43:13 +00004435// if (new_settings.get() == NULL)
4436// return;
4437//
4438// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004439}
4440
Caroline Ticebcb5b452010-09-20 21:37:42 +00004441bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004442ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4443 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00004444 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00004445 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004446{
Greg Claytonabb33022011-11-08 02:43:13 +00004447 if (err)
4448 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4449 return false;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004450}
4451
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004452const ConstString
4453ProcessInstanceSettings::CreateInstanceName ()
4454{
4455 static int instance_count = 1;
4456 StreamString sstr;
4457
4458 sstr.Printf ("process_%d", instance_count);
4459 ++instance_count;
4460
4461 const ConstString ret_val (sstr.GetData());
4462 return ret_val;
4463}
4464
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004465//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004466// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004467//--------------------------------------------------
4468
4469SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004470Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004471{
4472 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4473 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4474};
4475
4476
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004477SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004478Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004479{
Greg Clayton638351a2010-12-04 00:10:17 +00004480 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton638351a2010-12-04 00:10:17 +00004481 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004482};
4483
4484
Jim Ingham7508e732010-08-09 23:31:02 +00004485
Greg Claytonabb33022011-11-08 02:43:13 +00004486