blob: 94dce38a27201df329fc013b044754f73c141df1 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
39
40using namespace lldb;
41using namespace lldb_private;
42
Greg Clayton32e0a752011-03-30 18:16:51 +000043void
Greg Clayton8b82f082011-04-12 05:54:46 +000044ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +000045{
46 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +000047 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +000048 s.Printf (" pid = %llu\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000049
50 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +000051 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +000060 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +000061 if (argc > 0)
62 {
63 for (uint32_t i=0; i<argc; i++)
64 {
Greg Clayton8b82f082011-04-12 05:54:46 +000065 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000066 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +000067 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000068 else
Greg Clayton8b82f082011-04-12 05:54:46 +000069 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000070 }
71 }
Greg Clayton8b82f082011-04-12 05:54:46 +000072
73 const uint32_t envc = m_environment.GetArgumentCount();
74 if (envc > 0)
75 {
76 for (uint32_t i=0; i<envc; i++)
77 {
78 const char *env = m_environment.GetArgumentAtIndex(i);
79 if (i < 10)
80 s.Printf (" env[%u] = %s\n", i, env);
81 else
82 s.Printf ("env[%u] = %s\n", i, env);
83 }
84 }
85
Greg Clayton95bf0fd2011-04-01 00:29:43 +000086 if (m_arch.IsValid())
87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
88
Greg Clayton8b82f082011-04-12 05:54:46 +000089 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000090 {
Greg Clayton8b82f082011-04-12 05:54:46 +000091 cstr = platform->GetUserName (m_uid);
92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000093 }
Greg Clayton8b82f082011-04-12 05:54:46 +000094 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000095 {
Greg Clayton8b82f082011-04-12 05:54:46 +000096 cstr = platform->GetGroupName (m_gid);
97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000098 }
Greg Clayton8b82f082011-04-12 05:54:46 +000099 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000100 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000101 cstr = platform->GetUserName (m_euid);
102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000103 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000104 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000105 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000106 cstr = platform->GetGroupName (m_egid);
107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000108 }
109}
110
111void
Greg Clayton8b82f082011-04-12 05:54:46 +0000112ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000113{
Greg Clayton8b82f082011-04-12 05:54:46 +0000114 const char *label;
115 if (show_args || verbose)
116 label = "ARGUMENTS";
117 else
118 label = "NAME";
119
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000120 if (verbose)
121 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
124 }
125 else
126 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000127 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000128 s.PutCString ("====== ====== ========== ======= ============================\n");
129 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000130}
131
132void
Greg Clayton8b82f082011-04-12 05:54:46 +0000133ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000134{
135 if (m_pid != LLDB_INVALID_PROCESS_ID)
136 {
137 const char *cstr;
Greg Clayton61e7a582011-12-01 23:28:38 +0000138 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000139
Greg Clayton32e0a752011-03-30 18:16:51 +0000140
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000141 if (verbose)
142 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000143 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000144 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
145 s.Printf ("%-10s ", cstr);
146 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000147 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000148
Greg Clayton8b82f082011-04-12 05:54:46 +0000149 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000150 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
151 s.Printf ("%-10s ", cstr);
152 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000153 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000154
Greg Clayton8b82f082011-04-12 05:54:46 +0000155 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000156 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
157 s.Printf ("%-10s ", cstr);
158 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000159 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000160
Greg Clayton8b82f082011-04-12 05:54:46 +0000161 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000162 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
163 s.Printf ("%-10s ", cstr);
164 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000165 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000166 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
167 }
168 else
169 {
Jason Molendafd54b362011-09-20 21:44:10 +0000170 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000171 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000172 (int)m_arch.GetTriple().getArchName().size(),
173 m_arch.GetTriple().getArchName().data());
174 }
175
Greg Clayton8b82f082011-04-12 05:54:46 +0000176 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000177 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000178 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000179 if (argc > 0)
180 {
181 for (uint32_t i=0; i<argc; i++)
182 {
183 if (i > 0)
184 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000185 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000186 }
187 }
188 }
189 else
190 {
191 s.PutCString (GetName());
192 }
193
194 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000195 }
196}
197
Greg Clayton8b82f082011-04-12 05:54:46 +0000198
199void
Greg Clayton982c9762011-11-03 21:22:33 +0000200ProcessInfo::SetArguments (char const **argv,
201 bool first_arg_is_executable,
202 bool first_arg_is_executable_and_argument)
203{
204 m_arguments.SetArguments (argv);
205
206 // Is the first argument the executable?
207 if (first_arg_is_executable)
208 {
209 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
210 if (first_arg)
211 {
212 // Yes the first argument is an executable, set it as the executable
213 // in the launch options. Don't resolve the file path as the path
214 // could be a remote platform path
215 const bool resolve = false;
216 m_executable.SetFile(first_arg, resolve);
217
218 // If argument zero is an executable and shouldn't be included
219 // in the arguments, remove it from the front of the arguments
220 if (first_arg_is_executable_and_argument == false)
221 m_arguments.DeleteArgumentAtIndex (0);
222 }
223 }
224}
225void
226ProcessInfo::SetArguments (const Args& args,
227 bool first_arg_is_executable,
228 bool first_arg_is_executable_and_argument)
Greg Clayton8b82f082011-04-12 05:54:46 +0000229{
230 // Copy all arguments
231 m_arguments = args;
232
233 // Is the first argument the executable?
234 if (first_arg_is_executable)
235 {
Greg Clayton982c9762011-11-03 21:22:33 +0000236 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-04-12 05:54:46 +0000237 if (first_arg)
238 {
239 // Yes the first argument is an executable, set it as the executable
240 // in the launch options. Don't resolve the file path as the path
241 // could be a remote platform path
242 const bool resolve = false;
243 m_executable.SetFile(first_arg, resolve);
244
245 // If argument zero is an executable and shouldn't be included
246 // in the arguments, remove it from the front of the arguments
247 if (first_arg_is_executable_and_argument == false)
248 m_arguments.DeleteArgumentAtIndex (0);
249 }
250 }
251}
252
Greg Clayton1d885962011-11-08 02:43:13 +0000253void
Greg Claytonee95ed52011-11-17 22:14:31 +0000254ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-11-08 02:43:13 +0000255{
256 // If notthing was specified, then check the process for any default
257 // settings that were set with "settings set"
258 if (m_file_actions.empty())
259 {
Greg Clayton1d885962011-11-08 02:43:13 +0000260 if (m_flags.Test(eLaunchFlagDisableSTDIO))
261 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000262 AppendSuppressFileAction (STDIN_FILENO , true, false);
263 AppendSuppressFileAction (STDOUT_FILENO, false, true);
264 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-11-08 02:43:13 +0000265 }
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 Claytonee95ed52011-11-17 22:14:31 +0000272 const char *in_path = NULL;
273 const char *out_path = NULL;
274 const char *err_path = NULL;
Greg Clayton1d885962011-11-08 02:43:13 +0000275 if (target)
276 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000277 in_path = target->GetStandardInputPath();
278 out_path = target->GetStandardOutputPath();
279 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-11-17 22:14:31 +0000280 }
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 Clayton1d885962011-11-08 02:43:13 +0000285 {
Greg Claytonee95ed52011-11-17 22:14:31 +0000286 in_path = out_path = err_path = m_pty.GetSlaveName (NULL, 0);
Greg Clayton1d885962011-11-08 02:43:13 +0000287 }
288 }
289
Greg Claytonee95ed52011-11-17 22:14:31 +0000290 if (in_path)
Greg Clayton9845a8d2012-03-06 04:01:04 +0000291 AppendOpenFileAction(STDIN_FILENO, in_path, true, false);
292
Greg Claytonee95ed52011-11-17 22:14:31 +0000293 if (out_path)
Greg Clayton9845a8d2012-03-06 04:01:04 +0000294 AppendOpenFileAction(STDOUT_FILENO, out_path, false, true);
Greg Claytonee95ed52011-11-17 22:14:31 +0000295
296 if (err_path)
Greg Clayton9845a8d2012-03-06 04:01:04 +0000297 AppendOpenFileAction(STDERR_FILENO, err_path, false, true);
298
Greg Clayton1d885962011-11-08 02:43:13 +0000299 }
300 }
301}
302
Greg Clayton144f3a92011-11-15 03:53:30 +0000303
304bool
305ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error, bool localhost)
306{
307 error.Clear();
308
309 if (GetFlags().Test (eLaunchFlagLaunchInShell))
310 {
311 const char *shell_executable = GetShell();
312 if (shell_executable)
313 {
314 char shell_resolved_path[PATH_MAX];
315
316 if (localhost)
317 {
318 FileSpec shell_filespec (shell_executable, true);
319
320 if (!shell_filespec.Exists())
321 {
322 // Resolve the path in case we just got "bash", "sh" or "tcsh"
323 if (!shell_filespec.ResolveExecutableLocation ())
324 {
325 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
326 return false;
327 }
328 }
329 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
330 shell_executable = shell_resolved_path;
331 }
332
333 Args shell_arguments;
334 std::string safe_arg;
335 shell_arguments.AppendArgument (shell_executable);
336 StreamString shell_command;
337 shell_arguments.AppendArgument ("-c");
338 shell_command.PutCString ("exec");
339 if (GetArchitecture().IsValid())
340 {
341 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
342 // Set the resume count to 2:
343 // 1 - stop in shell
344 // 2 - stop in /usr/bin/arch
345 // 3 - then we will stop in our program
346 SetResumeCount(2);
347 }
348 else
349 {
350 // Set the resume count to 1:
351 // 1 - stop in shell
352 // 2 - then we will stop in our program
353 SetResumeCount(1);
354 }
355
356 const char **argv = GetArguments().GetConstArgumentVector ();
357 if (argv)
358 {
359 for (size_t i=0; argv[i] != NULL; ++i)
360 {
361 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
362 shell_command.Printf(" %s", arg);
363 }
364 }
365 shell_arguments.AppendArgument (shell_command.GetString().c_str());
366
367 m_executable.SetFile(shell_executable, false);
368 m_arguments = shell_arguments;
369 return true;
370 }
371 else
372 {
373 error.SetErrorString ("invalid shell path");
374 }
375 }
376 else
377 {
378 error.SetErrorString ("not launching in shell");
379 }
380 return false;
381}
382
383
Greg Clayton32e0a752011-03-30 18:16:51 +0000384bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000385ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
386{
387 if ((read || write) && fd >= 0 && path && path[0])
388 {
389 m_action = eFileActionOpen;
390 m_fd = fd;
391 if (read && write)
Greg Clayton144f3a92011-11-15 03:53:30 +0000392 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000393 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000394 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000395 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000396 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000397 m_path.assign (path);
398 return true;
399 }
400 else
401 {
402 Clear();
403 }
404 return false;
405}
406
407bool
408ProcessLaunchInfo::FileAction::Close (int fd)
409{
410 Clear();
411 if (fd >= 0)
412 {
413 m_action = eFileActionClose;
414 m_fd = fd;
415 }
416 return m_fd >= 0;
417}
418
419
420bool
421ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
422{
423 Clear();
424 if (fd >= 0 && dup_fd >= 0)
425 {
426 m_action = eFileActionDuplicate;
427 m_fd = fd;
428 m_arg = dup_fd;
429 }
430 return m_fd >= 0;
431}
432
433
434
435bool
436ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
437 const FileAction *info,
438 Log *log,
439 Error& error)
440{
441 if (info == NULL)
442 return false;
443
444 switch (info->m_action)
445 {
446 case eFileActionNone:
447 error.Clear();
448 break;
449
450 case eFileActionClose:
451 if (info->m_fd == -1)
452 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
453 else
454 {
455 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
456 eErrorTypePOSIX);
457 if (log && (error.Fail() || log))
458 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
459 file_actions, info->m_fd);
460 }
461 break;
462
463 case eFileActionDuplicate:
464 if (info->m_fd == -1)
465 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
466 else if (info->m_arg == -1)
467 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
468 else
469 {
470 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
471 eErrorTypePOSIX);
472 if (log && (error.Fail() || log))
473 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
474 file_actions, info->m_fd, info->m_arg);
475 }
476 break;
477
478 case eFileActionOpen:
479 if (info->m_fd == -1)
480 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
481 else
482 {
483 int oflag = info->m_arg;
Greg Clayton144f3a92011-11-15 03:53:30 +0000484
Greg Clayton8b82f082011-04-12 05:54:46 +0000485 mode_t mode = 0;
486
Greg Clayton144f3a92011-11-15 03:53:30 +0000487 if (oflag & O_CREAT)
488 mode = 0640;
489
Greg Clayton8b82f082011-04-12 05:54:46 +0000490 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
491 info->m_fd,
492 info->m_path.c_str(),
493 oflag,
494 mode),
495 eErrorTypePOSIX);
496 if (error.Fail() || log)
497 error.PutToLog(log,
498 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
499 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
500 }
501 break;
502
503 default:
504 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
505 break;
506 }
507 return error.Success();
508}
509
510Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000511ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000512{
513 Error error;
514 char short_option = (char) m_getopt_table[option_idx].val;
515
516 switch (short_option)
517 {
518 case 's': // Stop at program entry point
519 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
520 break;
521
Greg Clayton8b82f082011-04-12 05:54:46 +0000522 case 'i': // STDIN for read only
523 {
524 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000525 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000526 launch_info.AppendFileAction (action);
527 }
528 break;
529
530 case 'o': // Open STDOUT for write only
531 {
532 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000533 if (action.Open (STDOUT_FILENO, option_arg, false, true))
534 launch_info.AppendFileAction (action);
535 }
536 break;
537
538 case 'e': // STDERR for write only
539 {
540 ProcessLaunchInfo::FileAction action;
541 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000542 launch_info.AppendFileAction (action);
543 }
544 break;
545
Greg Clayton9845a8d2012-03-06 04:01:04 +0000546
Greg Clayton8b82f082011-04-12 05:54:46 +0000547 case 'p': // Process plug-in name
548 launch_info.SetProcessPluginName (option_arg);
549 break;
550
551 case 'n': // Disable STDIO
552 {
553 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000554 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000555 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000556 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000557 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000558 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000559 launch_info.AppendFileAction (action);
560 }
561 break;
562
563 case 'w':
564 launch_info.SetWorkingDirectory (option_arg);
565 break;
566
567 case 't': // Open process in new terminal window
568 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
569 break;
570
571 case 'a':
572 launch_info.GetArchitecture().SetTriple (option_arg,
573 m_interpreter.GetPlatform(true).get());
574 break;
575
576 case 'A':
577 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
578 break;
579
Greg Clayton982c9762011-11-03 21:22:33 +0000580 case 'c':
Greg Clayton144f3a92011-11-15 03:53:30 +0000581 if (option_arg && option_arg[0])
582 launch_info.SetShell (option_arg);
583 else
584 launch_info.SetShell ("/bin/bash");
Greg Clayton982c9762011-11-03 21:22:33 +0000585 break;
586
Greg Clayton8b82f082011-04-12 05:54:46 +0000587 case 'v':
588 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
589 break;
590
591 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000592 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000593 break;
594
595 }
596 return error;
597}
598
599OptionDefinition
600ProcessLaunchCommandOptions::g_option_table[] =
601{
602{ 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."},
603{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
604{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
605{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
606{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
607{ LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Greg Clayton144f3a92011-11-15 03:53:30 +0000608{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypePath, "Run the process in a shell (not supported on all platforms)."},
Greg Clayton8b82f082011-04-12 05:54:46 +0000609
610{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
611{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
612{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
613
614{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
615
616{ 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."},
617
618{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
619};
620
621
622
623bool
624ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000625{
626 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
627 return true;
628 const char *match_name = m_match_info.GetName();
629 if (!match_name)
630 return true;
631
632 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
633}
634
635bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000636ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000637{
638 if (!NameMatches (proc_info.GetName()))
639 return false;
640
641 if (m_match_info.ProcessIDIsValid() &&
642 m_match_info.GetProcessID() != proc_info.GetProcessID())
643 return false;
644
645 if (m_match_info.ParentProcessIDIsValid() &&
646 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
647 return false;
648
Greg Clayton8b82f082011-04-12 05:54:46 +0000649 if (m_match_info.UserIDIsValid () &&
650 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000651 return false;
652
Greg Clayton8b82f082011-04-12 05:54:46 +0000653 if (m_match_info.GroupIDIsValid () &&
654 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000655 return false;
656
657 if (m_match_info.EffectiveUserIDIsValid () &&
658 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
659 return false;
660
661 if (m_match_info.EffectiveGroupIDIsValid () &&
662 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
663 return false;
664
665 if (m_match_info.GetArchitecture().IsValid() &&
666 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
667 return false;
668 return true;
669}
670
671bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000672ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000673{
674 if (m_name_match_type != eNameMatchIgnore)
675 return false;
676
677 if (m_match_info.ProcessIDIsValid())
678 return false;
679
680 if (m_match_info.ParentProcessIDIsValid())
681 return false;
682
Greg Clayton8b82f082011-04-12 05:54:46 +0000683 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000684 return false;
685
Greg Clayton8b82f082011-04-12 05:54:46 +0000686 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000687 return false;
688
689 if (m_match_info.EffectiveUserIDIsValid ())
690 return false;
691
692 if (m_match_info.EffectiveGroupIDIsValid ())
693 return false;
694
695 if (m_match_info.GetArchitecture().IsValid())
696 return false;
697
698 if (m_match_all_users)
699 return false;
700
701 return true;
702
703}
704
705void
Greg Clayton8b82f082011-04-12 05:54:46 +0000706ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000707{
708 m_match_info.Clear();
709 m_name_match_type = eNameMatchIgnore;
710 m_match_all_users = false;
711}
Greg Clayton58be07b2011-01-07 06:08:19 +0000712
Greg Claytonc3776bf2012-02-09 06:16:32 +0000713ProcessSP
714Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000716 ProcessSP process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000717 ProcessCreateInstance create_callback = NULL;
718 if (plugin_name)
719 {
720 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
721 if (create_callback)
722 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000723 process_sp = create_callback(target, listener, crash_file_path);
724 if (process_sp)
725 {
726 if (!process_sp->CanDebug(target, true))
727 process_sp.reset();
728 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729 }
730 }
731 else
732 {
Greg Claytonc982c762010-07-09 20:39:50 +0000733 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734 {
Greg Claytonc3776bf2012-02-09 06:16:32 +0000735 process_sp = create_callback(target, listener, crash_file_path);
736 if (process_sp)
737 {
738 if (!process_sp->CanDebug(target, false))
739 process_sp.reset();
740 else
741 break;
742 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 }
744 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000745 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000746}
747
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000748ConstString &
749Process::GetStaticBroadcasterClass ()
750{
751 static ConstString class_name ("lldb.process");
752 return class_name;
753}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000754
755//----------------------------------------------------------------------
756// Process constructor
757//----------------------------------------------------------------------
758Process::Process(Target &target, Listener &listener) :
759 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000760 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Greg Claytonb9556ac2012-01-30 07:41:31 +0000761 ProcessInstanceSettings (GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000762 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000763 m_public_state (eStateUnloaded),
764 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000765 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
766 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000767 m_private_state_listener ("lldb.process.internal_state_listener"),
768 m_private_state_control_wait(),
769 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000770 m_mod_id (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000771 m_thread_index_id (0),
772 m_exit_status (-1),
773 m_exit_string (),
774 m_thread_list (this),
775 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000776 m_image_tokens (),
777 m_listener (listener),
778 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000779 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000780 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000781 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000782 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000783 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000784 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000785 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000786 m_stderr_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000787 m_memory_cache (*this),
788 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000789 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000790 m_next_event_action_ap(),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000791 m_run_lock (),
792 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793{
Caroline Tice1559a462010-09-27 00:30:10 +0000794 UpdateInstanceName();
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000795
796 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000797
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000798 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799 if (log)
800 log->Printf ("%p Process::Process()", this);
801
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000802 SetEventName (eBroadcastBitStateChanged, "state-changed");
803 SetEventName (eBroadcastBitInterrupt, "interrupt");
804 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
805 SetEventName (eBroadcastBitSTDERR, "stderr-available");
806
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000807 listener.StartListeningForEvents (this,
808 eBroadcastBitStateChanged |
809 eBroadcastBitInterrupt |
810 eBroadcastBitSTDOUT |
811 eBroadcastBitSTDERR);
812
813 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
814 eBroadcastBitStateChanged);
815
816 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
817 eBroadcastInternalStateControlStop |
818 eBroadcastInternalStateControlPause |
819 eBroadcastInternalStateControlResume);
820}
821
822//----------------------------------------------------------------------
823// Destructor
824//----------------------------------------------------------------------
825Process::~Process()
826{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000827 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000828 if (log)
829 log->Printf ("%p Process::~Process()", this);
830 StopPrivateStateThread();
831}
832
833void
834Process::Finalize()
835{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000836 switch (GetPrivateState())
837 {
838 case eStateConnected:
839 case eStateAttaching:
840 case eStateLaunching:
841 case eStateStopped:
842 case eStateRunning:
843 case eStateStepping:
844 case eStateCrashed:
845 case eStateSuspended:
846 if (GetShouldDetach())
847 Detach();
848 else
849 Destroy();
850 break;
851
852 case eStateInvalid:
853 case eStateUnloaded:
854 case eStateDetached:
855 case eStateExited:
856 break;
857 }
858
Greg Clayton1ed54f52011-10-01 00:45:15 +0000859 // Clear our broadcaster before we proceed with destroying
860 Broadcaster::Clear();
861
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000862 // Do any cleanup needed prior to being destructed... Subclasses
863 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000864
865 // We need to destroy the loader before the derived Process class gets destroyed
866 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000867 m_dynamic_checkers_ap.reset();
868 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000869 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000870 m_dyld_ap.reset();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000871 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +0000872 std::vector<Notifications> empty_notifications;
873 m_notifications.swap(empty_notifications);
874 m_image_tokens.clear();
875 m_memory_cache.Clear();
876 m_allocated_memory_cache.Clear();
877 m_language_runtimes.clear();
878 m_next_event_action_ap.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000879}
880
881void
882Process::RegisterNotificationCallbacks (const Notifications& callbacks)
883{
884 m_notifications.push_back(callbacks);
885 if (callbacks.initialize != NULL)
886 callbacks.initialize (callbacks.baton, this);
887}
888
889bool
890Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
891{
892 std::vector<Notifications>::iterator pos, end = m_notifications.end();
893 for (pos = m_notifications.begin(); pos != end; ++pos)
894 {
895 if (pos->baton == callbacks.baton &&
896 pos->initialize == callbacks.initialize &&
897 pos->process_state_changed == callbacks.process_state_changed)
898 {
899 m_notifications.erase(pos);
900 return true;
901 }
902 }
903 return false;
904}
905
906void
907Process::SynchronouslyNotifyStateChanged (StateType state)
908{
909 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
910 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
911 {
912 if (notification_pos->process_state_changed)
913 notification_pos->process_state_changed (notification_pos->baton, this, state);
914 }
915}
916
917// FIXME: We need to do some work on events before the general Listener sees them.
918// For instance if we are continuing from a breakpoint, we need to ensure that we do
919// the little "insert real insn, step & stop" trick. But we can't do that when the
920// event is delivered by the broadcaster - since that is done on the thread that is
921// waiting for new events, so if we needed more than one event for our handling, we would
922// stall. So instead we do it when we fetch the event off of the queue.
923//
924
925StateType
926Process::GetNextEvent (EventSP &event_sp)
927{
928 StateType state = eStateInvalid;
929
930 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
931 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
932
933 return state;
934}
935
936
937StateType
938Process::WaitForProcessToStop (const TimeValue *timeout)
939{
Jim Ingham4b536182011-08-09 02:12:22 +0000940 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
941 // We have to actually check each event, and in the case of a stopped event check the restarted flag
942 // on the event.
943 EventSP event_sp;
944 StateType state = GetState();
945 // If we are exited or detached, we won't ever get back to any
946 // other valid state...
947 if (state == eStateDetached || state == eStateExited)
948 return state;
949
950 while (state != eStateInvalid)
951 {
952 state = WaitForStateChangedEvents (timeout, event_sp);
953 switch (state)
954 {
955 case eStateCrashed:
956 case eStateDetached:
957 case eStateExited:
958 case eStateUnloaded:
959 return state;
960 case eStateStopped:
961 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
962 continue;
963 else
964 return state;
965 default:
966 continue;
967 }
968 }
969 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000970}
971
972
973StateType
974Process::WaitForState
975(
976 const TimeValue *timeout,
977 const StateType *match_states, const uint32_t num_match_states
978)
979{
980 EventSP event_sp;
981 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000982 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000983 while (state != eStateInvalid)
984 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000985 // If we are exited or detached, we won't ever get back to any
986 // other valid state...
987 if (state == eStateDetached || state == eStateExited)
988 return state;
989
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000990 state = WaitForStateChangedEvents (timeout, event_sp);
991
992 for (i=0; i<num_match_states; ++i)
993 {
994 if (match_states[i] == state)
995 return state;
996 }
997 }
998 return state;
999}
1000
Jim Ingham30f9b212010-10-11 23:53:14 +00001001bool
1002Process::HijackProcessEvents (Listener *listener)
1003{
1004 if (listener != NULL)
1005 {
1006 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
1007 }
1008 else
1009 return false;
1010}
1011
1012void
1013Process::RestoreProcessEvents ()
1014{
1015 RestoreBroadcaster();
1016}
1017
Jim Ingham0f16e732011-02-08 05:20:59 +00001018bool
1019Process::HijackPrivateProcessEvents (Listener *listener)
1020{
1021 if (listener != NULL)
1022 {
1023 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
1024 }
1025 else
1026 return false;
1027}
1028
1029void
1030Process::RestorePrivateProcessEvents ()
1031{
1032 m_private_state_broadcaster.RestoreBroadcaster();
1033}
1034
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001035StateType
1036Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1037{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001038 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001039
1040 if (log)
1041 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1042
1043 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001044 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1045 this,
1046 eBroadcastBitStateChanged,
1047 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1049
1050 if (log)
1051 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1052 __FUNCTION__,
1053 timeout,
1054 StateAsCString(state));
1055 return state;
1056}
1057
1058Event *
1059Process::PeekAtStateChangedEvents ()
1060{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001061 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062
1063 if (log)
1064 log->Printf ("Process::%s...", __FUNCTION__);
1065
1066 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001067 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1068 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001069 if (log)
1070 {
1071 if (event_ptr)
1072 {
1073 log->Printf ("Process::%s (event_ptr) => %s",
1074 __FUNCTION__,
1075 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1076 }
1077 else
1078 {
1079 log->Printf ("Process::%s no events found",
1080 __FUNCTION__);
1081 }
1082 }
1083 return event_ptr;
1084}
1085
1086StateType
1087Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1088{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001089 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001090
1091 if (log)
1092 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1093
1094 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001095 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1096 &m_private_state_broadcaster,
1097 eBroadcastBitStateChanged,
1098 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1100
1101 // This is a bit of a hack, but when we wait here we could very well return
1102 // to the command-line, and that could disable the log, which would render the
1103 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001105 {
1106 if (state == eStateInvalid)
1107 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1108 else
1109 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1110 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111 return state;
1112}
1113
1114bool
1115Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1116{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001117 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118
1119 if (log)
1120 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1121
1122 if (control_only)
1123 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1124 else
1125 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1126}
1127
1128bool
1129Process::IsRunning () const
1130{
1131 return StateIsRunningState (m_public_state.GetValue());
1132}
1133
1134int
1135Process::GetExitStatus ()
1136{
1137 if (m_public_state.GetValue() == eStateExited)
1138 return m_exit_status;
1139 return -1;
1140}
1141
Greg Clayton85851dd2010-12-04 00:10:17 +00001142
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143const char *
1144Process::GetExitDescription ()
1145{
1146 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1147 return m_exit_string.c_str();
1148 return NULL;
1149}
1150
Greg Clayton6779606a2011-01-22 23:43:18 +00001151bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001152Process::SetExitStatus (int status, const char *cstr)
1153{
Greg Clayton414f5d32011-01-25 02:58:48 +00001154 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1155 if (log)
1156 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1157 status, status,
1158 cstr ? "\"" : "",
1159 cstr ? cstr : "NULL",
1160 cstr ? "\"" : "");
1161
Greg Clayton6779606a2011-01-22 23:43:18 +00001162 // We were already in the exited state
1163 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001164 {
Greg Clayton385d6032011-01-26 23:47:29 +00001165 if (log)
1166 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001167 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001168 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001169
1170 m_exit_status = status;
1171 if (cstr)
1172 m_exit_string = cstr;
1173 else
1174 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175
Greg Clayton6779606a2011-01-22 23:43:18 +00001176 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001177
Greg Clayton6779606a2011-01-22 23:43:18 +00001178 SetPrivateState (eStateExited);
1179 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001180}
1181
1182// This static callback can be used to watch for local child processes on
1183// the current host. The the child process exits, the process will be
1184// found in the global target list (we want to be completely sure that the
1185// lldb_private::Process doesn't go away before we can deliver the signal.
1186bool
Greg Claytone4e45922011-11-16 05:37:56 +00001187Process::SetProcessExitStatus (void *callback_baton,
1188 lldb::pid_t pid,
1189 bool exited,
1190 int signo, // Zero for no signal
1191 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192)
1193{
Greg Claytone4e45922011-11-16 05:37:56 +00001194 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1195 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00001196 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001197 callback_baton,
1198 pid,
1199 exited,
1200 signo,
1201 exit_status);
1202
1203 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001204 {
Greg Clayton66111032010-06-23 01:19:29 +00001205 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001206 if (target_sp)
1207 {
1208 ProcessSP process_sp (target_sp->GetProcessSP());
1209 if (process_sp)
1210 {
1211 const char *signal_cstr = NULL;
1212 if (signo)
1213 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1214
1215 process_sp->SetExitStatus (exit_status, signal_cstr);
1216 }
1217 }
1218 return true;
1219 }
1220 return false;
1221}
1222
1223
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001224void
1225Process::UpdateThreadListIfNeeded ()
1226{
1227 const uint32_t stop_id = GetStopID();
1228 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1229 {
Greg Clayton2637f822011-11-17 01:23:07 +00001230 const StateType state = GetPrivateState();
1231 if (StateIsStoppedState (state, true))
1232 {
1233 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001234 // m_thread_list does have its own mutex, but we need to
1235 // hold onto the mutex between the call to UpdateThreadList(...)
1236 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton2637f822011-11-17 01:23:07 +00001237 ThreadList new_thread_list(this);
1238 // Always update the thread list with the protocol specific
1239 // thread list
1240 UpdateThreadList (m_thread_list, new_thread_list);
1241 OperatingSystem *os = GetOperatingSystem ();
1242 if (os)
1243 os->UpdateThreadList (m_thread_list, new_thread_list);
1244 m_thread_list.Update (new_thread_list);
1245 m_thread_list.SetStopID (stop_id);
1246 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001247 }
1248}
1249
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001250uint32_t
1251Process::GetNextThreadIndexID ()
1252{
1253 return ++m_thread_index_id;
1254}
1255
1256StateType
1257Process::GetState()
1258{
1259 // If any other threads access this we will need a mutex for it
1260 return m_public_state.GetValue ();
1261}
1262
1263void
1264Process::SetPublicState (StateType new_state)
1265{
Greg Clayton414f5d32011-01-25 02:58:48 +00001266 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001267 if (log)
1268 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001269 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001270 m_public_state.SetValue (new_state);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001271 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1272 {
1273 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1274 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1275 if (old_state_is_stopped != new_state_is_stopped)
1276 {
1277 if (new_state_is_stopped)
1278 {
1279 if (log)
1280 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1281 m_run_lock.WriteUnlock();
1282 }
1283 else
1284 {
1285 if (log)
1286 log->Printf("Process::SetPublicState (%s) -- locking run lock", StateAsCString(new_state));
1287 m_run_lock.WriteLock();
1288 }
1289 }
1290 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001291}
1292
1293StateType
1294Process::GetPrivateState ()
1295{
1296 return m_private_state.GetValue();
1297}
1298
1299void
1300Process::SetPrivateState (StateType new_state)
1301{
Greg Clayton414f5d32011-01-25 02:58:48 +00001302 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001303 bool state_changed = false;
1304
1305 if (log)
1306 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1307
1308 Mutex::Locker locker(m_private_state.GetMutex());
1309
1310 const StateType old_state = m_private_state.GetValueNoLock ();
1311 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001312 // This code is left commented out in case we ever need to control
1313 // the private process state with another run lock. Right now it doesn't
1314 // seem like we need to do this, but if we ever do, we can uncomment and
1315 // use this code.
1316// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1317// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1318// if (old_state_is_stopped != new_state_is_stopped)
1319// {
1320// if (new_state_is_stopped)
1321// m_private_run_lock.WriteUnlock();
1322// else
1323// m_private_run_lock.WriteLock();
1324// }
1325
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001326 if (state_changed)
1327 {
1328 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001329 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001330 {
Jim Ingham4b536182011-08-09 02:12:22 +00001331 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001332 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001333 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001334 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001335 }
1336 // Use our target to get a shared pointer to ourselves...
1337 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1338 }
1339 else
1340 {
1341 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001342 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001343 }
1344}
1345
Jim Ingham0faa43f2011-11-08 03:00:11 +00001346void
1347Process::SetRunningUserExpression (bool on)
1348{
1349 m_mod_id.SetRunningUserExpression (on);
1350}
1351
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001352addr_t
1353Process::GetImageInfoAddress()
1354{
1355 return LLDB_INVALID_ADDRESS;
1356}
1357
Greg Clayton8f343b02010-11-04 01:54:29 +00001358//----------------------------------------------------------------------
1359// LoadImage
1360//
1361// This function provides a default implementation that works for most
1362// unix variants. Any Process subclasses that need to do shared library
1363// loading differently should override LoadImage and UnloadImage and
1364// do what is needed.
1365//----------------------------------------------------------------------
1366uint32_t
1367Process::LoadImage (const FileSpec &image_spec, Error &error)
1368{
1369 DynamicLoader *loader = GetDynamicLoader();
1370 if (loader)
1371 {
1372 error = loader->CanLoadImage();
1373 if (error.Fail())
1374 return LLDB_INVALID_IMAGE_TOKEN;
1375 }
1376
1377 if (error.Success())
1378 {
1379 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001380
1381 if (thread_sp)
1382 {
1383 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1384
1385 if (frame_sp)
1386 {
1387 ExecutionContext exe_ctx;
1388 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001389 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001390 StreamString expr;
1391 char path[PATH_MAX];
1392 image_spec.GetPath(path, sizeof(path));
1393 expr.Printf("dlopen (\"%s\", 2)", path);
1394 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001395 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001396 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chene92aa432011-09-09 00:01:43 +00001397 error = result_valobj_sp->GetError();
1398 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001399 {
1400 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001401 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001402 {
1403 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1404 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1405 {
1406 uint32_t image_token = m_image_tokens.size();
1407 m_image_tokens.push_back (image_ptr);
1408 return image_token;
1409 }
1410 }
1411 }
1412 }
1413 }
1414 }
1415 return LLDB_INVALID_IMAGE_TOKEN;
1416}
1417
1418//----------------------------------------------------------------------
1419// UnloadImage
1420//
1421// This function provides a default implementation that works for most
1422// unix variants. Any Process subclasses that need to do shared library
1423// loading differently should override LoadImage and UnloadImage and
1424// do what is needed.
1425//----------------------------------------------------------------------
1426Error
1427Process::UnloadImage (uint32_t image_token)
1428{
1429 Error error;
1430 if (image_token < m_image_tokens.size())
1431 {
1432 const addr_t image_addr = m_image_tokens[image_token];
1433 if (image_addr == LLDB_INVALID_ADDRESS)
1434 {
1435 error.SetErrorString("image already unloaded");
1436 }
1437 else
1438 {
1439 DynamicLoader *loader = GetDynamicLoader();
1440 if (loader)
1441 error = loader->CanLoadImage();
1442
1443 if (error.Success())
1444 {
1445 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001446
1447 if (thread_sp)
1448 {
1449 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1450
1451 if (frame_sp)
1452 {
1453 ExecutionContext exe_ctx;
1454 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001455 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001456 StreamString expr;
1457 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1458 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001459 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001460 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +00001461 if (result_valobj_sp->GetError().Success())
1462 {
1463 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001464 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001465 {
1466 if (scalar.UInt(1))
1467 {
1468 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1469 }
1470 else
1471 {
1472 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1473 }
1474 }
1475 }
1476 else
1477 {
1478 error = result_valobj_sp->GetError();
1479 }
1480 }
1481 }
1482 }
1483 }
1484 }
1485 else
1486 {
1487 error.SetErrorString("invalid image token");
1488 }
1489 return error;
1490}
1491
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001492const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001493Process::GetABI()
1494{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001495 if (!m_abi_sp)
1496 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1497 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498}
1499
Jim Ingham22777012010-09-23 02:01:19 +00001500LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001501Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001502{
1503 LanguageRuntimeCollection::iterator pos;
1504 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001505 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001506 {
Jim Inghamab175242012-03-10 00:22:19 +00001507 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001508
Jim Inghamab175242012-03-10 00:22:19 +00001509 m_language_runtimes[language] = runtime_sp;
1510 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001511 }
1512 else
1513 return (*pos).second.get();
1514}
1515
1516CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001517Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001518{
Jim Inghamab175242012-03-10 00:22:19 +00001519 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001520 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1521 return static_cast<CPPLanguageRuntime *> (runtime);
1522 return NULL;
1523}
1524
1525ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001526Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001527{
Jim Inghamab175242012-03-10 00:22:19 +00001528 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001529 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1530 return static_cast<ObjCLanguageRuntime *> (runtime);
1531 return NULL;
1532}
1533
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001534BreakpointSiteList &
1535Process::GetBreakpointSiteList()
1536{
1537 return m_breakpoint_site_list;
1538}
1539
1540const BreakpointSiteList &
1541Process::GetBreakpointSiteList() const
1542{
1543 return m_breakpoint_site_list;
1544}
1545
1546
1547void
1548Process::DisableAllBreakpointSites ()
1549{
1550 m_breakpoint_site_list.SetEnabledForAll (false);
1551}
1552
1553Error
1554Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1555{
1556 Error error (DisableBreakpointSiteByID (break_id));
1557
1558 if (error.Success())
1559 m_breakpoint_site_list.Remove(break_id);
1560
1561 return error;
1562}
1563
1564Error
1565Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1566{
1567 Error error;
1568 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1569 if (bp_site_sp)
1570 {
1571 if (bp_site_sp->IsEnabled())
1572 error = DisableBreakpoint (bp_site_sp.get());
1573 }
1574 else
1575 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001576 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001577 }
1578
1579 return error;
1580}
1581
1582Error
1583Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1584{
1585 Error error;
1586 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1587 if (bp_site_sp)
1588 {
1589 if (!bp_site_sp->IsEnabled())
1590 error = EnableBreakpoint (bp_site_sp.get());
1591 }
1592 else
1593 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001594 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001595 }
1596 return error;
1597}
1598
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001599lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001600Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001601{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001602 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001603 if (load_addr != LLDB_INVALID_ADDRESS)
1604 {
1605 BreakpointSiteSP bp_site_sp;
1606
1607 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1608 // create a new breakpoint site and add it.
1609
1610 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1611
1612 if (bp_site_sp)
1613 {
1614 bp_site_sp->AddOwner (owner);
1615 owner->SetBreakpointSite (bp_site_sp);
1616 return bp_site_sp->GetID();
1617 }
1618 else
1619 {
1620 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1621 if (bp_site_sp)
1622 {
1623 if (EnableBreakpoint (bp_site_sp.get()).Success())
1624 {
1625 owner->SetBreakpointSite (bp_site_sp);
1626 return m_breakpoint_site_list.Add (bp_site_sp);
1627 }
1628 }
1629 }
1630 }
1631 // We failed to enable the breakpoint
1632 return LLDB_INVALID_BREAK_ID;
1633
1634}
1635
1636void
1637Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1638{
1639 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1640 if (num_owners == 0)
1641 {
1642 DisableBreakpoint(bp_site_sp.get());
1643 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1644 }
1645}
1646
1647
1648size_t
1649Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1650{
1651 size_t bytes_removed = 0;
1652 addr_t intersect_addr;
1653 size_t intersect_size;
1654 size_t opcode_offset;
1655 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001656 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001657 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001658
Jim Ingham20c77192011-06-29 19:42:28 +00001659 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001660 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001661 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001662 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001663 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001665 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001666 {
1667 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1668 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001669 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001670 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001671 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001672 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001673 }
1674 }
1675 }
1676 return bytes_removed;
1677}
1678
1679
Greg Claytonded470d2011-03-19 01:12:21 +00001680
1681size_t
1682Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1683{
1684 PlatformSP platform_sp (m_target.GetPlatform());
1685 if (platform_sp)
1686 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1687 return 0;
1688}
1689
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001690Error
1691Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1692{
1693 Error error;
1694 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001695 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001696 const addr_t bp_addr = bp_site->GetLoadAddress();
1697 if (log)
1698 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1699 if (bp_site->IsEnabled())
1700 {
1701 if (log)
1702 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1703 return error;
1704 }
1705
1706 if (bp_addr == LLDB_INVALID_ADDRESS)
1707 {
1708 error.SetErrorString("BreakpointSite contains an invalid load address.");
1709 return error;
1710 }
1711 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1712 // trap for the breakpoint site
1713 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1714
1715 if (bp_opcode_size == 0)
1716 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001717 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001718 }
1719 else
1720 {
1721 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1722
1723 if (bp_opcode_bytes == NULL)
1724 {
1725 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1726 return error;
1727 }
1728
1729 // Save the original opcode by reading it
1730 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1731 {
1732 // Write a software breakpoint in place of the original opcode
1733 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1734 {
1735 uint8_t verify_bp_opcode_bytes[64];
1736 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1737 {
1738 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1739 {
1740 bp_site->SetEnabled(true);
1741 bp_site->SetType (BreakpointSite::eSoftware);
1742 if (log)
1743 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1744 bp_site->GetID(),
1745 (uint64_t)bp_addr);
1746 }
1747 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001748 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001749 }
1750 else
1751 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1752 }
1753 else
1754 error.SetErrorString("Unable to write breakpoint trap to memory.");
1755 }
1756 else
1757 error.SetErrorString("Unable to read memory at breakpoint address.");
1758 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001759 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001760 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1761 bp_site->GetID(),
1762 (uint64_t)bp_addr,
1763 error.AsCString());
1764 return error;
1765}
1766
1767Error
1768Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1769{
1770 Error error;
1771 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001772 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001773 addr_t bp_addr = bp_site->GetLoadAddress();
1774 lldb::user_id_t breakID = bp_site->GetID();
1775 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001776 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001777
1778 if (bp_site->IsHardware())
1779 {
1780 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1781 }
1782 else if (bp_site->IsEnabled())
1783 {
1784 const size_t break_op_size = bp_site->GetByteSize();
1785 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1786 if (break_op_size > 0)
1787 {
1788 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001789 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001790 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001791 bool break_op_found = false;
1792
1793 // Read the breakpoint opcode
1794 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1795 {
1796 bool verify = false;
1797 // Make sure we have the a breakpoint opcode exists at this address
1798 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1799 {
1800 break_op_found = true;
1801 // We found a valid breakpoint opcode at this address, now restore
1802 // the saved opcode.
1803 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1804 {
1805 verify = true;
1806 }
1807 else
1808 error.SetErrorString("Memory write failed when restoring original opcode.");
1809 }
1810 else
1811 {
1812 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1813 // Set verify to true and so we can check if the original opcode has already been restored
1814 verify = true;
1815 }
1816
1817 if (verify)
1818 {
Greg Claytonc982c762010-07-09 20:39:50 +00001819 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001820 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001821 // Verify that our original opcode made it back to the inferior
1822 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1823 {
1824 // compare the memory we just read with the original opcode
1825 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1826 {
1827 // SUCCESS
1828 bp_site->SetEnabled(false);
1829 if (log)
1830 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1831 return error;
1832 }
1833 else
1834 {
1835 if (break_op_found)
1836 error.SetErrorString("Failed to restore original opcode.");
1837 }
1838 }
1839 else
1840 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1841 }
1842 }
1843 else
1844 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1845 }
1846 }
1847 else
1848 {
1849 if (log)
1850 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1851 return error;
1852 }
1853
1854 if (log)
1855 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1856 bp_site->GetID(),
1857 (uint64_t)bp_addr,
1858 error.AsCString());
1859 return error;
1860
1861}
1862
Greg Clayton58be07b2011-01-07 06:08:19 +00001863// Comment out line below to disable memory caching
1864#define ENABLE_MEMORY_CACHING
1865// Uncomment to verify memory caching works after making changes to caching code
1866//#define VERIFY_MEMORY_READS
1867
1868#if defined (ENABLE_MEMORY_CACHING)
1869
1870#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001871
1872size_t
1873Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1874{
Greg Clayton58be07b2011-01-07 06:08:19 +00001875 // Memory caching is enabled, with debug verification
1876 if (buf && size)
1877 {
1878 // Uncomment the line below to make sure memory caching is working.
1879 // I ran this through the test suite and got no assertions, so I am
1880 // pretty confident this is working well. If any changes are made to
1881 // memory caching, uncomment the line below and test your changes!
1882
1883 // Verify all memory reads by using the cache first, then redundantly
1884 // reading the same memory from the inferior and comparing to make sure
1885 // everything is exactly the same.
1886 std::string verify_buf (size, '\0');
1887 assert (verify_buf.size() == size);
1888 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1889 Error verify_error;
1890 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1891 assert (cache_bytes_read == verify_bytes_read);
1892 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1893 assert (verify_error.Success() == error.Success());
1894 return cache_bytes_read;
1895 }
1896 return 0;
1897}
1898
1899#else // #if defined (VERIFY_MEMORY_READS)
1900
1901size_t
1902Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1903{
1904 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001905 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001906}
1907
1908#endif // #else for #if defined (VERIFY_MEMORY_READS)
1909
1910#else // #if defined (ENABLE_MEMORY_CACHING)
1911
1912size_t
1913Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1914{
1915 // Memory caching is disabled
1916 return ReadMemoryFromInferior (addr, buf, size, error);
1917}
1918
1919#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1920
1921
1922size_t
Greg Claytone91b7952011-12-15 03:14:23 +00001923Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00001924{
1925 size_t total_cstr_len = 0;
1926 if (dst && dst_max_len)
1927 {
Greg Claytone91b7952011-12-15 03:14:23 +00001928 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00001929 // NULL out everything just to be safe
1930 memset (dst, 0, dst_max_len);
1931 Error error;
1932 addr_t curr_addr = addr;
1933 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1934 size_t bytes_left = dst_max_len - 1;
1935 char *curr_dst = dst;
1936
1937 while (bytes_left > 0)
1938 {
1939 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1940 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1941 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1942
1943 if (bytes_read == 0)
1944 {
Greg Claytone91b7952011-12-15 03:14:23 +00001945 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001946 dst[total_cstr_len] = '\0';
1947 break;
1948 }
1949 const size_t len = strlen(curr_dst);
1950
1951 total_cstr_len += len;
1952
1953 if (len < bytes_to_read)
1954 break;
1955
1956 curr_dst += bytes_read;
1957 curr_addr += bytes_read;
1958 bytes_left -= bytes_read;
1959 }
1960 }
Greg Claytone91b7952011-12-15 03:14:23 +00001961 else
1962 {
1963 if (dst == NULL)
1964 result_error.SetErrorString("invalid arguments");
1965 else
1966 result_error.Clear();
1967 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001968 return total_cstr_len;
1969}
1970
1971size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00001972Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1973{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001974 if (buf == NULL || size == 0)
1975 return 0;
1976
1977 size_t bytes_read = 0;
1978 uint8_t *bytes = (uint8_t *)buf;
1979
1980 while (bytes_read < size)
1981 {
1982 const size_t curr_size = size - bytes_read;
1983 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1984 bytes + bytes_read,
1985 curr_size,
1986 error);
1987 bytes_read += curr_bytes_read;
1988 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1989 break;
1990 }
1991
1992 // Replace any software breakpoint opcodes that fall into this range back
1993 // into "buf" before we return
1994 if (bytes_read > 0)
1995 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1996 return bytes_read;
1997}
1998
Greg Clayton58a4c462010-12-16 20:01:20 +00001999uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002000Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002001{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002002 Scalar scalar;
2003 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2004 return scalar.ULongLong(fail_value);
2005 return fail_value;
2006}
2007
2008addr_t
2009Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2010{
2011 Scalar scalar;
2012 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2013 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2014 return LLDB_INVALID_ADDRESS;
2015}
2016
2017
2018bool
2019Process::WritePointerToMemory (lldb::addr_t vm_addr,
2020 lldb::addr_t ptr_value,
2021 Error &error)
2022{
2023 Scalar scalar;
2024 const uint32_t addr_byte_size = GetAddressByteSize();
2025 if (addr_byte_size <= 4)
2026 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002027 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002028 scalar = ptr_value;
2029 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002030}
2031
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002032size_t
2033Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2034{
2035 size_t bytes_written = 0;
2036 const uint8_t *bytes = (const uint8_t *)buf;
2037
2038 while (bytes_written < size)
2039 {
2040 const size_t curr_size = size - bytes_written;
2041 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2042 bytes + bytes_written,
2043 curr_size,
2044 error);
2045 bytes_written += curr_bytes_written;
2046 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2047 break;
2048 }
2049 return bytes_written;
2050}
2051
2052size_t
2053Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2054{
Greg Clayton58be07b2011-01-07 06:08:19 +00002055#if defined (ENABLE_MEMORY_CACHING)
2056 m_memory_cache.Flush (addr, size);
2057#endif
2058
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002059 if (buf == NULL || size == 0)
2060 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002061
Jim Ingham4b536182011-08-09 02:12:22 +00002062 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002063
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002064 // We need to write any data that would go where any current software traps
2065 // (enabled software breakpoints) any software traps (breakpoints) that we
2066 // may have placed in our tasks memory.
2067
2068 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2069 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2070
2071 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002072 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002073
2074 BreakpointSiteList::collection::const_iterator pos;
2075 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002076 addr_t intersect_addr = 0;
2077 size_t intersect_size = 0;
2078 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002079 const uint8_t *ubuf = (const uint8_t *)buf;
2080
2081 for (pos = iter; pos != end; ++pos)
2082 {
2083 BreakpointSiteSP bp;
2084 bp = pos->second;
2085
2086 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2087 assert(addr <= intersect_addr && intersect_addr < addr + size);
2088 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2089 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2090
2091 // Check for bytes before this breakpoint
2092 const addr_t curr_addr = addr + bytes_written;
2093 if (intersect_addr > curr_addr)
2094 {
2095 // There are some bytes before this breakpoint that we need to
2096 // just write to memory
2097 size_t curr_size = intersect_addr - curr_addr;
2098 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2099 ubuf + bytes_written,
2100 curr_size,
2101 error);
2102 bytes_written += curr_bytes_written;
2103 if (curr_bytes_written != curr_size)
2104 {
2105 // We weren't able to write all of the requested bytes, we
2106 // are done looping and will return the number of bytes that
2107 // we have written so far.
2108 break;
2109 }
2110 }
2111
2112 // Now write any bytes that would cover up any software breakpoints
2113 // directly into the breakpoint opcode buffer
2114 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2115 bytes_written += intersect_size;
2116 }
2117
2118 // Write any remaining bytes after the last breakpoint if we have any left
2119 if (bytes_written < size)
2120 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2121 ubuf + bytes_written,
2122 size - bytes_written,
2123 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002124
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002125 return bytes_written;
2126}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002127
2128size_t
2129Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2130{
2131 if (byte_size == UINT32_MAX)
2132 byte_size = scalar.GetByteSize();
2133 if (byte_size > 0)
2134 {
2135 uint8_t buf[32];
2136 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2137 if (mem_size > 0)
2138 return WriteMemory(addr, buf, mem_size, error);
2139 else
2140 error.SetErrorString ("failed to get scalar as memory data");
2141 }
2142 else
2143 {
2144 error.SetErrorString ("invalid scalar value");
2145 }
2146 return 0;
2147}
2148
2149size_t
2150Process::ReadScalarIntegerFromMemory (addr_t addr,
2151 uint32_t byte_size,
2152 bool is_signed,
2153 Scalar &scalar,
2154 Error &error)
2155{
2156 uint64_t uval;
2157
2158 if (byte_size <= sizeof(uval))
2159 {
2160 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2161 if (bytes_read == byte_size)
2162 {
2163 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2164 uint32_t offset = 0;
2165 if (byte_size <= 4)
2166 scalar = data.GetMaxU32 (&offset, byte_size);
2167 else
2168 scalar = data.GetMaxU64 (&offset, byte_size);
2169
2170 if (is_signed)
2171 scalar.SignExtend(byte_size * 8);
2172 return bytes_read;
2173 }
2174 }
2175 else
2176 {
2177 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2178 }
2179 return 0;
2180}
2181
Greg Claytond495c532011-05-17 03:37:42 +00002182#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002183addr_t
2184Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2185{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002186 if (GetPrivateState() != eStateStopped)
2187 return LLDB_INVALID_ADDRESS;
2188
Greg Claytond495c532011-05-17 03:37:42 +00002189#if defined (USE_ALLOCATE_MEMORY_CACHE)
2190 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2191#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002192 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2193 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2194 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002195 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002196 size,
Greg Claytond495c532011-05-17 03:37:42 +00002197 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002198 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002199 m_mod_id.GetStopID(),
2200 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002201 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002202#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002203}
2204
Sean Callanan90539452011-09-20 23:01:51 +00002205bool
2206Process::CanJIT ()
2207{
Sean Callanana7b443a2012-02-14 22:50:38 +00002208 if (m_can_jit == eCanJITDontKnow)
2209 {
2210 Error err;
2211
2212 uint64_t allocated_memory = AllocateMemory(8,
2213 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2214 err);
2215
2216 if (err.Success())
2217 m_can_jit = eCanJITYes;
2218 else
2219 m_can_jit = eCanJITNo;
2220
2221 DeallocateMemory (allocated_memory);
2222 }
2223
Sean Callanan90539452011-09-20 23:01:51 +00002224 return m_can_jit == eCanJITYes;
2225}
2226
2227void
2228Process::SetCanJIT (bool can_jit)
2229{
2230 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2231}
2232
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002233Error
2234Process::DeallocateMemory (addr_t ptr)
2235{
Greg Claytond495c532011-05-17 03:37:42 +00002236 Error error;
2237#if defined (USE_ALLOCATE_MEMORY_CACHE)
2238 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2239 {
2240 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2241 }
2242#else
2243 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002244
2245 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2246 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002247 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002248 ptr,
2249 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002250 m_mod_id.GetStopID(),
2251 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002252#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002253 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254}
2255
Greg Claytonc9660542012-02-05 02:38:54 +00002256ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002257Process::ReadModuleFromMemory (const FileSpec& file_spec,
2258 lldb::addr_t header_addr,
2259 bool add_image_to_target,
2260 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002261{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002262 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002263 if (module_sp)
2264 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002265 Error error;
2266 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2267 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002268 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002269 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002270 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002271 m_target.GetImages().Append(module_sp);
2272 if (load_sections_in_target)
2273 {
2274 bool changed = false;
2275 module_sp->SetLoadAddress (m_target, 0, changed);
2276 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002277 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002278 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002279 }
Greg Claytonc9660542012-02-05 02:38:54 +00002280 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002281 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002282}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283
2284Error
Johnny Chen01a67862011-10-14 00:42:25 +00002285Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002286{
2287 Error error;
2288 error.SetErrorString("watchpoints are not supported");
2289 return error;
2290}
2291
2292Error
Johnny Chen01a67862011-10-14 00:42:25 +00002293Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002294{
2295 Error error;
2296 error.SetErrorString("watchpoints are not supported");
2297 return error;
2298}
2299
2300StateType
2301Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2302{
2303 StateType state;
2304 // Now wait for the process to launch and return control to us, and then
2305 // call DidLaunch:
2306 while (1)
2307 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002308 event_sp.reset();
2309 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2310
Greg Clayton2637f822011-11-17 01:23:07 +00002311 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002312 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002313
2314 // If state is invalid, then we timed out
2315 if (state == eStateInvalid)
2316 break;
2317
2318 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002319 HandlePrivateEvent (event_sp);
2320 }
2321 return state;
2322}
2323
2324Error
Greg Clayton982c9762011-11-03 21:22:33 +00002325Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326{
2327 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002328 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002329 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002330 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002331 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002332
Greg Claytonaa149cb2011-08-11 02:48:45 +00002333 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002334 if (exe_module)
2335 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002336 char local_exec_file_path[PATH_MAX];
2337 char platform_exec_file_path[PATH_MAX];
2338 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2339 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002340 if (exe_module->GetFileSpec().Exists())
2341 {
Greg Clayton71337622011-02-24 22:24:29 +00002342 if (PrivateStateThreadIsValid ())
2343 PausePrivateStateThread ();
2344
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002345 error = WillLaunch (exe_module);
2346 if (error.Success())
2347 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002348 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002349 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002350
2351 // Now launch using these arguments.
Greg Clayton982c9762011-11-03 21:22:33 +00002352 error = DoLaunch (exe_module, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002353
2354 if (error.Fail())
2355 {
2356 if (GetID() != LLDB_INVALID_PROCESS_ID)
2357 {
2358 SetID (LLDB_INVALID_PROCESS_ID);
2359 const char *error_string = error.AsCString();
2360 if (error_string == NULL)
2361 error_string = "launch failed";
2362 SetExitStatus (-1, error_string);
2363 }
2364 }
2365 else
2366 {
2367 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002368 TimeValue timeout_time;
2369 timeout_time = TimeValue::Now();
2370 timeout_time.OffsetWithSeconds(10);
2371 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002372
Greg Clayton1a38ea72011-06-22 01:42:17 +00002373 if (state == eStateInvalid || event_sp.get() == NULL)
2374 {
2375 // We were able to launch the process, but we failed to
2376 // catch the initial stop.
2377 SetExitStatus (0, "failed to catch stop after launch");
2378 Destroy();
2379 }
2380 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002381 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002382
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383 DidLaunch ();
2384
Greg Claytonc859e2d2012-02-13 23:10:39 +00002385 DynamicLoader *dyld = GetDynamicLoader ();
2386 if (dyld)
2387 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002388
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002389 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002390 // This delays passing the stopped event to listeners till DidLaunch gets
2391 // a chance to complete...
2392 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002393
2394 if (PrivateStateThreadIsValid ())
2395 ResumePrivateStateThread ();
2396 else
2397 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002398 }
2399 else if (state == eStateExited)
2400 {
2401 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2402 // not likely to work, and return an invalid pid.
2403 HandlePrivateEvent (event_sp);
2404 }
2405 }
2406 }
2407 }
2408 else
2409 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002410 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002411 }
2412 }
2413 return error;
2414}
2415
Greg Claytonc3776bf2012-02-09 06:16:32 +00002416
2417Error
2418Process::LoadCore ()
2419{
2420 Error error = DoLoadCore();
2421 if (error.Success())
2422 {
2423 if (PrivateStateThreadIsValid ())
2424 ResumePrivateStateThread ();
2425 else
2426 StartPrivateStateThread ();
2427
Greg Claytonc859e2d2012-02-13 23:10:39 +00002428 DynamicLoader *dyld = GetDynamicLoader ();
2429 if (dyld)
2430 dyld->DidAttach();
2431
2432 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002433 // We successfully loaded a core file, now pretend we stopped so we can
2434 // show all of the threads in the core file and explore the crashed
2435 // state.
2436 SetPrivateState (eStateStopped);
2437
2438 }
2439 return error;
2440}
2441
Greg Claytonc859e2d2012-02-13 23:10:39 +00002442DynamicLoader *
2443Process::GetDynamicLoader ()
2444{
2445 if (m_dyld_ap.get() == NULL)
2446 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2447 return m_dyld_ap.get();
2448}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002449
2450
Jim Inghambb3a2832011-01-29 01:49:25 +00002451Process::NextEventAction::EventActionResult
2452Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002453{
Jim Inghambb3a2832011-01-29 01:49:25 +00002454 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2455 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002456 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002457 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002458 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002459 return eEventActionRetry;
2460
2461 case eStateStopped:
2462 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002463 {
2464 // During attach, prior to sending the eStateStopped event,
2465 // lldb_private::Process subclasses must set the process must set
2466 // the new process ID.
2467 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2468 if (m_exec_count > 0)
2469 {
2470 --m_exec_count;
2471 m_process->Resume();
2472 return eEventActionRetry;
2473 }
2474 else
2475 {
2476 m_process->CompleteAttach ();
2477 return eEventActionSuccess;
2478 }
2479 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002480 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002481
Greg Clayton513c26c2011-01-29 07:10:55 +00002482 default:
2483 case eStateExited:
2484 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002485 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002486 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002487
2488 m_exit_string.assign ("No valid Process");
2489 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002490}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002491
Jim Inghambb3a2832011-01-29 01:49:25 +00002492Process::NextEventAction::EventActionResult
2493Process::AttachCompletionHandler::HandleBeingInterrupted()
2494{
2495 return eEventActionSuccess;
2496}
2497
2498const char *
2499Process::AttachCompletionHandler::GetExitString ()
2500{
2501 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002502}
2503
2504Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002505Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002506{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002507 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002508 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002509 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002510 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002511
Greg Clayton144f3a92011-11-15 03:53:30 +00002512 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002513 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002514 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002515 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002516 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002517
Greg Clayton144f3a92011-11-15 03:53:30 +00002518 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002519 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002520 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2521
2522 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002523 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002524 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2525 if (error.Success())
2526 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002527 m_should_detach = true;
2528
Greg Clayton144f3a92011-11-15 03:53:30 +00002529 SetPublicState (eStateAttaching);
Han Ming Ong84647042012-02-25 01:07:38 +00002530 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002531 if (error.Fail())
2532 {
2533 if (GetID() != LLDB_INVALID_PROCESS_ID)
2534 {
2535 SetID (LLDB_INVALID_PROCESS_ID);
2536 if (error.AsCString() == NULL)
2537 error.SetErrorString("attach failed");
2538
2539 SetExitStatus(-1, error.AsCString());
2540 }
2541 }
2542 else
2543 {
2544 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2545 StartPrivateStateThread();
2546 }
2547 return error;
2548 }
Greg Claytone996fd32011-03-08 22:40:15 +00002549 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002550 else
Greg Claytone996fd32011-03-08 22:40:15 +00002551 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002552 ProcessInstanceInfoList process_infos;
2553 PlatformSP platform_sp (m_target.GetPlatform ());
2554
2555 if (platform_sp)
2556 {
2557 ProcessInstanceInfoMatch match_info;
2558 match_info.GetProcessInfo() = attach_info;
2559 match_info.SetNameMatchType (eNameMatchEquals);
2560 platform_sp->FindProcesses (match_info, process_infos);
2561 const uint32_t num_matches = process_infos.GetSize();
2562 if (num_matches == 1)
2563 {
2564 attach_pid = process_infos.GetProcessIDAtIndex(0);
2565 // Fall through and attach using the above process ID
2566 }
2567 else
2568 {
2569 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2570 if (num_matches > 1)
2571 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2572 else
2573 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2574 }
2575 }
2576 else
2577 {
2578 error.SetErrorString ("invalid platform, can't find processes by name");
2579 return error;
2580 }
Greg Claytone996fd32011-03-08 22:40:15 +00002581 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002582 }
2583 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002584 {
2585 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002586 }
2587 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002588
2589 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002590 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002591 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002592 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002593 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002594 m_should_detach = true;
Greg Claytone996fd32011-03-08 22:40:15 +00002595 SetPublicState (eStateAttaching);
Greg Clayton144f3a92011-11-15 03:53:30 +00002596
Han Ming Ong84647042012-02-25 01:07:38 +00002597 error = DoAttachToProcessWithID (attach_pid, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002598 if (error.Success())
2599 {
2600
2601 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2602 StartPrivateStateThread();
2603 }
2604 else
Greg Claytone996fd32011-03-08 22:40:15 +00002605 {
2606 if (GetID() != LLDB_INVALID_PROCESS_ID)
2607 {
2608 SetID (LLDB_INVALID_PROCESS_ID);
2609 const char *error_string = error.AsCString();
2610 if (error_string == NULL)
2611 error_string = "attach failed";
2612
2613 SetExitStatus(-1, error_string);
2614 }
2615 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002616 }
2617 }
2618 return error;
2619}
2620
Greg Clayton144f3a92011-11-15 03:53:30 +00002621//Error
2622//Process::Attach (const char *process_name, bool wait_for_launch)
2623//{
2624// m_abi_sp.reset();
2625// m_process_input_reader.reset();
2626//
2627// // Find the process and its architecture. Make sure it matches the architecture
2628// // of the current Target, and if not adjust it.
2629// Error error;
2630//
2631// if (!wait_for_launch)
2632// {
2633// ProcessInstanceInfoList process_infos;
2634// PlatformSP platform_sp (m_target.GetPlatform ());
2635// assert (platform_sp.get());
2636//
2637// if (platform_sp)
2638// {
2639// ProcessInstanceInfoMatch match_info;
2640// match_info.GetProcessInfo().SetName(process_name);
2641// match_info.SetNameMatchType (eNameMatchEquals);
2642// platform_sp->FindProcesses (match_info, process_infos);
2643// if (process_infos.GetSize() > 1)
2644// {
2645// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2646// }
2647// else if (process_infos.GetSize() == 0)
2648// {
2649// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2650// }
2651// }
2652// else
2653// {
2654// error.SetErrorString ("invalid platform");
2655// }
2656// }
2657//
2658// if (error.Success())
2659// {
2660// m_dyld_ap.reset();
2661// m_os_ap.reset();
2662//
2663// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2664// if (error.Success())
2665// {
2666// SetPublicState (eStateAttaching);
2667// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2668// if (error.Fail())
2669// {
2670// if (GetID() != LLDB_INVALID_PROCESS_ID)
2671// {
2672// SetID (LLDB_INVALID_PROCESS_ID);
2673// const char *error_string = error.AsCString();
2674// if (error_string == NULL)
2675// error_string = "attach failed";
2676//
2677// SetExitStatus(-1, error_string);
2678// }
2679// }
2680// else
2681// {
2682// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2683// StartPrivateStateThread();
2684// }
2685// }
2686// }
2687// return error;
2688//}
2689
Greg Clayton93d3c8332011-02-16 04:46:07 +00002690void
2691Process::CompleteAttach ()
2692{
2693 // Let the process subclass figure out at much as it can about the process
2694 // before we go looking for a dynamic loader plug-in.
2695 DidAttach();
2696
Jim Ingham4299fdb2011-09-15 01:10:17 +00002697 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2698 // the same as the one we've already set, switch architectures.
2699 PlatformSP platform_sp (m_target.GetPlatform ());
2700 assert (platform_sp.get());
2701 if (platform_sp)
2702 {
2703 ProcessInstanceInfo process_info;
2704 platform_sp->GetProcessInfo (GetID(), process_info);
2705 const ArchSpec &process_arch = process_info.GetArchitecture();
2706 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2707 m_target.SetArchitecture (process_arch);
2708 }
2709
2710 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002711 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002712 DynamicLoader *dyld = GetDynamicLoader ();
2713 if (dyld)
2714 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002715
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002716 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002717 // Figure out which one is the executable, and set that in our target:
2718 ModuleList &modules = m_target.GetImages();
2719
2720 size_t num_modules = modules.GetSize();
2721 for (int i = 0; i < num_modules; i++)
2722 {
2723 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002724 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002725 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002726 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002727 m_target.SetExecutableModule (module_sp, false);
2728 break;
2729 }
2730 }
2731}
2732
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002733Error
Greg Claytonb766a732011-02-04 01:58:07 +00002734Process::ConnectRemote (const char *remote_url)
2735{
Greg Claytonb766a732011-02-04 01:58:07 +00002736 m_abi_sp.reset();
2737 m_process_input_reader.reset();
2738
2739 // Find the process and its architecture. Make sure it matches the architecture
2740 // of the current Target, and if not adjust it.
2741
2742 Error error (DoConnectRemote (remote_url));
2743 if (error.Success())
2744 {
Greg Clayton71337622011-02-24 22:24:29 +00002745 if (GetID() != LLDB_INVALID_PROCESS_ID)
2746 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002747 EventSP event_sp;
2748 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2749
2750 if (state == eStateStopped || state == eStateCrashed)
2751 {
2752 // If we attached and actually have a process on the other end, then
2753 // this ended up being the equivalent of an attach.
2754 CompleteAttach ();
2755
2756 // This delays passing the stopped event to listeners till
2757 // CompleteAttach gets a chance to complete...
2758 HandlePrivateEvent (event_sp);
2759
2760 }
Greg Clayton71337622011-02-24 22:24:29 +00002761 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002762
2763 if (PrivateStateThreadIsValid ())
2764 ResumePrivateStateThread ();
2765 else
2766 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002767 }
2768 return error;
2769}
2770
2771
2772Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773Process::Resume ()
2774{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002775 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002776 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002777 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002778 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002779 StateAsCString(m_public_state.GetValue()),
2780 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781
2782 Error error (WillResume());
2783 // Tell the process it is about to resume before the thread list
2784 if (error.Success())
2785 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002786 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002787 // can let all of our threads know that they are about to be
2788 // resumed. Threads will each be called with
2789 // Thread::WillResume(StateType) where StateType contains the state
2790 // that they are supposed to have when the process is resumed
2791 // (suspended/running/stepping). Threads should also check
2792 // their resume signal in lldb::Thread::GetResumeSignal()
2793 // to see if they are suppoed to start back up with a signal.
2794 if (m_thread_list.WillResume())
2795 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00002796 m_mod_id.BumpResumeID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002797 error = DoResume();
2798 if (error.Success())
2799 {
2800 DidResume();
2801 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00002802 if (log)
2803 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002804 }
2805 }
2806 else
2807 {
Jim Ingham444586b2011-01-24 06:34:17 +00002808 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002809 }
2810 }
Jim Ingham444586b2011-01-24 06:34:17 +00002811 else if (log)
2812 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813 return error;
2814}
2815
2816Error
2817Process::Halt ()
2818{
Jim Inghambb3a2832011-01-29 01:49:25 +00002819 // Pause our private state thread so we can ensure no one else eats
2820 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002821 Listener halt_listener ("lldb.process.halt_listener");
2822 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002823
Jim Inghambb3a2832011-01-29 01:49:25 +00002824 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002825 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002826
Greg Clayton513c26c2011-01-29 07:10:55 +00002827 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002828 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002829
Greg Clayton513c26c2011-01-29 07:10:55 +00002830 bool caused_stop = false;
2831
2832 // Ask the process subclass to actually halt our process
2833 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002834 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002835 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002836 if (m_public_state.GetValue() == eStateAttaching)
2837 {
2838 SetExitStatus(SIGKILL, "Cancelled async attach.");
2839 Destroy ();
2840 }
2841 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002842 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002843 // If "caused_stop" is true, then DoHalt stopped the process. If
2844 // "caused_stop" is false, the process was already stopped.
2845 // If the DoHalt caused the process to stop, then we want to catch
2846 // this event and set the interrupted bool to true before we pass
2847 // this along so clients know that the process was interrupted by
2848 // a halt command.
2849 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002850 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002851 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002852 TimeValue timeout_time;
2853 timeout_time = TimeValue::Now();
2854 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002855 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2856 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002857
Jim Ingham0f16e732011-02-08 05:20:59 +00002858 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002859 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002860 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002861 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002862 }
2863 else
2864 {
Greg Clayton2637f822011-11-17 01:23:07 +00002865 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00002866 {
2867 // We caused the process to interrupt itself, so mark this
2868 // as such in the stop event so clients can tell an interrupted
2869 // process from a natural stop
2870 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2871 }
2872 else
2873 {
2874 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2875 if (log)
2876 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2877 error.SetErrorString ("Did not get stopped event after halt.");
2878 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002879 }
2880 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002881 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002882 }
2883 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002884 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002885 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002886 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002887
2888 // Post any event we might have consumed. If all goes well, we will have
2889 // stopped the process, intercepted the event and set the interrupted
2890 // bool in the event. Post it to the private event queue and that will end up
2891 // correctly setting the state.
2892 if (event_sp)
2893 m_private_state_broadcaster.BroadcastEvent(event_sp);
2894
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002895 return error;
2896}
2897
2898Error
2899Process::Detach ()
2900{
2901 Error error (WillDetach());
2902
2903 if (error.Success())
2904 {
2905 DisableAllBreakpointSites();
2906 error = DoDetach();
2907 if (error.Success())
2908 {
2909 DidDetach();
2910 StopPrivateStateThread();
2911 }
2912 }
2913 return error;
2914}
2915
2916Error
2917Process::Destroy ()
2918{
2919 Error error (WillDestroy());
2920 if (error.Success())
2921 {
2922 DisableAllBreakpointSites();
2923 error = DoDestroy();
2924 if (error.Success())
2925 {
2926 DidDestroy();
2927 StopPrivateStateThread();
2928 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002929 m_stdio_communication.StopReadThread();
2930 m_stdio_communication.Disconnect();
2931 if (m_process_input_reader && m_process_input_reader->IsActive())
2932 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2933 if (m_process_input_reader)
2934 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002935 }
2936 return error;
2937}
2938
2939Error
2940Process::Signal (int signal)
2941{
2942 Error error (WillSignal());
2943 if (error.Success())
2944 {
2945 error = DoSignal(signal);
2946 if (error.Success())
2947 DidSignal();
2948 }
2949 return error;
2950}
2951
Greg Clayton514487e2011-02-15 21:59:32 +00002952lldb::ByteOrder
2953Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002954{
Greg Clayton514487e2011-02-15 21:59:32 +00002955 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002956}
2957
2958uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002959Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002960{
Greg Clayton514487e2011-02-15 21:59:32 +00002961 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002962}
2963
Greg Clayton514487e2011-02-15 21:59:32 +00002964
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002965bool
2966Process::ShouldBroadcastEvent (Event *event_ptr)
2967{
2968 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2969 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002970 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002971
2972 switch (state)
2973 {
Greg Claytonb766a732011-02-04 01:58:07 +00002974 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002975 case eStateAttaching:
2976 case eStateLaunching:
2977 case eStateDetached:
2978 case eStateExited:
2979 case eStateUnloaded:
2980 // These events indicate changes in the state of the debugging session, always report them.
2981 return_value = true;
2982 break;
2983 case eStateInvalid:
2984 // We stopped for no apparent reason, don't report it.
2985 return_value = false;
2986 break;
2987 case eStateRunning:
2988 case eStateStepping:
2989 // If we've started the target running, we handle the cases where we
2990 // are already running and where there is a transition from stopped to
2991 // running differently.
2992 // running -> running: Automatically suppress extra running events
2993 // stopped -> running: Report except when there is one or more no votes
2994 // and no yes votes.
2995 SynchronouslyNotifyStateChanged (state);
2996 switch (m_public_state.GetValue())
2997 {
2998 case eStateRunning:
2999 case eStateStepping:
3000 // We always suppress multiple runnings with no PUBLIC stop in between.
3001 return_value = false;
3002 break;
3003 default:
3004 // TODO: make this work correctly. For now always report
3005 // run if we aren't running so we don't miss any runnning
3006 // events. If I run the lldb/test/thread/a.out file and
3007 // break at main.cpp:58, run and hit the breakpoints on
3008 // multiple threads, then somehow during the stepping over
3009 // of all breakpoints no run gets reported.
3010 return_value = true;
3011
3012 // This is a transition from stop to run.
3013 switch (m_thread_list.ShouldReportRun (event_ptr))
3014 {
3015 case eVoteYes:
3016 case eVoteNoOpinion:
3017 return_value = true;
3018 break;
3019 case eVoteNo:
3020 return_value = false;
3021 break;
3022 }
3023 break;
3024 }
3025 break;
3026 case eStateStopped:
3027 case eStateCrashed:
3028 case eStateSuspended:
3029 {
3030 // We've stopped. First see if we're going to restart the target.
3031 // If we are going to stop, then we always broadcast the event.
3032 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00003033 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003034 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003035 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003036 if (log)
3037 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003038 return true;
3039 }
3040 else
3041 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003042 RefreshStateAfterStop ();
3043
3044 if (m_thread_list.ShouldStop (event_ptr) == false)
3045 {
3046 switch (m_thread_list.ShouldReportStop (event_ptr))
3047 {
3048 case eVoteYes:
3049 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003050 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003051 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003052 case eVoteNo:
3053 return_value = false;
3054 break;
3055 }
3056
3057 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003058 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003059 Resume ();
3060 }
3061 else
3062 {
3063 return_value = true;
3064 SynchronouslyNotifyStateChanged (state);
3065 }
3066 }
3067 }
3068 }
3069
3070 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003071 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003072 return return_value;
3073}
3074
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003075
3076bool
3077Process::StartPrivateStateThread ()
3078{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003079 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003080
Greg Clayton8b82f082011-04-12 05:54:46 +00003081 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003082 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003083 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3084
3085 if (already_running)
3086 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003087
3088 // Create a thread that watches our internal state and controls which
3089 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003090 char thread_name[1024];
Greg Clayton81c22f62011-10-19 18:09:39 +00003091 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Clayton3e06bd92011-01-09 21:07:35 +00003092 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00003093 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003094}
3095
3096void
3097Process::PausePrivateStateThread ()
3098{
3099 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3100}
3101
3102void
3103Process::ResumePrivateStateThread ()
3104{
3105 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3106}
3107
3108void
3109Process::StopPrivateStateThread ()
3110{
Greg Clayton8b82f082011-04-12 05:54:46 +00003111 if (PrivateStateThreadIsValid ())
3112 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003113}
3114
3115void
3116Process::ControlPrivateStateThread (uint32_t signal)
3117{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003118 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003119
3120 assert (signal == eBroadcastInternalStateControlStop ||
3121 signal == eBroadcastInternalStateControlPause ||
3122 signal == eBroadcastInternalStateControlResume);
3123
3124 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003125 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003126
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003127 // Signal the private state thread. First we should copy this is case the
3128 // thread starts exiting since the private state thread will NULL this out
3129 // when it exits
3130 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003131 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132 {
3133 TimeValue timeout_time;
3134 bool timed_out;
3135
3136 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3137
3138 timeout_time = TimeValue::Now();
3139 timeout_time.OffsetWithSeconds(2);
3140 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3141 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3142
3143 if (signal == eBroadcastInternalStateControlStop)
3144 {
3145 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003146 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003147
3148 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003149 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003150 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003151 }
3152 }
3153}
3154
3155void
3156Process::HandlePrivateEvent (EventSP &event_sp)
3157{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003158 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003159
Greg Clayton414f5d32011-01-25 02:58:48 +00003160 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003161
3162 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003163 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003164 {
Jim Ingham754ab982011-01-29 04:05:41 +00003165 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003166 switch (action_result)
3167 {
3168 case NextEventAction::eEventActionSuccess:
3169 SetNextEventAction(NULL);
3170 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003171
Jim Inghambb3a2832011-01-29 01:49:25 +00003172 case NextEventAction::eEventActionRetry:
3173 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003174
Jim Inghambb3a2832011-01-29 01:49:25 +00003175 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003176 // Handle Exiting Here. If we already got an exited event,
3177 // we should just propagate it. Otherwise, swallow this event,
3178 // and set our state to exit so the next event will kill us.
3179 if (new_state != eStateExited)
3180 {
3181 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003182 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003183 SetNextEventAction(NULL);
3184 return;
3185 }
3186 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003187 break;
3188 }
3189 }
3190
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003191 // See if we should broadcast this state to external clients?
3192 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003193
3194 if (should_broadcast)
3195 {
3196 if (log)
3197 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003198 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003199 __FUNCTION__,
3200 GetID(),
3201 StateAsCString(new_state),
3202 StateAsCString (GetState ()),
3203 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003204 }
Jim Ingham9575d842011-03-11 03:53:59 +00003205 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003206 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003207 PushProcessInputReader ();
3208 else
3209 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003210
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003211 BroadcastEvent (event_sp);
3212 }
3213 else
3214 {
3215 if (log)
3216 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003217 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003218 __FUNCTION__,
3219 GetID(),
3220 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003221 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003222 }
3223 }
3224}
3225
3226void *
3227Process::PrivateStateThread (void *arg)
3228{
3229 Process *proc = static_cast<Process*> (arg);
3230 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003231 return result;
3232}
3233
3234void *
3235Process::RunPrivateStateThread ()
3236{
3237 bool control_only = false;
3238 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3239
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003240 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003241 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003242 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003243
3244 bool exit_now = false;
3245 while (!exit_now)
3246 {
3247 EventSP event_sp;
3248 WaitForEventsPrivate (NULL, event_sp, control_only);
3249 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3250 {
3251 switch (event_sp->GetType())
3252 {
3253 case eBroadcastInternalStateControlStop:
3254 exit_now = true;
3255 continue; // Go to next loop iteration so we exit without
3256 break; // doing any internal state managment below
3257
3258 case eBroadcastInternalStateControlPause:
3259 control_only = true;
3260 break;
3261
3262 case eBroadcastInternalStateControlResume:
3263 control_only = false;
3264 break;
3265 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003266
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003267 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003268 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003269
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003270 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003271 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003272 }
3273
3274
3275 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3276
3277 if (internal_state != eStateInvalid)
3278 {
3279 HandlePrivateEvent (event_sp);
3280 }
3281
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003282 if (internal_state == eStateInvalid ||
3283 internal_state == eStateExited ||
3284 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003285 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003286 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003287 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003288
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003289 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003290 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003291 }
3292
Caroline Tice20ad3c42010-10-29 21:48:37 +00003293 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003294 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003295 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003296
Greg Clayton6ed95942011-01-22 07:12:45 +00003297 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3298 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003299 return NULL;
3300}
3301
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003302//------------------------------------------------------------------
3303// Process Event Data
3304//------------------------------------------------------------------
3305
3306Process::ProcessEventData::ProcessEventData () :
3307 EventData (),
3308 m_process_sp (),
3309 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003310 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003311 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003312 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003313{
3314}
3315
3316Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3317 EventData (),
3318 m_process_sp (process_sp),
3319 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003320 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003321 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003322 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003323{
3324}
3325
3326Process::ProcessEventData::~ProcessEventData()
3327{
3328}
3329
3330const ConstString &
3331Process::ProcessEventData::GetFlavorString ()
3332{
3333 static ConstString g_flavor ("Process::ProcessEventData");
3334 return g_flavor;
3335}
3336
3337const ConstString &
3338Process::ProcessEventData::GetFlavor () const
3339{
3340 return ProcessEventData::GetFlavorString ();
3341}
3342
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003343void
3344Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3345{
3346 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003347 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3348 // the public event queue, then other times when we're pretending that this is where we stopped at the
3349 // end of expression evaluation. m_update_state is used to distinguish these
3350 // three cases; it is 0 when we're just pulling it off for private handling,
3351 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003352
Jim Inghama8604692011-05-22 21:45:01 +00003353 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003354 return;
3355
3356 m_process_sp->SetPublicState (m_state);
3357
3358 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3359 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003360 {
3361 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003362 uint32_t num_threads = curr_thread_list.GetSize();
3363 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003364
Jim Ingham4b536182011-08-09 02:12:22 +00003365 // The actions might change one of the thread's stop_info's opinions about whether we should
3366 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003367
3368 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3369 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3370 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3371 // 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
3372 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003373 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003374 for (idx = 0; idx < num_threads; ++idx)
3375 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3376
Jim Ingham4b536182011-08-09 02:12:22 +00003377 bool still_should_stop = true;
3378
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003379 for (idx = 0; idx < num_threads; ++idx)
3380 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003381 curr_thread_list = m_process_sp->GetThreadList();
3382 if (curr_thread_list.GetSize() != num_threads)
3383 {
3384 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003385 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003386 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003387 break;
3388 }
3389
3390 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3391
3392 if (thread_sp->GetIndexID() != thread_index_array[idx])
3393 {
3394 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003395 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003396 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003397 idx,
3398 thread_index_array[idx],
3399 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003400 break;
3401 }
3402
Jim Inghamb15bfc72010-10-20 00:39:53 +00003403 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3404 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003405 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003406 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003407 // The stop action might restart the target. If it does, then we want to mark that in the
3408 // event so that whoever is receiving it will know to wait for the running event and reflect
3409 // that state appropriately.
3410 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003411
3412 // FIXME: we might have run.
3413 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003414 {
3415 SetRestarted (true);
3416 break;
3417 }
3418 else if (!stop_info_sp->ShouldStop(event_ptr))
3419 {
3420 still_should_stop = false;
3421 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003422 }
3423 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003424
Jim Ingham4b536182011-08-09 02:12:22 +00003425
3426 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003427 {
Jim Ingham4b536182011-08-09 02:12:22 +00003428 if (!still_should_stop)
3429 {
3430 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003431 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003432 m_process_sp->Resume();
3433 }
3434 else
3435 {
3436 // If we didn't restart, run the Stop Hooks here:
3437 // They might also restart the target, so watch for that.
3438 m_process_sp->GetTarget().RunStopHooks();
3439 if (m_process_sp->GetPrivateState() == eStateRunning)
3440 SetRestarted(true);
3441 }
Jim Ingham9575d842011-03-11 03:53:59 +00003442 }
3443
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003444 }
3445}
3446
3447void
3448Process::ProcessEventData::Dump (Stream *s) const
3449{
3450 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003451 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003452
Greg Clayton8b82f082011-04-12 05:54:46 +00003453 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003454}
3455
3456const Process::ProcessEventData *
3457Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3458{
3459 if (event_ptr)
3460 {
3461 const EventData *event_data = event_ptr->GetData();
3462 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3463 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3464 }
3465 return NULL;
3466}
3467
3468ProcessSP
3469Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3470{
3471 ProcessSP process_sp;
3472 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3473 if (data)
3474 process_sp = data->GetProcessSP();
3475 return process_sp;
3476}
3477
3478StateType
3479Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3480{
3481 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3482 if (data == NULL)
3483 return eStateInvalid;
3484 else
3485 return data->GetState();
3486}
3487
3488bool
3489Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3490{
3491 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3492 if (data == NULL)
3493 return false;
3494 else
3495 return data->GetRestarted();
3496}
3497
3498void
3499Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3500{
3501 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3502 if (data != NULL)
3503 data->SetRestarted(new_value);
3504}
3505
3506bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003507Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3508{
3509 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3510 if (data == NULL)
3511 return false;
3512 else
3513 return data->GetInterrupted ();
3514}
3515
3516void
3517Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3518{
3519 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3520 if (data != NULL)
3521 data->SetInterrupted(new_value);
3522}
3523
3524bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003525Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3526{
3527 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3528 if (data)
3529 {
3530 data->SetUpdateStateOnRemoval();
3531 return true;
3532 }
3533 return false;
3534}
3535
Greg Claytond9e416c2012-02-18 05:35:26 +00003536lldb::TargetSP
3537Process::CalculateTarget ()
3538{
3539 return m_target.shared_from_this();
3540}
3541
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003542void
Greg Clayton0603aa92010-10-04 01:05:56 +00003543Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003544{
Greg Claytonc14ee322011-09-22 04:58:26 +00003545 exe_ctx.SetTargetPtr (&m_target);
3546 exe_ctx.SetProcessPtr (this);
3547 exe_ctx.SetThreadPtr(NULL);
3548 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003549}
3550
Greg Claytone996fd32011-03-08 22:40:15 +00003551//uint32_t
3552//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3553//{
3554// return 0;
3555//}
3556//
3557//ArchSpec
3558//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3559//{
3560// return Host::GetArchSpecForExistingProcess (pid);
3561//}
3562//
3563//ArchSpec
3564//Process::GetArchSpecForExistingProcess (const char *process_name)
3565//{
3566// return Host::GetArchSpecForExistingProcess (process_name);
3567//}
3568//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003569void
3570Process::AppendSTDOUT (const char * s, size_t len)
3571{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003572 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003573 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003574 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003575}
3576
3577void
Greg Clayton93e86192011-11-13 04:45:22 +00003578Process::AppendSTDERR (const char * s, size_t len)
3579{
3580 Mutex::Locker locker (m_stdio_communication_mutex);
3581 m_stderr_data.append (s, len);
3582 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3583}
3584
3585//------------------------------------------------------------------
3586// Process STDIO
3587//------------------------------------------------------------------
3588
3589size_t
3590Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3591{
3592 Mutex::Locker locker(m_stdio_communication_mutex);
3593 size_t bytes_available = m_stdout_data.size();
3594 if (bytes_available > 0)
3595 {
3596 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3597 if (log)
3598 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3599 if (bytes_available > buf_size)
3600 {
3601 memcpy(buf, m_stdout_data.c_str(), buf_size);
3602 m_stdout_data.erase(0, buf_size);
3603 bytes_available = buf_size;
3604 }
3605 else
3606 {
3607 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3608 m_stdout_data.clear();
3609 }
3610 }
3611 return bytes_available;
3612}
3613
3614
3615size_t
3616Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3617{
3618 Mutex::Locker locker(m_stdio_communication_mutex);
3619 size_t bytes_available = m_stderr_data.size();
3620 if (bytes_available > 0)
3621 {
3622 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3623 if (log)
3624 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3625 if (bytes_available > buf_size)
3626 {
3627 memcpy(buf, m_stderr_data.c_str(), buf_size);
3628 m_stderr_data.erase(0, buf_size);
3629 bytes_available = buf_size;
3630 }
3631 else
3632 {
3633 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3634 m_stderr_data.clear();
3635 }
3636 }
3637 return bytes_available;
3638}
3639
3640void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003641Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3642{
3643 Process *process = (Process *) baton;
3644 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3645}
3646
3647size_t
3648Process::ProcessInputReaderCallback (void *baton,
3649 InputReader &reader,
3650 lldb::InputReaderAction notification,
3651 const char *bytes,
3652 size_t bytes_len)
3653{
3654 Process *process = (Process *) baton;
3655
3656 switch (notification)
3657 {
3658 case eInputReaderActivate:
3659 break;
3660
3661 case eInputReaderDeactivate:
3662 break;
3663
3664 case eInputReaderReactivate:
3665 break;
3666
Caroline Tice969ed3d2011-05-02 20:41:46 +00003667 case eInputReaderAsynchronousOutputWritten:
3668 break;
3669
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003670 case eInputReaderGotToken:
3671 {
3672 Error error;
3673 process->PutSTDIN (bytes, bytes_len, error);
3674 }
3675 break;
3676
Caroline Ticeefed6132010-11-19 20:47:54 +00003677 case eInputReaderInterrupt:
3678 process->Halt ();
3679 break;
3680
3681 case eInputReaderEndOfFile:
3682 process->AppendSTDOUT ("^D", 2);
3683 break;
3684
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003685 case eInputReaderDone:
3686 break;
3687
3688 }
3689
3690 return bytes_len;
3691}
3692
3693void
3694Process::ResetProcessInputReader ()
3695{
3696 m_process_input_reader.reset();
3697}
3698
3699void
Greg Claytonee95ed52011-11-17 22:14:31 +00003700Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003701{
3702 // First set up the Read Thread for reading/handling process I/O
3703
3704 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3705
3706 if (conn_ap.get())
3707 {
3708 m_stdio_communication.SetConnection (conn_ap.release());
3709 if (m_stdio_communication.IsConnected())
3710 {
3711 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3712 m_stdio_communication.StartReadThread();
3713
3714 // Now read thread is set up, set up input reader.
3715
3716 if (!m_process_input_reader.get())
3717 {
3718 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3719 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3720 this,
3721 eInputReaderGranularityByte,
3722 NULL,
3723 NULL,
3724 false));
3725
3726 if (err.Fail())
3727 m_process_input_reader.reset();
3728 }
3729 }
3730 }
3731}
3732
3733void
3734Process::PushProcessInputReader ()
3735{
3736 if (m_process_input_reader && !m_process_input_reader->IsActive())
3737 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3738}
3739
3740void
3741Process::PopProcessInputReader ()
3742{
3743 if (m_process_input_reader && m_process_input_reader->IsActive())
3744 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3745}
3746
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003747// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003748void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003749Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003750{
Greg Claytone0d378b2011-03-24 21:19:54 +00003751 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003752
3753 int i=0;
3754 const char *name;
3755 OptionEnumValueElement option_enum;
3756 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3757 {
3758 if (name)
3759 {
3760 option_enum.value = i;
3761 option_enum.string_value = name;
3762 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3763 g_plugins.push_back (option_enum);
3764 }
3765 ++i;
3766 }
3767 option_enum.value = 0;
3768 option_enum.string_value = NULL;
3769 option_enum.usage = NULL;
3770 g_plugins.push_back (option_enum);
3771
3772 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3773 {
3774 if (::strcmp (name, "plugin") == 0)
3775 {
3776 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3777 break;
3778 }
3779 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003780 UserSettingsControllerSP &usc = GetSettingsController();
3781 usc.reset (new SettingsController);
3782 UserSettingsController::InitializeSettingsController (usc,
3783 SettingsController::global_settings_table,
3784 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003785
3786 // Now call SettingsInitialize() for each 'child' of Process settings
3787 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003788}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003789
Greg Clayton99d0faf2010-11-18 23:32:35 +00003790void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003791Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003792{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003793 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3794
3795 Thread::SettingsTerminate ();
3796
3797 // Now terminate Process Settings.
3798
Greg Clayton99d0faf2010-11-18 23:32:35 +00003799 UserSettingsControllerSP &usc = GetSettingsController();
3800 UserSettingsController::FinalizeSettingsController (usc);
3801 usc.reset();
3802}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003803
Greg Clayton99d0faf2010-11-18 23:32:35 +00003804UserSettingsControllerSP &
3805Process::GetSettingsController ()
3806{
Greg Claytonb9556ac2012-01-30 07:41:31 +00003807 static UserSettingsControllerSP g_settings_controller_sp;
3808 if (!g_settings_controller_sp)
3809 {
3810 g_settings_controller_sp.reset (new Process::SettingsController);
3811 // The first shared pointer to Process::SettingsController in
3812 // g_settings_controller_sp must be fully created above so that
3813 // the TargetInstanceSettings can use a weak_ptr to refer back
3814 // to the master setttings controller
3815 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp,
3816 false,
3817 InstanceSettings::GetDefaultName().AsCString()));
3818 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
3819 }
3820 return g_settings_controller_sp;
3821
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003822}
3823
Caroline Tice1559a462010-09-27 00:30:10 +00003824void
3825Process::UpdateInstanceName ()
3826{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003827 Module *module = GetTarget().GetExecutableModulePointer();
Greg Claytone1cd1be2012-01-29 20:56:30 +00003828 if (module && module->GetFileSpec().GetFilename())
Caroline Tice1559a462010-09-27 00:30:10 +00003829 {
Greg Claytondbe54502010-11-19 03:46:01 +00003830 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytone1cd1be2012-01-29 20:56:30 +00003831 module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003832 }
3833}
3834
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003835ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003836Process::RunThreadPlan (ExecutionContext &exe_ctx,
3837 lldb::ThreadPlanSP &thread_plan_sp,
3838 bool stop_others,
3839 bool try_all_threads,
3840 bool discard_on_error,
3841 uint32_t single_thread_timeout_usec,
3842 Stream &errors)
3843{
3844 ExecutionResults return_value = eExecutionSetupError;
3845
Jim Ingham77787032011-01-20 02:03:18 +00003846 if (thread_plan_sp.get() == NULL)
3847 {
3848 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003849 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003850 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003851
3852 if (exe_ctx.GetProcessPtr() != this)
3853 {
3854 errors.Printf("RunThreadPlan called on wrong process.");
3855 return eExecutionSetupError;
3856 }
3857
3858 Thread *thread = exe_ctx.GetThreadPtr();
3859 if (thread == NULL)
3860 {
3861 errors.Printf("RunThreadPlan called with invalid thread.");
3862 return eExecutionSetupError;
3863 }
Jim Ingham77787032011-01-20 02:03:18 +00003864
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003865 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3866 // For that to be true the plan can't be private - since private plans suppress themselves in the
3867 // GetCompletedPlan call.
3868
3869 bool orig_plan_private = thread_plan_sp->GetPrivate();
3870 thread_plan_sp->SetPrivate(false);
3871
Jim Ingham444586b2011-01-24 06:34:17 +00003872 if (m_private_state.GetValue() != eStateStopped)
3873 {
3874 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003875 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003876 }
3877
Jim Ingham66243842011-08-13 00:56:10 +00003878 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00003879 const uint32_t thread_idx_id = thread->GetIndexID();
3880 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003881
3882 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3883 // so we should arrange to reset them as well.
3884
Greg Claytonc14ee322011-09-22 04:58:26 +00003885 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003886
Jim Ingham66243842011-08-13 00:56:10 +00003887 uint32_t selected_tid;
3888 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00003889 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00003890 {
3891 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003892 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003893 }
3894 else
3895 {
3896 selected_tid = LLDB_INVALID_THREAD_ID;
3897 }
3898
Greg Claytonc14ee322011-09-22 04:58:26 +00003899 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Inghamf48169b2010-11-30 02:22:11 +00003900
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003901 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003902
3903 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3904 // restored on exit to the function.
3905
3906 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003907
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003908 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003909 if (log)
3910 {
3911 StreamString s;
3912 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton81c22f62011-10-19 18:09:39 +00003913 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00003914 thread->GetIndexID(),
3915 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00003916 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003917 }
3918
Jim Ingham0f16e732011-02-08 05:20:59 +00003919 bool got_event;
3920 lldb::EventSP event_sp;
3921 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003922
3923 TimeValue* timeout_ptr = NULL;
3924 TimeValue real_timeout;
3925
Jim Ingham0f16e732011-02-08 05:20:59 +00003926 bool first_timeout = true;
3927 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003928
Jim Inghamf48169b2010-11-30 02:22:11 +00003929 while (1)
3930 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003931 // We usually want to resume the process if we get to the top of the loop.
3932 // The only exception is if we get two running events with no intervening
3933 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003934
Jim Ingham0f16e732011-02-08 05:20:59 +00003935 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003936 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003937 // Do the initial resume and wait for the running event before going further.
3938
Greg Claytonc14ee322011-09-22 04:58:26 +00003939 Error resume_error = Resume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00003940 if (!resume_error.Success())
3941 {
3942 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003943 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003944 break;
3945 }
3946
3947 real_timeout = TimeValue::Now();
3948 real_timeout.OffsetWithMicroSeconds(500000);
3949 timeout_ptr = &real_timeout;
3950
Sean Callananc1b312a2012-01-05 02:00:14 +00003951 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
Jim Ingham0f16e732011-02-08 05:20:59 +00003952 if (!got_event)
3953 {
3954 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003955 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003956
3957 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003958 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003959 break;
3960 }
3961
3962 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3963 if (stop_state != eStateRunning)
3964 {
3965 if (log)
3966 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3967
3968 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003969 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003970 break;
3971 }
3972
3973 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003974 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003975 // We need to call the function synchronously, so spin waiting for it to return.
3976 // If we get interrupted while executing, we're going to lose our context, and
3977 // won't be able to gather the result at this point.
3978 // We set the timeout AFTER the resume, since the resume takes some time and we
3979 // don't want to charge that to the timeout.
3980
3981 if (single_thread_timeout_usec != 0)
3982 {
3983 real_timeout = TimeValue::Now();
3984 if (first_timeout)
3985 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3986 else
3987 real_timeout.OffsetWithSeconds(10);
3988
3989 timeout_ptr = &real_timeout;
3990 }
3991 }
3992 else
3993 {
3994 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003995 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003996 do_resume = true;
3997 }
3998
3999 // Now wait for the process to stop again:
4000 stop_state = lldb::eStateInvalid;
4001 event_sp.reset();
4002 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4003
4004 if (got_event)
4005 {
4006 if (event_sp.get())
4007 {
4008 bool keep_going = false;
4009 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4010 if (log)
4011 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
4012
4013 switch (stop_state)
4014 {
4015 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00004016 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004017 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00004018 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00004019 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00004020 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004021 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00004022 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00004023 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4024 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00004025 }
4026 else
4027 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004028 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4029 StopReason stop_reason = eStopReasonInvalid;
4030 if (stop_info_sp)
4031 stop_reason = stop_info_sp->GetStopReason();
4032 if (stop_reason == eStopReasonPlanComplete)
4033 {
4034 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004035 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004036 // Now mark this plan as private so it doesn't get reported as the stop reason
4037 // after this point.
4038 if (thread_plan_sp)
4039 thread_plan_sp->SetPrivate (orig_plan_private);
4040 return_value = eExecutionCompleted;
4041 }
4042 else
4043 {
4044 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004045 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004046
4047 return_value = eExecutionInterrupted;
4048 }
Jim Ingham160f78c2011-05-17 01:10:11 +00004049 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00004050 }
4051 break;
4052
Jim Ingham0f16e732011-02-08 05:20:59 +00004053 case lldb::eStateCrashed:
4054 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004055 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004056 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004057 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004058
Jim Ingham0f16e732011-02-08 05:20:59 +00004059 case lldb::eStateRunning:
4060 do_resume = false;
4061 keep_going = true;
4062 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004063
Jim Ingham0f16e732011-02-08 05:20:59 +00004064 default:
4065 if (log)
4066 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00004067
4068 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004069 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004070 break;
4071 }
4072 if (keep_going)
4073 continue;
4074 else
4075 break;
4076 }
4077 else
4078 {
4079 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004080 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00004081 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004082 break;
4083 }
4084 }
4085 else
4086 {
4087 // If we didn't get an event that means we've timed out...
4088 // We will interrupt the process here. Depending on what we were asked to do we will
4089 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00004090 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00004091
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004092 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00004093 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00004094 {
4095 if (first_timeout)
4096 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4097 "trying with all threads enabled.",
4098 single_thread_timeout_usec);
4099 else
4100 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4101 "and timeout: %d timed out.",
4102 single_thread_timeout_usec);
4103 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004104 else
Jim Ingham0f16e732011-02-08 05:20:59 +00004105 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4106 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00004107 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004108 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004109
Greg Claytonc14ee322011-09-22 04:58:26 +00004110 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00004111 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00004112 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004113 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004114 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004115
Jim Ingham0f16e732011-02-08 05:20:59 +00004116 // If halt succeeds, it always produces a stopped event. Wait for that:
4117
4118 real_timeout = TimeValue::Now();
4119 real_timeout.OffsetWithMicroSeconds(500000);
4120
4121 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004122
4123 if (got_event)
4124 {
4125 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4126 if (log)
4127 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004128 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00004129 if (stop_state == lldb::eStateStopped
4130 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00004131 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004132 }
4133
Jim Ingham0f16e732011-02-08 05:20:59 +00004134 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00004135 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004136 // Between the time we initiated the Halt and the time we delivered it, the process could have
4137 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00004138
Greg Claytonc14ee322011-09-22 04:58:26 +00004139 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004140 {
4141 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004142 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004143 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004144 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004145 break;
4146 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004147
Jim Ingham0f16e732011-02-08 05:20:59 +00004148 if (!try_all_threads)
4149 {
4150 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004151 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004152 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004153 break;
4154 }
4155
4156 if (first_timeout)
4157 {
4158 // Set all the other threads to run, and return to the top of the loop, which will continue;
4159 first_timeout = false;
4160 thread_plan_sp->SetStopOthers (false);
4161 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004162 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004163
4164 continue;
4165 }
4166 else
4167 {
4168 // Running all threads failed, so return Interrupted.
4169 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004170 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004171 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004172 break;
4173 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004174 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004175 }
4176 else
4177 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004178 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004179 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004180 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004181 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00004182 }
4183 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004184 else
4185 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004186 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4187 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00004188 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004189 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.",
4190 halt_error.AsCString());
4191 real_timeout = TimeValue::Now();
4192 real_timeout.OffsetWithMicroSeconds(500000);
4193 timeout_ptr = &real_timeout;
4194 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4195 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004196 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004197 // This is not going anywhere, bag out.
4198 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004199 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004200 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004201 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004202 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004203 else
4204 {
4205 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4206 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004207 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00004208 if (stop_state == lldb::eStateStopped)
4209 {
4210 // Between the time we initiated the Halt and the time we delivered it, the process could have
4211 // already finished its job. Check that here:
4212
Greg Claytonc14ee322011-09-22 04:58:26 +00004213 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004214 {
4215 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004216 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004217 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004218 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004219 break;
4220 }
4221
4222 if (first_timeout)
4223 {
4224 // Set all the other threads to run, and return to the top of the loop, which will continue;
4225 first_timeout = false;
4226 thread_plan_sp->SetStopOthers (false);
4227 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004228 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004229
4230 continue;
4231 }
4232 else
4233 {
4234 // Running all threads failed, so return Interrupted.
4235 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004236 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004237 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004238 break;
4239 }
4240 }
4241 else
4242 {
Sean Callanan39821ac2011-08-09 22:07:08 +00004243 if (log)
4244 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4245 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00004246 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004247 break;
4248 }
4249 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004250 }
4251
Jim Inghamf48169b2010-11-30 02:22:11 +00004252 }
4253
Jim Ingham0f16e732011-02-08 05:20:59 +00004254 } // END WAIT LOOP
4255
4256 // Now do some processing on the results of the run:
4257 if (return_value == eExecutionInterrupted)
4258 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004259 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004260 {
4261 StreamString s;
4262 if (event_sp)
4263 event_sp->Dump (&s);
4264 else
4265 {
Jim Ingham20829ac2011-08-09 22:24:33 +00004266 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004267 }
4268
4269 StreamString ts;
4270
Jim Ingham20829ac2011-08-09 22:24:33 +00004271 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00004272
4273 do
4274 {
4275 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4276
4277 if (!event_data)
4278 {
4279 event_explanation = "<no event data>";
4280 break;
4281 }
4282
4283 Process *process = event_data->GetProcessSP().get();
4284
4285 if (!process)
4286 {
4287 event_explanation = "<no process>";
4288 break;
4289 }
4290
4291 ThreadList &thread_list = process->GetThreadList();
4292
4293 uint32_t num_threads = thread_list.GetSize();
4294 uint32_t thread_index;
4295
4296 ts.Printf("<%u threads> ", num_threads);
4297
4298 for (thread_index = 0;
4299 thread_index < num_threads;
4300 ++thread_index)
4301 {
4302 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4303
4304 if (!thread)
4305 {
4306 ts.Printf("<?> ");
4307 continue;
4308 }
4309
Greg Clayton81c22f62011-10-19 18:09:39 +00004310 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Ingham0f16e732011-02-08 05:20:59 +00004311 RegisterContext *register_context = thread->GetRegisterContext().get();
4312
4313 if (register_context)
4314 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4315 else
4316 ts.Printf("[ip unknown] ");
4317
4318 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4319 if (stop_info_sp)
4320 {
4321 const char *stop_desc = stop_info_sp->GetDescription();
4322 if (stop_desc)
4323 ts.PutCString (stop_desc);
4324 }
4325 ts.Printf(">");
4326 }
4327
4328 event_explanation = ts.GetData();
4329 } while (0);
4330
4331 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004332 {
4333 if (event_explanation)
4334 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4335 else
4336 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4337 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004338
4339 if (discard_on_error && thread_plan_sp)
4340 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004341 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004342 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004343 }
4344 }
4345 }
4346 else if (return_value == eExecutionSetupError)
4347 {
4348 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004349 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004350
4351 if (discard_on_error && thread_plan_sp)
4352 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004353 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004354 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004355 }
4356 }
4357 else
4358 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004359 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004360 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004361 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004362 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00004363 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00004364 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004365 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004366 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004367 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004368 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00004369 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00004370 }
4371 else
4372 {
4373 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004374 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00004375 if (discard_on_error && thread_plan_sp)
4376 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004377 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004378 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00004379 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004380 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00004381 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004382 }
4383 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004384
Jim Inghamf48169b2010-11-30 02:22:11 +00004385 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00004386 // Check that it's still there, and if it is put it back in the context. Also restore the
4387 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00004388 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4389 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00004390 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004391 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00004392 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004393
4394 // Also restore the current process'es selected frame & thread, since this function calling may
4395 // be done behind the user's back.
4396
4397 if (selected_tid != LLDB_INVALID_THREAD_ID)
4398 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004399 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00004400 {
4401 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00004402 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00004403 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00004404 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004405 }
4406 }
4407
4408 return return_value;
4409}
4410
4411const char *
4412Process::ExecutionResultAsCString (ExecutionResults result)
4413{
4414 const char *result_name;
4415
4416 switch (result)
4417 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004418 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004419 result_name = "eExecutionCompleted";
4420 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004421 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004422 result_name = "eExecutionDiscarded";
4423 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004424 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004425 result_name = "eExecutionInterrupted";
4426 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004427 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004428 result_name = "eExecutionSetupError";
4429 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004430 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004431 result_name = "eExecutionTimedOut";
4432 break;
4433 }
4434 return result_name;
4435}
4436
Greg Clayton7260f622011-04-18 08:33:37 +00004437void
4438Process::GetStatus (Stream &strm)
4439{
4440 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00004441 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00004442 {
4443 if (state == eStateExited)
4444 {
4445 int exit_status = GetExitStatus();
4446 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004447 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004448 GetID(),
4449 exit_status,
4450 exit_status,
4451 exit_description ? exit_description : "");
4452 }
4453 else
4454 {
4455 if (state == eStateConnected)
4456 strm.Printf ("Connected to remote target.\n");
4457 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004458 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004459 }
4460 }
4461 else
4462 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004463 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004464 }
4465}
4466
4467size_t
4468Process::GetThreadStatus (Stream &strm,
4469 bool only_threads_with_stop_reason,
4470 uint32_t start_frame,
4471 uint32_t num_frames,
4472 uint32_t num_frames_with_source)
4473{
4474 size_t num_thread_infos_dumped = 0;
4475
4476 const size_t num_threads = GetThreadList().GetSize();
4477 for (uint32_t i = 0; i < num_threads; i++)
4478 {
4479 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4480 if (thread)
4481 {
4482 if (only_threads_with_stop_reason)
4483 {
4484 if (thread->GetStopInfo().get() == NULL)
4485 continue;
4486 }
4487 thread->GetStatus (strm,
4488 start_frame,
4489 num_frames,
4490 num_frames_with_source);
4491 ++num_thread_infos_dumped;
4492 }
4493 }
4494 return num_thread_infos_dumped;
4495}
4496
Greg Claytona9f40ad2012-02-22 04:37:26 +00004497void
4498Process::AddInvalidMemoryRegion (const LoadRange &region)
4499{
4500 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4501}
4502
4503bool
4504Process::RemoveInvalidMemoryRange (const LoadRange &region)
4505{
4506 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4507}
4508
4509
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004510//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004511// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004512//--------------------------------------------------------------
4513
Greg Clayton1b654882010-09-19 02:33:57 +00004514Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004515 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004516{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004517}
4518
Greg Clayton1b654882010-09-19 02:33:57 +00004519Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004520{
4521}
4522
4523lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004524Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004525{
Greg Claytonb9556ac2012-01-30 07:41:31 +00004526 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4527 false,
4528 instance_name));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004529 return new_settings_sp;
4530}
4531
4532//--------------------------------------------------------------
4533// class ProcessInstanceSettings
4534//--------------------------------------------------------------
4535
Greg Clayton85851dd2010-12-04 00:10:17 +00004536ProcessInstanceSettings::ProcessInstanceSettings
4537(
Greg Claytonb9556ac2012-01-30 07:41:31 +00004538 const UserSettingsControllerSP &owner_sp,
Greg Clayton85851dd2010-12-04 00:10:17 +00004539 bool live_instance,
4540 const char *name
4541) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004542 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004543{
Caroline Ticef20e8232010-09-09 18:26:37 +00004544 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4545 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4546 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice9e41c152010-09-16 19:05:55 +00004547 // This is true for CreateInstanceName() too.
Greg Clayton1d885962011-11-08 02:43:13 +00004548
Caroline Tice9e41c152010-09-16 19:05:55 +00004549 if (GetInstanceName () == InstanceSettings::InvalidName())
4550 {
4551 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
Greg Claytonb9556ac2012-01-30 07:41:31 +00004552 owner_sp->RegisterInstanceSettings (this);
Caroline Tice9e41c152010-09-16 19:05:55 +00004553 }
Greg Clayton1d885962011-11-08 02:43:13 +00004554
Caroline Ticef20e8232010-09-09 18:26:37 +00004555 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004556 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004557 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004558 CopyInstanceSettings (pending_settings,false);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004559 }
4560}
4561
4562ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004563 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004564{
4565 if (m_instance_name != InstanceSettings::GetDefaultName())
4566 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004567 UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4568 if (owner_sp)
4569 {
4570 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4571 owner_sp->RemovePendingSettings (m_instance_name);
4572 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004573 }
4574}
4575
4576ProcessInstanceSettings::~ProcessInstanceSettings ()
4577{
4578}
4579
4580ProcessInstanceSettings&
4581ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4582{
4583 if (this != &rhs)
4584 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004585 }
4586
4587 return *this;
4588}
4589
4590
4591void
4592ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4593 const char *index_value,
4594 const char *value,
4595 const ConstString &instance_name,
4596 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004597 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004598 Error &err,
4599 bool pending)
4600{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004601}
4602
4603void
4604ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4605 bool pending)
4606{
Greg Clayton1d885962011-11-08 02:43:13 +00004607// if (new_settings.get() == NULL)
4608// return;
4609//
4610// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004611}
4612
Caroline Tice12cecd72010-09-20 21:37:42 +00004613bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004614ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4615 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004616 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004617 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004618{
Greg Clayton1d885962011-11-08 02:43:13 +00004619 if (err)
4620 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4621 return false;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004622}
4623
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004624const ConstString
4625ProcessInstanceSettings::CreateInstanceName ()
4626{
4627 static int instance_count = 1;
4628 StreamString sstr;
4629
4630 sstr.Printf ("process_%d", instance_count);
4631 ++instance_count;
4632
4633 const ConstString ret_val (sstr.GetData());
4634 return ret_val;
4635}
4636
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004637//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004638// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004639//--------------------------------------------------
4640
4641SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004642Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004643{
4644 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4645 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4646};
4647
4648
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004649SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004650Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004651{
Greg Clayton85851dd2010-12-04 00:10:17 +00004652 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton85851dd2010-12-04 00:10:17 +00004653 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004654};
4655
4656
Jim Ingham5aee1622010-08-09 23:31:02 +00004657
Greg Clayton1d885962011-11-08 02:43:13 +00004658