blob: d17449128d012f22c62ebac8bc7fb68f897cd5fc [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 Ingham372787f2012-04-07 00:00:41 +00002796 // Last thing, do the PreResumeActions.
2797 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002798 {
Jim Ingham372787f2012-04-07 00:00:41 +00002799 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
2800 }
2801 else
2802 {
2803 m_mod_id.BumpResumeID();
2804 error = DoResume();
2805 if (error.Success())
2806 {
2807 DidResume();
2808 m_thread_list.DidResume();
2809 if (log)
2810 log->Printf ("Process thinks the process has resumed.");
2811 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002812 }
2813 }
2814 else
2815 {
Jim Ingham444586b2011-01-24 06:34:17 +00002816 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002817 }
2818 }
Jim Ingham444586b2011-01-24 06:34:17 +00002819 else if (log)
2820 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002821 return error;
2822}
2823
2824Error
2825Process::Halt ()
2826{
Jim Inghambb3a2832011-01-29 01:49:25 +00002827 // Pause our private state thread so we can ensure no one else eats
2828 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002829 Listener halt_listener ("lldb.process.halt_listener");
2830 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002831
Jim Inghambb3a2832011-01-29 01:49:25 +00002832 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002833 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002834
Greg Clayton513c26c2011-01-29 07:10:55 +00002835 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002836 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002837
Greg Clayton513c26c2011-01-29 07:10:55 +00002838 bool caused_stop = false;
2839
2840 // Ask the process subclass to actually halt our process
2841 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002842 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002843 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002844 if (m_public_state.GetValue() == eStateAttaching)
2845 {
2846 SetExitStatus(SIGKILL, "Cancelled async attach.");
2847 Destroy ();
2848 }
2849 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002850 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002851 // If "caused_stop" is true, then DoHalt stopped the process. If
2852 // "caused_stop" is false, the process was already stopped.
2853 // If the DoHalt caused the process to stop, then we want to catch
2854 // this event and set the interrupted bool to true before we pass
2855 // this along so clients know that the process was interrupted by
2856 // a halt command.
2857 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002858 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002859 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002860 TimeValue timeout_time;
2861 timeout_time = TimeValue::Now();
2862 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002863 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2864 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002865
Jim Ingham0f16e732011-02-08 05:20:59 +00002866 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002867 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002868 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002869 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002870 }
2871 else
2872 {
Greg Clayton2637f822011-11-17 01:23:07 +00002873 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00002874 {
2875 // We caused the process to interrupt itself, so mark this
2876 // as such in the stop event so clients can tell an interrupted
2877 // process from a natural stop
2878 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2879 }
2880 else
2881 {
2882 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2883 if (log)
2884 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2885 error.SetErrorString ("Did not get stopped event after halt.");
2886 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002887 }
2888 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002889 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002890 }
2891 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002892 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002893 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002894 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002895
2896 // Post any event we might have consumed. If all goes well, we will have
2897 // stopped the process, intercepted the event and set the interrupted
2898 // bool in the event. Post it to the private event queue and that will end up
2899 // correctly setting the state.
2900 if (event_sp)
2901 m_private_state_broadcaster.BroadcastEvent(event_sp);
2902
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002903 return error;
2904}
2905
2906Error
2907Process::Detach ()
2908{
2909 Error error (WillDetach());
2910
2911 if (error.Success())
2912 {
2913 DisableAllBreakpointSites();
2914 error = DoDetach();
2915 if (error.Success())
2916 {
2917 DidDetach();
2918 StopPrivateStateThread();
2919 }
2920 }
2921 return error;
2922}
2923
2924Error
2925Process::Destroy ()
2926{
2927 Error error (WillDestroy());
2928 if (error.Success())
2929 {
2930 DisableAllBreakpointSites();
2931 error = DoDestroy();
2932 if (error.Success())
2933 {
2934 DidDestroy();
2935 StopPrivateStateThread();
2936 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002937 m_stdio_communication.StopReadThread();
2938 m_stdio_communication.Disconnect();
2939 if (m_process_input_reader && m_process_input_reader->IsActive())
2940 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2941 if (m_process_input_reader)
2942 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002943 }
2944 return error;
2945}
2946
2947Error
2948Process::Signal (int signal)
2949{
2950 Error error (WillSignal());
2951 if (error.Success())
2952 {
2953 error = DoSignal(signal);
2954 if (error.Success())
2955 DidSignal();
2956 }
2957 return error;
2958}
2959
Greg Clayton514487e2011-02-15 21:59:32 +00002960lldb::ByteOrder
2961Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002962{
Greg Clayton514487e2011-02-15 21:59:32 +00002963 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002964}
2965
2966uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002967Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002968{
Greg Clayton514487e2011-02-15 21:59:32 +00002969 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002970}
2971
Greg Clayton514487e2011-02-15 21:59:32 +00002972
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002973bool
2974Process::ShouldBroadcastEvent (Event *event_ptr)
2975{
2976 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2977 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002978 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002979
2980 switch (state)
2981 {
Greg Claytonb766a732011-02-04 01:58:07 +00002982 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002983 case eStateAttaching:
2984 case eStateLaunching:
2985 case eStateDetached:
2986 case eStateExited:
2987 case eStateUnloaded:
2988 // These events indicate changes in the state of the debugging session, always report them.
2989 return_value = true;
2990 break;
2991 case eStateInvalid:
2992 // We stopped for no apparent reason, don't report it.
2993 return_value = false;
2994 break;
2995 case eStateRunning:
2996 case eStateStepping:
2997 // If we've started the target running, we handle the cases where we
2998 // are already running and where there is a transition from stopped to
2999 // running differently.
3000 // running -> running: Automatically suppress extra running events
3001 // stopped -> running: Report except when there is one or more no votes
3002 // and no yes votes.
3003 SynchronouslyNotifyStateChanged (state);
3004 switch (m_public_state.GetValue())
3005 {
3006 case eStateRunning:
3007 case eStateStepping:
3008 // We always suppress multiple runnings with no PUBLIC stop in between.
3009 return_value = false;
3010 break;
3011 default:
3012 // TODO: make this work correctly. For now always report
3013 // run if we aren't running so we don't miss any runnning
3014 // events. If I run the lldb/test/thread/a.out file and
3015 // break at main.cpp:58, run and hit the breakpoints on
3016 // multiple threads, then somehow during the stepping over
3017 // of all breakpoints no run gets reported.
3018 return_value = true;
3019
3020 // This is a transition from stop to run.
3021 switch (m_thread_list.ShouldReportRun (event_ptr))
3022 {
3023 case eVoteYes:
3024 case eVoteNoOpinion:
3025 return_value = true;
3026 break;
3027 case eVoteNo:
3028 return_value = false;
3029 break;
3030 }
3031 break;
3032 }
3033 break;
3034 case eStateStopped:
3035 case eStateCrashed:
3036 case eStateSuspended:
3037 {
3038 // We've stopped. First see if we're going to restart the target.
3039 // If we are going to stop, then we always broadcast the event.
3040 // 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 +00003041 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003042 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003043 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003044 if (log)
3045 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003046 return true;
3047 }
3048 else
3049 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003050 RefreshStateAfterStop ();
3051
3052 if (m_thread_list.ShouldStop (event_ptr) == false)
3053 {
3054 switch (m_thread_list.ShouldReportStop (event_ptr))
3055 {
3056 case eVoteYes:
3057 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003058 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003059 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003060 case eVoteNo:
3061 return_value = false;
3062 break;
3063 }
3064
3065 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003066 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003067 Resume ();
3068 }
3069 else
3070 {
3071 return_value = true;
3072 SynchronouslyNotifyStateChanged (state);
3073 }
3074 }
3075 }
3076 }
3077
3078 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003079 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003080 return return_value;
3081}
3082
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003083
3084bool
Jim Ingham372787f2012-04-07 00:00:41 +00003085Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003086{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003087 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003088
Greg Clayton8b82f082011-04-12 05:54:46 +00003089 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003090 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003091 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3092
Jim Ingham372787f2012-04-07 00:00:41 +00003093 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003094 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003095
3096 // Create a thread that watches our internal state and controls which
3097 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003098 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003099 if (already_running)
3100 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3101 else
3102 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Clayton3e06bd92011-01-09 21:07:35 +00003103 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00003104 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003105}
3106
3107void
3108Process::PausePrivateStateThread ()
3109{
3110 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3111}
3112
3113void
3114Process::ResumePrivateStateThread ()
3115{
3116 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3117}
3118
3119void
3120Process::StopPrivateStateThread ()
3121{
Greg Clayton8b82f082011-04-12 05:54:46 +00003122 if (PrivateStateThreadIsValid ())
3123 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003124}
3125
3126void
3127Process::ControlPrivateStateThread (uint32_t signal)
3128{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003129 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003130
3131 assert (signal == eBroadcastInternalStateControlStop ||
3132 signal == eBroadcastInternalStateControlPause ||
3133 signal == eBroadcastInternalStateControlResume);
3134
3135 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003136 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003137
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003138 // Signal the private state thread. First we should copy this is case the
3139 // thread starts exiting since the private state thread will NULL this out
3140 // when it exits
3141 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003142 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003143 {
3144 TimeValue timeout_time;
3145 bool timed_out;
3146
3147 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3148
3149 timeout_time = TimeValue::Now();
3150 timeout_time.OffsetWithSeconds(2);
3151 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3152 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3153
3154 if (signal == eBroadcastInternalStateControlStop)
3155 {
3156 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003157 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003158
3159 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003160 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003161 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003162 }
3163 }
3164}
3165
3166void
3167Process::HandlePrivateEvent (EventSP &event_sp)
3168{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003169 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003170
Greg Clayton414f5d32011-01-25 02:58:48 +00003171 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003172
3173 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003174 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003175 {
Jim Ingham754ab982011-01-29 04:05:41 +00003176 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003177 switch (action_result)
3178 {
3179 case NextEventAction::eEventActionSuccess:
3180 SetNextEventAction(NULL);
3181 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003182
Jim Inghambb3a2832011-01-29 01:49:25 +00003183 case NextEventAction::eEventActionRetry:
3184 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003185
Jim Inghambb3a2832011-01-29 01:49:25 +00003186 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003187 // Handle Exiting Here. If we already got an exited event,
3188 // we should just propagate it. Otherwise, swallow this event,
3189 // and set our state to exit so the next event will kill us.
3190 if (new_state != eStateExited)
3191 {
3192 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003193 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003194 SetNextEventAction(NULL);
3195 return;
3196 }
3197 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003198 break;
3199 }
3200 }
3201
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003202 // See if we should broadcast this state to external clients?
3203 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003204
3205 if (should_broadcast)
3206 {
3207 if (log)
3208 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003209 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003210 __FUNCTION__,
3211 GetID(),
3212 StateAsCString(new_state),
3213 StateAsCString (GetState ()),
3214 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003215 }
Jim Ingham9575d842011-03-11 03:53:59 +00003216 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003217 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003218 PushProcessInputReader ();
3219 else
3220 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003221
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003222 BroadcastEvent (event_sp);
3223 }
3224 else
3225 {
3226 if (log)
3227 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003228 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003229 __FUNCTION__,
3230 GetID(),
3231 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003232 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233 }
3234 }
3235}
3236
3237void *
3238Process::PrivateStateThread (void *arg)
3239{
3240 Process *proc = static_cast<Process*> (arg);
3241 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003242 return result;
3243}
3244
3245void *
3246Process::RunPrivateStateThread ()
3247{
3248 bool control_only = false;
3249 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3250
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003251 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003252 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003253 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003254
3255 bool exit_now = false;
3256 while (!exit_now)
3257 {
3258 EventSP event_sp;
3259 WaitForEventsPrivate (NULL, event_sp, control_only);
3260 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3261 {
3262 switch (event_sp->GetType())
3263 {
3264 case eBroadcastInternalStateControlStop:
3265 exit_now = true;
3266 continue; // Go to next loop iteration so we exit without
3267 break; // doing any internal state managment below
3268
3269 case eBroadcastInternalStateControlPause:
3270 control_only = true;
3271 break;
3272
3273 case eBroadcastInternalStateControlResume:
3274 control_only = false;
3275 break;
3276 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003277
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003278 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003279 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 +00003280
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003281 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003282 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003283 }
3284
3285
3286 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3287
3288 if (internal_state != eStateInvalid)
3289 {
3290 HandlePrivateEvent (event_sp);
3291 }
3292
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003293 if (internal_state == eStateInvalid ||
3294 internal_state == eStateExited ||
3295 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003296 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003297 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003298 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 +00003299
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003300 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003301 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003302 }
3303
Caroline Tice20ad3c42010-10-29 21:48:37 +00003304 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003305 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003306 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003307
Greg Clayton6ed95942011-01-22 07:12:45 +00003308 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3309 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003310 return NULL;
3311}
3312
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003313//------------------------------------------------------------------
3314// Process Event Data
3315//------------------------------------------------------------------
3316
3317Process::ProcessEventData::ProcessEventData () :
3318 EventData (),
3319 m_process_sp (),
3320 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003321 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003322 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003323 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003324{
3325}
3326
3327Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3328 EventData (),
3329 m_process_sp (process_sp),
3330 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003331 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003332 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003333 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003334{
3335}
3336
3337Process::ProcessEventData::~ProcessEventData()
3338{
3339}
3340
3341const ConstString &
3342Process::ProcessEventData::GetFlavorString ()
3343{
3344 static ConstString g_flavor ("Process::ProcessEventData");
3345 return g_flavor;
3346}
3347
3348const ConstString &
3349Process::ProcessEventData::GetFlavor () const
3350{
3351 return ProcessEventData::GetFlavorString ();
3352}
3353
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003354void
3355Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3356{
3357 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003358 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3359 // the public event queue, then other times when we're pretending that this is where we stopped at the
3360 // end of expression evaluation. m_update_state is used to distinguish these
3361 // three cases; it is 0 when we're just pulling it off for private handling,
3362 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003363
Jim Inghama8604692011-05-22 21:45:01 +00003364 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365 return;
3366
3367 m_process_sp->SetPublicState (m_state);
3368
3369 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3370 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003371 {
3372 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003373 uint32_t num_threads = curr_thread_list.GetSize();
3374 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003375
Jim Ingham4b536182011-08-09 02:12:22 +00003376 // The actions might change one of the thread's stop_info's opinions about whether we should
3377 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003378
3379 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3380 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3381 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3382 // 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
3383 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003384 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003385 for (idx = 0; idx < num_threads; ++idx)
3386 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3387
Jim Ingham4b536182011-08-09 02:12:22 +00003388 bool still_should_stop = true;
3389
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003390 for (idx = 0; idx < num_threads; ++idx)
3391 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003392 curr_thread_list = m_process_sp->GetThreadList();
3393 if (curr_thread_list.GetSize() != num_threads)
3394 {
3395 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003396 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003397 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 +00003398 break;
3399 }
3400
3401 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3402
3403 if (thread_sp->GetIndexID() != thread_index_array[idx])
3404 {
3405 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003406 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003407 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003408 idx,
3409 thread_index_array[idx],
3410 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003411 break;
3412 }
3413
Jim Inghamb15bfc72010-10-20 00:39:53 +00003414 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3415 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003416 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003417 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003418 // The stop action might restart the target. If it does, then we want to mark that in the
3419 // event so that whoever is receiving it will know to wait for the running event and reflect
3420 // that state appropriately.
3421 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003422
3423 // FIXME: we might have run.
3424 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003425 {
3426 SetRestarted (true);
3427 break;
3428 }
3429 else if (!stop_info_sp->ShouldStop(event_ptr))
3430 {
3431 still_should_stop = false;
3432 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003433 }
3434 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003435
Jim Ingham4b536182011-08-09 02:12:22 +00003436
3437 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003438 {
Jim Ingham4b536182011-08-09 02:12:22 +00003439 if (!still_should_stop)
3440 {
3441 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003442 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003443 m_process_sp->Resume();
3444 }
3445 else
3446 {
3447 // If we didn't restart, run the Stop Hooks here:
3448 // They might also restart the target, so watch for that.
3449 m_process_sp->GetTarget().RunStopHooks();
3450 if (m_process_sp->GetPrivateState() == eStateRunning)
3451 SetRestarted(true);
3452 }
Jim Ingham9575d842011-03-11 03:53:59 +00003453 }
3454
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003455 }
3456}
3457
3458void
3459Process::ProcessEventData::Dump (Stream *s) const
3460{
3461 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003462 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003463
Greg Clayton8b82f082011-04-12 05:54:46 +00003464 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003465}
3466
3467const Process::ProcessEventData *
3468Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3469{
3470 if (event_ptr)
3471 {
3472 const EventData *event_data = event_ptr->GetData();
3473 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3474 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3475 }
3476 return NULL;
3477}
3478
3479ProcessSP
3480Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3481{
3482 ProcessSP process_sp;
3483 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3484 if (data)
3485 process_sp = data->GetProcessSP();
3486 return process_sp;
3487}
3488
3489StateType
3490Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3491{
3492 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3493 if (data == NULL)
3494 return eStateInvalid;
3495 else
3496 return data->GetState();
3497}
3498
3499bool
3500Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3501{
3502 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3503 if (data == NULL)
3504 return false;
3505 else
3506 return data->GetRestarted();
3507}
3508
3509void
3510Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3511{
3512 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3513 if (data != NULL)
3514 data->SetRestarted(new_value);
3515}
3516
3517bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003518Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3519{
3520 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3521 if (data == NULL)
3522 return false;
3523 else
3524 return data->GetInterrupted ();
3525}
3526
3527void
3528Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3529{
3530 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3531 if (data != NULL)
3532 data->SetInterrupted(new_value);
3533}
3534
3535bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003536Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3537{
3538 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3539 if (data)
3540 {
3541 data->SetUpdateStateOnRemoval();
3542 return true;
3543 }
3544 return false;
3545}
3546
Greg Claytond9e416c2012-02-18 05:35:26 +00003547lldb::TargetSP
3548Process::CalculateTarget ()
3549{
3550 return m_target.shared_from_this();
3551}
3552
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003553void
Greg Clayton0603aa92010-10-04 01:05:56 +00003554Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003555{
Greg Claytonc14ee322011-09-22 04:58:26 +00003556 exe_ctx.SetTargetPtr (&m_target);
3557 exe_ctx.SetProcessPtr (this);
3558 exe_ctx.SetThreadPtr(NULL);
3559 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003560}
3561
Greg Claytone996fd32011-03-08 22:40:15 +00003562//uint32_t
3563//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3564//{
3565// return 0;
3566//}
3567//
3568//ArchSpec
3569//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3570//{
3571// return Host::GetArchSpecForExistingProcess (pid);
3572//}
3573//
3574//ArchSpec
3575//Process::GetArchSpecForExistingProcess (const char *process_name)
3576//{
3577// return Host::GetArchSpecForExistingProcess (process_name);
3578//}
3579//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003580void
3581Process::AppendSTDOUT (const char * s, size_t len)
3582{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003583 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003584 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003585 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003586}
3587
3588void
Greg Clayton93e86192011-11-13 04:45:22 +00003589Process::AppendSTDERR (const char * s, size_t len)
3590{
3591 Mutex::Locker locker (m_stdio_communication_mutex);
3592 m_stderr_data.append (s, len);
3593 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3594}
3595
3596//------------------------------------------------------------------
3597// Process STDIO
3598//------------------------------------------------------------------
3599
3600size_t
3601Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3602{
3603 Mutex::Locker locker(m_stdio_communication_mutex);
3604 size_t bytes_available = m_stdout_data.size();
3605 if (bytes_available > 0)
3606 {
3607 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3608 if (log)
3609 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3610 if (bytes_available > buf_size)
3611 {
3612 memcpy(buf, m_stdout_data.c_str(), buf_size);
3613 m_stdout_data.erase(0, buf_size);
3614 bytes_available = buf_size;
3615 }
3616 else
3617 {
3618 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3619 m_stdout_data.clear();
3620 }
3621 }
3622 return bytes_available;
3623}
3624
3625
3626size_t
3627Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3628{
3629 Mutex::Locker locker(m_stdio_communication_mutex);
3630 size_t bytes_available = m_stderr_data.size();
3631 if (bytes_available > 0)
3632 {
3633 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3634 if (log)
3635 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3636 if (bytes_available > buf_size)
3637 {
3638 memcpy(buf, m_stderr_data.c_str(), buf_size);
3639 m_stderr_data.erase(0, buf_size);
3640 bytes_available = buf_size;
3641 }
3642 else
3643 {
3644 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3645 m_stderr_data.clear();
3646 }
3647 }
3648 return bytes_available;
3649}
3650
3651void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003652Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3653{
3654 Process *process = (Process *) baton;
3655 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3656}
3657
3658size_t
3659Process::ProcessInputReaderCallback (void *baton,
3660 InputReader &reader,
3661 lldb::InputReaderAction notification,
3662 const char *bytes,
3663 size_t bytes_len)
3664{
3665 Process *process = (Process *) baton;
3666
3667 switch (notification)
3668 {
3669 case eInputReaderActivate:
3670 break;
3671
3672 case eInputReaderDeactivate:
3673 break;
3674
3675 case eInputReaderReactivate:
3676 break;
3677
Caroline Tice969ed3d2011-05-02 20:41:46 +00003678 case eInputReaderAsynchronousOutputWritten:
3679 break;
3680
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003681 case eInputReaderGotToken:
3682 {
3683 Error error;
3684 process->PutSTDIN (bytes, bytes_len, error);
3685 }
3686 break;
3687
Caroline Ticeefed6132010-11-19 20:47:54 +00003688 case eInputReaderInterrupt:
3689 process->Halt ();
3690 break;
3691
3692 case eInputReaderEndOfFile:
3693 process->AppendSTDOUT ("^D", 2);
3694 break;
3695
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003696 case eInputReaderDone:
3697 break;
3698
3699 }
3700
3701 return bytes_len;
3702}
3703
3704void
3705Process::ResetProcessInputReader ()
3706{
3707 m_process_input_reader.reset();
3708}
3709
3710void
Greg Claytonee95ed52011-11-17 22:14:31 +00003711Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003712{
3713 // First set up the Read Thread for reading/handling process I/O
3714
3715 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3716
3717 if (conn_ap.get())
3718 {
3719 m_stdio_communication.SetConnection (conn_ap.release());
3720 if (m_stdio_communication.IsConnected())
3721 {
3722 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3723 m_stdio_communication.StartReadThread();
3724
3725 // Now read thread is set up, set up input reader.
3726
3727 if (!m_process_input_reader.get())
3728 {
3729 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3730 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3731 this,
3732 eInputReaderGranularityByte,
3733 NULL,
3734 NULL,
3735 false));
3736
3737 if (err.Fail())
3738 m_process_input_reader.reset();
3739 }
3740 }
3741 }
3742}
3743
3744void
3745Process::PushProcessInputReader ()
3746{
3747 if (m_process_input_reader && !m_process_input_reader->IsActive())
3748 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3749}
3750
3751void
3752Process::PopProcessInputReader ()
3753{
3754 if (m_process_input_reader && m_process_input_reader->IsActive())
3755 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3756}
3757
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003758// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003759void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003760Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003761{
Greg Claytone0d378b2011-03-24 21:19:54 +00003762 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003763
3764 int i=0;
3765 const char *name;
3766 OptionEnumValueElement option_enum;
3767 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3768 {
3769 if (name)
3770 {
3771 option_enum.value = i;
3772 option_enum.string_value = name;
3773 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3774 g_plugins.push_back (option_enum);
3775 }
3776 ++i;
3777 }
3778 option_enum.value = 0;
3779 option_enum.string_value = NULL;
3780 option_enum.usage = NULL;
3781 g_plugins.push_back (option_enum);
3782
3783 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3784 {
3785 if (::strcmp (name, "plugin") == 0)
3786 {
3787 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3788 break;
3789 }
3790 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003791 UserSettingsControllerSP &usc = GetSettingsController();
3792 usc.reset (new SettingsController);
3793 UserSettingsController::InitializeSettingsController (usc,
3794 SettingsController::global_settings_table,
3795 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003796
3797 // Now call SettingsInitialize() for each 'child' of Process settings
3798 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003799}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003800
Greg Clayton99d0faf2010-11-18 23:32:35 +00003801void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003802Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003803{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003804 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3805
3806 Thread::SettingsTerminate ();
3807
3808 // Now terminate Process Settings.
3809
Greg Clayton99d0faf2010-11-18 23:32:35 +00003810 UserSettingsControllerSP &usc = GetSettingsController();
3811 UserSettingsController::FinalizeSettingsController (usc);
3812 usc.reset();
3813}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003814
Greg Clayton99d0faf2010-11-18 23:32:35 +00003815UserSettingsControllerSP &
3816Process::GetSettingsController ()
3817{
Greg Claytonb9556ac2012-01-30 07:41:31 +00003818 static UserSettingsControllerSP g_settings_controller_sp;
3819 if (!g_settings_controller_sp)
3820 {
3821 g_settings_controller_sp.reset (new Process::SettingsController);
3822 // The first shared pointer to Process::SettingsController in
3823 // g_settings_controller_sp must be fully created above so that
3824 // the TargetInstanceSettings can use a weak_ptr to refer back
3825 // to the master setttings controller
3826 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp,
3827 false,
3828 InstanceSettings::GetDefaultName().AsCString()));
3829 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
3830 }
3831 return g_settings_controller_sp;
3832
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003833}
3834
Caroline Tice1559a462010-09-27 00:30:10 +00003835void
3836Process::UpdateInstanceName ()
3837{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003838 Module *module = GetTarget().GetExecutableModulePointer();
Greg Claytone1cd1be2012-01-29 20:56:30 +00003839 if (module && module->GetFileSpec().GetFilename())
Caroline Tice1559a462010-09-27 00:30:10 +00003840 {
Greg Claytondbe54502010-11-19 03:46:01 +00003841 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytone1cd1be2012-01-29 20:56:30 +00003842 module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003843 }
3844}
3845
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003846ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003847Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00003848 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00003849 bool stop_others,
3850 bool try_all_threads,
3851 bool discard_on_error,
3852 uint32_t single_thread_timeout_usec,
3853 Stream &errors)
3854{
3855 ExecutionResults return_value = eExecutionSetupError;
3856
Jim Ingham77787032011-01-20 02:03:18 +00003857 if (thread_plan_sp.get() == NULL)
3858 {
3859 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003860 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003861 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003862
3863 if (exe_ctx.GetProcessPtr() != this)
3864 {
3865 errors.Printf("RunThreadPlan called on wrong process.");
3866 return eExecutionSetupError;
3867 }
3868
3869 Thread *thread = exe_ctx.GetThreadPtr();
3870 if (thread == NULL)
3871 {
3872 errors.Printf("RunThreadPlan called with invalid thread.");
3873 return eExecutionSetupError;
3874 }
Jim Ingham77787032011-01-20 02:03:18 +00003875
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003876 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3877 // For that to be true the plan can't be private - since private plans suppress themselves in the
3878 // GetCompletedPlan call.
3879
3880 bool orig_plan_private = thread_plan_sp->GetPrivate();
3881 thread_plan_sp->SetPrivate(false);
3882
Jim Ingham444586b2011-01-24 06:34:17 +00003883 if (m_private_state.GetValue() != eStateStopped)
3884 {
3885 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003886 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003887 }
3888
Jim Ingham66243842011-08-13 00:56:10 +00003889 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00003890 const uint32_t thread_idx_id = thread->GetIndexID();
3891 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003892
3893 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3894 // so we should arrange to reset them as well.
3895
Greg Claytonc14ee322011-09-22 04:58:26 +00003896 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003897
Jim Ingham66243842011-08-13 00:56:10 +00003898 uint32_t selected_tid;
3899 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00003900 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00003901 {
3902 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003903 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003904 }
3905 else
3906 {
3907 selected_tid = LLDB_INVALID_THREAD_ID;
3908 }
3909
Jim Ingham372787f2012-04-07 00:00:41 +00003910 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
3911
3912 if (Host::GetCurrentThread() == m_private_state_thread)
3913 {
3914 // Yikes, we are running on the private state thread! So we can't call DoRunThreadPlan on this thread, since
3915 // then nobody will be around to fetch internal events.
3916 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
3917 // we are doing the RunThreadPlan here.
3918 backup_private_state_thread = m_private_state_thread;
3919 printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.\n");
3920 StartPrivateStateThread(true);
3921 }
3922
3923 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00003924
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003925 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003926
3927 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3928 // restored on exit to the function.
3929
3930 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003931
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003932 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003933 if (log)
3934 {
3935 StreamString s;
3936 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton81c22f62011-10-19 18:09:39 +00003937 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00003938 thread->GetIndexID(),
3939 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00003940 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003941 }
3942
Jim Ingham0f16e732011-02-08 05:20:59 +00003943 bool got_event;
3944 lldb::EventSP event_sp;
3945 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003946
3947 TimeValue* timeout_ptr = NULL;
3948 TimeValue real_timeout;
3949
Jim Ingham0f16e732011-02-08 05:20:59 +00003950 bool first_timeout = true;
3951 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003952
Jim Inghamf48169b2010-11-30 02:22:11 +00003953 while (1)
3954 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003955 // We usually want to resume the process if we get to the top of the loop.
3956 // The only exception is if we get two running events with no intervening
3957 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003958
Jim Ingham0f16e732011-02-08 05:20:59 +00003959 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003960 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003961 // Do the initial resume and wait for the running event before going further.
3962
Greg Claytonc14ee322011-09-22 04:58:26 +00003963 Error resume_error = Resume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00003964 if (!resume_error.Success())
3965 {
3966 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003967 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003968 break;
3969 }
3970
3971 real_timeout = TimeValue::Now();
3972 real_timeout.OffsetWithMicroSeconds(500000);
3973 timeout_ptr = &real_timeout;
3974
Sean Callananc1b312a2012-01-05 02:00:14 +00003975 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
Jim Ingham0f16e732011-02-08 05:20:59 +00003976 if (!got_event)
3977 {
3978 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003979 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003980
3981 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003982 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003983 break;
3984 }
3985
3986 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3987 if (stop_state != eStateRunning)
3988 {
3989 if (log)
3990 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3991
3992 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003993 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003994 break;
3995 }
3996
3997 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003998 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003999 // We need to call the function synchronously, so spin waiting for it to return.
4000 // If we get interrupted while executing, we're going to lose our context, and
4001 // won't be able to gather the result at this point.
4002 // We set the timeout AFTER the resume, since the resume takes some time and we
4003 // don't want to charge that to the timeout.
4004
4005 if (single_thread_timeout_usec != 0)
4006 {
4007 real_timeout = TimeValue::Now();
4008 if (first_timeout)
4009 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
4010 else
4011 real_timeout.OffsetWithSeconds(10);
4012
4013 timeout_ptr = &real_timeout;
4014 }
4015 }
4016 else
4017 {
4018 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004019 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004020 do_resume = true;
4021 }
4022
4023 // Now wait for the process to stop again:
4024 stop_state = lldb::eStateInvalid;
4025 event_sp.reset();
4026 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4027
4028 if (got_event)
4029 {
4030 if (event_sp.get())
4031 {
4032 bool keep_going = false;
4033 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4034 if (log)
4035 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
4036
4037 switch (stop_state)
4038 {
4039 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00004040 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004041 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00004042 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00004043 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00004044 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004045 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00004046 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00004047 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4048 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00004049 }
4050 else
4051 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004052 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4053 StopReason stop_reason = eStopReasonInvalid;
4054 if (stop_info_sp)
4055 stop_reason = stop_info_sp->GetStopReason();
4056 if (stop_reason == eStopReasonPlanComplete)
4057 {
4058 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004059 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004060 // Now mark this plan as private so it doesn't get reported as the stop reason
4061 // after this point.
4062 if (thread_plan_sp)
4063 thread_plan_sp->SetPrivate (orig_plan_private);
4064 return_value = eExecutionCompleted;
4065 }
4066 else
4067 {
4068 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004069 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004070
4071 return_value = eExecutionInterrupted;
4072 }
Jim Ingham160f78c2011-05-17 01:10:11 +00004073 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00004074 }
4075 break;
4076
Jim Ingham0f16e732011-02-08 05:20:59 +00004077 case lldb::eStateCrashed:
4078 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004079 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004080 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004081 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004082
Jim Ingham0f16e732011-02-08 05:20:59 +00004083 case lldb::eStateRunning:
4084 do_resume = false;
4085 keep_going = true;
4086 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004087
Jim Ingham0f16e732011-02-08 05:20:59 +00004088 default:
4089 if (log)
4090 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00004091
4092 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004093 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004094 break;
4095 }
4096 if (keep_going)
4097 continue;
4098 else
4099 break;
4100 }
4101 else
4102 {
4103 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004104 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00004105 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004106 break;
4107 }
4108 }
4109 else
4110 {
4111 // If we didn't get an event that means we've timed out...
4112 // We will interrupt the process here. Depending on what we were asked to do we will
4113 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00004114 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00004115
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004116 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00004117 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00004118 {
4119 if (first_timeout)
4120 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4121 "trying with all threads enabled.",
4122 single_thread_timeout_usec);
4123 else
4124 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4125 "and timeout: %d timed out.",
4126 single_thread_timeout_usec);
4127 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004128 else
Jim Ingham0f16e732011-02-08 05:20:59 +00004129 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4130 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00004131 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004132 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004133
Greg Claytonc14ee322011-09-22 04:58:26 +00004134 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00004135 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00004136 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004137 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004138 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004139
Jim Ingham0f16e732011-02-08 05:20:59 +00004140 // If halt succeeds, it always produces a stopped event. Wait for that:
4141
4142 real_timeout = TimeValue::Now();
4143 real_timeout.OffsetWithMicroSeconds(500000);
4144
4145 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004146
4147 if (got_event)
4148 {
4149 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4150 if (log)
4151 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004152 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00004153 if (stop_state == lldb::eStateStopped
4154 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00004155 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004156 }
4157
Jim Ingham0f16e732011-02-08 05:20:59 +00004158 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00004159 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004160 // Between the time we initiated the Halt and the time we delivered it, the process could have
4161 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00004162
Greg Claytonc14ee322011-09-22 04:58:26 +00004163 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004164 {
4165 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004166 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004167 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004168 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004169 break;
4170 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004171
Jim Ingham0f16e732011-02-08 05:20:59 +00004172 if (!try_all_threads)
4173 {
4174 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004175 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004176 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004177 break;
4178 }
4179
4180 if (first_timeout)
4181 {
4182 // Set all the other threads to run, and return to the top of the loop, which will continue;
4183 first_timeout = false;
4184 thread_plan_sp->SetStopOthers (false);
4185 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004186 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004187
4188 continue;
4189 }
4190 else
4191 {
4192 // Running all threads failed, so return Interrupted.
4193 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004194 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004195 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004196 break;
4197 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004198 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004199 }
4200 else
4201 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004202 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004203 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004204 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004205 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00004206 }
4207 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004208 else
4209 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004210 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4211 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00004212 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004213 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.",
4214 halt_error.AsCString());
4215 real_timeout = TimeValue::Now();
4216 real_timeout.OffsetWithMicroSeconds(500000);
4217 timeout_ptr = &real_timeout;
4218 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4219 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004220 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004221 // This is not going anywhere, bag out.
4222 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004223 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004224 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004225 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004226 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004227 else
4228 {
4229 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4230 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004231 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00004232 if (stop_state == lldb::eStateStopped)
4233 {
4234 // Between the time we initiated the Halt and the time we delivered it, the process could have
4235 // already finished its job. Check that here:
4236
Greg Claytonc14ee322011-09-22 04:58:26 +00004237 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004238 {
4239 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004240 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004241 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004242 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004243 break;
4244 }
4245
4246 if (first_timeout)
4247 {
4248 // Set all the other threads to run, and return to the top of the loop, which will continue;
4249 first_timeout = false;
4250 thread_plan_sp->SetStopOthers (false);
4251 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004252 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004253
4254 continue;
4255 }
4256 else
4257 {
4258 // Running all threads failed, so return Interrupted.
4259 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004260 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004261 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004262 break;
4263 }
4264 }
4265 else
4266 {
Sean Callanan39821ac2011-08-09 22:07:08 +00004267 if (log)
4268 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4269 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00004270 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004271 break;
4272 }
4273 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004274 }
4275
Jim Inghamf48169b2010-11-30 02:22:11 +00004276 }
4277
Jim Ingham0f16e732011-02-08 05:20:59 +00004278 } // END WAIT LOOP
4279
Jim Ingham372787f2012-04-07 00:00:41 +00004280 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4281 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4282 {
4283 StopPrivateStateThread();
4284 lldb::thread_result_t thread_result;
4285 Error error;
4286 // Host::ThreadJoin(m_private_state_thread, &thread_result, &error);
4287 m_private_state_thread = backup_private_state_thread;
4288 }
4289
4290
Jim Ingham0f16e732011-02-08 05:20:59 +00004291 // Now do some processing on the results of the run:
4292 if (return_value == eExecutionInterrupted)
4293 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004294 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004295 {
4296 StreamString s;
4297 if (event_sp)
4298 event_sp->Dump (&s);
4299 else
4300 {
Jim Ingham20829ac2011-08-09 22:24:33 +00004301 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004302 }
4303
4304 StreamString ts;
4305
Jim Ingham20829ac2011-08-09 22:24:33 +00004306 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00004307
4308 do
4309 {
4310 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4311
4312 if (!event_data)
4313 {
4314 event_explanation = "<no event data>";
4315 break;
4316 }
4317
4318 Process *process = event_data->GetProcessSP().get();
4319
4320 if (!process)
4321 {
4322 event_explanation = "<no process>";
4323 break;
4324 }
4325
4326 ThreadList &thread_list = process->GetThreadList();
4327
4328 uint32_t num_threads = thread_list.GetSize();
4329 uint32_t thread_index;
4330
4331 ts.Printf("<%u threads> ", num_threads);
4332
4333 for (thread_index = 0;
4334 thread_index < num_threads;
4335 ++thread_index)
4336 {
4337 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4338
4339 if (!thread)
4340 {
4341 ts.Printf("<?> ");
4342 continue;
4343 }
4344
Greg Clayton81c22f62011-10-19 18:09:39 +00004345 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Ingham0f16e732011-02-08 05:20:59 +00004346 RegisterContext *register_context = thread->GetRegisterContext().get();
4347
4348 if (register_context)
4349 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4350 else
4351 ts.Printf("[ip unknown] ");
4352
4353 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4354 if (stop_info_sp)
4355 {
4356 const char *stop_desc = stop_info_sp->GetDescription();
4357 if (stop_desc)
4358 ts.PutCString (stop_desc);
4359 }
4360 ts.Printf(">");
4361 }
4362
4363 event_explanation = ts.GetData();
4364 } while (0);
4365
4366 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004367 {
4368 if (event_explanation)
4369 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4370 else
4371 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4372 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004373
4374 if (discard_on_error && thread_plan_sp)
4375 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004376 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004377 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004378 }
4379 }
4380 }
4381 else if (return_value == eExecutionSetupError)
4382 {
4383 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004384 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004385
4386 if (discard_on_error && thread_plan_sp)
4387 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004388 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004389 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004390 }
4391 }
4392 else
4393 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004394 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004395 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004396 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004397 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00004398 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00004399 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004400 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004401 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004402 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004403 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00004404 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00004405 }
4406 else
4407 {
4408 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004409 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00004410 if (discard_on_error && thread_plan_sp)
4411 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004412 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004413 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00004414 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004415 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00004416 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004417 }
4418 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004419
Jim Inghamf48169b2010-11-30 02:22:11 +00004420 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00004421 // Check that it's still there, and if it is put it back in the context. Also restore the
4422 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00004423 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4424 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00004425 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004426 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00004427 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004428
4429 // Also restore the current process'es selected frame & thread, since this function calling may
4430 // be done behind the user's back.
4431
4432 if (selected_tid != LLDB_INVALID_THREAD_ID)
4433 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004434 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00004435 {
4436 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00004437 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00004438 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00004439 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004440 }
4441 }
4442
4443 return return_value;
4444}
4445
4446const char *
4447Process::ExecutionResultAsCString (ExecutionResults result)
4448{
4449 const char *result_name;
4450
4451 switch (result)
4452 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004453 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004454 result_name = "eExecutionCompleted";
4455 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004456 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004457 result_name = "eExecutionDiscarded";
4458 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004459 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004460 result_name = "eExecutionInterrupted";
4461 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004462 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004463 result_name = "eExecutionSetupError";
4464 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004465 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004466 result_name = "eExecutionTimedOut";
4467 break;
4468 }
4469 return result_name;
4470}
4471
Greg Clayton7260f622011-04-18 08:33:37 +00004472void
4473Process::GetStatus (Stream &strm)
4474{
4475 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00004476 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00004477 {
4478 if (state == eStateExited)
4479 {
4480 int exit_status = GetExitStatus();
4481 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004482 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004483 GetID(),
4484 exit_status,
4485 exit_status,
4486 exit_description ? exit_description : "");
4487 }
4488 else
4489 {
4490 if (state == eStateConnected)
4491 strm.Printf ("Connected to remote target.\n");
4492 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004493 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004494 }
4495 }
4496 else
4497 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004498 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004499 }
4500}
4501
4502size_t
4503Process::GetThreadStatus (Stream &strm,
4504 bool only_threads_with_stop_reason,
4505 uint32_t start_frame,
4506 uint32_t num_frames,
4507 uint32_t num_frames_with_source)
4508{
4509 size_t num_thread_infos_dumped = 0;
4510
4511 const size_t num_threads = GetThreadList().GetSize();
4512 for (uint32_t i = 0; i < num_threads; i++)
4513 {
4514 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4515 if (thread)
4516 {
4517 if (only_threads_with_stop_reason)
4518 {
4519 if (thread->GetStopInfo().get() == NULL)
4520 continue;
4521 }
4522 thread->GetStatus (strm,
4523 start_frame,
4524 num_frames,
4525 num_frames_with_source);
4526 ++num_thread_infos_dumped;
4527 }
4528 }
4529 return num_thread_infos_dumped;
4530}
4531
Greg Claytona9f40ad2012-02-22 04:37:26 +00004532void
4533Process::AddInvalidMemoryRegion (const LoadRange &region)
4534{
4535 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4536}
4537
4538bool
4539Process::RemoveInvalidMemoryRange (const LoadRange &region)
4540{
4541 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4542}
4543
Jim Ingham372787f2012-04-07 00:00:41 +00004544void
4545Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4546{
4547 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4548}
4549
4550bool
4551Process::RunPreResumeActions ()
4552{
4553 bool result = true;
4554 while (!m_pre_resume_actions.empty())
4555 {
4556 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
4557 m_pre_resume_actions.pop_back();
4558 bool this_result = action.callback (action.baton);
4559 if (result == true) result = this_result;
4560 }
4561 return result;
4562}
4563
4564void
4565Process::ClearPreResumeActions ()
4566{
4567 m_pre_resume_actions.clear();
4568}
Greg Claytona9f40ad2012-02-22 04:37:26 +00004569
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004570//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004571// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004572//--------------------------------------------------------------
4573
Greg Clayton1b654882010-09-19 02:33:57 +00004574Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004575 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004576{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004577}
4578
Greg Clayton1b654882010-09-19 02:33:57 +00004579Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004580{
4581}
4582
4583lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004584Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004585{
Greg Claytonb9556ac2012-01-30 07:41:31 +00004586 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4587 false,
4588 instance_name));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004589 return new_settings_sp;
4590}
4591
4592//--------------------------------------------------------------
4593// class ProcessInstanceSettings
4594//--------------------------------------------------------------
4595
Greg Clayton85851dd2010-12-04 00:10:17 +00004596ProcessInstanceSettings::ProcessInstanceSettings
4597(
Greg Claytonb9556ac2012-01-30 07:41:31 +00004598 const UserSettingsControllerSP &owner_sp,
Greg Clayton85851dd2010-12-04 00:10:17 +00004599 bool live_instance,
4600 const char *name
4601) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004602 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004603{
Caroline Ticef20e8232010-09-09 18:26:37 +00004604 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4605 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4606 // 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 +00004607 // This is true for CreateInstanceName() too.
Greg Clayton1d885962011-11-08 02:43:13 +00004608
Caroline Tice9e41c152010-09-16 19:05:55 +00004609 if (GetInstanceName () == InstanceSettings::InvalidName())
4610 {
4611 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
Greg Claytonb9556ac2012-01-30 07:41:31 +00004612 owner_sp->RegisterInstanceSettings (this);
Caroline Tice9e41c152010-09-16 19:05:55 +00004613 }
Greg Clayton1d885962011-11-08 02:43:13 +00004614
Caroline Ticef20e8232010-09-09 18:26:37 +00004615 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004616 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004617 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004618 CopyInstanceSettings (pending_settings,false);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004619 }
4620}
4621
4622ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004623 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004624{
4625 if (m_instance_name != InstanceSettings::GetDefaultName())
4626 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004627 UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4628 if (owner_sp)
4629 {
4630 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4631 owner_sp->RemovePendingSettings (m_instance_name);
4632 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004633 }
4634}
4635
4636ProcessInstanceSettings::~ProcessInstanceSettings ()
4637{
4638}
4639
4640ProcessInstanceSettings&
4641ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4642{
4643 if (this != &rhs)
4644 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004645 }
4646
4647 return *this;
4648}
4649
4650
4651void
4652ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4653 const char *index_value,
4654 const char *value,
4655 const ConstString &instance_name,
4656 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004657 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004658 Error &err,
4659 bool pending)
4660{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004661}
4662
4663void
4664ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4665 bool pending)
4666{
Greg Clayton1d885962011-11-08 02:43:13 +00004667// if (new_settings.get() == NULL)
4668// return;
4669//
4670// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004671}
4672
Caroline Tice12cecd72010-09-20 21:37:42 +00004673bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004674ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4675 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004676 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004677 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004678{
Greg Clayton1d885962011-11-08 02:43:13 +00004679 if (err)
4680 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4681 return false;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004682}
4683
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004684const ConstString
4685ProcessInstanceSettings::CreateInstanceName ()
4686{
4687 static int instance_count = 1;
4688 StreamString sstr;
4689
4690 sstr.Printf ("process_%d", instance_count);
4691 ++instance_count;
4692
4693 const ConstString ret_val (sstr.GetData());
4694 return ret_val;
4695}
4696
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004697//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004698// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004699//--------------------------------------------------
4700
4701SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004702Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004703{
4704 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4705 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4706};
4707
4708
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004709SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004710Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004711{
Greg Clayton85851dd2010-12-04 00:10:17 +00004712 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton85851dd2010-12-04 00:10:17 +00004713 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004714};
4715
4716
Jim Ingham5aee1622010-08-09 23:31:02 +00004717
Greg Clayton1d885962011-11-08 02:43:13 +00004718