blob: fdd6b1753c7f61a46d264a32fca04d84b24a9946 [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)
Greg Claytond9919d32011-12-01 23:28:38 +000048 s.Printf (" pid = %llu\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +000049
50 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +000051 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +000052
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;
Greg Claytond9919d32011-12-01 23:28:38 +0000138 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000139
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)
Greg Claytond9919d32011-12-01 23:28:38 +00001166 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001167 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 Clayton4a2e3372011-12-15 03:14:23 +00001859Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001860{
1861 size_t total_cstr_len = 0;
1862 if (dst && dst_max_len)
1863 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00001864 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00001865 // NULL out everything just to be safe
1866 memset (dst, 0, dst_max_len);
1867 Error error;
1868 addr_t curr_addr = addr;
1869 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1870 size_t bytes_left = dst_max_len - 1;
1871 char *curr_dst = dst;
1872
1873 while (bytes_left > 0)
1874 {
1875 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1876 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1877 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1878
1879 if (bytes_read == 0)
1880 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00001881 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00001882 dst[total_cstr_len] = '\0';
1883 break;
1884 }
1885 const size_t len = strlen(curr_dst);
1886
1887 total_cstr_len += len;
1888
1889 if (len < bytes_to_read)
1890 break;
1891
1892 curr_dst += bytes_read;
1893 curr_addr += bytes_read;
1894 bytes_left -= bytes_read;
1895 }
1896 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00001897 else
1898 {
1899 if (dst == NULL)
1900 result_error.SetErrorString("invalid arguments");
1901 else
1902 result_error.Clear();
1903 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001904 return total_cstr_len;
1905}
1906
1907size_t
Greg Claytonfd119992011-01-07 06:08:19 +00001908Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1909{
Chris Lattner24943d22010-06-08 16:52:24 +00001910 if (buf == NULL || size == 0)
1911 return 0;
1912
1913 size_t bytes_read = 0;
1914 uint8_t *bytes = (uint8_t *)buf;
1915
1916 while (bytes_read < size)
1917 {
1918 const size_t curr_size = size - bytes_read;
1919 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1920 bytes + bytes_read,
1921 curr_size,
1922 error);
1923 bytes_read += curr_bytes_read;
1924 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1925 break;
1926 }
1927
1928 // Replace any software breakpoint opcodes that fall into this range back
1929 // into "buf" before we return
1930 if (bytes_read > 0)
1931 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1932 return bytes_read;
1933}
1934
Greg Claytonf72fdee2010-12-16 20:01:20 +00001935uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00001936Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00001937{
Greg Claytonc0fa5332011-05-22 22:46:53 +00001938 Scalar scalar;
1939 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1940 return scalar.ULongLong(fail_value);
1941 return fail_value;
1942}
1943
1944addr_t
1945Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1946{
1947 Scalar scalar;
1948 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1949 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1950 return LLDB_INVALID_ADDRESS;
1951}
1952
1953
1954bool
1955Process::WritePointerToMemory (lldb::addr_t vm_addr,
1956 lldb::addr_t ptr_value,
1957 Error &error)
1958{
1959 Scalar scalar;
1960 const uint32_t addr_byte_size = GetAddressByteSize();
1961 if (addr_byte_size <= 4)
1962 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001963 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00001964 scalar = ptr_value;
1965 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001966}
1967
Chris Lattner24943d22010-06-08 16:52:24 +00001968size_t
1969Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1970{
1971 size_t bytes_written = 0;
1972 const uint8_t *bytes = (const uint8_t *)buf;
1973
1974 while (bytes_written < size)
1975 {
1976 const size_t curr_size = size - bytes_written;
1977 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1978 bytes + bytes_written,
1979 curr_size,
1980 error);
1981 bytes_written += curr_bytes_written;
1982 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1983 break;
1984 }
1985 return bytes_written;
1986}
1987
1988size_t
1989Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1990{
Greg Claytonfd119992011-01-07 06:08:19 +00001991#if defined (ENABLE_MEMORY_CACHING)
1992 m_memory_cache.Flush (addr, size);
1993#endif
1994
Chris Lattner24943d22010-06-08 16:52:24 +00001995 if (buf == NULL || size == 0)
1996 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00001997
Jim Ingham21f37ad2011-08-09 02:12:22 +00001998 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00001999
Chris Lattner24943d22010-06-08 16:52:24 +00002000 // We need to write any data that would go where any current software traps
2001 // (enabled software breakpoints) any software traps (breakpoints) that we
2002 // may have placed in our tasks memory.
2003
2004 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2005 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2006
2007 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002008 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002009
2010 BreakpointSiteList::collection::const_iterator pos;
2011 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002012 addr_t intersect_addr = 0;
2013 size_t intersect_size = 0;
2014 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002015 const uint8_t *ubuf = (const uint8_t *)buf;
2016
2017 for (pos = iter; pos != end; ++pos)
2018 {
2019 BreakpointSiteSP bp;
2020 bp = pos->second;
2021
2022 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2023 assert(addr <= intersect_addr && intersect_addr < addr + size);
2024 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2025 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2026
2027 // Check for bytes before this breakpoint
2028 const addr_t curr_addr = addr + bytes_written;
2029 if (intersect_addr > curr_addr)
2030 {
2031 // There are some bytes before this breakpoint that we need to
2032 // just write to memory
2033 size_t curr_size = intersect_addr - curr_addr;
2034 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2035 ubuf + bytes_written,
2036 curr_size,
2037 error);
2038 bytes_written += curr_bytes_written;
2039 if (curr_bytes_written != curr_size)
2040 {
2041 // We weren't able to write all of the requested bytes, we
2042 // are done looping and will return the number of bytes that
2043 // we have written so far.
2044 break;
2045 }
2046 }
2047
2048 // Now write any bytes that would cover up any software breakpoints
2049 // directly into the breakpoint opcode buffer
2050 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2051 bytes_written += intersect_size;
2052 }
2053
2054 // Write any remaining bytes after the last breakpoint if we have any left
2055 if (bytes_written < size)
2056 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2057 ubuf + bytes_written,
2058 size - bytes_written,
2059 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002060
Chris Lattner24943d22010-06-08 16:52:24 +00002061 return bytes_written;
2062}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002063
2064size_t
2065Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2066{
2067 if (byte_size == UINT32_MAX)
2068 byte_size = scalar.GetByteSize();
2069 if (byte_size > 0)
2070 {
2071 uint8_t buf[32];
2072 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2073 if (mem_size > 0)
2074 return WriteMemory(addr, buf, mem_size, error);
2075 else
2076 error.SetErrorString ("failed to get scalar as memory data");
2077 }
2078 else
2079 {
2080 error.SetErrorString ("invalid scalar value");
2081 }
2082 return 0;
2083}
2084
2085size_t
2086Process::ReadScalarIntegerFromMemory (addr_t addr,
2087 uint32_t byte_size,
2088 bool is_signed,
2089 Scalar &scalar,
2090 Error &error)
2091{
2092 uint64_t uval;
2093
2094 if (byte_size <= sizeof(uval))
2095 {
2096 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2097 if (bytes_read == byte_size)
2098 {
2099 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2100 uint32_t offset = 0;
2101 if (byte_size <= 4)
2102 scalar = data.GetMaxU32 (&offset, byte_size);
2103 else
2104 scalar = data.GetMaxU64 (&offset, byte_size);
2105
2106 if (is_signed)
2107 scalar.SignExtend(byte_size * 8);
2108 return bytes_read;
2109 }
2110 }
2111 else
2112 {
2113 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2114 }
2115 return 0;
2116}
2117
Greg Clayton613b8732011-05-17 03:37:42 +00002118#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002119addr_t
2120Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2121{
Jim Inghame6bd1422011-06-20 17:32:44 +00002122 if (GetPrivateState() != eStateStopped)
2123 return LLDB_INVALID_ADDRESS;
2124
Greg Clayton613b8732011-05-17 03:37:42 +00002125#if defined (USE_ALLOCATE_MEMORY_CACHE)
2126 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2127#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002128 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2129 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2130 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002131 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 +00002132 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002133 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002134 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002135 m_mod_id.GetStopID(),
2136 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002137 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002138#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002139}
2140
Sean Callanan6cf6c472011-09-20 23:01:51 +00002141bool
2142Process::CanJIT ()
2143{
2144 return m_can_jit == eCanJITYes;
2145}
2146
2147void
2148Process::SetCanJIT (bool can_jit)
2149{
2150 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2151}
2152
Chris Lattner24943d22010-06-08 16:52:24 +00002153Error
2154Process::DeallocateMemory (addr_t ptr)
2155{
Greg Clayton613b8732011-05-17 03:37:42 +00002156 Error error;
2157#if defined (USE_ALLOCATE_MEMORY_CACHE)
2158 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2159 {
2160 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2161 }
2162#else
2163 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002164
2165 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2166 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002167 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 +00002168 ptr,
2169 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002170 m_mod_id.GetStopID(),
2171 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002172#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002173 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002174}
2175
2176
2177Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002178Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002179{
2180 Error error;
2181 error.SetErrorString("watchpoints are not supported");
2182 return error;
2183}
2184
2185Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002186Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002187{
2188 Error error;
2189 error.SetErrorString("watchpoints are not supported");
2190 return error;
2191}
2192
2193StateType
2194Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2195{
2196 StateType state;
2197 // Now wait for the process to launch and return control to us, and then
2198 // call DidLaunch:
2199 while (1)
2200 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002201 event_sp.reset();
2202 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2203
Greg Clayton20206082011-11-17 01:23:07 +00002204 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002205 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002206
2207 // If state is invalid, then we timed out
2208 if (state == eStateInvalid)
2209 break;
2210
2211 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002212 HandlePrivateEvent (event_sp);
2213 }
2214 return state;
2215}
2216
2217Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002218Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002219{
2220 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002221 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002222 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002223 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002224 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002225
Greg Clayton5beb99d2011-08-11 02:48:45 +00002226 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002227 if (exe_module)
2228 {
Greg Clayton180546b2011-04-30 01:09:13 +00002229 char local_exec_file_path[PATH_MAX];
2230 char platform_exec_file_path[PATH_MAX];
2231 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2232 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002233 if (exe_module->GetFileSpec().Exists())
2234 {
Greg Claytona2f74232011-02-24 22:24:29 +00002235 if (PrivateStateThreadIsValid ())
2236 PausePrivateStateThread ();
2237
Chris Lattner24943d22010-06-08 16:52:24 +00002238 error = WillLaunch (exe_module);
2239 if (error.Success())
2240 {
Greg Claytond8c62532010-10-07 04:19:01 +00002241 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002242 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002243
2244 // Now launch using these arguments.
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002245 error = DoLaunch (exe_module, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +00002246
2247 if (error.Fail())
2248 {
2249 if (GetID() != LLDB_INVALID_PROCESS_ID)
2250 {
2251 SetID (LLDB_INVALID_PROCESS_ID);
2252 const char *error_string = error.AsCString();
2253 if (error_string == NULL)
2254 error_string = "launch failed";
2255 SetExitStatus (-1, error_string);
2256 }
2257 }
2258 else
2259 {
2260 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002261 TimeValue timeout_time;
2262 timeout_time = TimeValue::Now();
2263 timeout_time.OffsetWithSeconds(10);
2264 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002265
Greg Clayton49859592011-06-22 01:42:17 +00002266 if (state == eStateInvalid || event_sp.get() == NULL)
2267 {
2268 // We were able to launch the process, but we failed to
2269 // catch the initial stop.
2270 SetExitStatus (0, "failed to catch stop after launch");
2271 Destroy();
2272 }
2273 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002274 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002275
Chris Lattner24943d22010-06-08 16:52:24 +00002276 DidLaunch ();
2277
Greg Clayton37f962e2011-08-22 02:49:39 +00002278 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002279 if (m_dyld_ap.get())
2280 m_dyld_ap->DidLaunch();
2281
Greg Clayton37f962e2011-08-22 02:49:39 +00002282 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002283 // This delays passing the stopped event to listeners till DidLaunch gets
2284 // a chance to complete...
2285 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002286
2287 if (PrivateStateThreadIsValid ())
2288 ResumePrivateStateThread ();
2289 else
2290 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002291 }
2292 else if (state == eStateExited)
2293 {
2294 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2295 // not likely to work, and return an invalid pid.
2296 HandlePrivateEvent (event_sp);
2297 }
2298 }
2299 }
2300 }
2301 else
2302 {
Greg Clayton9c236732011-10-26 00:56:27 +00002303 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002304 }
2305 }
2306 return error;
2307}
2308
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002309Process::NextEventAction::EventActionResult
2310Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002311{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002312 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2313 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002314 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002315 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002316 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002317 return eEventActionRetry;
2318
2319 case eStateStopped:
2320 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002321 {
2322 // During attach, prior to sending the eStateStopped event,
2323 // lldb_private::Process subclasses must set the process must set
2324 // the new process ID.
2325 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2326 if (m_exec_count > 0)
2327 {
2328 --m_exec_count;
2329 m_process->Resume();
2330 return eEventActionRetry;
2331 }
2332 else
2333 {
2334 m_process->CompleteAttach ();
2335 return eEventActionSuccess;
2336 }
2337 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002338 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002339
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002340 default:
2341 case eStateExited:
2342 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002343 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002344 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002345
2346 m_exit_string.assign ("No valid Process");
2347 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002348}
Chris Lattner24943d22010-06-08 16:52:24 +00002349
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002350Process::NextEventAction::EventActionResult
2351Process::AttachCompletionHandler::HandleBeingInterrupted()
2352{
2353 return eEventActionSuccess;
2354}
2355
2356const char *
2357Process::AttachCompletionHandler::GetExitString ()
2358{
2359 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002360}
2361
2362Error
Greg Clayton527154d2011-11-15 03:53:30 +00002363Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002364{
Chris Lattner24943d22010-06-08 16:52:24 +00002365 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002366 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002367 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002368 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002369
Greg Clayton527154d2011-11-15 03:53:30 +00002370 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002371 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002372 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002373 {
Greg Clayton527154d2011-11-15 03:53:30 +00002374 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002375
Greg Clayton527154d2011-11-15 03:53:30 +00002376 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002377 {
Greg Clayton527154d2011-11-15 03:53:30 +00002378 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2379
2380 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002381 {
Greg Clayton527154d2011-11-15 03:53:30 +00002382 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2383 if (error.Success())
2384 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002385 m_should_detach = true;
2386
Greg Clayton527154d2011-11-15 03:53:30 +00002387 SetPublicState (eStateAttaching);
2388 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2389 if (error.Fail())
2390 {
2391 if (GetID() != LLDB_INVALID_PROCESS_ID)
2392 {
2393 SetID (LLDB_INVALID_PROCESS_ID);
2394 if (error.AsCString() == NULL)
2395 error.SetErrorString("attach failed");
2396
2397 SetExitStatus(-1, error.AsCString());
2398 }
2399 }
2400 else
2401 {
2402 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2403 StartPrivateStateThread();
2404 }
2405 return error;
2406 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002407 }
Greg Clayton527154d2011-11-15 03:53:30 +00002408 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002409 {
Greg Clayton527154d2011-11-15 03:53:30 +00002410 ProcessInstanceInfoList process_infos;
2411 PlatformSP platform_sp (m_target.GetPlatform ());
2412
2413 if (platform_sp)
2414 {
2415 ProcessInstanceInfoMatch match_info;
2416 match_info.GetProcessInfo() = attach_info;
2417 match_info.SetNameMatchType (eNameMatchEquals);
2418 platform_sp->FindProcesses (match_info, process_infos);
2419 const uint32_t num_matches = process_infos.GetSize();
2420 if (num_matches == 1)
2421 {
2422 attach_pid = process_infos.GetProcessIDAtIndex(0);
2423 // Fall through and attach using the above process ID
2424 }
2425 else
2426 {
2427 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2428 if (num_matches > 1)
2429 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2430 else
2431 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2432 }
2433 }
2434 else
2435 {
2436 error.SetErrorString ("invalid platform, can't find processes by name");
2437 return error;
2438 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002439 }
Chris Lattner24943d22010-06-08 16:52:24 +00002440 }
2441 else
Greg Clayton527154d2011-11-15 03:53:30 +00002442 {
2443 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002444 }
2445 }
Greg Clayton527154d2011-11-15 03:53:30 +00002446
2447 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002448 {
Greg Clayton527154d2011-11-15 03:53:30 +00002449 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002450 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002451 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002452 m_should_detach = true;
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002453 SetPublicState (eStateAttaching);
Greg Clayton527154d2011-11-15 03:53:30 +00002454
2455 error = DoAttachToProcessWithID (attach_pid);
2456 if (error.Success())
2457 {
2458
2459 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2460 StartPrivateStateThread();
2461 }
2462 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002463 {
2464 if (GetID() != LLDB_INVALID_PROCESS_ID)
2465 {
2466 SetID (LLDB_INVALID_PROCESS_ID);
2467 const char *error_string = error.AsCString();
2468 if (error_string == NULL)
2469 error_string = "attach failed";
2470
2471 SetExitStatus(-1, error_string);
2472 }
2473 }
Chris Lattner24943d22010-06-08 16:52:24 +00002474 }
2475 }
2476 return error;
2477}
2478
Greg Clayton527154d2011-11-15 03:53:30 +00002479//Error
2480//Process::Attach (const char *process_name, bool wait_for_launch)
2481//{
2482// m_abi_sp.reset();
2483// m_process_input_reader.reset();
2484//
2485// // Find the process and its architecture. Make sure it matches the architecture
2486// // of the current Target, and if not adjust it.
2487// Error error;
2488//
2489// if (!wait_for_launch)
2490// {
2491// ProcessInstanceInfoList process_infos;
2492// PlatformSP platform_sp (m_target.GetPlatform ());
2493// assert (platform_sp.get());
2494//
2495// if (platform_sp)
2496// {
2497// ProcessInstanceInfoMatch match_info;
2498// match_info.GetProcessInfo().SetName(process_name);
2499// match_info.SetNameMatchType (eNameMatchEquals);
2500// platform_sp->FindProcesses (match_info, process_infos);
2501// if (process_infos.GetSize() > 1)
2502// {
2503// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2504// }
2505// else if (process_infos.GetSize() == 0)
2506// {
2507// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2508// }
2509// }
2510// else
2511// {
2512// error.SetErrorString ("invalid platform");
2513// }
2514// }
2515//
2516// if (error.Success())
2517// {
2518// m_dyld_ap.reset();
2519// m_os_ap.reset();
2520//
2521// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2522// if (error.Success())
2523// {
2524// SetPublicState (eStateAttaching);
2525// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2526// if (error.Fail())
2527// {
2528// if (GetID() != LLDB_INVALID_PROCESS_ID)
2529// {
2530// SetID (LLDB_INVALID_PROCESS_ID);
2531// const char *error_string = error.AsCString();
2532// if (error_string == NULL)
2533// error_string = "attach failed";
2534//
2535// SetExitStatus(-1, error_string);
2536// }
2537// }
2538// else
2539// {
2540// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2541// StartPrivateStateThread();
2542// }
2543// }
2544// }
2545// return error;
2546//}
2547
Greg Clayton75c703d2011-02-16 04:46:07 +00002548void
2549Process::CompleteAttach ()
2550{
2551 // Let the process subclass figure out at much as it can about the process
2552 // before we go looking for a dynamic loader plug-in.
2553 DidAttach();
2554
Jim Ingham0d7f7772011-09-15 01:10:17 +00002555 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2556 // the same as the one we've already set, switch architectures.
2557 PlatformSP platform_sp (m_target.GetPlatform ());
2558 assert (platform_sp.get());
2559 if (platform_sp)
2560 {
2561 ProcessInstanceInfo process_info;
2562 platform_sp->GetProcessInfo (GetID(), process_info);
2563 const ArchSpec &process_arch = process_info.GetArchitecture();
2564 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2565 m_target.SetArchitecture (process_arch);
2566 }
2567
2568 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002569 // plug-in
Greg Clayton4fdf7602011-03-20 04:57:14 +00002570 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002571 if (m_dyld_ap.get())
2572 m_dyld_ap->DidAttach();
2573
Greg Clayton37f962e2011-08-22 02:49:39 +00002574 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002575 // Figure out which one is the executable, and set that in our target:
2576 ModuleList &modules = m_target.GetImages();
2577
2578 size_t num_modules = modules.GetSize();
2579 for (int i = 0; i < num_modules; i++)
2580 {
2581 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002582 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002583 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002584 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton75c703d2011-02-16 04:46:07 +00002585 m_target.SetExecutableModule (module_sp, false);
2586 break;
2587 }
2588 }
2589}
2590
Chris Lattner24943d22010-06-08 16:52:24 +00002591Error
Greg Claytone71e2582011-02-04 01:58:07 +00002592Process::ConnectRemote (const char *remote_url)
2593{
Greg Claytone71e2582011-02-04 01:58:07 +00002594 m_abi_sp.reset();
2595 m_process_input_reader.reset();
2596
2597 // Find the process and its architecture. Make sure it matches the architecture
2598 // of the current Target, and if not adjust it.
2599
2600 Error error (DoConnectRemote (remote_url));
2601 if (error.Success())
2602 {
Greg Claytona2f74232011-02-24 22:24:29 +00002603 if (GetID() != LLDB_INVALID_PROCESS_ID)
2604 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002605 EventSP event_sp;
2606 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2607
2608 if (state == eStateStopped || state == eStateCrashed)
2609 {
2610 // If we attached and actually have a process on the other end, then
2611 // this ended up being the equivalent of an attach.
2612 CompleteAttach ();
2613
2614 // This delays passing the stopped event to listeners till
2615 // CompleteAttach gets a chance to complete...
2616 HandlePrivateEvent (event_sp);
2617
2618 }
Greg Claytona2f74232011-02-24 22:24:29 +00002619 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002620
2621 if (PrivateStateThreadIsValid ())
2622 ResumePrivateStateThread ();
2623 else
2624 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002625 }
2626 return error;
2627}
2628
2629
2630Error
Chris Lattner24943d22010-06-08 16:52:24 +00002631Process::Resume ()
2632{
Greg Claytone005f2c2010-11-06 01:53:30 +00002633 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002634 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002635 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002636 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002637 StateAsCString(m_public_state.GetValue()),
2638 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002639
2640 Error error (WillResume());
2641 // Tell the process it is about to resume before the thread list
2642 if (error.Success())
2643 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002644 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002645 // can let all of our threads know that they are about to be
2646 // resumed. Threads will each be called with
2647 // Thread::WillResume(StateType) where StateType contains the state
2648 // that they are supposed to have when the process is resumed
2649 // (suspended/running/stepping). Threads should also check
2650 // their resume signal in lldb::Thread::GetResumeSignal()
2651 // to see if they are suppoed to start back up with a signal.
2652 if (m_thread_list.WillResume())
2653 {
Jim Ingham0296fe72011-11-08 03:00:11 +00002654 m_mod_id.BumpResumeID();
Chris Lattner24943d22010-06-08 16:52:24 +00002655 error = DoResume();
2656 if (error.Success())
2657 {
2658 DidResume();
2659 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00002660 if (log)
2661 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00002662 }
2663 }
2664 else
2665 {
Jim Inghamac959662011-01-24 06:34:17 +00002666 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002667 }
2668 }
Jim Inghamac959662011-01-24 06:34:17 +00002669 else if (log)
2670 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002671 return error;
2672}
2673
2674Error
2675Process::Halt ()
2676{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002677 // Pause our private state thread so we can ensure no one else eats
2678 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002679 Listener halt_listener ("lldb.process.halt_listener");
2680 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002681
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002682 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002683 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002684
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002685 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002686 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002687
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002688 bool caused_stop = false;
2689
2690 // Ask the process subclass to actually halt our process
2691 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002692 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002693 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002694 if (m_public_state.GetValue() == eStateAttaching)
2695 {
2696 SetExitStatus(SIGKILL, "Cancelled async attach.");
2697 Destroy ();
2698 }
2699 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002700 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002701 // If "caused_stop" is true, then DoHalt stopped the process. If
2702 // "caused_stop" is false, the process was already stopped.
2703 // If the DoHalt caused the process to stop, then we want to catch
2704 // this event and set the interrupted bool to true before we pass
2705 // this along so clients know that the process was interrupted by
2706 // a halt command.
2707 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002708 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002709 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002710 TimeValue timeout_time;
2711 timeout_time = TimeValue::Now();
2712 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002713 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2714 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002715
Jim Inghamf9f40c22011-02-08 05:20:59 +00002716 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002717 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002718 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002719 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002720 }
2721 else
2722 {
Greg Clayton20206082011-11-17 01:23:07 +00002723 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002724 {
2725 // We caused the process to interrupt itself, so mark this
2726 // as such in the stop event so clients can tell an interrupted
2727 // process from a natural stop
2728 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2729 }
2730 else
2731 {
2732 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2733 if (log)
2734 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2735 error.SetErrorString ("Did not get stopped event after halt.");
2736 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002737 }
2738 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002739 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002740 }
2741 }
Chris Lattner24943d22010-06-08 16:52:24 +00002742 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002743 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002744 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002745
2746 // Post any event we might have consumed. If all goes well, we will have
2747 // stopped the process, intercepted the event and set the interrupted
2748 // bool in the event. Post it to the private event queue and that will end up
2749 // correctly setting the state.
2750 if (event_sp)
2751 m_private_state_broadcaster.BroadcastEvent(event_sp);
2752
Chris Lattner24943d22010-06-08 16:52:24 +00002753 return error;
2754}
2755
2756Error
2757Process::Detach ()
2758{
2759 Error error (WillDetach());
2760
2761 if (error.Success())
2762 {
2763 DisableAllBreakpointSites();
2764 error = DoDetach();
2765 if (error.Success())
2766 {
2767 DidDetach();
2768 StopPrivateStateThread();
2769 }
2770 }
2771 return error;
2772}
2773
2774Error
2775Process::Destroy ()
2776{
2777 Error error (WillDestroy());
2778 if (error.Success())
2779 {
2780 DisableAllBreakpointSites();
2781 error = DoDestroy();
2782 if (error.Success())
2783 {
2784 DidDestroy();
2785 StopPrivateStateThread();
2786 }
Caroline Tice861efb32010-11-16 05:07:41 +00002787 m_stdio_communication.StopReadThread();
2788 m_stdio_communication.Disconnect();
2789 if (m_process_input_reader && m_process_input_reader->IsActive())
2790 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2791 if (m_process_input_reader)
2792 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002793 }
2794 return error;
2795}
2796
2797Error
2798Process::Signal (int signal)
2799{
2800 Error error (WillSignal());
2801 if (error.Success())
2802 {
2803 error = DoSignal(signal);
2804 if (error.Success())
2805 DidSignal();
2806 }
2807 return error;
2808}
2809
Greg Clayton395fc332011-02-15 21:59:32 +00002810lldb::ByteOrder
2811Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002812{
Greg Clayton395fc332011-02-15 21:59:32 +00002813 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002814}
2815
2816uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002817Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002818{
Greg Clayton395fc332011-02-15 21:59:32 +00002819 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002820}
2821
Greg Clayton395fc332011-02-15 21:59:32 +00002822
Chris Lattner24943d22010-06-08 16:52:24 +00002823bool
2824Process::ShouldBroadcastEvent (Event *event_ptr)
2825{
2826 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2827 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002828 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002829
2830 switch (state)
2831 {
Greg Claytone71e2582011-02-04 01:58:07 +00002832 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002833 case eStateAttaching:
2834 case eStateLaunching:
2835 case eStateDetached:
2836 case eStateExited:
2837 case eStateUnloaded:
2838 // These events indicate changes in the state of the debugging session, always report them.
2839 return_value = true;
2840 break;
2841 case eStateInvalid:
2842 // We stopped for no apparent reason, don't report it.
2843 return_value = false;
2844 break;
2845 case eStateRunning:
2846 case eStateStepping:
2847 // If we've started the target running, we handle the cases where we
2848 // are already running and where there is a transition from stopped to
2849 // running differently.
2850 // running -> running: Automatically suppress extra running events
2851 // stopped -> running: Report except when there is one or more no votes
2852 // and no yes votes.
2853 SynchronouslyNotifyStateChanged (state);
2854 switch (m_public_state.GetValue())
2855 {
2856 case eStateRunning:
2857 case eStateStepping:
2858 // We always suppress multiple runnings with no PUBLIC stop in between.
2859 return_value = false;
2860 break;
2861 default:
2862 // TODO: make this work correctly. For now always report
2863 // run if we aren't running so we don't miss any runnning
2864 // events. If I run the lldb/test/thread/a.out file and
2865 // break at main.cpp:58, run and hit the breakpoints on
2866 // multiple threads, then somehow during the stepping over
2867 // of all breakpoints no run gets reported.
2868 return_value = true;
2869
2870 // This is a transition from stop to run.
2871 switch (m_thread_list.ShouldReportRun (event_ptr))
2872 {
2873 case eVoteYes:
2874 case eVoteNoOpinion:
2875 return_value = true;
2876 break;
2877 case eVoteNo:
2878 return_value = false;
2879 break;
2880 }
2881 break;
2882 }
2883 break;
2884 case eStateStopped:
2885 case eStateCrashed:
2886 case eStateSuspended:
2887 {
2888 // We've stopped. First see if we're going to restart the target.
2889 // If we are going to stop, then we always broadcast the event.
2890 // 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 +00002891 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002892 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002893 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002894 if (log)
2895 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002896 return true;
2897 }
2898 else
2899 {
Chris Lattner24943d22010-06-08 16:52:24 +00002900 RefreshStateAfterStop ();
2901
2902 if (m_thread_list.ShouldStop (event_ptr) == false)
2903 {
2904 switch (m_thread_list.ShouldReportStop (event_ptr))
2905 {
2906 case eVoteYes:
2907 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00002908 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00002909 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00002910 case eVoteNo:
2911 return_value = false;
2912 break;
2913 }
2914
2915 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002916 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002917 Resume ();
2918 }
2919 else
2920 {
2921 return_value = true;
2922 SynchronouslyNotifyStateChanged (state);
2923 }
2924 }
2925 }
2926 }
2927
2928 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00002929 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00002930 return return_value;
2931}
2932
Chris Lattner24943d22010-06-08 16:52:24 +00002933
2934bool
2935Process::StartPrivateStateThread ()
2936{
Greg Claytone005f2c2010-11-06 01:53:30 +00002937 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002938
Greg Claytonb72d0f02011-04-12 05:54:46 +00002939 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00002940 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002941 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2942
2943 if (already_running)
2944 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00002945
2946 // Create a thread that watches our internal state and controls which
2947 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002948 char thread_name[1024];
Greg Clayton444e35b2011-10-19 18:09:39 +00002949 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Claytona875b642011-01-09 21:07:35 +00002950 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002951 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002952}
2953
2954void
2955Process::PausePrivateStateThread ()
2956{
2957 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2958}
2959
2960void
2961Process::ResumePrivateStateThread ()
2962{
2963 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2964}
2965
2966void
2967Process::StopPrivateStateThread ()
2968{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002969 if (PrivateStateThreadIsValid ())
2970 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner24943d22010-06-08 16:52:24 +00002971}
2972
2973void
2974Process::ControlPrivateStateThread (uint32_t signal)
2975{
Greg Claytone005f2c2010-11-06 01:53:30 +00002976 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002977
2978 assert (signal == eBroadcastInternalStateControlStop ||
2979 signal == eBroadcastInternalStateControlPause ||
2980 signal == eBroadcastInternalStateControlResume);
2981
2982 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002983 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002984
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002985 // Signal the private state thread. First we should copy this is case the
2986 // thread starts exiting since the private state thread will NULL this out
2987 // when it exits
2988 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00002989 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002990 {
2991 TimeValue timeout_time;
2992 bool timed_out;
2993
2994 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2995
2996 timeout_time = TimeValue::Now();
2997 timeout_time.OffsetWithSeconds(2);
2998 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2999 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3000
3001 if (signal == eBroadcastInternalStateControlStop)
3002 {
3003 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003004 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003005
3006 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003007 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003008 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003009 }
3010 }
3011}
3012
3013void
3014Process::HandlePrivateEvent (EventSP &event_sp)
3015{
Greg Claytone005f2c2010-11-06 01:53:30 +00003016 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003017
Greg Clayton68ca8232011-01-25 02:58:48 +00003018 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003019
3020 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003021 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003022 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003023 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003024 switch (action_result)
3025 {
3026 case NextEventAction::eEventActionSuccess:
3027 SetNextEventAction(NULL);
3028 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003029
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003030 case NextEventAction::eEventActionRetry:
3031 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003032
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003033 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003034 // Handle Exiting Here. If we already got an exited event,
3035 // we should just propagate it. Otherwise, swallow this event,
3036 // and set our state to exit so the next event will kill us.
3037 if (new_state != eStateExited)
3038 {
3039 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003040 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003041 SetNextEventAction(NULL);
3042 return;
3043 }
3044 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003045 break;
3046 }
3047 }
3048
Chris Lattner24943d22010-06-08 16:52:24 +00003049 // See if we should broadcast this state to external clients?
3050 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003051
3052 if (should_broadcast)
3053 {
3054 if (log)
3055 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003056 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003057 __FUNCTION__,
3058 GetID(),
3059 StateAsCString(new_state),
3060 StateAsCString (GetState ()),
3061 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003062 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003063 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003064 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003065 PushProcessInputReader ();
3066 else
3067 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003068
Chris Lattner24943d22010-06-08 16:52:24 +00003069 BroadcastEvent (event_sp);
3070 }
3071 else
3072 {
3073 if (log)
3074 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003075 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003076 __FUNCTION__,
3077 GetID(),
3078 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003079 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003080 }
3081 }
3082}
3083
3084void *
3085Process::PrivateStateThread (void *arg)
3086{
3087 Process *proc = static_cast<Process*> (arg);
3088 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003089 return result;
3090}
3091
3092void *
3093Process::RunPrivateStateThread ()
3094{
3095 bool control_only = false;
3096 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3097
Greg Claytone005f2c2010-11-06 01:53:30 +00003098 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003099 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003100 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003101
3102 bool exit_now = false;
3103 while (!exit_now)
3104 {
3105 EventSP event_sp;
3106 WaitForEventsPrivate (NULL, event_sp, control_only);
3107 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3108 {
3109 switch (event_sp->GetType())
3110 {
3111 case eBroadcastInternalStateControlStop:
3112 exit_now = true;
3113 continue; // Go to next loop iteration so we exit without
3114 break; // doing any internal state managment below
3115
3116 case eBroadcastInternalStateControlPause:
3117 control_only = true;
3118 break;
3119
3120 case eBroadcastInternalStateControlResume:
3121 control_only = false;
3122 break;
3123 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003124
Jim Ingham3ae449a2010-11-17 02:32:00 +00003125 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003126 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 +00003127
Chris Lattner24943d22010-06-08 16:52:24 +00003128 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003129 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003130 }
3131
3132
3133 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3134
3135 if (internal_state != eStateInvalid)
3136 {
3137 HandlePrivateEvent (event_sp);
3138 }
3139
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003140 if (internal_state == eStateInvalid ||
3141 internal_state == eStateExited ||
3142 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003143 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003144 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003145 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 +00003146
Chris Lattner24943d22010-06-08 16:52:24 +00003147 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003148 }
Chris Lattner24943d22010-06-08 16:52:24 +00003149 }
3150
Caroline Tice926060e2010-10-29 21:48:37 +00003151 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003152 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003153 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003154
Greg Claytona4881d02011-01-22 07:12:45 +00003155 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3156 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003157 return NULL;
3158}
3159
Chris Lattner24943d22010-06-08 16:52:24 +00003160//------------------------------------------------------------------
3161// Process Event Data
3162//------------------------------------------------------------------
3163
3164Process::ProcessEventData::ProcessEventData () :
3165 EventData (),
3166 m_process_sp (),
3167 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003168 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003169 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003170 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003171{
3172}
3173
3174Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3175 EventData (),
3176 m_process_sp (process_sp),
3177 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003178 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003179 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003180 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003181{
3182}
3183
3184Process::ProcessEventData::~ProcessEventData()
3185{
3186}
3187
3188const ConstString &
3189Process::ProcessEventData::GetFlavorString ()
3190{
3191 static ConstString g_flavor ("Process::ProcessEventData");
3192 return g_flavor;
3193}
3194
3195const ConstString &
3196Process::ProcessEventData::GetFlavor () const
3197{
3198 return ProcessEventData::GetFlavorString ();
3199}
3200
Chris Lattner24943d22010-06-08 16:52:24 +00003201void
3202Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3203{
3204 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003205 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3206 // the public event queue, then other times when we're pretending that this is where we stopped at the
3207 // end of expression evaluation. m_update_state is used to distinguish these
3208 // three cases; it is 0 when we're just pulling it off for private handling,
3209 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003210
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003211 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003212 return;
3213
3214 m_process_sp->SetPublicState (m_state);
3215
3216 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3217 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003218 {
3219 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003220 uint32_t num_threads = curr_thread_list.GetSize();
3221 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003222
Jim Ingham21f37ad2011-08-09 02:12:22 +00003223 // The actions might change one of the thread's stop_info's opinions about whether we should
3224 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003225
3226 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3227 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3228 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3229 // 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
3230 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003231 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003232 for (idx = 0; idx < num_threads; ++idx)
3233 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3234
Jim Ingham21f37ad2011-08-09 02:12:22 +00003235 bool still_should_stop = true;
3236
Chris Lattner24943d22010-06-08 16:52:24 +00003237 for (idx = 0; idx < num_threads; ++idx)
3238 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003239 curr_thread_list = m_process_sp->GetThreadList();
3240 if (curr_thread_list.GetSize() != num_threads)
3241 {
3242 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003243 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003244 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0296fe72011-11-08 03:00:11 +00003245 break;
3246 }
3247
3248 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3249
3250 if (thread_sp->GetIndexID() != thread_index_array[idx])
3251 {
3252 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003253 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003254 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003255 idx,
3256 thread_index_array[idx],
3257 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003258 break;
3259 }
3260
Jim Ingham6297a3a2010-10-20 00:39:53 +00003261 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3262 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00003263 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003264 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003265 // The stop action might restart the target. If it does, then we want to mark that in the
3266 // event so that whoever is receiving it will know to wait for the running event and reflect
3267 // that state appropriately.
3268 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003269
3270 // FIXME: we might have run.
3271 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003272 {
3273 SetRestarted (true);
3274 break;
3275 }
3276 else if (!stop_info_sp->ShouldStop(event_ptr))
3277 {
3278 still_should_stop = false;
3279 }
Chris Lattner24943d22010-06-08 16:52:24 +00003280 }
3281 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003282
Jim Ingham21f37ad2011-08-09 02:12:22 +00003283
3284 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003285 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003286 if (!still_should_stop)
3287 {
3288 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003289 SetRestarted(true);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003290 m_process_sp->Resume();
3291 }
3292 else
3293 {
3294 // If we didn't restart, run the Stop Hooks here:
3295 // They might also restart the target, so watch for that.
3296 m_process_sp->GetTarget().RunStopHooks();
3297 if (m_process_sp->GetPrivateState() == eStateRunning)
3298 SetRestarted(true);
3299 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003300 }
3301
Chris Lattner24943d22010-06-08 16:52:24 +00003302 }
3303}
3304
3305void
3306Process::ProcessEventData::Dump (Stream *s) const
3307{
3308 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003309 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003310
Greg Claytonb72d0f02011-04-12 05:54:46 +00003311 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003312}
3313
3314const Process::ProcessEventData *
3315Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3316{
3317 if (event_ptr)
3318 {
3319 const EventData *event_data = event_ptr->GetData();
3320 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3321 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3322 }
3323 return NULL;
3324}
3325
3326ProcessSP
3327Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3328{
3329 ProcessSP process_sp;
3330 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3331 if (data)
3332 process_sp = data->GetProcessSP();
3333 return process_sp;
3334}
3335
3336StateType
3337Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3338{
3339 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3340 if (data == NULL)
3341 return eStateInvalid;
3342 else
3343 return data->GetState();
3344}
3345
3346bool
3347Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3348{
3349 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3350 if (data == NULL)
3351 return false;
3352 else
3353 return data->GetRestarted();
3354}
3355
3356void
3357Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3358{
3359 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3360 if (data != NULL)
3361 data->SetRestarted(new_value);
3362}
3363
3364bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003365Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3366{
3367 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3368 if (data == NULL)
3369 return false;
3370 else
3371 return data->GetInterrupted ();
3372}
3373
3374void
3375Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3376{
3377 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3378 if (data != NULL)
3379 data->SetInterrupted(new_value);
3380}
3381
3382bool
Chris Lattner24943d22010-06-08 16:52:24 +00003383Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3384{
3385 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3386 if (data)
3387 {
3388 data->SetUpdateStateOnRemoval();
3389 return true;
3390 }
3391 return false;
3392}
3393
Chris Lattner24943d22010-06-08 16:52:24 +00003394void
Greg Claytona830adb2010-10-04 01:05:56 +00003395Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003396{
Greg Clayton567e7f32011-09-22 04:58:26 +00003397 exe_ctx.SetTargetPtr (&m_target);
3398 exe_ctx.SetProcessPtr (this);
3399 exe_ctx.SetThreadPtr(NULL);
3400 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003401}
3402
3403lldb::ProcessSP
3404Process::GetSP ()
3405{
3406 return GetTarget().GetProcessSP();
3407}
3408
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003409//uint32_t
3410//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3411//{
3412// return 0;
3413//}
3414//
3415//ArchSpec
3416//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3417//{
3418// return Host::GetArchSpecForExistingProcess (pid);
3419//}
3420//
3421//ArchSpec
3422//Process::GetArchSpecForExistingProcess (const char *process_name)
3423//{
3424// return Host::GetArchSpecForExistingProcess (process_name);
3425//}
3426//
Caroline Tice861efb32010-11-16 05:07:41 +00003427void
3428Process::AppendSTDOUT (const char * s, size_t len)
3429{
Greg Clayton20d338f2010-11-18 05:57:03 +00003430 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003431 m_stdout_data.append (s, len);
Greg Claytonb3781332010-12-05 19:16:56 +00003432 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003433}
3434
3435void
Greg Claytonbd06ff42011-11-13 04:45:22 +00003436Process::AppendSTDERR (const char * s, size_t len)
3437{
3438 Mutex::Locker locker (m_stdio_communication_mutex);
3439 m_stderr_data.append (s, len);
3440 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3441}
3442
3443//------------------------------------------------------------------
3444// Process STDIO
3445//------------------------------------------------------------------
3446
3447size_t
3448Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3449{
3450 Mutex::Locker locker(m_stdio_communication_mutex);
3451 size_t bytes_available = m_stdout_data.size();
3452 if (bytes_available > 0)
3453 {
3454 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3455 if (log)
3456 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3457 if (bytes_available > buf_size)
3458 {
3459 memcpy(buf, m_stdout_data.c_str(), buf_size);
3460 m_stdout_data.erase(0, buf_size);
3461 bytes_available = buf_size;
3462 }
3463 else
3464 {
3465 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3466 m_stdout_data.clear();
3467 }
3468 }
3469 return bytes_available;
3470}
3471
3472
3473size_t
3474Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3475{
3476 Mutex::Locker locker(m_stdio_communication_mutex);
3477 size_t bytes_available = m_stderr_data.size();
3478 if (bytes_available > 0)
3479 {
3480 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3481 if (log)
3482 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3483 if (bytes_available > buf_size)
3484 {
3485 memcpy(buf, m_stderr_data.c_str(), buf_size);
3486 m_stderr_data.erase(0, buf_size);
3487 bytes_available = buf_size;
3488 }
3489 else
3490 {
3491 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3492 m_stderr_data.clear();
3493 }
3494 }
3495 return bytes_available;
3496}
3497
3498void
Caroline Tice861efb32010-11-16 05:07:41 +00003499Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3500{
3501 Process *process = (Process *) baton;
3502 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3503}
3504
3505size_t
3506Process::ProcessInputReaderCallback (void *baton,
3507 InputReader &reader,
3508 lldb::InputReaderAction notification,
3509 const char *bytes,
3510 size_t bytes_len)
3511{
3512 Process *process = (Process *) baton;
3513
3514 switch (notification)
3515 {
3516 case eInputReaderActivate:
3517 break;
3518
3519 case eInputReaderDeactivate:
3520 break;
3521
3522 case eInputReaderReactivate:
3523 break;
3524
Caroline Tice4a348082011-05-02 20:41:46 +00003525 case eInputReaderAsynchronousOutputWritten:
3526 break;
3527
Caroline Tice861efb32010-11-16 05:07:41 +00003528 case eInputReaderGotToken:
3529 {
3530 Error error;
3531 process->PutSTDIN (bytes, bytes_len, error);
3532 }
3533 break;
3534
Caroline Ticec4f55fe2010-11-19 20:47:54 +00003535 case eInputReaderInterrupt:
3536 process->Halt ();
3537 break;
3538
3539 case eInputReaderEndOfFile:
3540 process->AppendSTDOUT ("^D", 2);
3541 break;
3542
Caroline Tice861efb32010-11-16 05:07:41 +00003543 case eInputReaderDone:
3544 break;
3545
3546 }
3547
3548 return bytes_len;
3549}
3550
3551void
3552Process::ResetProcessInputReader ()
3553{
3554 m_process_input_reader.reset();
3555}
3556
3557void
Greg Clayton464c6162011-11-17 22:14:31 +00003558Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00003559{
3560 // First set up the Read Thread for reading/handling process I/O
3561
3562 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3563
3564 if (conn_ap.get())
3565 {
3566 m_stdio_communication.SetConnection (conn_ap.release());
3567 if (m_stdio_communication.IsConnected())
3568 {
3569 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3570 m_stdio_communication.StartReadThread();
3571
3572 // Now read thread is set up, set up input reader.
3573
3574 if (!m_process_input_reader.get())
3575 {
3576 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3577 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3578 this,
3579 eInputReaderGranularityByte,
3580 NULL,
3581 NULL,
3582 false));
3583
3584 if (err.Fail())
3585 m_process_input_reader.reset();
3586 }
3587 }
3588 }
3589}
3590
3591void
3592Process::PushProcessInputReader ()
3593{
3594 if (m_process_input_reader && !m_process_input_reader->IsActive())
3595 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3596}
3597
3598void
3599Process::PopProcessInputReader ()
3600{
3601 if (m_process_input_reader && m_process_input_reader->IsActive())
3602 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3603}
3604
Greg Claytond284b662011-02-18 01:44:25 +00003605// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00003606void
Caroline Tice2a456812011-03-10 22:14:10 +00003607Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003608{
Greg Claytonb3448432011-03-24 21:19:54 +00003609 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00003610
3611 int i=0;
3612 const char *name;
3613 OptionEnumValueElement option_enum;
3614 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3615 {
3616 if (name)
3617 {
3618 option_enum.value = i;
3619 option_enum.string_value = name;
3620 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3621 g_plugins.push_back (option_enum);
3622 }
3623 ++i;
3624 }
3625 option_enum.value = 0;
3626 option_enum.string_value = NULL;
3627 option_enum.usage = NULL;
3628 g_plugins.push_back (option_enum);
3629
3630 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3631 {
3632 if (::strcmp (name, "plugin") == 0)
3633 {
3634 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3635 break;
3636 }
3637 }
Greg Clayton990de7b2010-11-18 23:32:35 +00003638 UserSettingsControllerSP &usc = GetSettingsController();
3639 usc.reset (new SettingsController);
3640 UserSettingsController::InitializeSettingsController (usc,
3641 SettingsController::global_settings_table,
3642 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00003643
3644 // Now call SettingsInitialize() for each 'child' of Process settings
3645 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00003646}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003647
Greg Clayton990de7b2010-11-18 23:32:35 +00003648void
Caroline Tice2a456812011-03-10 22:14:10 +00003649Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00003650{
Caroline Tice2a456812011-03-10 22:14:10 +00003651 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3652
3653 Thread::SettingsTerminate ();
3654
3655 // Now terminate Process Settings.
3656
Greg Clayton990de7b2010-11-18 23:32:35 +00003657 UserSettingsControllerSP &usc = GetSettingsController();
3658 UserSettingsController::FinalizeSettingsController (usc);
3659 usc.reset();
3660}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003661
Greg Clayton990de7b2010-11-18 23:32:35 +00003662UserSettingsControllerSP &
3663Process::GetSettingsController ()
3664{
3665 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003666 return g_settings_controller;
3667}
3668
Caroline Tice1ebef442010-09-27 00:30:10 +00003669void
3670Process::UpdateInstanceName ()
3671{
Greg Clayton5beb99d2011-08-11 02:48:45 +00003672 Module *module = GetTarget().GetExecutableModulePointer();
3673 if (module)
Caroline Tice1ebef442010-09-27 00:30:10 +00003674 {
3675 StreamString sstr;
Greg Clayton5beb99d2011-08-11 02:48:45 +00003676 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1ebef442010-09-27 00:30:10 +00003677
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003678 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytonb72d0f02011-04-12 05:54:46 +00003679 sstr.GetData());
Caroline Tice1ebef442010-09-27 00:30:10 +00003680 }
3681}
3682
Greg Clayton427f2902010-12-14 02:59:59 +00003683ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00003684Process::RunThreadPlan (ExecutionContext &exe_ctx,
3685 lldb::ThreadPlanSP &thread_plan_sp,
3686 bool stop_others,
3687 bool try_all_threads,
3688 bool discard_on_error,
3689 uint32_t single_thread_timeout_usec,
3690 Stream &errors)
3691{
3692 ExecutionResults return_value = eExecutionSetupError;
3693
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003694 if (thread_plan_sp.get() == NULL)
3695 {
3696 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00003697 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003698 }
Greg Clayton567e7f32011-09-22 04:58:26 +00003699
3700 if (exe_ctx.GetProcessPtr() != this)
3701 {
3702 errors.Printf("RunThreadPlan called on wrong process.");
3703 return eExecutionSetupError;
3704 }
3705
3706 Thread *thread = exe_ctx.GetThreadPtr();
3707 if (thread == NULL)
3708 {
3709 errors.Printf("RunThreadPlan called with invalid thread.");
3710 return eExecutionSetupError;
3711 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003712
Jim Ingham5ab7fba2011-05-17 22:24:54 +00003713 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3714 // For that to be true the plan can't be private - since private plans suppress themselves in the
3715 // GetCompletedPlan call.
3716
3717 bool orig_plan_private = thread_plan_sp->GetPrivate();
3718 thread_plan_sp->SetPrivate(false);
3719
Jim Inghamac959662011-01-24 06:34:17 +00003720 if (m_private_state.GetValue() != eStateStopped)
3721 {
3722 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00003723 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00003724 }
3725
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003726 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00003727 const uint32_t thread_idx_id = thread->GetIndexID();
3728 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003729
3730 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3731 // so we should arrange to reset them as well.
3732
Greg Clayton567e7f32011-09-22 04:58:26 +00003733 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00003734
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003735 uint32_t selected_tid;
3736 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00003737 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00003738 {
3739 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003740 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003741 }
3742 else
3743 {
3744 selected_tid = LLDB_INVALID_THREAD_ID;
3745 }
3746
Greg Clayton567e7f32011-09-22 04:58:26 +00003747 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Ingham360f53f2010-11-30 02:22:11 +00003748
Jim Ingham6ae318c2011-01-23 21:14:08 +00003749 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003750
3751 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3752 // restored on exit to the function.
3753
3754 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00003755
Jim Ingham6ae318c2011-01-23 21:14:08 +00003756 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003757 if (log)
3758 {
3759 StreamString s;
3760 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton444e35b2011-10-19 18:09:39 +00003761 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Clayton567e7f32011-09-22 04:58:26 +00003762 thread->GetIndexID(),
3763 thread->GetID(),
Jim Inghamf9f40c22011-02-08 05:20:59 +00003764 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003765 }
3766
Jim Inghamf9f40c22011-02-08 05:20:59 +00003767 bool got_event;
3768 lldb::EventSP event_sp;
3769 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00003770
3771 TimeValue* timeout_ptr = NULL;
3772 TimeValue real_timeout;
3773
Jim Inghamf9f40c22011-02-08 05:20:59 +00003774 bool first_timeout = true;
3775 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00003776
Jim Ingham360f53f2010-11-30 02:22:11 +00003777 while (1)
3778 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003779 // We usually want to resume the process if we get to the top of the loop.
3780 // The only exception is if we get two running events with no intervening
3781 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00003782
Jim Inghamf9f40c22011-02-08 05:20:59 +00003783 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00003784 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003785 // Do the initial resume and wait for the running event before going further.
3786
Greg Clayton567e7f32011-09-22 04:58:26 +00003787 Error resume_error = Resume ();
Jim Inghamf9f40c22011-02-08 05:20:59 +00003788 if (!resume_error.Success())
3789 {
3790 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00003791 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003792 break;
3793 }
3794
3795 real_timeout = TimeValue::Now();
3796 real_timeout.OffsetWithMicroSeconds(500000);
3797 timeout_ptr = &real_timeout;
3798
3799 got_event = listener.WaitForEvent(NULL, event_sp);
3800 if (!got_event)
3801 {
3802 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003803 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003804
3805 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003806 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003807 break;
3808 }
3809
3810 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3811 if (stop_state != eStateRunning)
3812 {
3813 if (log)
3814 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3815
3816 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003817 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003818 break;
3819 }
3820
3821 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003822 log->PutCString ("Resuming succeeded.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003823 // We need to call the function synchronously, so spin waiting for it to return.
3824 // If we get interrupted while executing, we're going to lose our context, and
3825 // won't be able to gather the result at this point.
3826 // We set the timeout AFTER the resume, since the resume takes some time and we
3827 // don't want to charge that to the timeout.
3828
3829 if (single_thread_timeout_usec != 0)
3830 {
3831 real_timeout = TimeValue::Now();
3832 if (first_timeout)
3833 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3834 else
3835 real_timeout.OffsetWithSeconds(10);
3836
3837 timeout_ptr = &real_timeout;
3838 }
3839 }
3840 else
3841 {
3842 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003843 log->PutCString ("Handled an extra running event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003844 do_resume = true;
3845 }
3846
3847 // Now wait for the process to stop again:
3848 stop_state = lldb::eStateInvalid;
3849 event_sp.reset();
3850 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3851
3852 if (got_event)
3853 {
3854 if (event_sp.get())
3855 {
3856 bool keep_going = false;
3857 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3858 if (log)
3859 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3860
3861 switch (stop_state)
3862 {
3863 case lldb::eStateStopped:
Jim Ingham2370a972011-05-17 01:10:11 +00003864 {
Greg Clayton43994462011-06-03 22:12:42 +00003865 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Clayton567e7f32011-09-22 04:58:26 +00003866 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton43994462011-06-03 22:12:42 +00003867 if (!thread_sp)
Jim Ingham2370a972011-05-17 01:10:11 +00003868 {
Greg Clayton43994462011-06-03 22:12:42 +00003869 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham2370a972011-05-17 01:10:11 +00003870 if (log)
Greg Clayton43994462011-06-03 22:12:42 +00003871 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3872 return_value = eExecutionInterrupted;
Jim Ingham2370a972011-05-17 01:10:11 +00003873 }
3874 else
3875 {
Greg Clayton43994462011-06-03 22:12:42 +00003876 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3877 StopReason stop_reason = eStopReasonInvalid;
3878 if (stop_info_sp)
3879 stop_reason = stop_info_sp->GetStopReason();
3880 if (stop_reason == eStopReasonPlanComplete)
3881 {
3882 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003883 log->PutCString ("Execution completed successfully.");
Greg Clayton43994462011-06-03 22:12:42 +00003884 // Now mark this plan as private so it doesn't get reported as the stop reason
3885 // after this point.
3886 if (thread_plan_sp)
3887 thread_plan_sp->SetPrivate (orig_plan_private);
3888 return_value = eExecutionCompleted;
3889 }
3890 else
3891 {
3892 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003893 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton43994462011-06-03 22:12:42 +00003894
3895 return_value = eExecutionInterrupted;
3896 }
Jim Ingham2370a972011-05-17 01:10:11 +00003897 }
Greg Clayton43994462011-06-03 22:12:42 +00003898 }
3899 break;
3900
Jim Inghamf9f40c22011-02-08 05:20:59 +00003901 case lldb::eStateCrashed:
3902 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003903 log->PutCString ("Execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003904 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003905 break;
Greg Clayton43994462011-06-03 22:12:42 +00003906
Jim Inghamf9f40c22011-02-08 05:20:59 +00003907 case lldb::eStateRunning:
3908 do_resume = false;
3909 keep_going = true;
3910 break;
Greg Clayton43994462011-06-03 22:12:42 +00003911
Jim Inghamf9f40c22011-02-08 05:20:59 +00003912 default:
3913 if (log)
3914 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham2370a972011-05-17 01:10:11 +00003915
3916 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytonb3448432011-03-24 21:19:54 +00003917 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003918 break;
3919 }
3920 if (keep_going)
3921 continue;
3922 else
3923 break;
3924 }
3925 else
3926 {
3927 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003928 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00003929 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003930 break;
3931 }
3932 }
3933 else
3934 {
3935 // If we didn't get an event that means we've timed out...
3936 // We will interrupt the process here. Depending on what we were asked to do we will
3937 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00003938 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003939
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003940 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00003941 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003942 {
3943 if (first_timeout)
3944 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3945 "trying with all threads enabled.",
3946 single_thread_timeout_usec);
3947 else
3948 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3949 "and timeout: %d timed out.",
3950 single_thread_timeout_usec);
3951 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003952 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00003953 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3954 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00003955 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003956 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003957
Greg Clayton567e7f32011-09-22 04:58:26 +00003958 Error halt_error = Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00003959 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00003960 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003961 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003962 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003963
Jim Inghamf9f40c22011-02-08 05:20:59 +00003964 // If halt succeeds, it always produces a stopped event. Wait for that:
3965
3966 real_timeout = TimeValue::Now();
3967 real_timeout.OffsetWithMicroSeconds(500000);
3968
3969 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00003970
3971 if (got_event)
3972 {
3973 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3974 if (log)
3975 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003976 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00003977 if (stop_state == lldb::eStateStopped
3978 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf6d3d792011-08-09 22:24:33 +00003979 log->PutCString (" Event was the Halt interruption event.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003980 }
3981
Jim Inghamf9f40c22011-02-08 05:20:59 +00003982 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00003983 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003984 // Between the time we initiated the Halt and the time we delivered it, the process could have
3985 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00003986
Greg Clayton567e7f32011-09-22 04:58:26 +00003987 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00003988 {
3989 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003990 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00003991 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003992 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003993 break;
3994 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003995
Jim Inghamf9f40c22011-02-08 05:20:59 +00003996 if (!try_all_threads)
3997 {
3998 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003999 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00004000 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004001 break;
4002 }
4003
4004 if (first_timeout)
4005 {
4006 // Set all the other threads to run, and return to the top of the loop, which will continue;
4007 first_timeout = false;
4008 thread_plan_sp->SetStopOthers (false);
4009 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004010 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004011
4012 continue;
4013 }
4014 else
4015 {
4016 // Running all threads failed, so return Interrupted.
4017 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004018 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00004019 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004020 break;
4021 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004022 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004023 }
4024 else
4025 { if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004026 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004027 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00004028 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004029 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00004030 }
4031 }
Jim Inghamc556b462011-01-22 01:30:53 +00004032 else
4033 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004034 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4035 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00004036 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004037 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.",
4038 halt_error.AsCString());
4039 real_timeout = TimeValue::Now();
4040 real_timeout.OffsetWithMicroSeconds(500000);
4041 timeout_ptr = &real_timeout;
4042 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4043 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00004044 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004045 // This is not going anywhere, bag out.
4046 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004047 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00004048 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004049 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00004050 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004051 else
4052 {
4053 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4054 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004055 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004056 if (stop_state == lldb::eStateStopped)
4057 {
4058 // Between the time we initiated the Halt and the time we delivered it, the process could have
4059 // already finished its job. Check that here:
4060
Greg Clayton567e7f32011-09-22 04:58:26 +00004061 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00004062 {
4063 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004064 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004065 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00004066 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004067 break;
4068 }
4069
4070 if (first_timeout)
4071 {
4072 // Set all the other threads to run, and return to the top of the loop, which will continue;
4073 first_timeout = false;
4074 thread_plan_sp->SetStopOthers (false);
4075 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004076 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004077
4078 continue;
4079 }
4080 else
4081 {
4082 // Running all threads failed, so return Interrupted.
4083 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004084 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00004085 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004086 break;
4087 }
4088 }
4089 else
4090 {
Sean Callananed3f86b2011-08-09 22:07:08 +00004091 if (log)
4092 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4093 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00004094 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004095 break;
4096 }
4097 }
Jim Inghamc556b462011-01-22 01:30:53 +00004098 }
4099
Jim Ingham360f53f2010-11-30 02:22:11 +00004100 }
4101
Jim Inghamf9f40c22011-02-08 05:20:59 +00004102 } // END WAIT LOOP
4103
4104 // Now do some processing on the results of the run:
4105 if (return_value == eExecutionInterrupted)
4106 {
Jim Ingham360f53f2010-11-30 02:22:11 +00004107 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004108 {
4109 StreamString s;
4110 if (event_sp)
4111 event_sp->Dump (&s);
4112 else
4113 {
Jim Inghamf6d3d792011-08-09 22:24:33 +00004114 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004115 }
4116
4117 StreamString ts;
4118
Jim Inghamf6d3d792011-08-09 22:24:33 +00004119 const char *event_explanation = NULL;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004120
4121 do
4122 {
4123 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4124
4125 if (!event_data)
4126 {
4127 event_explanation = "<no event data>";
4128 break;
4129 }
4130
4131 Process *process = event_data->GetProcessSP().get();
4132
4133 if (!process)
4134 {
4135 event_explanation = "<no process>";
4136 break;
4137 }
4138
4139 ThreadList &thread_list = process->GetThreadList();
4140
4141 uint32_t num_threads = thread_list.GetSize();
4142 uint32_t thread_index;
4143
4144 ts.Printf("<%u threads> ", num_threads);
4145
4146 for (thread_index = 0;
4147 thread_index < num_threads;
4148 ++thread_index)
4149 {
4150 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4151
4152 if (!thread)
4153 {
4154 ts.Printf("<?> ");
4155 continue;
4156 }
4157
Greg Clayton444e35b2011-10-19 18:09:39 +00004158 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Inghamf9f40c22011-02-08 05:20:59 +00004159 RegisterContext *register_context = thread->GetRegisterContext().get();
4160
4161 if (register_context)
4162 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4163 else
4164 ts.Printf("[ip unknown] ");
4165
4166 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4167 if (stop_info_sp)
4168 {
4169 const char *stop_desc = stop_info_sp->GetDescription();
4170 if (stop_desc)
4171 ts.PutCString (stop_desc);
4172 }
4173 ts.Printf(">");
4174 }
4175
4176 event_explanation = ts.GetData();
4177 } while (0);
4178
4179 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004180 {
4181 if (event_explanation)
4182 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4183 else
4184 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4185 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004186
4187 if (discard_on_error && thread_plan_sp)
4188 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004189 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004190 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004191 }
4192 }
4193 }
4194 else if (return_value == eExecutionSetupError)
4195 {
4196 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004197 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004198
4199 if (discard_on_error && thread_plan_sp)
4200 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004201 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004202 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004203 }
4204 }
4205 else
4206 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004207 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004208 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004209 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004210 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00004211 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00004212 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004213 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004214 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004215 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004216 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00004217 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00004218 }
4219 else
4220 {
4221 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004222 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00004223 if (discard_on_error && thread_plan_sp)
4224 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004225 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004226 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Clayton567e7f32011-09-22 04:58:26 +00004227 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004228 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham360f53f2010-11-30 02:22:11 +00004229 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004230 }
4231 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004232
Jim Ingham360f53f2010-11-30 02:22:11 +00004233 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004234 // Check that it's still there, and if it is put it back in the context. Also restore the
4235 // frame in the context if it is still present.
Greg Clayton567e7f32011-09-22 04:58:26 +00004236 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4237 if (thread)
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004238 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004239 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004240 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004241
4242 // Also restore the current process'es selected frame & thread, since this function calling may
4243 // be done behind the user's back.
4244
4245 if (selected_tid != LLDB_INVALID_THREAD_ID)
4246 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004247 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Ingham360f53f2010-11-30 02:22:11 +00004248 {
4249 // We were able to restore the selected thread, now restore the frame:
Greg Clayton567e7f32011-09-22 04:58:26 +00004250 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004251 if (old_frame_sp)
Greg Clayton567e7f32011-09-22 04:58:26 +00004252 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00004253 }
4254 }
4255
4256 return return_value;
4257}
4258
4259const char *
4260Process::ExecutionResultAsCString (ExecutionResults result)
4261{
4262 const char *result_name;
4263
4264 switch (result)
4265 {
Greg Claytonb3448432011-03-24 21:19:54 +00004266 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004267 result_name = "eExecutionCompleted";
4268 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004269 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00004270 result_name = "eExecutionDiscarded";
4271 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004272 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004273 result_name = "eExecutionInterrupted";
4274 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004275 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00004276 result_name = "eExecutionSetupError";
4277 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004278 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00004279 result_name = "eExecutionTimedOut";
4280 break;
4281 }
4282 return result_name;
4283}
4284
Greg Claytonabe0fed2011-04-18 08:33:37 +00004285void
4286Process::GetStatus (Stream &strm)
4287{
4288 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00004289 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00004290 {
4291 if (state == eStateExited)
4292 {
4293 int exit_status = GetExitStatus();
4294 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00004295 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00004296 GetID(),
4297 exit_status,
4298 exit_status,
4299 exit_description ? exit_description : "");
4300 }
4301 else
4302 {
4303 if (state == eStateConnected)
4304 strm.Printf ("Connected to remote target.\n");
4305 else
Greg Clayton444e35b2011-10-19 18:09:39 +00004306 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00004307 }
4308 }
4309 else
4310 {
Greg Clayton444e35b2011-10-19 18:09:39 +00004311 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004312 }
4313}
4314
4315size_t
4316Process::GetThreadStatus (Stream &strm,
4317 bool only_threads_with_stop_reason,
4318 uint32_t start_frame,
4319 uint32_t num_frames,
4320 uint32_t num_frames_with_source)
4321{
4322 size_t num_thread_infos_dumped = 0;
4323
4324 const size_t num_threads = GetThreadList().GetSize();
4325 for (uint32_t i = 0; i < num_threads; i++)
4326 {
4327 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4328 if (thread)
4329 {
4330 if (only_threads_with_stop_reason)
4331 {
4332 if (thread->GetStopInfo().get() == NULL)
4333 continue;
4334 }
4335 thread->GetStatus (strm,
4336 start_frame,
4337 num_frames,
4338 num_frames_with_source);
4339 ++num_thread_infos_dumped;
4340 }
4341 }
4342 return num_thread_infos_dumped;
4343}
4344
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004345//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004346// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004347//--------------------------------------------------------------
4348
Greg Claytond0a5a232010-09-19 02:33:57 +00004349Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00004350 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004351{
Greg Clayton638351a2010-12-04 00:10:17 +00004352 m_default_settings.reset (new ProcessInstanceSettings (*this,
4353 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00004354 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004355}
4356
Greg Claytond0a5a232010-09-19 02:33:57 +00004357Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004358{
4359}
4360
4361lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00004362Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004363{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00004364 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4365 false,
4366 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004367 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4368 return new_settings_sp;
4369}
4370
4371//--------------------------------------------------------------
4372// class ProcessInstanceSettings
4373//--------------------------------------------------------------
4374
Greg Clayton638351a2010-12-04 00:10:17 +00004375ProcessInstanceSettings::ProcessInstanceSettings
4376(
4377 UserSettingsController &owner,
4378 bool live_instance,
4379 const char *name
4380) :
Greg Claytonabb33022011-11-08 02:43:13 +00004381 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004382{
Caroline Tice396704b2010-09-09 18:26:37 +00004383 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4384 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4385 // 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 +00004386 // This is true for CreateInstanceName() too.
Greg Claytonabb33022011-11-08 02:43:13 +00004387
Caroline Tice75b11a32010-09-16 19:05:55 +00004388 if (GetInstanceName () == InstanceSettings::InvalidName())
4389 {
4390 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4391 m_owner.RegisterInstanceSettings (this);
4392 }
Greg Claytonabb33022011-11-08 02:43:13 +00004393
Caroline Tice396704b2010-09-09 18:26:37 +00004394 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004395 {
4396 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4397 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00004398 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004399 }
4400}
4401
4402ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonabb33022011-11-08 02:43:13 +00004403 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004404{
4405 if (m_instance_name != InstanceSettings::GetDefaultName())
4406 {
4407 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4408 CopyInstanceSettings (pending_settings,false);
4409 m_owner.RemovePendingSettings (m_instance_name);
4410 }
4411}
4412
4413ProcessInstanceSettings::~ProcessInstanceSettings ()
4414{
4415}
4416
4417ProcessInstanceSettings&
4418ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4419{
4420 if (this != &rhs)
4421 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004422 }
4423
4424 return *this;
4425}
4426
4427
4428void
4429ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4430 const char *index_value,
4431 const char *value,
4432 const ConstString &instance_name,
4433 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00004434 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004435 Error &err,
4436 bool pending)
4437{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004438}
4439
4440void
4441ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4442 bool pending)
4443{
Greg Claytonabb33022011-11-08 02:43:13 +00004444// if (new_settings.get() == NULL)
4445// return;
4446//
4447// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004448}
4449
Caroline Ticebcb5b452010-09-20 21:37:42 +00004450bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004451ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4452 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00004453 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00004454 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004455{
Greg Claytonabb33022011-11-08 02:43:13 +00004456 if (err)
4457 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4458 return false;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004459}
4460
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004461const ConstString
4462ProcessInstanceSettings::CreateInstanceName ()
4463{
4464 static int instance_count = 1;
4465 StreamString sstr;
4466
4467 sstr.Printf ("process_%d", instance_count);
4468 ++instance_count;
4469
4470 const ConstString ret_val (sstr.GetData());
4471 return ret_val;
4472}
4473
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004474//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004475// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004476//--------------------------------------------------
4477
4478SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004479Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004480{
4481 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4482 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4483};
4484
4485
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004486SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004487Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004488{
Greg Clayton638351a2010-12-04 00:10:17 +00004489 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton638351a2010-12-04 00:10:17 +00004490 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004491};
4492
4493
Jim Ingham7508e732010-08-09 23:31:02 +00004494
Greg Claytonabb33022011-11-08 02:43:13 +00004495