blob: 6ad0ed05c6e893af98a5019f4a9e2d49fa249fe6 [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
Greg Clayton9fc13552012-04-10 00:18:59 +00001239 // thread list, but only update if "true" is returned
1240 if (UpdateThreadList (m_thread_list, new_thread_list))
1241 {
1242 OperatingSystem *os = GetOperatingSystem ();
1243 if (os)
1244 os->UpdateThreadList (m_thread_list, new_thread_list);
1245 m_thread_list.Update (new_thread_list);
1246 m_thread_list.SetStopID (stop_id);
1247 }
Greg Clayton2637f822011-11-17 01:23:07 +00001248 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001249 }
1250}
1251
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001252uint32_t
1253Process::GetNextThreadIndexID ()
1254{
1255 return ++m_thread_index_id;
1256}
1257
1258StateType
1259Process::GetState()
1260{
1261 // If any other threads access this we will need a mutex for it
1262 return m_public_state.GetValue ();
1263}
1264
1265void
1266Process::SetPublicState (StateType new_state)
1267{
Greg Clayton414f5d32011-01-25 02:58:48 +00001268 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001269 if (log)
1270 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001271 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001272 m_public_state.SetValue (new_state);
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001273 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1274 {
1275 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1276 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1277 if (old_state_is_stopped != new_state_is_stopped)
1278 {
1279 if (new_state_is_stopped)
1280 {
1281 if (log)
1282 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1283 m_run_lock.WriteUnlock();
1284 }
1285 else
1286 {
1287 if (log)
1288 log->Printf("Process::SetPublicState (%s) -- locking run lock", StateAsCString(new_state));
1289 m_run_lock.WriteLock();
1290 }
1291 }
1292 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001293}
1294
1295StateType
1296Process::GetPrivateState ()
1297{
1298 return m_private_state.GetValue();
1299}
1300
1301void
1302Process::SetPrivateState (StateType new_state)
1303{
Greg Clayton414f5d32011-01-25 02:58:48 +00001304 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001305 bool state_changed = false;
1306
1307 if (log)
1308 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1309
1310 Mutex::Locker locker(m_private_state.GetMutex());
1311
1312 const StateType old_state = m_private_state.GetValueNoLock ();
1313 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001314 // This code is left commented out in case we ever need to control
1315 // the private process state with another run lock. Right now it doesn't
1316 // seem like we need to do this, but if we ever do, we can uncomment and
1317 // use this code.
1318// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1319// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1320// if (old_state_is_stopped != new_state_is_stopped)
1321// {
1322// if (new_state_is_stopped)
1323// m_private_run_lock.WriteUnlock();
1324// else
1325// m_private_run_lock.WriteLock();
1326// }
1327
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001328 if (state_changed)
1329 {
1330 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001331 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001332 {
Jim Ingham4b536182011-08-09 02:12:22 +00001333 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001334 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001335 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001336 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001337 }
1338 // Use our target to get a shared pointer to ourselves...
1339 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1340 }
1341 else
1342 {
1343 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001344 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001345 }
1346}
1347
Jim Ingham0faa43f2011-11-08 03:00:11 +00001348void
1349Process::SetRunningUserExpression (bool on)
1350{
1351 m_mod_id.SetRunningUserExpression (on);
1352}
1353
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001354addr_t
1355Process::GetImageInfoAddress()
1356{
1357 return LLDB_INVALID_ADDRESS;
1358}
1359
Greg Clayton8f343b02010-11-04 01:54:29 +00001360//----------------------------------------------------------------------
1361// LoadImage
1362//
1363// This function provides a default implementation that works for most
1364// unix variants. Any Process subclasses that need to do shared library
1365// loading differently should override LoadImage and UnloadImage and
1366// do what is needed.
1367//----------------------------------------------------------------------
1368uint32_t
1369Process::LoadImage (const FileSpec &image_spec, Error &error)
1370{
1371 DynamicLoader *loader = GetDynamicLoader();
1372 if (loader)
1373 {
1374 error = loader->CanLoadImage();
1375 if (error.Fail())
1376 return LLDB_INVALID_IMAGE_TOKEN;
1377 }
1378
1379 if (error.Success())
1380 {
1381 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001382
1383 if (thread_sp)
1384 {
1385 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1386
1387 if (frame_sp)
1388 {
1389 ExecutionContext exe_ctx;
1390 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001391 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001392 StreamString expr;
1393 char path[PATH_MAX];
1394 image_spec.GetPath(path, sizeof(path));
1395 expr.Printf("dlopen (\"%s\", 2)", path);
1396 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001397 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001398 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 +00001399 error = result_valobj_sp->GetError();
1400 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001401 {
1402 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001403 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001404 {
1405 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1406 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1407 {
1408 uint32_t image_token = m_image_tokens.size();
1409 m_image_tokens.push_back (image_ptr);
1410 return image_token;
1411 }
1412 }
1413 }
1414 }
1415 }
1416 }
1417 return LLDB_INVALID_IMAGE_TOKEN;
1418}
1419
1420//----------------------------------------------------------------------
1421// UnloadImage
1422//
1423// This function provides a default implementation that works for most
1424// unix variants. Any Process subclasses that need to do shared library
1425// loading differently should override LoadImage and UnloadImage and
1426// do what is needed.
1427//----------------------------------------------------------------------
1428Error
1429Process::UnloadImage (uint32_t image_token)
1430{
1431 Error error;
1432 if (image_token < m_image_tokens.size())
1433 {
1434 const addr_t image_addr = m_image_tokens[image_token];
1435 if (image_addr == LLDB_INVALID_ADDRESS)
1436 {
1437 error.SetErrorString("image already unloaded");
1438 }
1439 else
1440 {
1441 DynamicLoader *loader = GetDynamicLoader();
1442 if (loader)
1443 error = loader->CanLoadImage();
1444
1445 if (error.Success())
1446 {
1447 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001448
1449 if (thread_sp)
1450 {
1451 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1452
1453 if (frame_sp)
1454 {
1455 ExecutionContext exe_ctx;
1456 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001457 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001458 StreamString expr;
1459 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1460 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001461 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001462 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 +00001463 if (result_valobj_sp->GetError().Success())
1464 {
1465 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001466 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001467 {
1468 if (scalar.UInt(1))
1469 {
1470 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1471 }
1472 else
1473 {
1474 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1475 }
1476 }
1477 }
1478 else
1479 {
1480 error = result_valobj_sp->GetError();
1481 }
1482 }
1483 }
1484 }
1485 }
1486 }
1487 else
1488 {
1489 error.SetErrorString("invalid image token");
1490 }
1491 return error;
1492}
1493
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001494const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001495Process::GetABI()
1496{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001497 if (!m_abi_sp)
1498 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1499 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001500}
1501
Jim Ingham22777012010-09-23 02:01:19 +00001502LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001503Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001504{
1505 LanguageRuntimeCollection::iterator pos;
1506 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001507 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001508 {
Jim Inghamab175242012-03-10 00:22:19 +00001509 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001510
Jim Inghamab175242012-03-10 00:22:19 +00001511 m_language_runtimes[language] = runtime_sp;
1512 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001513 }
1514 else
1515 return (*pos).second.get();
1516}
1517
1518CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001519Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001520{
Jim Inghamab175242012-03-10 00:22:19 +00001521 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001522 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1523 return static_cast<CPPLanguageRuntime *> (runtime);
1524 return NULL;
1525}
1526
1527ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001528Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001529{
Jim Inghamab175242012-03-10 00:22:19 +00001530 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001531 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1532 return static_cast<ObjCLanguageRuntime *> (runtime);
1533 return NULL;
1534}
1535
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001536BreakpointSiteList &
1537Process::GetBreakpointSiteList()
1538{
1539 return m_breakpoint_site_list;
1540}
1541
1542const BreakpointSiteList &
1543Process::GetBreakpointSiteList() const
1544{
1545 return m_breakpoint_site_list;
1546}
1547
1548
1549void
1550Process::DisableAllBreakpointSites ()
1551{
1552 m_breakpoint_site_list.SetEnabledForAll (false);
1553}
1554
1555Error
1556Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1557{
1558 Error error (DisableBreakpointSiteByID (break_id));
1559
1560 if (error.Success())
1561 m_breakpoint_site_list.Remove(break_id);
1562
1563 return error;
1564}
1565
1566Error
1567Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1568{
1569 Error error;
1570 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1571 if (bp_site_sp)
1572 {
1573 if (bp_site_sp->IsEnabled())
1574 error = DisableBreakpoint (bp_site_sp.get());
1575 }
1576 else
1577 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001578 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001579 }
1580
1581 return error;
1582}
1583
1584Error
1585Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1586{
1587 Error error;
1588 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1589 if (bp_site_sp)
1590 {
1591 if (!bp_site_sp->IsEnabled())
1592 error = EnableBreakpoint (bp_site_sp.get());
1593 }
1594 else
1595 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001596 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001597 }
1598 return error;
1599}
1600
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001601lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001602Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001603{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001604 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001605 if (load_addr != LLDB_INVALID_ADDRESS)
1606 {
1607 BreakpointSiteSP bp_site_sp;
1608
1609 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1610 // create a new breakpoint site and add it.
1611
1612 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1613
1614 if (bp_site_sp)
1615 {
1616 bp_site_sp->AddOwner (owner);
1617 owner->SetBreakpointSite (bp_site_sp);
1618 return bp_site_sp->GetID();
1619 }
1620 else
1621 {
1622 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1623 if (bp_site_sp)
1624 {
1625 if (EnableBreakpoint (bp_site_sp.get()).Success())
1626 {
1627 owner->SetBreakpointSite (bp_site_sp);
1628 return m_breakpoint_site_list.Add (bp_site_sp);
1629 }
1630 }
1631 }
1632 }
1633 // We failed to enable the breakpoint
1634 return LLDB_INVALID_BREAK_ID;
1635
1636}
1637
1638void
1639Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1640{
1641 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1642 if (num_owners == 0)
1643 {
1644 DisableBreakpoint(bp_site_sp.get());
1645 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1646 }
1647}
1648
1649
1650size_t
1651Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1652{
1653 size_t bytes_removed = 0;
1654 addr_t intersect_addr;
1655 size_t intersect_size;
1656 size_t opcode_offset;
1657 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001658 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001659 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001660
Jim Ingham20c77192011-06-29 19:42:28 +00001661 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001662 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001663 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001665 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001666 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001667 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001668 {
1669 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1670 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001671 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001672 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001673 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001674 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001675 }
1676 }
1677 }
1678 return bytes_removed;
1679}
1680
1681
Greg Claytonded470d2011-03-19 01:12:21 +00001682
1683size_t
1684Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1685{
1686 PlatformSP platform_sp (m_target.GetPlatform());
1687 if (platform_sp)
1688 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1689 return 0;
1690}
1691
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001692Error
1693Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1694{
1695 Error error;
1696 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001697 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001698 const addr_t bp_addr = bp_site->GetLoadAddress();
1699 if (log)
1700 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1701 if (bp_site->IsEnabled())
1702 {
1703 if (log)
1704 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1705 return error;
1706 }
1707
1708 if (bp_addr == LLDB_INVALID_ADDRESS)
1709 {
1710 error.SetErrorString("BreakpointSite contains an invalid load address.");
1711 return error;
1712 }
1713 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1714 // trap for the breakpoint site
1715 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1716
1717 if (bp_opcode_size == 0)
1718 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001719 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001720 }
1721 else
1722 {
1723 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1724
1725 if (bp_opcode_bytes == NULL)
1726 {
1727 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1728 return error;
1729 }
1730
1731 // Save the original opcode by reading it
1732 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1733 {
1734 // Write a software breakpoint in place of the original opcode
1735 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1736 {
1737 uint8_t verify_bp_opcode_bytes[64];
1738 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1739 {
1740 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1741 {
1742 bp_site->SetEnabled(true);
1743 bp_site->SetType (BreakpointSite::eSoftware);
1744 if (log)
1745 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1746 bp_site->GetID(),
1747 (uint64_t)bp_addr);
1748 }
1749 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001750 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001751 }
1752 else
1753 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1754 }
1755 else
1756 error.SetErrorString("Unable to write breakpoint trap to memory.");
1757 }
1758 else
1759 error.SetErrorString("Unable to read memory at breakpoint address.");
1760 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001761 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001762 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1763 bp_site->GetID(),
1764 (uint64_t)bp_addr,
1765 error.AsCString());
1766 return error;
1767}
1768
1769Error
1770Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1771{
1772 Error error;
1773 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001774 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001775 addr_t bp_addr = bp_site->GetLoadAddress();
1776 lldb::user_id_t breakID = bp_site->GetID();
1777 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001778 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001779
1780 if (bp_site->IsHardware())
1781 {
1782 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1783 }
1784 else if (bp_site->IsEnabled())
1785 {
1786 const size_t break_op_size = bp_site->GetByteSize();
1787 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1788 if (break_op_size > 0)
1789 {
1790 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001791 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001792 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001793 bool break_op_found = false;
1794
1795 // Read the breakpoint opcode
1796 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1797 {
1798 bool verify = false;
1799 // Make sure we have the a breakpoint opcode exists at this address
1800 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1801 {
1802 break_op_found = true;
1803 // We found a valid breakpoint opcode at this address, now restore
1804 // the saved opcode.
1805 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1806 {
1807 verify = true;
1808 }
1809 else
1810 error.SetErrorString("Memory write failed when restoring original opcode.");
1811 }
1812 else
1813 {
1814 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1815 // Set verify to true and so we can check if the original opcode has already been restored
1816 verify = true;
1817 }
1818
1819 if (verify)
1820 {
Greg Claytonc982c762010-07-09 20:39:50 +00001821 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001822 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001823 // Verify that our original opcode made it back to the inferior
1824 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1825 {
1826 // compare the memory we just read with the original opcode
1827 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1828 {
1829 // SUCCESS
1830 bp_site->SetEnabled(false);
1831 if (log)
1832 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1833 return error;
1834 }
1835 else
1836 {
1837 if (break_op_found)
1838 error.SetErrorString("Failed to restore original opcode.");
1839 }
1840 }
1841 else
1842 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1843 }
1844 }
1845 else
1846 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1847 }
1848 }
1849 else
1850 {
1851 if (log)
1852 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1853 return error;
1854 }
1855
1856 if (log)
1857 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1858 bp_site->GetID(),
1859 (uint64_t)bp_addr,
1860 error.AsCString());
1861 return error;
1862
1863}
1864
Greg Clayton58be07b2011-01-07 06:08:19 +00001865// Comment out line below to disable memory caching
1866#define ENABLE_MEMORY_CACHING
1867// Uncomment to verify memory caching works after making changes to caching code
1868//#define VERIFY_MEMORY_READS
1869
1870#if defined (ENABLE_MEMORY_CACHING)
1871
1872#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001873
1874size_t
1875Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1876{
Greg Clayton58be07b2011-01-07 06:08:19 +00001877 // Memory caching is enabled, with debug verification
1878 if (buf && size)
1879 {
1880 // Uncomment the line below to make sure memory caching is working.
1881 // I ran this through the test suite and got no assertions, so I am
1882 // pretty confident this is working well. If any changes are made to
1883 // memory caching, uncomment the line below and test your changes!
1884
1885 // Verify all memory reads by using the cache first, then redundantly
1886 // reading the same memory from the inferior and comparing to make sure
1887 // everything is exactly the same.
1888 std::string verify_buf (size, '\0');
1889 assert (verify_buf.size() == size);
1890 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1891 Error verify_error;
1892 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1893 assert (cache_bytes_read == verify_bytes_read);
1894 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1895 assert (verify_error.Success() == error.Success());
1896 return cache_bytes_read;
1897 }
1898 return 0;
1899}
1900
1901#else // #if defined (VERIFY_MEMORY_READS)
1902
1903size_t
1904Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1905{
1906 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001907 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001908}
1909
1910#endif // #else for #if defined (VERIFY_MEMORY_READS)
1911
1912#else // #if defined (ENABLE_MEMORY_CACHING)
1913
1914size_t
1915Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1916{
1917 // Memory caching is disabled
1918 return ReadMemoryFromInferior (addr, buf, size, error);
1919}
1920
1921#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1922
1923
1924size_t
Greg Claytone91b7952011-12-15 03:14:23 +00001925Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00001926{
1927 size_t total_cstr_len = 0;
1928 if (dst && dst_max_len)
1929 {
Greg Claytone91b7952011-12-15 03:14:23 +00001930 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00001931 // NULL out everything just to be safe
1932 memset (dst, 0, dst_max_len);
1933 Error error;
1934 addr_t curr_addr = addr;
1935 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1936 size_t bytes_left = dst_max_len - 1;
1937 char *curr_dst = dst;
1938
1939 while (bytes_left > 0)
1940 {
1941 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1942 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1943 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1944
1945 if (bytes_read == 0)
1946 {
Greg Claytone91b7952011-12-15 03:14:23 +00001947 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001948 dst[total_cstr_len] = '\0';
1949 break;
1950 }
1951 const size_t len = strlen(curr_dst);
1952
1953 total_cstr_len += len;
1954
1955 if (len < bytes_to_read)
1956 break;
1957
1958 curr_dst += bytes_read;
1959 curr_addr += bytes_read;
1960 bytes_left -= bytes_read;
1961 }
1962 }
Greg Claytone91b7952011-12-15 03:14:23 +00001963 else
1964 {
1965 if (dst == NULL)
1966 result_error.SetErrorString("invalid arguments");
1967 else
1968 result_error.Clear();
1969 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001970 return total_cstr_len;
1971}
1972
1973size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00001974Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1975{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001976 if (buf == NULL || size == 0)
1977 return 0;
1978
1979 size_t bytes_read = 0;
1980 uint8_t *bytes = (uint8_t *)buf;
1981
1982 while (bytes_read < size)
1983 {
1984 const size_t curr_size = size - bytes_read;
1985 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1986 bytes + bytes_read,
1987 curr_size,
1988 error);
1989 bytes_read += curr_bytes_read;
1990 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1991 break;
1992 }
1993
1994 // Replace any software breakpoint opcodes that fall into this range back
1995 // into "buf" before we return
1996 if (bytes_read > 0)
1997 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1998 return bytes_read;
1999}
2000
Greg Clayton58a4c462010-12-16 20:01:20 +00002001uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002002Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002003{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002004 Scalar scalar;
2005 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2006 return scalar.ULongLong(fail_value);
2007 return fail_value;
2008}
2009
2010addr_t
2011Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2012{
2013 Scalar scalar;
2014 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2015 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2016 return LLDB_INVALID_ADDRESS;
2017}
2018
2019
2020bool
2021Process::WritePointerToMemory (lldb::addr_t vm_addr,
2022 lldb::addr_t ptr_value,
2023 Error &error)
2024{
2025 Scalar scalar;
2026 const uint32_t addr_byte_size = GetAddressByteSize();
2027 if (addr_byte_size <= 4)
2028 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002029 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002030 scalar = ptr_value;
2031 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002032}
2033
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002034size_t
2035Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2036{
2037 size_t bytes_written = 0;
2038 const uint8_t *bytes = (const uint8_t *)buf;
2039
2040 while (bytes_written < size)
2041 {
2042 const size_t curr_size = size - bytes_written;
2043 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2044 bytes + bytes_written,
2045 curr_size,
2046 error);
2047 bytes_written += curr_bytes_written;
2048 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2049 break;
2050 }
2051 return bytes_written;
2052}
2053
2054size_t
2055Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2056{
Greg Clayton58be07b2011-01-07 06:08:19 +00002057#if defined (ENABLE_MEMORY_CACHING)
2058 m_memory_cache.Flush (addr, size);
2059#endif
2060
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002061 if (buf == NULL || size == 0)
2062 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002063
Jim Ingham4b536182011-08-09 02:12:22 +00002064 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002065
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002066 // We need to write any data that would go where any current software traps
2067 // (enabled software breakpoints) any software traps (breakpoints) that we
2068 // may have placed in our tasks memory.
2069
2070 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2071 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2072
2073 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002074 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002075
2076 BreakpointSiteList::collection::const_iterator pos;
2077 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002078 addr_t intersect_addr = 0;
2079 size_t intersect_size = 0;
2080 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002081 const uint8_t *ubuf = (const uint8_t *)buf;
2082
2083 for (pos = iter; pos != end; ++pos)
2084 {
2085 BreakpointSiteSP bp;
2086 bp = pos->second;
2087
2088 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2089 assert(addr <= intersect_addr && intersect_addr < addr + size);
2090 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2091 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2092
2093 // Check for bytes before this breakpoint
2094 const addr_t curr_addr = addr + bytes_written;
2095 if (intersect_addr > curr_addr)
2096 {
2097 // There are some bytes before this breakpoint that we need to
2098 // just write to memory
2099 size_t curr_size = intersect_addr - curr_addr;
2100 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2101 ubuf + bytes_written,
2102 curr_size,
2103 error);
2104 bytes_written += curr_bytes_written;
2105 if (curr_bytes_written != curr_size)
2106 {
2107 // We weren't able to write all of the requested bytes, we
2108 // are done looping and will return the number of bytes that
2109 // we have written so far.
2110 break;
2111 }
2112 }
2113
2114 // Now write any bytes that would cover up any software breakpoints
2115 // directly into the breakpoint opcode buffer
2116 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2117 bytes_written += intersect_size;
2118 }
2119
2120 // Write any remaining bytes after the last breakpoint if we have any left
2121 if (bytes_written < size)
2122 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2123 ubuf + bytes_written,
2124 size - bytes_written,
2125 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002126
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002127 return bytes_written;
2128}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002129
2130size_t
2131Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2132{
2133 if (byte_size == UINT32_MAX)
2134 byte_size = scalar.GetByteSize();
2135 if (byte_size > 0)
2136 {
2137 uint8_t buf[32];
2138 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2139 if (mem_size > 0)
2140 return WriteMemory(addr, buf, mem_size, error);
2141 else
2142 error.SetErrorString ("failed to get scalar as memory data");
2143 }
2144 else
2145 {
2146 error.SetErrorString ("invalid scalar value");
2147 }
2148 return 0;
2149}
2150
2151size_t
2152Process::ReadScalarIntegerFromMemory (addr_t addr,
2153 uint32_t byte_size,
2154 bool is_signed,
2155 Scalar &scalar,
2156 Error &error)
2157{
2158 uint64_t uval;
2159
2160 if (byte_size <= sizeof(uval))
2161 {
2162 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2163 if (bytes_read == byte_size)
2164 {
2165 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2166 uint32_t offset = 0;
2167 if (byte_size <= 4)
2168 scalar = data.GetMaxU32 (&offset, byte_size);
2169 else
2170 scalar = data.GetMaxU64 (&offset, byte_size);
2171
2172 if (is_signed)
2173 scalar.SignExtend(byte_size * 8);
2174 return bytes_read;
2175 }
2176 }
2177 else
2178 {
2179 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2180 }
2181 return 0;
2182}
2183
Greg Claytond495c532011-05-17 03:37:42 +00002184#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002185addr_t
2186Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2187{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002188 if (GetPrivateState() != eStateStopped)
2189 return LLDB_INVALID_ADDRESS;
2190
Greg Claytond495c532011-05-17 03:37:42 +00002191#if defined (USE_ALLOCATE_MEMORY_CACHE)
2192 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2193#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002194 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2195 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2196 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002197 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 +00002198 size,
Greg Claytond495c532011-05-17 03:37:42 +00002199 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002200 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002201 m_mod_id.GetStopID(),
2202 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002203 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002204#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002205}
2206
Sean Callanan90539452011-09-20 23:01:51 +00002207bool
2208Process::CanJIT ()
2209{
Sean Callanana7b443a2012-02-14 22:50:38 +00002210 if (m_can_jit == eCanJITDontKnow)
2211 {
2212 Error err;
2213
2214 uint64_t allocated_memory = AllocateMemory(8,
2215 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2216 err);
2217
2218 if (err.Success())
2219 m_can_jit = eCanJITYes;
2220 else
2221 m_can_jit = eCanJITNo;
2222
2223 DeallocateMemory (allocated_memory);
2224 }
2225
Sean Callanan90539452011-09-20 23:01:51 +00002226 return m_can_jit == eCanJITYes;
2227}
2228
2229void
2230Process::SetCanJIT (bool can_jit)
2231{
2232 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2233}
2234
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002235Error
2236Process::DeallocateMemory (addr_t ptr)
2237{
Greg Claytond495c532011-05-17 03:37:42 +00002238 Error error;
2239#if defined (USE_ALLOCATE_MEMORY_CACHE)
2240 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2241 {
2242 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2243 }
2244#else
2245 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002246
2247 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2248 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002249 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 +00002250 ptr,
2251 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002252 m_mod_id.GetStopID(),
2253 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002254#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002255 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002256}
2257
Greg Claytonc9660542012-02-05 02:38:54 +00002258ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002259Process::ReadModuleFromMemory (const FileSpec& file_spec,
2260 lldb::addr_t header_addr,
2261 bool add_image_to_target,
2262 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002263{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002264 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002265 if (module_sp)
2266 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002267 Error error;
2268 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2269 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002270 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002271 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002272 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002273 m_target.GetImages().Append(module_sp);
2274 if (load_sections_in_target)
2275 {
2276 bool changed = false;
2277 module_sp->SetLoadAddress (m_target, 0, changed);
2278 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002279 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002280 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002281 }
Greg Claytonc9660542012-02-05 02:38:54 +00002282 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002283 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002284}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002285
2286Error
Johnny Chen01a67862011-10-14 00:42:25 +00002287Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002288{
2289 Error error;
2290 error.SetErrorString("watchpoints are not supported");
2291 return error;
2292}
2293
2294Error
Johnny Chen01a67862011-10-14 00:42:25 +00002295Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002296{
2297 Error error;
2298 error.SetErrorString("watchpoints are not supported");
2299 return error;
2300}
2301
2302StateType
2303Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2304{
2305 StateType state;
2306 // Now wait for the process to launch and return control to us, and then
2307 // call DidLaunch:
2308 while (1)
2309 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002310 event_sp.reset();
2311 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2312
Greg Clayton2637f822011-11-17 01:23:07 +00002313 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002314 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002315
2316 // If state is invalid, then we timed out
2317 if (state == eStateInvalid)
2318 break;
2319
2320 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321 HandlePrivateEvent (event_sp);
2322 }
2323 return state;
2324}
2325
2326Error
Greg Clayton982c9762011-11-03 21:22:33 +00002327Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002328{
2329 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002331 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002332 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002333 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002334
Greg Claytonaa149cb2011-08-11 02:48:45 +00002335 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002336 if (exe_module)
2337 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002338 char local_exec_file_path[PATH_MAX];
2339 char platform_exec_file_path[PATH_MAX];
2340 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2341 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002342 if (exe_module->GetFileSpec().Exists())
2343 {
Greg Clayton71337622011-02-24 22:24:29 +00002344 if (PrivateStateThreadIsValid ())
2345 PausePrivateStateThread ();
2346
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002347 error = WillLaunch (exe_module);
2348 if (error.Success())
2349 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002350 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002351 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002352
2353 // Now launch using these arguments.
Greg Clayton982c9762011-11-03 21:22:33 +00002354 error = DoLaunch (exe_module, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002355
2356 if (error.Fail())
2357 {
2358 if (GetID() != LLDB_INVALID_PROCESS_ID)
2359 {
2360 SetID (LLDB_INVALID_PROCESS_ID);
2361 const char *error_string = error.AsCString();
2362 if (error_string == NULL)
2363 error_string = "launch failed";
2364 SetExitStatus (-1, error_string);
2365 }
2366 }
2367 else
2368 {
2369 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002370 TimeValue timeout_time;
2371 timeout_time = TimeValue::Now();
2372 timeout_time.OffsetWithSeconds(10);
2373 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002374
Greg Clayton1a38ea72011-06-22 01:42:17 +00002375 if (state == eStateInvalid || event_sp.get() == NULL)
2376 {
2377 // We were able to launch the process, but we failed to
2378 // catch the initial stop.
2379 SetExitStatus (0, "failed to catch stop after launch");
2380 Destroy();
2381 }
2382 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002383 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002384
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002385 DidLaunch ();
2386
Greg Claytonc859e2d2012-02-13 23:10:39 +00002387 DynamicLoader *dyld = GetDynamicLoader ();
2388 if (dyld)
2389 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002390
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002391 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002392 // This delays passing the stopped event to listeners till DidLaunch gets
2393 // a chance to complete...
2394 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002395
2396 if (PrivateStateThreadIsValid ())
2397 ResumePrivateStateThread ();
2398 else
2399 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002400 }
2401 else if (state == eStateExited)
2402 {
2403 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2404 // not likely to work, and return an invalid pid.
2405 HandlePrivateEvent (event_sp);
2406 }
2407 }
2408 }
2409 }
2410 else
2411 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002412 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413 }
2414 }
2415 return error;
2416}
2417
Greg Claytonc3776bf2012-02-09 06:16:32 +00002418
2419Error
2420Process::LoadCore ()
2421{
2422 Error error = DoLoadCore();
2423 if (error.Success())
2424 {
2425 if (PrivateStateThreadIsValid ())
2426 ResumePrivateStateThread ();
2427 else
2428 StartPrivateStateThread ();
2429
Greg Claytonc859e2d2012-02-13 23:10:39 +00002430 DynamicLoader *dyld = GetDynamicLoader ();
2431 if (dyld)
2432 dyld->DidAttach();
2433
2434 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002435 // We successfully loaded a core file, now pretend we stopped so we can
2436 // show all of the threads in the core file and explore the crashed
2437 // state.
2438 SetPrivateState (eStateStopped);
2439
2440 }
2441 return error;
2442}
2443
Greg Claytonc859e2d2012-02-13 23:10:39 +00002444DynamicLoader *
2445Process::GetDynamicLoader ()
2446{
2447 if (m_dyld_ap.get() == NULL)
2448 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2449 return m_dyld_ap.get();
2450}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002451
2452
Jim Inghambb3a2832011-01-29 01:49:25 +00002453Process::NextEventAction::EventActionResult
2454Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002455{
Jim Inghambb3a2832011-01-29 01:49:25 +00002456 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2457 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002458 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002459 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002460 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002461 return eEventActionRetry;
2462
2463 case eStateStopped:
2464 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002465 {
2466 // During attach, prior to sending the eStateStopped event,
2467 // lldb_private::Process subclasses must set the process must set
2468 // the new process ID.
2469 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2470 if (m_exec_count > 0)
2471 {
2472 --m_exec_count;
2473 m_process->Resume();
2474 return eEventActionRetry;
2475 }
2476 else
2477 {
2478 m_process->CompleteAttach ();
2479 return eEventActionSuccess;
2480 }
2481 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002482 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002483
Greg Clayton513c26c2011-01-29 07:10:55 +00002484 default:
2485 case eStateExited:
2486 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002487 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002488 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002489
2490 m_exit_string.assign ("No valid Process");
2491 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002492}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002493
Jim Inghambb3a2832011-01-29 01:49:25 +00002494Process::NextEventAction::EventActionResult
2495Process::AttachCompletionHandler::HandleBeingInterrupted()
2496{
2497 return eEventActionSuccess;
2498}
2499
2500const char *
2501Process::AttachCompletionHandler::GetExitString ()
2502{
2503 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002504}
2505
2506Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002507Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002508{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002509 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002510 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002511 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002512 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002513
Greg Clayton144f3a92011-11-15 03:53:30 +00002514 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002515 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002516 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002517 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002518 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002519
Greg Clayton144f3a92011-11-15 03:53:30 +00002520 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002521 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002522 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2523
2524 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002525 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002526 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2527 if (error.Success())
2528 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002529 m_should_detach = true;
2530
Greg Clayton144f3a92011-11-15 03:53:30 +00002531 SetPublicState (eStateAttaching);
Han Ming Ong84647042012-02-25 01:07:38 +00002532 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002533 if (error.Fail())
2534 {
2535 if (GetID() != LLDB_INVALID_PROCESS_ID)
2536 {
2537 SetID (LLDB_INVALID_PROCESS_ID);
2538 if (error.AsCString() == NULL)
2539 error.SetErrorString("attach failed");
2540
2541 SetExitStatus(-1, error.AsCString());
2542 }
2543 }
2544 else
2545 {
2546 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2547 StartPrivateStateThread();
2548 }
2549 return error;
2550 }
Greg Claytone996fd32011-03-08 22:40:15 +00002551 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002552 else
Greg Claytone996fd32011-03-08 22:40:15 +00002553 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002554 ProcessInstanceInfoList process_infos;
2555 PlatformSP platform_sp (m_target.GetPlatform ());
2556
2557 if (platform_sp)
2558 {
2559 ProcessInstanceInfoMatch match_info;
2560 match_info.GetProcessInfo() = attach_info;
2561 match_info.SetNameMatchType (eNameMatchEquals);
2562 platform_sp->FindProcesses (match_info, process_infos);
2563 const uint32_t num_matches = process_infos.GetSize();
2564 if (num_matches == 1)
2565 {
2566 attach_pid = process_infos.GetProcessIDAtIndex(0);
2567 // Fall through and attach using the above process ID
2568 }
2569 else
2570 {
2571 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2572 if (num_matches > 1)
2573 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2574 else
2575 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2576 }
2577 }
2578 else
2579 {
2580 error.SetErrorString ("invalid platform, can't find processes by name");
2581 return error;
2582 }
Greg Claytone996fd32011-03-08 22:40:15 +00002583 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002584 }
2585 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002586 {
2587 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002588 }
2589 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002590
2591 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002592 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002593 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002594 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002595 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002596 m_should_detach = true;
Greg Claytone996fd32011-03-08 22:40:15 +00002597 SetPublicState (eStateAttaching);
Greg Clayton144f3a92011-11-15 03:53:30 +00002598
Han Ming Ong84647042012-02-25 01:07:38 +00002599 error = DoAttachToProcessWithID (attach_pid, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002600 if (error.Success())
2601 {
2602
2603 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2604 StartPrivateStateThread();
2605 }
2606 else
Greg Claytone996fd32011-03-08 22:40:15 +00002607 {
2608 if (GetID() != LLDB_INVALID_PROCESS_ID)
2609 {
2610 SetID (LLDB_INVALID_PROCESS_ID);
2611 const char *error_string = error.AsCString();
2612 if (error_string == NULL)
2613 error_string = "attach failed";
2614
2615 SetExitStatus(-1, error_string);
2616 }
2617 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002618 }
2619 }
2620 return error;
2621}
2622
Greg Clayton144f3a92011-11-15 03:53:30 +00002623//Error
2624//Process::Attach (const char *process_name, bool wait_for_launch)
2625//{
2626// m_abi_sp.reset();
2627// m_process_input_reader.reset();
2628//
2629// // Find the process and its architecture. Make sure it matches the architecture
2630// // of the current Target, and if not adjust it.
2631// Error error;
2632//
2633// if (!wait_for_launch)
2634// {
2635// ProcessInstanceInfoList process_infos;
2636// PlatformSP platform_sp (m_target.GetPlatform ());
2637// assert (platform_sp.get());
2638//
2639// if (platform_sp)
2640// {
2641// ProcessInstanceInfoMatch match_info;
2642// match_info.GetProcessInfo().SetName(process_name);
2643// match_info.SetNameMatchType (eNameMatchEquals);
2644// platform_sp->FindProcesses (match_info, process_infos);
2645// if (process_infos.GetSize() > 1)
2646// {
2647// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2648// }
2649// else if (process_infos.GetSize() == 0)
2650// {
2651// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2652// }
2653// }
2654// else
2655// {
2656// error.SetErrorString ("invalid platform");
2657// }
2658// }
2659//
2660// if (error.Success())
2661// {
2662// m_dyld_ap.reset();
2663// m_os_ap.reset();
2664//
2665// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2666// if (error.Success())
2667// {
2668// SetPublicState (eStateAttaching);
2669// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2670// if (error.Fail())
2671// {
2672// if (GetID() != LLDB_INVALID_PROCESS_ID)
2673// {
2674// SetID (LLDB_INVALID_PROCESS_ID);
2675// const char *error_string = error.AsCString();
2676// if (error_string == NULL)
2677// error_string = "attach failed";
2678//
2679// SetExitStatus(-1, error_string);
2680// }
2681// }
2682// else
2683// {
2684// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2685// StartPrivateStateThread();
2686// }
2687// }
2688// }
2689// return error;
2690//}
2691
Greg Clayton93d3c8332011-02-16 04:46:07 +00002692void
2693Process::CompleteAttach ()
2694{
2695 // Let the process subclass figure out at much as it can about the process
2696 // before we go looking for a dynamic loader plug-in.
2697 DidAttach();
2698
Jim Ingham4299fdb2011-09-15 01:10:17 +00002699 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2700 // the same as the one we've already set, switch architectures.
2701 PlatformSP platform_sp (m_target.GetPlatform ());
2702 assert (platform_sp.get());
2703 if (platform_sp)
2704 {
2705 ProcessInstanceInfo process_info;
2706 platform_sp->GetProcessInfo (GetID(), process_info);
2707 const ArchSpec &process_arch = process_info.GetArchitecture();
2708 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2709 m_target.SetArchitecture (process_arch);
2710 }
2711
2712 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002713 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002714 DynamicLoader *dyld = GetDynamicLoader ();
2715 if (dyld)
2716 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002717
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002718 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002719 // Figure out which one is the executable, and set that in our target:
2720 ModuleList &modules = m_target.GetImages();
2721
2722 size_t num_modules = modules.GetSize();
2723 for (int i = 0; i < num_modules; i++)
2724 {
2725 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002726 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002727 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002728 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002729 m_target.SetExecutableModule (module_sp, false);
2730 break;
2731 }
2732 }
2733}
2734
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002735Error
Greg Claytonb766a732011-02-04 01:58:07 +00002736Process::ConnectRemote (const char *remote_url)
2737{
Greg Claytonb766a732011-02-04 01:58:07 +00002738 m_abi_sp.reset();
2739 m_process_input_reader.reset();
2740
2741 // Find the process and its architecture. Make sure it matches the architecture
2742 // of the current Target, and if not adjust it.
2743
2744 Error error (DoConnectRemote (remote_url));
2745 if (error.Success())
2746 {
Greg Clayton71337622011-02-24 22:24:29 +00002747 if (GetID() != LLDB_INVALID_PROCESS_ID)
2748 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002749 EventSP event_sp;
2750 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2751
2752 if (state == eStateStopped || state == eStateCrashed)
2753 {
2754 // If we attached and actually have a process on the other end, then
2755 // this ended up being the equivalent of an attach.
2756 CompleteAttach ();
2757
2758 // This delays passing the stopped event to listeners till
2759 // CompleteAttach gets a chance to complete...
2760 HandlePrivateEvent (event_sp);
2761
2762 }
Greg Clayton71337622011-02-24 22:24:29 +00002763 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002764
2765 if (PrivateStateThreadIsValid ())
2766 ResumePrivateStateThread ();
2767 else
2768 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002769 }
2770 return error;
2771}
2772
2773
2774Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002775Process::Resume ()
2776{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002777 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002779 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002780 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002781 StateAsCString(m_public_state.GetValue()),
2782 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002783
2784 Error error (WillResume());
2785 // Tell the process it is about to resume before the thread list
2786 if (error.Success())
2787 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002788 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002789 // can let all of our threads know that they are about to be
2790 // resumed. Threads will each be called with
2791 // Thread::WillResume(StateType) where StateType contains the state
2792 // that they are supposed to have when the process is resumed
2793 // (suspended/running/stepping). Threads should also check
2794 // their resume signal in lldb::Thread::GetResumeSignal()
2795 // to see if they are suppoed to start back up with a signal.
2796 if (m_thread_list.WillResume())
2797 {
Jim Ingham372787f2012-04-07 00:00:41 +00002798 // Last thing, do the PreResumeActions.
2799 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002800 {
Jim Ingham372787f2012-04-07 00:00:41 +00002801 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
2802 }
2803 else
2804 {
2805 m_mod_id.BumpResumeID();
2806 error = DoResume();
2807 if (error.Success())
2808 {
2809 DidResume();
2810 m_thread_list.DidResume();
2811 if (log)
2812 log->Printf ("Process thinks the process has resumed.");
2813 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002814 }
2815 }
2816 else
2817 {
Jim Ingham444586b2011-01-24 06:34:17 +00002818 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002819 }
2820 }
Jim Ingham444586b2011-01-24 06:34:17 +00002821 else if (log)
2822 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002823 return error;
2824}
2825
2826Error
2827Process::Halt ()
2828{
Jim Inghambb3a2832011-01-29 01:49:25 +00002829 // Pause our private state thread so we can ensure no one else eats
2830 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002831 Listener halt_listener ("lldb.process.halt_listener");
2832 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002833
Jim Inghambb3a2832011-01-29 01:49:25 +00002834 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002835 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002836
Greg Clayton513c26c2011-01-29 07:10:55 +00002837 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002838 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002839
Greg Clayton513c26c2011-01-29 07:10:55 +00002840 bool caused_stop = false;
2841
2842 // Ask the process subclass to actually halt our process
2843 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002844 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002845 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002846 if (m_public_state.GetValue() == eStateAttaching)
2847 {
2848 SetExitStatus(SIGKILL, "Cancelled async attach.");
2849 Destroy ();
2850 }
2851 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002852 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002853 // If "caused_stop" is true, then DoHalt stopped the process. If
2854 // "caused_stop" is false, the process was already stopped.
2855 // If the DoHalt caused the process to stop, then we want to catch
2856 // this event and set the interrupted bool to true before we pass
2857 // this along so clients know that the process was interrupted by
2858 // a halt command.
2859 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002860 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002861 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002862 TimeValue timeout_time;
2863 timeout_time = TimeValue::Now();
2864 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002865 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2866 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002867
Jim Ingham0f16e732011-02-08 05:20:59 +00002868 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002869 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002870 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002871 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002872 }
2873 else
2874 {
Greg Clayton2637f822011-11-17 01:23:07 +00002875 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00002876 {
2877 // We caused the process to interrupt itself, so mark this
2878 // as such in the stop event so clients can tell an interrupted
2879 // process from a natural stop
2880 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2881 }
2882 else
2883 {
2884 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2885 if (log)
2886 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2887 error.SetErrorString ("Did not get stopped event after halt.");
2888 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002889 }
2890 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002891 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002892 }
2893 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002894 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002895 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002896 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002897
2898 // Post any event we might have consumed. If all goes well, we will have
2899 // stopped the process, intercepted the event and set the interrupted
2900 // bool in the event. Post it to the private event queue and that will end up
2901 // correctly setting the state.
2902 if (event_sp)
2903 m_private_state_broadcaster.BroadcastEvent(event_sp);
2904
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002905 return error;
2906}
2907
2908Error
2909Process::Detach ()
2910{
2911 Error error (WillDetach());
2912
2913 if (error.Success())
2914 {
2915 DisableAllBreakpointSites();
2916 error = DoDetach();
2917 if (error.Success())
2918 {
2919 DidDetach();
2920 StopPrivateStateThread();
2921 }
2922 }
2923 return error;
2924}
2925
2926Error
2927Process::Destroy ()
2928{
2929 Error error (WillDestroy());
2930 if (error.Success())
2931 {
2932 DisableAllBreakpointSites();
2933 error = DoDestroy();
2934 if (error.Success())
2935 {
2936 DidDestroy();
2937 StopPrivateStateThread();
2938 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002939 m_stdio_communication.StopReadThread();
2940 m_stdio_communication.Disconnect();
2941 if (m_process_input_reader && m_process_input_reader->IsActive())
2942 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2943 if (m_process_input_reader)
2944 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002945 }
2946 return error;
2947}
2948
2949Error
2950Process::Signal (int signal)
2951{
2952 Error error (WillSignal());
2953 if (error.Success())
2954 {
2955 error = DoSignal(signal);
2956 if (error.Success())
2957 DidSignal();
2958 }
2959 return error;
2960}
2961
Greg Clayton514487e2011-02-15 21:59:32 +00002962lldb::ByteOrder
2963Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002964{
Greg Clayton514487e2011-02-15 21:59:32 +00002965 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002966}
2967
2968uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002969Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002970{
Greg Clayton514487e2011-02-15 21:59:32 +00002971 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002972}
2973
Greg Clayton514487e2011-02-15 21:59:32 +00002974
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002975bool
2976Process::ShouldBroadcastEvent (Event *event_ptr)
2977{
2978 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2979 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002980 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002981
2982 switch (state)
2983 {
Greg Claytonb766a732011-02-04 01:58:07 +00002984 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002985 case eStateAttaching:
2986 case eStateLaunching:
2987 case eStateDetached:
2988 case eStateExited:
2989 case eStateUnloaded:
2990 // These events indicate changes in the state of the debugging session, always report them.
2991 return_value = true;
2992 break;
2993 case eStateInvalid:
2994 // We stopped for no apparent reason, don't report it.
2995 return_value = false;
2996 break;
2997 case eStateRunning:
2998 case eStateStepping:
2999 // If we've started the target running, we handle the cases where we
3000 // are already running and where there is a transition from stopped to
3001 // running differently.
3002 // running -> running: Automatically suppress extra running events
3003 // stopped -> running: Report except when there is one or more no votes
3004 // and no yes votes.
3005 SynchronouslyNotifyStateChanged (state);
3006 switch (m_public_state.GetValue())
3007 {
3008 case eStateRunning:
3009 case eStateStepping:
3010 // We always suppress multiple runnings with no PUBLIC stop in between.
3011 return_value = false;
3012 break;
3013 default:
3014 // TODO: make this work correctly. For now always report
3015 // run if we aren't running so we don't miss any runnning
3016 // events. If I run the lldb/test/thread/a.out file and
3017 // break at main.cpp:58, run and hit the breakpoints on
3018 // multiple threads, then somehow during the stepping over
3019 // of all breakpoints no run gets reported.
3020 return_value = true;
3021
3022 // This is a transition from stop to run.
3023 switch (m_thread_list.ShouldReportRun (event_ptr))
3024 {
3025 case eVoteYes:
3026 case eVoteNoOpinion:
3027 return_value = true;
3028 break;
3029 case eVoteNo:
3030 return_value = false;
3031 break;
3032 }
3033 break;
3034 }
3035 break;
3036 case eStateStopped:
3037 case eStateCrashed:
3038 case eStateSuspended:
3039 {
3040 // We've stopped. First see if we're going to restart the target.
3041 // If we are going to stop, then we always broadcast the event.
3042 // 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 +00003043 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003044 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003046 if (log)
3047 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003048 return true;
3049 }
3050 else
3051 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003052 RefreshStateAfterStop ();
3053
3054 if (m_thread_list.ShouldStop (event_ptr) == false)
3055 {
3056 switch (m_thread_list.ShouldReportStop (event_ptr))
3057 {
3058 case eVoteYes:
3059 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003060 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003061 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003062 case eVoteNo:
3063 return_value = false;
3064 break;
3065 }
3066
3067 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003068 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003069 Resume ();
3070 }
3071 else
3072 {
3073 return_value = true;
3074 SynchronouslyNotifyStateChanged (state);
3075 }
3076 }
3077 }
3078 }
3079
3080 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003081 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003082 return return_value;
3083}
3084
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003085
3086bool
Jim Ingham372787f2012-04-07 00:00:41 +00003087Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003088{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003089 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003090
Greg Clayton8b82f082011-04-12 05:54:46 +00003091 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003092 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003093 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3094
Jim Ingham372787f2012-04-07 00:00:41 +00003095 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003096 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003097
3098 // Create a thread that watches our internal state and controls which
3099 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003100 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003101 if (already_running)
3102 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3103 else
3104 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Clayton3e06bd92011-01-09 21:07:35 +00003105 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00003106 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003107}
3108
3109void
3110Process::PausePrivateStateThread ()
3111{
3112 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3113}
3114
3115void
3116Process::ResumePrivateStateThread ()
3117{
3118 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3119}
3120
3121void
3122Process::StopPrivateStateThread ()
3123{
Greg Clayton8b82f082011-04-12 05:54:46 +00003124 if (PrivateStateThreadIsValid ())
3125 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003126}
3127
3128void
3129Process::ControlPrivateStateThread (uint32_t signal)
3130{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003131 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132
3133 assert (signal == eBroadcastInternalStateControlStop ||
3134 signal == eBroadcastInternalStateControlPause ||
3135 signal == eBroadcastInternalStateControlResume);
3136
3137 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003138 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003139
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003140 // Signal the private state thread. First we should copy this is case the
3141 // thread starts exiting since the private state thread will NULL this out
3142 // when it exits
3143 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003144 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003145 {
3146 TimeValue timeout_time;
3147 bool timed_out;
3148
3149 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3150
3151 timeout_time = TimeValue::Now();
3152 timeout_time.OffsetWithSeconds(2);
3153 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3154 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3155
3156 if (signal == eBroadcastInternalStateControlStop)
3157 {
3158 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003159 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003160
3161 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003162 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003163 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003164 }
3165 }
3166}
3167
3168void
3169Process::HandlePrivateEvent (EventSP &event_sp)
3170{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003171 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003172
Greg Clayton414f5d32011-01-25 02:58:48 +00003173 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003174
3175 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003176 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003177 {
Jim Ingham754ab982011-01-29 04:05:41 +00003178 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003179 switch (action_result)
3180 {
3181 case NextEventAction::eEventActionSuccess:
3182 SetNextEventAction(NULL);
3183 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003184
Jim Inghambb3a2832011-01-29 01:49:25 +00003185 case NextEventAction::eEventActionRetry:
3186 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003187
Jim Inghambb3a2832011-01-29 01:49:25 +00003188 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003189 // Handle Exiting Here. If we already got an exited event,
3190 // we should just propagate it. Otherwise, swallow this event,
3191 // and set our state to exit so the next event will kill us.
3192 if (new_state != eStateExited)
3193 {
3194 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003195 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003196 SetNextEventAction(NULL);
3197 return;
3198 }
3199 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003200 break;
3201 }
3202 }
3203
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003204 // See if we should broadcast this state to external clients?
3205 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003206
3207 if (should_broadcast)
3208 {
3209 if (log)
3210 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003211 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003212 __FUNCTION__,
3213 GetID(),
3214 StateAsCString(new_state),
3215 StateAsCString (GetState ()),
3216 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003217 }
Jim Ingham9575d842011-03-11 03:53:59 +00003218 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003219 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003220 PushProcessInputReader ();
3221 else
3222 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003223
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003224 BroadcastEvent (event_sp);
3225 }
3226 else
3227 {
3228 if (log)
3229 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003230 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003231 __FUNCTION__,
3232 GetID(),
3233 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003234 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003235 }
3236 }
3237}
3238
3239void *
3240Process::PrivateStateThread (void *arg)
3241{
3242 Process *proc = static_cast<Process*> (arg);
3243 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003244 return result;
3245}
3246
3247void *
3248Process::RunPrivateStateThread ()
3249{
3250 bool control_only = false;
3251 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3252
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003253 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003254 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003255 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003256
3257 bool exit_now = false;
3258 while (!exit_now)
3259 {
3260 EventSP event_sp;
3261 WaitForEventsPrivate (NULL, event_sp, control_only);
3262 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3263 {
3264 switch (event_sp->GetType())
3265 {
3266 case eBroadcastInternalStateControlStop:
3267 exit_now = true;
3268 continue; // Go to next loop iteration so we exit without
3269 break; // doing any internal state managment below
3270
3271 case eBroadcastInternalStateControlPause:
3272 control_only = true;
3273 break;
3274
3275 case eBroadcastInternalStateControlResume:
3276 control_only = false;
3277 break;
3278 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003279
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003280 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003281 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 +00003282
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003283 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003284 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003285 }
3286
3287
3288 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3289
3290 if (internal_state != eStateInvalid)
3291 {
3292 HandlePrivateEvent (event_sp);
3293 }
3294
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003295 if (internal_state == eStateInvalid ||
3296 internal_state == eStateExited ||
3297 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003298 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003299 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003300 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 +00003301
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003302 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003303 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003304 }
3305
Caroline Tice20ad3c42010-10-29 21:48:37 +00003306 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003307 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003308 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003309
Greg Clayton6ed95942011-01-22 07:12:45 +00003310 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3311 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003312 return NULL;
3313}
3314
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003315//------------------------------------------------------------------
3316// Process Event Data
3317//------------------------------------------------------------------
3318
3319Process::ProcessEventData::ProcessEventData () :
3320 EventData (),
3321 m_process_sp (),
3322 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003323 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003324 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003325 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003326{
3327}
3328
3329Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3330 EventData (),
3331 m_process_sp (process_sp),
3332 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003333 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003334 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003335 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003336{
3337}
3338
3339Process::ProcessEventData::~ProcessEventData()
3340{
3341}
3342
3343const ConstString &
3344Process::ProcessEventData::GetFlavorString ()
3345{
3346 static ConstString g_flavor ("Process::ProcessEventData");
3347 return g_flavor;
3348}
3349
3350const ConstString &
3351Process::ProcessEventData::GetFlavor () const
3352{
3353 return ProcessEventData::GetFlavorString ();
3354}
3355
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003356void
3357Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3358{
3359 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003360 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3361 // the public event queue, then other times when we're pretending that this is where we stopped at the
3362 // end of expression evaluation. m_update_state is used to distinguish these
3363 // three cases; it is 0 when we're just pulling it off for private handling,
3364 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003365
Jim Inghama8604692011-05-22 21:45:01 +00003366 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003367 return;
3368
3369 m_process_sp->SetPublicState (m_state);
3370
3371 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3372 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003373 {
3374 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003375 uint32_t num_threads = curr_thread_list.GetSize();
3376 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003377
Jim Ingham4b536182011-08-09 02:12:22 +00003378 // The actions might change one of the thread's stop_info's opinions about whether we should
3379 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003380
3381 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3382 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3383 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3384 // 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
3385 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003386 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003387 for (idx = 0; idx < num_threads; ++idx)
3388 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3389
Jim Ingham4b536182011-08-09 02:12:22 +00003390 bool still_should_stop = true;
3391
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003392 for (idx = 0; idx < num_threads; ++idx)
3393 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003394 curr_thread_list = m_process_sp->GetThreadList();
3395 if (curr_thread_list.GetSize() != num_threads)
3396 {
3397 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003398 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003399 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 +00003400 break;
3401 }
3402
3403 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3404
3405 if (thread_sp->GetIndexID() != thread_index_array[idx])
3406 {
3407 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003408 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003409 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003410 idx,
3411 thread_index_array[idx],
3412 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003413 break;
3414 }
3415
Jim Inghamb15bfc72010-10-20 00:39:53 +00003416 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3417 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003418 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003419 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003420 // The stop action might restart the target. If it does, then we want to mark that in the
3421 // event so that whoever is receiving it will know to wait for the running event and reflect
3422 // that state appropriately.
3423 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003424
3425 // FIXME: we might have run.
3426 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003427 {
3428 SetRestarted (true);
3429 break;
3430 }
3431 else if (!stop_info_sp->ShouldStop(event_ptr))
3432 {
3433 still_should_stop = false;
3434 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003435 }
3436 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003437
Jim Ingham4b536182011-08-09 02:12:22 +00003438
3439 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003440 {
Jim Ingham4b536182011-08-09 02:12:22 +00003441 if (!still_should_stop)
3442 {
3443 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003444 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003445 m_process_sp->Resume();
3446 }
3447 else
3448 {
3449 // If we didn't restart, run the Stop Hooks here:
3450 // They might also restart the target, so watch for that.
3451 m_process_sp->GetTarget().RunStopHooks();
3452 if (m_process_sp->GetPrivateState() == eStateRunning)
3453 SetRestarted(true);
3454 }
Jim Ingham9575d842011-03-11 03:53:59 +00003455 }
3456
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003457 }
3458}
3459
3460void
3461Process::ProcessEventData::Dump (Stream *s) const
3462{
3463 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003464 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003465
Greg Clayton8b82f082011-04-12 05:54:46 +00003466 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003467}
3468
3469const Process::ProcessEventData *
3470Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3471{
3472 if (event_ptr)
3473 {
3474 const EventData *event_data = event_ptr->GetData();
3475 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3476 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3477 }
3478 return NULL;
3479}
3480
3481ProcessSP
3482Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3483{
3484 ProcessSP process_sp;
3485 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3486 if (data)
3487 process_sp = data->GetProcessSP();
3488 return process_sp;
3489}
3490
3491StateType
3492Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3493{
3494 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3495 if (data == NULL)
3496 return eStateInvalid;
3497 else
3498 return data->GetState();
3499}
3500
3501bool
3502Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3503{
3504 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3505 if (data == NULL)
3506 return false;
3507 else
3508 return data->GetRestarted();
3509}
3510
3511void
3512Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3513{
3514 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3515 if (data != NULL)
3516 data->SetRestarted(new_value);
3517}
3518
3519bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003520Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3521{
3522 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3523 if (data == NULL)
3524 return false;
3525 else
3526 return data->GetInterrupted ();
3527}
3528
3529void
3530Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3531{
3532 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3533 if (data != NULL)
3534 data->SetInterrupted(new_value);
3535}
3536
3537bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003538Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3539{
3540 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3541 if (data)
3542 {
3543 data->SetUpdateStateOnRemoval();
3544 return true;
3545 }
3546 return false;
3547}
3548
Greg Claytond9e416c2012-02-18 05:35:26 +00003549lldb::TargetSP
3550Process::CalculateTarget ()
3551{
3552 return m_target.shared_from_this();
3553}
3554
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003555void
Greg Clayton0603aa92010-10-04 01:05:56 +00003556Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003557{
Greg Claytonc14ee322011-09-22 04:58:26 +00003558 exe_ctx.SetTargetPtr (&m_target);
3559 exe_ctx.SetProcessPtr (this);
3560 exe_ctx.SetThreadPtr(NULL);
3561 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003562}
3563
Greg Claytone996fd32011-03-08 22:40:15 +00003564//uint32_t
3565//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3566//{
3567// return 0;
3568//}
3569//
3570//ArchSpec
3571//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3572//{
3573// return Host::GetArchSpecForExistingProcess (pid);
3574//}
3575//
3576//ArchSpec
3577//Process::GetArchSpecForExistingProcess (const char *process_name)
3578//{
3579// return Host::GetArchSpecForExistingProcess (process_name);
3580//}
3581//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003582void
3583Process::AppendSTDOUT (const char * s, size_t len)
3584{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003585 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003586 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003587 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003588}
3589
3590void
Greg Clayton93e86192011-11-13 04:45:22 +00003591Process::AppendSTDERR (const char * s, size_t len)
3592{
3593 Mutex::Locker locker (m_stdio_communication_mutex);
3594 m_stderr_data.append (s, len);
3595 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3596}
3597
3598//------------------------------------------------------------------
3599// Process STDIO
3600//------------------------------------------------------------------
3601
3602size_t
3603Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3604{
3605 Mutex::Locker locker(m_stdio_communication_mutex);
3606 size_t bytes_available = m_stdout_data.size();
3607 if (bytes_available > 0)
3608 {
3609 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3610 if (log)
3611 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3612 if (bytes_available > buf_size)
3613 {
3614 memcpy(buf, m_stdout_data.c_str(), buf_size);
3615 m_stdout_data.erase(0, buf_size);
3616 bytes_available = buf_size;
3617 }
3618 else
3619 {
3620 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3621 m_stdout_data.clear();
3622 }
3623 }
3624 return bytes_available;
3625}
3626
3627
3628size_t
3629Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3630{
3631 Mutex::Locker locker(m_stdio_communication_mutex);
3632 size_t bytes_available = m_stderr_data.size();
3633 if (bytes_available > 0)
3634 {
3635 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3636 if (log)
3637 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3638 if (bytes_available > buf_size)
3639 {
3640 memcpy(buf, m_stderr_data.c_str(), buf_size);
3641 m_stderr_data.erase(0, buf_size);
3642 bytes_available = buf_size;
3643 }
3644 else
3645 {
3646 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3647 m_stderr_data.clear();
3648 }
3649 }
3650 return bytes_available;
3651}
3652
3653void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003654Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3655{
3656 Process *process = (Process *) baton;
3657 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3658}
3659
3660size_t
3661Process::ProcessInputReaderCallback (void *baton,
3662 InputReader &reader,
3663 lldb::InputReaderAction notification,
3664 const char *bytes,
3665 size_t bytes_len)
3666{
3667 Process *process = (Process *) baton;
3668
3669 switch (notification)
3670 {
3671 case eInputReaderActivate:
3672 break;
3673
3674 case eInputReaderDeactivate:
3675 break;
3676
3677 case eInputReaderReactivate:
3678 break;
3679
Caroline Tice969ed3d2011-05-02 20:41:46 +00003680 case eInputReaderAsynchronousOutputWritten:
3681 break;
3682
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003683 case eInputReaderGotToken:
3684 {
3685 Error error;
3686 process->PutSTDIN (bytes, bytes_len, error);
3687 }
3688 break;
3689
Caroline Ticeefed6132010-11-19 20:47:54 +00003690 case eInputReaderInterrupt:
3691 process->Halt ();
3692 break;
3693
3694 case eInputReaderEndOfFile:
3695 process->AppendSTDOUT ("^D", 2);
3696 break;
3697
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003698 case eInputReaderDone:
3699 break;
3700
3701 }
3702
3703 return bytes_len;
3704}
3705
3706void
3707Process::ResetProcessInputReader ()
3708{
3709 m_process_input_reader.reset();
3710}
3711
3712void
Greg Claytonee95ed52011-11-17 22:14:31 +00003713Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003714{
3715 // First set up the Read Thread for reading/handling process I/O
3716
3717 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3718
3719 if (conn_ap.get())
3720 {
3721 m_stdio_communication.SetConnection (conn_ap.release());
3722 if (m_stdio_communication.IsConnected())
3723 {
3724 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3725 m_stdio_communication.StartReadThread();
3726
3727 // Now read thread is set up, set up input reader.
3728
3729 if (!m_process_input_reader.get())
3730 {
3731 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3732 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3733 this,
3734 eInputReaderGranularityByte,
3735 NULL,
3736 NULL,
3737 false));
3738
3739 if (err.Fail())
3740 m_process_input_reader.reset();
3741 }
3742 }
3743 }
3744}
3745
3746void
3747Process::PushProcessInputReader ()
3748{
3749 if (m_process_input_reader && !m_process_input_reader->IsActive())
3750 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3751}
3752
3753void
3754Process::PopProcessInputReader ()
3755{
3756 if (m_process_input_reader && m_process_input_reader->IsActive())
3757 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3758}
3759
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003760// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003761void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003762Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003763{
Greg Claytone0d378b2011-03-24 21:19:54 +00003764 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003765
3766 int i=0;
3767 const char *name;
3768 OptionEnumValueElement option_enum;
3769 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3770 {
3771 if (name)
3772 {
3773 option_enum.value = i;
3774 option_enum.string_value = name;
3775 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3776 g_plugins.push_back (option_enum);
3777 }
3778 ++i;
3779 }
3780 option_enum.value = 0;
3781 option_enum.string_value = NULL;
3782 option_enum.usage = NULL;
3783 g_plugins.push_back (option_enum);
3784
3785 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3786 {
3787 if (::strcmp (name, "plugin") == 0)
3788 {
3789 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3790 break;
3791 }
3792 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003793 UserSettingsControllerSP &usc = GetSettingsController();
3794 usc.reset (new SettingsController);
3795 UserSettingsController::InitializeSettingsController (usc,
3796 SettingsController::global_settings_table,
3797 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003798
3799 // Now call SettingsInitialize() for each 'child' of Process settings
3800 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003801}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003802
Greg Clayton99d0faf2010-11-18 23:32:35 +00003803void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003804Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003805{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003806 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3807
3808 Thread::SettingsTerminate ();
3809
3810 // Now terminate Process Settings.
3811
Greg Clayton99d0faf2010-11-18 23:32:35 +00003812 UserSettingsControllerSP &usc = GetSettingsController();
3813 UserSettingsController::FinalizeSettingsController (usc);
3814 usc.reset();
3815}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003816
Greg Clayton99d0faf2010-11-18 23:32:35 +00003817UserSettingsControllerSP &
3818Process::GetSettingsController ()
3819{
Greg Claytonb9556ac2012-01-30 07:41:31 +00003820 static UserSettingsControllerSP g_settings_controller_sp;
3821 if (!g_settings_controller_sp)
3822 {
3823 g_settings_controller_sp.reset (new Process::SettingsController);
3824 // The first shared pointer to Process::SettingsController in
3825 // g_settings_controller_sp must be fully created above so that
3826 // the TargetInstanceSettings can use a weak_ptr to refer back
3827 // to the master setttings controller
3828 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp,
3829 false,
3830 InstanceSettings::GetDefaultName().AsCString()));
3831 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
3832 }
3833 return g_settings_controller_sp;
3834
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003835}
3836
Caroline Tice1559a462010-09-27 00:30:10 +00003837void
3838Process::UpdateInstanceName ()
3839{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003840 Module *module = GetTarget().GetExecutableModulePointer();
Greg Claytone1cd1be2012-01-29 20:56:30 +00003841 if (module && module->GetFileSpec().GetFilename())
Caroline Tice1559a462010-09-27 00:30:10 +00003842 {
Greg Claytondbe54502010-11-19 03:46:01 +00003843 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytone1cd1be2012-01-29 20:56:30 +00003844 module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003845 }
3846}
3847
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003848ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003849Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00003850 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00003851 bool stop_others,
3852 bool try_all_threads,
3853 bool discard_on_error,
3854 uint32_t single_thread_timeout_usec,
3855 Stream &errors)
3856{
3857 ExecutionResults return_value = eExecutionSetupError;
3858
Jim Ingham77787032011-01-20 02:03:18 +00003859 if (thread_plan_sp.get() == NULL)
3860 {
3861 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003862 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003863 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003864
3865 if (exe_ctx.GetProcessPtr() != this)
3866 {
3867 errors.Printf("RunThreadPlan called on wrong process.");
3868 return eExecutionSetupError;
3869 }
3870
3871 Thread *thread = exe_ctx.GetThreadPtr();
3872 if (thread == NULL)
3873 {
3874 errors.Printf("RunThreadPlan called with invalid thread.");
3875 return eExecutionSetupError;
3876 }
Jim Ingham77787032011-01-20 02:03:18 +00003877
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003878 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3879 // For that to be true the plan can't be private - since private plans suppress themselves in the
3880 // GetCompletedPlan call.
3881
3882 bool orig_plan_private = thread_plan_sp->GetPrivate();
3883 thread_plan_sp->SetPrivate(false);
3884
Jim Ingham444586b2011-01-24 06:34:17 +00003885 if (m_private_state.GetValue() != eStateStopped)
3886 {
3887 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003888 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003889 }
3890
Jim Ingham66243842011-08-13 00:56:10 +00003891 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00003892 const uint32_t thread_idx_id = thread->GetIndexID();
3893 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003894
3895 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3896 // so we should arrange to reset them as well.
3897
Greg Claytonc14ee322011-09-22 04:58:26 +00003898 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003899
Jim Ingham66243842011-08-13 00:56:10 +00003900 uint32_t selected_tid;
3901 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00003902 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00003903 {
3904 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003905 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003906 }
3907 else
3908 {
3909 selected_tid = LLDB_INVALID_THREAD_ID;
3910 }
3911
Jim Ingham372787f2012-04-07 00:00:41 +00003912 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
3913
3914 if (Host::GetCurrentThread() == m_private_state_thread)
3915 {
3916 // Yikes, we are running on the private state thread! So we can't call DoRunThreadPlan on this thread, since
3917 // then nobody will be around to fetch internal events.
3918 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
3919 // we are doing the RunThreadPlan here.
3920 backup_private_state_thread = m_private_state_thread;
3921 printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.\n");
3922 StartPrivateStateThread(true);
3923 }
3924
3925 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00003926
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003927 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003928
3929 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3930 // restored on exit to the function.
3931
3932 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003933
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003934 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003935 if (log)
3936 {
3937 StreamString s;
3938 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton81c22f62011-10-19 18:09:39 +00003939 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00003940 thread->GetIndexID(),
3941 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00003942 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003943 }
3944
Jim Ingham0f16e732011-02-08 05:20:59 +00003945 bool got_event;
3946 lldb::EventSP event_sp;
3947 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003948
3949 TimeValue* timeout_ptr = NULL;
3950 TimeValue real_timeout;
3951
Jim Ingham0f16e732011-02-08 05:20:59 +00003952 bool first_timeout = true;
3953 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003954
Jim Inghamf48169b2010-11-30 02:22:11 +00003955 while (1)
3956 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003957 // We usually want to resume the process if we get to the top of the loop.
3958 // The only exception is if we get two running events with no intervening
3959 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003960
Jim Ingham0f16e732011-02-08 05:20:59 +00003961 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003962 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003963 // Do the initial resume and wait for the running event before going further.
3964
Greg Claytonc14ee322011-09-22 04:58:26 +00003965 Error resume_error = Resume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00003966 if (!resume_error.Success())
3967 {
3968 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003969 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003970 break;
3971 }
3972
3973 real_timeout = TimeValue::Now();
3974 real_timeout.OffsetWithMicroSeconds(500000);
3975 timeout_ptr = &real_timeout;
3976
Sean Callananc1b312a2012-01-05 02:00:14 +00003977 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
Jim Ingham0f16e732011-02-08 05:20:59 +00003978 if (!got_event)
3979 {
3980 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003981 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003982
3983 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003984 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003985 break;
3986 }
3987
3988 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3989 if (stop_state != eStateRunning)
3990 {
3991 if (log)
3992 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3993
3994 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003995 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003996 break;
3997 }
3998
3999 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004000 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004001 // We need to call the function synchronously, so spin waiting for it to return.
4002 // If we get interrupted while executing, we're going to lose our context, and
4003 // won't be able to gather the result at this point.
4004 // We set the timeout AFTER the resume, since the resume takes some time and we
4005 // don't want to charge that to the timeout.
4006
4007 if (single_thread_timeout_usec != 0)
4008 {
4009 real_timeout = TimeValue::Now();
4010 if (first_timeout)
4011 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
4012 else
4013 real_timeout.OffsetWithSeconds(10);
4014
4015 timeout_ptr = &real_timeout;
4016 }
4017 }
4018 else
4019 {
4020 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004021 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004022 do_resume = true;
4023 }
4024
4025 // Now wait for the process to stop again:
4026 stop_state = lldb::eStateInvalid;
4027 event_sp.reset();
4028 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4029
4030 if (got_event)
4031 {
4032 if (event_sp.get())
4033 {
4034 bool keep_going = false;
4035 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4036 if (log)
4037 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
4038
4039 switch (stop_state)
4040 {
4041 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00004042 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004043 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00004044 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00004045 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00004046 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004047 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00004048 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00004049 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4050 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00004051 }
4052 else
4053 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004054 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4055 StopReason stop_reason = eStopReasonInvalid;
4056 if (stop_info_sp)
4057 stop_reason = stop_info_sp->GetStopReason();
4058 if (stop_reason == eStopReasonPlanComplete)
4059 {
4060 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004061 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004062 // Now mark this plan as private so it doesn't get reported as the stop reason
4063 // after this point.
4064 if (thread_plan_sp)
4065 thread_plan_sp->SetPrivate (orig_plan_private);
4066 return_value = eExecutionCompleted;
4067 }
4068 else
4069 {
4070 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004071 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004072
4073 return_value = eExecutionInterrupted;
4074 }
Jim Ingham160f78c2011-05-17 01:10:11 +00004075 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00004076 }
4077 break;
4078
Jim Ingham0f16e732011-02-08 05:20:59 +00004079 case lldb::eStateCrashed:
4080 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004081 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004082 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004083 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004084
Jim Ingham0f16e732011-02-08 05:20:59 +00004085 case lldb::eStateRunning:
4086 do_resume = false;
4087 keep_going = true;
4088 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004089
Jim Ingham0f16e732011-02-08 05:20:59 +00004090 default:
4091 if (log)
4092 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00004093
4094 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004095 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004096 break;
4097 }
4098 if (keep_going)
4099 continue;
4100 else
4101 break;
4102 }
4103 else
4104 {
4105 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004106 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00004107 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004108 break;
4109 }
4110 }
4111 else
4112 {
4113 // If we didn't get an event that means we've timed out...
4114 // We will interrupt the process here. Depending on what we were asked to do we will
4115 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00004116 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00004117
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004118 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00004119 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00004120 {
4121 if (first_timeout)
4122 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4123 "trying with all threads enabled.",
4124 single_thread_timeout_usec);
4125 else
4126 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4127 "and timeout: %d timed out.",
4128 single_thread_timeout_usec);
4129 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004130 else
Jim Ingham0f16e732011-02-08 05:20:59 +00004131 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4132 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00004133 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004134 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004135
Greg Claytonc14ee322011-09-22 04:58:26 +00004136 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00004137 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00004138 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004139 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004140 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004141
Jim Ingham0f16e732011-02-08 05:20:59 +00004142 // If halt succeeds, it always produces a stopped event. Wait for that:
4143
4144 real_timeout = TimeValue::Now();
4145 real_timeout.OffsetWithMicroSeconds(500000);
4146
4147 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004148
4149 if (got_event)
4150 {
4151 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4152 if (log)
4153 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004154 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00004155 if (stop_state == lldb::eStateStopped
4156 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00004157 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004158 }
4159
Jim Ingham0f16e732011-02-08 05:20:59 +00004160 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00004161 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004162 // Between the time we initiated the Halt and the time we delivered it, the process could have
4163 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00004164
Greg Claytonc14ee322011-09-22 04:58:26 +00004165 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004166 {
4167 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004168 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004169 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004170 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004171 break;
4172 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004173
Jim Ingham0f16e732011-02-08 05:20:59 +00004174 if (!try_all_threads)
4175 {
4176 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004177 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004178 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004179 break;
4180 }
4181
4182 if (first_timeout)
4183 {
4184 // Set all the other threads to run, and return to the top of the loop, which will continue;
4185 first_timeout = false;
4186 thread_plan_sp->SetStopOthers (false);
4187 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004188 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004189
4190 continue;
4191 }
4192 else
4193 {
4194 // Running all threads failed, so return Interrupted.
4195 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004196 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004197 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004198 break;
4199 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004200 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004201 }
4202 else
4203 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004204 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004205 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004206 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004207 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00004208 }
4209 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004210 else
4211 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004212 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4213 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00004214 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004215 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.",
4216 halt_error.AsCString());
4217 real_timeout = TimeValue::Now();
4218 real_timeout.OffsetWithMicroSeconds(500000);
4219 timeout_ptr = &real_timeout;
4220 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4221 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004222 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004223 // This is not going anywhere, bag out.
4224 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004225 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004226 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004227 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004228 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004229 else
4230 {
4231 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4232 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004233 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00004234 if (stop_state == lldb::eStateStopped)
4235 {
4236 // Between the time we initiated the Halt and the time we delivered it, the process could have
4237 // already finished its job. Check that here:
4238
Greg Claytonc14ee322011-09-22 04:58:26 +00004239 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004240 {
4241 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004242 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004243 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004244 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004245 break;
4246 }
4247
4248 if (first_timeout)
4249 {
4250 // Set all the other threads to run, and return to the top of the loop, which will continue;
4251 first_timeout = false;
4252 thread_plan_sp->SetStopOthers (false);
4253 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004254 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004255
4256 continue;
4257 }
4258 else
4259 {
4260 // Running all threads failed, so return Interrupted.
4261 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004262 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004263 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004264 break;
4265 }
4266 }
4267 else
4268 {
Sean Callanan39821ac2011-08-09 22:07:08 +00004269 if (log)
4270 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4271 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00004272 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004273 break;
4274 }
4275 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004276 }
4277
Jim Inghamf48169b2010-11-30 02:22:11 +00004278 }
4279
Jim Ingham0f16e732011-02-08 05:20:59 +00004280 } // END WAIT LOOP
4281
Jim Ingham372787f2012-04-07 00:00:41 +00004282 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4283 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4284 {
4285 StopPrivateStateThread();
Jim Ingham372787f2012-04-07 00:00:41 +00004286 Error error;
4287 // Host::ThreadJoin(m_private_state_thread, &thread_result, &error);
4288 m_private_state_thread = backup_private_state_thread;
4289 }
4290
4291
Jim Ingham0f16e732011-02-08 05:20:59 +00004292 // Now do some processing on the results of the run:
4293 if (return_value == eExecutionInterrupted)
4294 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004295 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004296 {
4297 StreamString s;
4298 if (event_sp)
4299 event_sp->Dump (&s);
4300 else
4301 {
Jim Ingham20829ac2011-08-09 22:24:33 +00004302 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004303 }
4304
4305 StreamString ts;
4306
Jim Ingham20829ac2011-08-09 22:24:33 +00004307 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00004308
4309 do
4310 {
4311 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4312
4313 if (!event_data)
4314 {
4315 event_explanation = "<no event data>";
4316 break;
4317 }
4318
4319 Process *process = event_data->GetProcessSP().get();
4320
4321 if (!process)
4322 {
4323 event_explanation = "<no process>";
4324 break;
4325 }
4326
4327 ThreadList &thread_list = process->GetThreadList();
4328
4329 uint32_t num_threads = thread_list.GetSize();
4330 uint32_t thread_index;
4331
4332 ts.Printf("<%u threads> ", num_threads);
4333
4334 for (thread_index = 0;
4335 thread_index < num_threads;
4336 ++thread_index)
4337 {
4338 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4339
4340 if (!thread)
4341 {
4342 ts.Printf("<?> ");
4343 continue;
4344 }
4345
Greg Clayton81c22f62011-10-19 18:09:39 +00004346 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Ingham0f16e732011-02-08 05:20:59 +00004347 RegisterContext *register_context = thread->GetRegisterContext().get();
4348
4349 if (register_context)
4350 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4351 else
4352 ts.Printf("[ip unknown] ");
4353
4354 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4355 if (stop_info_sp)
4356 {
4357 const char *stop_desc = stop_info_sp->GetDescription();
4358 if (stop_desc)
4359 ts.PutCString (stop_desc);
4360 }
4361 ts.Printf(">");
4362 }
4363
4364 event_explanation = ts.GetData();
4365 } while (0);
4366
4367 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004368 {
4369 if (event_explanation)
4370 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4371 else
4372 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4373 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004374
4375 if (discard_on_error && thread_plan_sp)
4376 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004377 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004378 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004379 }
4380 }
4381 }
4382 else if (return_value == eExecutionSetupError)
4383 {
4384 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004385 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004386
4387 if (discard_on_error && thread_plan_sp)
4388 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004389 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004390 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004391 }
4392 }
4393 else
4394 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004395 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004396 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004397 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004398 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00004399 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00004400 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004401 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004402 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004403 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004404 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00004405 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00004406 }
4407 else
4408 {
4409 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004410 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00004411 if (discard_on_error && thread_plan_sp)
4412 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004413 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004414 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00004415 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004416 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00004417 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004418 }
4419 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004420
Jim Inghamf48169b2010-11-30 02:22:11 +00004421 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00004422 // Check that it's still there, and if it is put it back in the context. Also restore the
4423 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00004424 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4425 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00004426 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004427 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00004428 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004429
4430 // Also restore the current process'es selected frame & thread, since this function calling may
4431 // be done behind the user's back.
4432
4433 if (selected_tid != LLDB_INVALID_THREAD_ID)
4434 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004435 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00004436 {
4437 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00004438 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00004439 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00004440 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004441 }
4442 }
4443
4444 return return_value;
4445}
4446
4447const char *
4448Process::ExecutionResultAsCString (ExecutionResults result)
4449{
4450 const char *result_name;
4451
4452 switch (result)
4453 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004454 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004455 result_name = "eExecutionCompleted";
4456 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004457 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004458 result_name = "eExecutionDiscarded";
4459 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004460 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004461 result_name = "eExecutionInterrupted";
4462 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004463 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004464 result_name = "eExecutionSetupError";
4465 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004466 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004467 result_name = "eExecutionTimedOut";
4468 break;
4469 }
4470 return result_name;
4471}
4472
Greg Clayton7260f622011-04-18 08:33:37 +00004473void
4474Process::GetStatus (Stream &strm)
4475{
4476 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00004477 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00004478 {
4479 if (state == eStateExited)
4480 {
4481 int exit_status = GetExitStatus();
4482 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004483 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004484 GetID(),
4485 exit_status,
4486 exit_status,
4487 exit_description ? exit_description : "");
4488 }
4489 else
4490 {
4491 if (state == eStateConnected)
4492 strm.Printf ("Connected to remote target.\n");
4493 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004494 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004495 }
4496 }
4497 else
4498 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004499 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004500 }
4501}
4502
4503size_t
4504Process::GetThreadStatus (Stream &strm,
4505 bool only_threads_with_stop_reason,
4506 uint32_t start_frame,
4507 uint32_t num_frames,
4508 uint32_t num_frames_with_source)
4509{
4510 size_t num_thread_infos_dumped = 0;
4511
4512 const size_t num_threads = GetThreadList().GetSize();
4513 for (uint32_t i = 0; i < num_threads; i++)
4514 {
4515 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4516 if (thread)
4517 {
4518 if (only_threads_with_stop_reason)
4519 {
4520 if (thread->GetStopInfo().get() == NULL)
4521 continue;
4522 }
4523 thread->GetStatus (strm,
4524 start_frame,
4525 num_frames,
4526 num_frames_with_source);
4527 ++num_thread_infos_dumped;
4528 }
4529 }
4530 return num_thread_infos_dumped;
4531}
4532
Greg Claytona9f40ad2012-02-22 04:37:26 +00004533void
4534Process::AddInvalidMemoryRegion (const LoadRange &region)
4535{
4536 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4537}
4538
4539bool
4540Process::RemoveInvalidMemoryRange (const LoadRange &region)
4541{
4542 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4543}
4544
Jim Ingham372787f2012-04-07 00:00:41 +00004545void
4546Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4547{
4548 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4549}
4550
4551bool
4552Process::RunPreResumeActions ()
4553{
4554 bool result = true;
4555 while (!m_pre_resume_actions.empty())
4556 {
4557 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
4558 m_pre_resume_actions.pop_back();
4559 bool this_result = action.callback (action.baton);
4560 if (result == true) result = this_result;
4561 }
4562 return result;
4563}
4564
4565void
4566Process::ClearPreResumeActions ()
4567{
4568 m_pre_resume_actions.clear();
4569}
Greg Claytona9f40ad2012-02-22 04:37:26 +00004570
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004571//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004572// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004573//--------------------------------------------------------------
4574
Greg Clayton1b654882010-09-19 02:33:57 +00004575Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004576 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004577{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004578}
4579
Greg Clayton1b654882010-09-19 02:33:57 +00004580Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004581{
4582}
4583
4584lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004585Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004586{
Greg Claytonb9556ac2012-01-30 07:41:31 +00004587 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4588 false,
4589 instance_name));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004590 return new_settings_sp;
4591}
4592
4593//--------------------------------------------------------------
4594// class ProcessInstanceSettings
4595//--------------------------------------------------------------
4596
Greg Clayton85851dd2010-12-04 00:10:17 +00004597ProcessInstanceSettings::ProcessInstanceSettings
4598(
Greg Claytonb9556ac2012-01-30 07:41:31 +00004599 const UserSettingsControllerSP &owner_sp,
Greg Clayton85851dd2010-12-04 00:10:17 +00004600 bool live_instance,
4601 const char *name
4602) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004603 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004604{
Caroline Ticef20e8232010-09-09 18:26:37 +00004605 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4606 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4607 // 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 +00004608 // This is true for CreateInstanceName() too.
Greg Clayton1d885962011-11-08 02:43:13 +00004609
Caroline Tice9e41c152010-09-16 19:05:55 +00004610 if (GetInstanceName () == InstanceSettings::InvalidName())
4611 {
4612 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
Greg Claytonb9556ac2012-01-30 07:41:31 +00004613 owner_sp->RegisterInstanceSettings (this);
Caroline Tice9e41c152010-09-16 19:05:55 +00004614 }
Greg Clayton1d885962011-11-08 02:43:13 +00004615
Caroline Ticef20e8232010-09-09 18:26:37 +00004616 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004617 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004618 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004619 CopyInstanceSettings (pending_settings,false);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004620 }
4621}
4622
4623ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004624 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004625{
4626 if (m_instance_name != InstanceSettings::GetDefaultName())
4627 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004628 UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4629 if (owner_sp)
4630 {
4631 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4632 owner_sp->RemovePendingSettings (m_instance_name);
4633 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004634 }
4635}
4636
4637ProcessInstanceSettings::~ProcessInstanceSettings ()
4638{
4639}
4640
4641ProcessInstanceSettings&
4642ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4643{
4644 if (this != &rhs)
4645 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004646 }
4647
4648 return *this;
4649}
4650
4651
4652void
4653ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4654 const char *index_value,
4655 const char *value,
4656 const ConstString &instance_name,
4657 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004658 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004659 Error &err,
4660 bool pending)
4661{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004662}
4663
4664void
4665ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4666 bool pending)
4667{
Greg Clayton1d885962011-11-08 02:43:13 +00004668// if (new_settings.get() == NULL)
4669// return;
4670//
4671// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004672}
4673
Caroline Tice12cecd72010-09-20 21:37:42 +00004674bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004675ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4676 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004677 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004678 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004679{
Greg Clayton1d885962011-11-08 02:43:13 +00004680 if (err)
4681 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4682 return false;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004683}
4684
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004685const ConstString
4686ProcessInstanceSettings::CreateInstanceName ()
4687{
4688 static int instance_count = 1;
4689 StreamString sstr;
4690
4691 sstr.Printf ("process_%d", instance_count);
4692 ++instance_count;
4693
4694 const ConstString ret_val (sstr.GetData());
4695 return ret_val;
4696}
4697
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004698//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004699// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004700//--------------------------------------------------
4701
4702SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004703Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004704{
4705 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4706 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4707};
4708
4709
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004710SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004711Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004712{
Greg Clayton85851dd2010-12-04 00:10:17 +00004713 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton85851dd2010-12-04 00:10:17 +00004714 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004715};
4716
4717
Jim Ingham5aee1622010-08-09 23:31:02 +00004718
Greg Clayton1d885962011-11-08 02:43:13 +00004719