blob: 973fc54d760088383131364b3938fb1c29845514 [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(),
Sean Callanana7b443a2012-02-14 22:50:38 +0000791 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000792{
Caroline Tice1559a462010-09-27 00:30:10 +0000793 UpdateInstanceName();
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000794
795 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000796
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000797 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000798 if (log)
799 log->Printf ("%p Process::Process()", this);
800
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000801 SetEventName (eBroadcastBitStateChanged, "state-changed");
802 SetEventName (eBroadcastBitInterrupt, "interrupt");
803 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
804 SetEventName (eBroadcastBitSTDERR, "stderr-available");
805
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806 listener.StartListeningForEvents (this,
807 eBroadcastBitStateChanged |
808 eBroadcastBitInterrupt |
809 eBroadcastBitSTDOUT |
810 eBroadcastBitSTDERR);
811
812 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
813 eBroadcastBitStateChanged);
814
815 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
816 eBroadcastInternalStateControlStop |
817 eBroadcastInternalStateControlPause |
818 eBroadcastInternalStateControlResume);
819}
820
821//----------------------------------------------------------------------
822// Destructor
823//----------------------------------------------------------------------
824Process::~Process()
825{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000826 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000827 if (log)
828 log->Printf ("%p Process::~Process()", this);
829 StopPrivateStateThread();
830}
831
832void
833Process::Finalize()
834{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000835 switch (GetPrivateState())
836 {
837 case eStateConnected:
838 case eStateAttaching:
839 case eStateLaunching:
840 case eStateStopped:
841 case eStateRunning:
842 case eStateStepping:
843 case eStateCrashed:
844 case eStateSuspended:
845 if (GetShouldDetach())
846 Detach();
847 else
848 Destroy();
849 break;
850
851 case eStateInvalid:
852 case eStateUnloaded:
853 case eStateDetached:
854 case eStateExited:
855 break;
856 }
857
Greg Clayton1ed54f52011-10-01 00:45:15 +0000858 // Clear our broadcaster before we proceed with destroying
859 Broadcaster::Clear();
860
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000861 // Do any cleanup needed prior to being destructed... Subclasses
862 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000863
864 // We need to destroy the loader before the derived Process class gets destroyed
865 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000866 m_dynamic_checkers_ap.reset();
867 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000868 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000869 m_dyld_ap.reset();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000870 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +0000871 std::vector<Notifications> empty_notifications;
872 m_notifications.swap(empty_notifications);
873 m_image_tokens.clear();
874 m_memory_cache.Clear();
875 m_allocated_memory_cache.Clear();
876 m_language_runtimes.clear();
877 m_next_event_action_ap.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878}
879
880void
881Process::RegisterNotificationCallbacks (const Notifications& callbacks)
882{
883 m_notifications.push_back(callbacks);
884 if (callbacks.initialize != NULL)
885 callbacks.initialize (callbacks.baton, this);
886}
887
888bool
889Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
890{
891 std::vector<Notifications>::iterator pos, end = m_notifications.end();
892 for (pos = m_notifications.begin(); pos != end; ++pos)
893 {
894 if (pos->baton == callbacks.baton &&
895 pos->initialize == callbacks.initialize &&
896 pos->process_state_changed == callbacks.process_state_changed)
897 {
898 m_notifications.erase(pos);
899 return true;
900 }
901 }
902 return false;
903}
904
905void
906Process::SynchronouslyNotifyStateChanged (StateType state)
907{
908 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
909 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
910 {
911 if (notification_pos->process_state_changed)
912 notification_pos->process_state_changed (notification_pos->baton, this, state);
913 }
914}
915
916// FIXME: We need to do some work on events before the general Listener sees them.
917// For instance if we are continuing from a breakpoint, we need to ensure that we do
918// the little "insert real insn, step & stop" trick. But we can't do that when the
919// event is delivered by the broadcaster - since that is done on the thread that is
920// waiting for new events, so if we needed more than one event for our handling, we would
921// stall. So instead we do it when we fetch the event off of the queue.
922//
923
924StateType
925Process::GetNextEvent (EventSP &event_sp)
926{
927 StateType state = eStateInvalid;
928
929 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
930 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
931
932 return state;
933}
934
935
936StateType
937Process::WaitForProcessToStop (const TimeValue *timeout)
938{
Jim Ingham4b536182011-08-09 02:12:22 +0000939 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
940 // We have to actually check each event, and in the case of a stopped event check the restarted flag
941 // on the event.
942 EventSP event_sp;
943 StateType state = GetState();
944 // If we are exited or detached, we won't ever get back to any
945 // other valid state...
946 if (state == eStateDetached || state == eStateExited)
947 return state;
948
949 while (state != eStateInvalid)
950 {
951 state = WaitForStateChangedEvents (timeout, event_sp);
952 switch (state)
953 {
954 case eStateCrashed:
955 case eStateDetached:
956 case eStateExited:
957 case eStateUnloaded:
958 return state;
959 case eStateStopped:
960 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
961 continue;
962 else
963 return state;
964 default:
965 continue;
966 }
967 }
968 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000969}
970
971
972StateType
973Process::WaitForState
974(
975 const TimeValue *timeout,
976 const StateType *match_states, const uint32_t num_match_states
977)
978{
979 EventSP event_sp;
980 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000981 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000982 while (state != eStateInvalid)
983 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000984 // If we are exited or detached, we won't ever get back to any
985 // other valid state...
986 if (state == eStateDetached || state == eStateExited)
987 return state;
988
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989 state = WaitForStateChangedEvents (timeout, event_sp);
990
991 for (i=0; i<num_match_states; ++i)
992 {
993 if (match_states[i] == state)
994 return state;
995 }
996 }
997 return state;
998}
999
Jim Ingham30f9b212010-10-11 23:53:14 +00001000bool
1001Process::HijackProcessEvents (Listener *listener)
1002{
1003 if (listener != NULL)
1004 {
1005 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
1006 }
1007 else
1008 return false;
1009}
1010
1011void
1012Process::RestoreProcessEvents ()
1013{
1014 RestoreBroadcaster();
1015}
1016
Jim Ingham0f16e732011-02-08 05:20:59 +00001017bool
1018Process::HijackPrivateProcessEvents (Listener *listener)
1019{
1020 if (listener != NULL)
1021 {
1022 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
1023 }
1024 else
1025 return false;
1026}
1027
1028void
1029Process::RestorePrivateProcessEvents ()
1030{
1031 m_private_state_broadcaster.RestoreBroadcaster();
1032}
1033
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001034StateType
1035Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1036{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001037 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001038
1039 if (log)
1040 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1041
1042 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001043 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1044 this,
1045 eBroadcastBitStateChanged,
1046 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001047 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1048
1049 if (log)
1050 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1051 __FUNCTION__,
1052 timeout,
1053 StateAsCString(state));
1054 return state;
1055}
1056
1057Event *
1058Process::PeekAtStateChangedEvents ()
1059{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001060 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001061
1062 if (log)
1063 log->Printf ("Process::%s...", __FUNCTION__);
1064
1065 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001066 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1067 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001068 if (log)
1069 {
1070 if (event_ptr)
1071 {
1072 log->Printf ("Process::%s (event_ptr) => %s",
1073 __FUNCTION__,
1074 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1075 }
1076 else
1077 {
1078 log->Printf ("Process::%s no events found",
1079 __FUNCTION__);
1080 }
1081 }
1082 return event_ptr;
1083}
1084
1085StateType
1086Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1087{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001088 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089
1090 if (log)
1091 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1092
1093 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001094 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1095 &m_private_state_broadcaster,
1096 eBroadcastBitStateChanged,
1097 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1099
1100 // This is a bit of a hack, but when we wait here we could very well return
1101 // to the command-line, and that could disable the log, which would render the
1102 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001103 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001104 {
1105 if (state == eStateInvalid)
1106 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1107 else
1108 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1109 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001110 return state;
1111}
1112
1113bool
1114Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1115{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001116 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117
1118 if (log)
1119 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1120
1121 if (control_only)
1122 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1123 else
1124 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1125}
1126
1127bool
1128Process::IsRunning () const
1129{
1130 return StateIsRunningState (m_public_state.GetValue());
1131}
1132
1133int
1134Process::GetExitStatus ()
1135{
1136 if (m_public_state.GetValue() == eStateExited)
1137 return m_exit_status;
1138 return -1;
1139}
1140
Greg Clayton85851dd2010-12-04 00:10:17 +00001141
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142const char *
1143Process::GetExitDescription ()
1144{
1145 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1146 return m_exit_string.c_str();
1147 return NULL;
1148}
1149
Greg Clayton6779606a2011-01-22 23:43:18 +00001150bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001151Process::SetExitStatus (int status, const char *cstr)
1152{
Greg Clayton414f5d32011-01-25 02:58:48 +00001153 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1154 if (log)
1155 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1156 status, status,
1157 cstr ? "\"" : "",
1158 cstr ? cstr : "NULL",
1159 cstr ? "\"" : "");
1160
Greg Clayton6779606a2011-01-22 23:43:18 +00001161 // We were already in the exited state
1162 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001163 {
Greg Clayton385d6032011-01-26 23:47:29 +00001164 if (log)
1165 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001166 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001167 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001168
1169 m_exit_status = status;
1170 if (cstr)
1171 m_exit_string = cstr;
1172 else
1173 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174
Greg Clayton6779606a2011-01-22 23:43:18 +00001175 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001176
Greg Clayton6779606a2011-01-22 23:43:18 +00001177 SetPrivateState (eStateExited);
1178 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001179}
1180
1181// This static callback can be used to watch for local child processes on
1182// the current host. The the child process exits, the process will be
1183// found in the global target list (we want to be completely sure that the
1184// lldb_private::Process doesn't go away before we can deliver the signal.
1185bool
Greg Claytone4e45922011-11-16 05:37:56 +00001186Process::SetProcessExitStatus (void *callback_baton,
1187 lldb::pid_t pid,
1188 bool exited,
1189 int signo, // Zero for no signal
1190 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001191)
1192{
Greg Claytone4e45922011-11-16 05:37:56 +00001193 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1194 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00001195 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001196 callback_baton,
1197 pid,
1198 exited,
1199 signo,
1200 exit_status);
1201
1202 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001203 {
Greg Clayton66111032010-06-23 01:19:29 +00001204 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001205 if (target_sp)
1206 {
1207 ProcessSP process_sp (target_sp->GetProcessSP());
1208 if (process_sp)
1209 {
1210 const char *signal_cstr = NULL;
1211 if (signo)
1212 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1213
1214 process_sp->SetExitStatus (exit_status, signal_cstr);
1215 }
1216 }
1217 return true;
1218 }
1219 return false;
1220}
1221
1222
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001223void
1224Process::UpdateThreadListIfNeeded ()
1225{
1226 const uint32_t stop_id = GetStopID();
1227 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1228 {
Greg Clayton2637f822011-11-17 01:23:07 +00001229 const StateType state = GetPrivateState();
1230 if (StateIsStoppedState (state, true))
1231 {
1232 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001233 // m_thread_list does have its own mutex, but we need to
1234 // hold onto the mutex between the call to UpdateThreadList(...)
1235 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton2637f822011-11-17 01:23:07 +00001236 ThreadList new_thread_list(this);
1237 // Always update the thread list with the protocol specific
1238 // thread list
1239 UpdateThreadList (m_thread_list, new_thread_list);
1240 OperatingSystem *os = GetOperatingSystem ();
1241 if (os)
1242 os->UpdateThreadList (m_thread_list, new_thread_list);
1243 m_thread_list.Update (new_thread_list);
1244 m_thread_list.SetStopID (stop_id);
1245 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001246 }
1247}
1248
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001249uint32_t
1250Process::GetNextThreadIndexID ()
1251{
1252 return ++m_thread_index_id;
1253}
1254
1255StateType
1256Process::GetState()
1257{
1258 // If any other threads access this we will need a mutex for it
1259 return m_public_state.GetValue ();
1260}
1261
1262void
1263Process::SetPublicState (StateType new_state)
1264{
Greg Clayton414f5d32011-01-25 02:58:48 +00001265 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001266 if (log)
1267 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1268 m_public_state.SetValue (new_state);
1269}
1270
1271StateType
1272Process::GetPrivateState ()
1273{
1274 return m_private_state.GetValue();
1275}
1276
1277void
1278Process::SetPrivateState (StateType new_state)
1279{
Greg Clayton414f5d32011-01-25 02:58:48 +00001280 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001281 bool state_changed = false;
1282
1283 if (log)
1284 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1285
1286 Mutex::Locker locker(m_private_state.GetMutex());
1287
1288 const StateType old_state = m_private_state.GetValueNoLock ();
1289 state_changed = old_state != new_state;
1290 if (state_changed)
1291 {
1292 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001293 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001294 {
Jim Ingham4b536182011-08-09 02:12:22 +00001295 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001296 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001297 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001298 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001299 }
1300 // Use our target to get a shared pointer to ourselves...
1301 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1302 }
1303 else
1304 {
1305 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001306 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001307 }
1308}
1309
Jim Ingham0faa43f2011-11-08 03:00:11 +00001310void
1311Process::SetRunningUserExpression (bool on)
1312{
1313 m_mod_id.SetRunningUserExpression (on);
1314}
1315
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001316addr_t
1317Process::GetImageInfoAddress()
1318{
1319 return LLDB_INVALID_ADDRESS;
1320}
1321
Greg Clayton8f343b02010-11-04 01:54:29 +00001322//----------------------------------------------------------------------
1323// LoadImage
1324//
1325// This function provides a default implementation that works for most
1326// unix variants. Any Process subclasses that need to do shared library
1327// loading differently should override LoadImage and UnloadImage and
1328// do what is needed.
1329//----------------------------------------------------------------------
1330uint32_t
1331Process::LoadImage (const FileSpec &image_spec, Error &error)
1332{
1333 DynamicLoader *loader = GetDynamicLoader();
1334 if (loader)
1335 {
1336 error = loader->CanLoadImage();
1337 if (error.Fail())
1338 return LLDB_INVALID_IMAGE_TOKEN;
1339 }
1340
1341 if (error.Success())
1342 {
1343 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001344
1345 if (thread_sp)
1346 {
1347 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1348
1349 if (frame_sp)
1350 {
1351 ExecutionContext exe_ctx;
1352 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001353 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001354 StreamString expr;
1355 char path[PATH_MAX];
1356 image_spec.GetPath(path, sizeof(path));
1357 expr.Printf("dlopen (\"%s\", 2)", path);
1358 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001359 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001360 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 +00001361 error = result_valobj_sp->GetError();
1362 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001363 {
1364 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001365 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001366 {
1367 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1368 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1369 {
1370 uint32_t image_token = m_image_tokens.size();
1371 m_image_tokens.push_back (image_ptr);
1372 return image_token;
1373 }
1374 }
1375 }
1376 }
1377 }
1378 }
1379 return LLDB_INVALID_IMAGE_TOKEN;
1380}
1381
1382//----------------------------------------------------------------------
1383// UnloadImage
1384//
1385// This function provides a default implementation that works for most
1386// unix variants. Any Process subclasses that need to do shared library
1387// loading differently should override LoadImage and UnloadImage and
1388// do what is needed.
1389//----------------------------------------------------------------------
1390Error
1391Process::UnloadImage (uint32_t image_token)
1392{
1393 Error error;
1394 if (image_token < m_image_tokens.size())
1395 {
1396 const addr_t image_addr = m_image_tokens[image_token];
1397 if (image_addr == LLDB_INVALID_ADDRESS)
1398 {
1399 error.SetErrorString("image already unloaded");
1400 }
1401 else
1402 {
1403 DynamicLoader *loader = GetDynamicLoader();
1404 if (loader)
1405 error = loader->CanLoadImage();
1406
1407 if (error.Success())
1408 {
1409 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001410
1411 if (thread_sp)
1412 {
1413 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1414
1415 if (frame_sp)
1416 {
1417 ExecutionContext exe_ctx;
1418 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001419 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001420 StreamString expr;
1421 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1422 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001423 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001424 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 +00001425 if (result_valobj_sp->GetError().Success())
1426 {
1427 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001428 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001429 {
1430 if (scalar.UInt(1))
1431 {
1432 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1433 }
1434 else
1435 {
1436 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1437 }
1438 }
1439 }
1440 else
1441 {
1442 error = result_valobj_sp->GetError();
1443 }
1444 }
1445 }
1446 }
1447 }
1448 }
1449 else
1450 {
1451 error.SetErrorString("invalid image token");
1452 }
1453 return error;
1454}
1455
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001456const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001457Process::GetABI()
1458{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001459 if (!m_abi_sp)
1460 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1461 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001462}
1463
Jim Ingham22777012010-09-23 02:01:19 +00001464LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001465Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001466{
1467 LanguageRuntimeCollection::iterator pos;
1468 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001469 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001470 {
Jim Inghamab175242012-03-10 00:22:19 +00001471 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001472
Jim Inghamab175242012-03-10 00:22:19 +00001473 m_language_runtimes[language] = runtime_sp;
1474 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001475 }
1476 else
1477 return (*pos).second.get();
1478}
1479
1480CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001481Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001482{
Jim Inghamab175242012-03-10 00:22:19 +00001483 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001484 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1485 return static_cast<CPPLanguageRuntime *> (runtime);
1486 return NULL;
1487}
1488
1489ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001490Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001491{
Jim Inghamab175242012-03-10 00:22:19 +00001492 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001493 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1494 return static_cast<ObjCLanguageRuntime *> (runtime);
1495 return NULL;
1496}
1497
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001498BreakpointSiteList &
1499Process::GetBreakpointSiteList()
1500{
1501 return m_breakpoint_site_list;
1502}
1503
1504const BreakpointSiteList &
1505Process::GetBreakpointSiteList() const
1506{
1507 return m_breakpoint_site_list;
1508}
1509
1510
1511void
1512Process::DisableAllBreakpointSites ()
1513{
1514 m_breakpoint_site_list.SetEnabledForAll (false);
1515}
1516
1517Error
1518Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1519{
1520 Error error (DisableBreakpointSiteByID (break_id));
1521
1522 if (error.Success())
1523 m_breakpoint_site_list.Remove(break_id);
1524
1525 return error;
1526}
1527
1528Error
1529Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1530{
1531 Error error;
1532 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1533 if (bp_site_sp)
1534 {
1535 if (bp_site_sp->IsEnabled())
1536 error = DisableBreakpoint (bp_site_sp.get());
1537 }
1538 else
1539 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001540 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001541 }
1542
1543 return error;
1544}
1545
1546Error
1547Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1548{
1549 Error error;
1550 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1551 if (bp_site_sp)
1552 {
1553 if (!bp_site_sp->IsEnabled())
1554 error = EnableBreakpoint (bp_site_sp.get());
1555 }
1556 else
1557 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001558 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001559 }
1560 return error;
1561}
1562
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001563lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001564Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001565{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001566 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001567 if (load_addr != LLDB_INVALID_ADDRESS)
1568 {
1569 BreakpointSiteSP bp_site_sp;
1570
1571 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1572 // create a new breakpoint site and add it.
1573
1574 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1575
1576 if (bp_site_sp)
1577 {
1578 bp_site_sp->AddOwner (owner);
1579 owner->SetBreakpointSite (bp_site_sp);
1580 return bp_site_sp->GetID();
1581 }
1582 else
1583 {
1584 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1585 if (bp_site_sp)
1586 {
1587 if (EnableBreakpoint (bp_site_sp.get()).Success())
1588 {
1589 owner->SetBreakpointSite (bp_site_sp);
1590 return m_breakpoint_site_list.Add (bp_site_sp);
1591 }
1592 }
1593 }
1594 }
1595 // We failed to enable the breakpoint
1596 return LLDB_INVALID_BREAK_ID;
1597
1598}
1599
1600void
1601Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1602{
1603 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1604 if (num_owners == 0)
1605 {
1606 DisableBreakpoint(bp_site_sp.get());
1607 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1608 }
1609}
1610
1611
1612size_t
1613Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1614{
1615 size_t bytes_removed = 0;
1616 addr_t intersect_addr;
1617 size_t intersect_size;
1618 size_t opcode_offset;
1619 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001620 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001621 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001622
Jim Ingham20c77192011-06-29 19:42:28 +00001623 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001624 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001625 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001626 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001627 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001628 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001629 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001630 {
1631 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1632 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001633 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001634 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001635 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001636 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001637 }
1638 }
1639 }
1640 return bytes_removed;
1641}
1642
1643
Greg Claytonded470d2011-03-19 01:12:21 +00001644
1645size_t
1646Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1647{
1648 PlatformSP platform_sp (m_target.GetPlatform());
1649 if (platform_sp)
1650 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1651 return 0;
1652}
1653
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001654Error
1655Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1656{
1657 Error error;
1658 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001659 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001660 const addr_t bp_addr = bp_site->GetLoadAddress();
1661 if (log)
1662 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1663 if (bp_site->IsEnabled())
1664 {
1665 if (log)
1666 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1667 return error;
1668 }
1669
1670 if (bp_addr == LLDB_INVALID_ADDRESS)
1671 {
1672 error.SetErrorString("BreakpointSite contains an invalid load address.");
1673 return error;
1674 }
1675 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1676 // trap for the breakpoint site
1677 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1678
1679 if (bp_opcode_size == 0)
1680 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001681 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001682 }
1683 else
1684 {
1685 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1686
1687 if (bp_opcode_bytes == NULL)
1688 {
1689 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1690 return error;
1691 }
1692
1693 // Save the original opcode by reading it
1694 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1695 {
1696 // Write a software breakpoint in place of the original opcode
1697 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1698 {
1699 uint8_t verify_bp_opcode_bytes[64];
1700 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1701 {
1702 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1703 {
1704 bp_site->SetEnabled(true);
1705 bp_site->SetType (BreakpointSite::eSoftware);
1706 if (log)
1707 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1708 bp_site->GetID(),
1709 (uint64_t)bp_addr);
1710 }
1711 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001712 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001713 }
1714 else
1715 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1716 }
1717 else
1718 error.SetErrorString("Unable to write breakpoint trap to memory.");
1719 }
1720 else
1721 error.SetErrorString("Unable to read memory at breakpoint address.");
1722 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001723 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001724 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1725 bp_site->GetID(),
1726 (uint64_t)bp_addr,
1727 error.AsCString());
1728 return error;
1729}
1730
1731Error
1732Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1733{
1734 Error error;
1735 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001736 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001737 addr_t bp_addr = bp_site->GetLoadAddress();
1738 lldb::user_id_t breakID = bp_site->GetID();
1739 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001740 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001741
1742 if (bp_site->IsHardware())
1743 {
1744 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1745 }
1746 else if (bp_site->IsEnabled())
1747 {
1748 const size_t break_op_size = bp_site->GetByteSize();
1749 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1750 if (break_op_size > 0)
1751 {
1752 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001753 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001754 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001755 bool break_op_found = false;
1756
1757 // Read the breakpoint opcode
1758 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1759 {
1760 bool verify = false;
1761 // Make sure we have the a breakpoint opcode exists at this address
1762 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1763 {
1764 break_op_found = true;
1765 // We found a valid breakpoint opcode at this address, now restore
1766 // the saved opcode.
1767 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1768 {
1769 verify = true;
1770 }
1771 else
1772 error.SetErrorString("Memory write failed when restoring original opcode.");
1773 }
1774 else
1775 {
1776 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1777 // Set verify to true and so we can check if the original opcode has already been restored
1778 verify = true;
1779 }
1780
1781 if (verify)
1782 {
Greg Claytonc982c762010-07-09 20:39:50 +00001783 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001784 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001785 // Verify that our original opcode made it back to the inferior
1786 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1787 {
1788 // compare the memory we just read with the original opcode
1789 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1790 {
1791 // SUCCESS
1792 bp_site->SetEnabled(false);
1793 if (log)
1794 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1795 return error;
1796 }
1797 else
1798 {
1799 if (break_op_found)
1800 error.SetErrorString("Failed to restore original opcode.");
1801 }
1802 }
1803 else
1804 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1805 }
1806 }
1807 else
1808 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1809 }
1810 }
1811 else
1812 {
1813 if (log)
1814 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1815 return error;
1816 }
1817
1818 if (log)
1819 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1820 bp_site->GetID(),
1821 (uint64_t)bp_addr,
1822 error.AsCString());
1823 return error;
1824
1825}
1826
Greg Clayton58be07b2011-01-07 06:08:19 +00001827// Comment out line below to disable memory caching
1828#define ENABLE_MEMORY_CACHING
1829// Uncomment to verify memory caching works after making changes to caching code
1830//#define VERIFY_MEMORY_READS
1831
1832#if defined (ENABLE_MEMORY_CACHING)
1833
1834#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001835
1836size_t
1837Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1838{
Greg Clayton58be07b2011-01-07 06:08:19 +00001839 // Memory caching is enabled, with debug verification
1840 if (buf && size)
1841 {
1842 // Uncomment the line below to make sure memory caching is working.
1843 // I ran this through the test suite and got no assertions, so I am
1844 // pretty confident this is working well. If any changes are made to
1845 // memory caching, uncomment the line below and test your changes!
1846
1847 // Verify all memory reads by using the cache first, then redundantly
1848 // reading the same memory from the inferior and comparing to make sure
1849 // everything is exactly the same.
1850 std::string verify_buf (size, '\0');
1851 assert (verify_buf.size() == size);
1852 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1853 Error verify_error;
1854 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1855 assert (cache_bytes_read == verify_bytes_read);
1856 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1857 assert (verify_error.Success() == error.Success());
1858 return cache_bytes_read;
1859 }
1860 return 0;
1861}
1862
1863#else // #if defined (VERIFY_MEMORY_READS)
1864
1865size_t
1866Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1867{
1868 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001869 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001870}
1871
1872#endif // #else for #if defined (VERIFY_MEMORY_READS)
1873
1874#else // #if defined (ENABLE_MEMORY_CACHING)
1875
1876size_t
1877Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1878{
1879 // Memory caching is disabled
1880 return ReadMemoryFromInferior (addr, buf, size, error);
1881}
1882
1883#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1884
1885
1886size_t
Greg Claytone91b7952011-12-15 03:14:23 +00001887Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00001888{
1889 size_t total_cstr_len = 0;
1890 if (dst && dst_max_len)
1891 {
Greg Claytone91b7952011-12-15 03:14:23 +00001892 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00001893 // NULL out everything just to be safe
1894 memset (dst, 0, dst_max_len);
1895 Error error;
1896 addr_t curr_addr = addr;
1897 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1898 size_t bytes_left = dst_max_len - 1;
1899 char *curr_dst = dst;
1900
1901 while (bytes_left > 0)
1902 {
1903 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1904 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1905 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1906
1907 if (bytes_read == 0)
1908 {
Greg Claytone91b7952011-12-15 03:14:23 +00001909 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001910 dst[total_cstr_len] = '\0';
1911 break;
1912 }
1913 const size_t len = strlen(curr_dst);
1914
1915 total_cstr_len += len;
1916
1917 if (len < bytes_to_read)
1918 break;
1919
1920 curr_dst += bytes_read;
1921 curr_addr += bytes_read;
1922 bytes_left -= bytes_read;
1923 }
1924 }
Greg Claytone91b7952011-12-15 03:14:23 +00001925 else
1926 {
1927 if (dst == NULL)
1928 result_error.SetErrorString("invalid arguments");
1929 else
1930 result_error.Clear();
1931 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001932 return total_cstr_len;
1933}
1934
1935size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00001936Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1937{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001938 if (buf == NULL || size == 0)
1939 return 0;
1940
1941 size_t bytes_read = 0;
1942 uint8_t *bytes = (uint8_t *)buf;
1943
1944 while (bytes_read < size)
1945 {
1946 const size_t curr_size = size - bytes_read;
1947 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1948 bytes + bytes_read,
1949 curr_size,
1950 error);
1951 bytes_read += curr_bytes_read;
1952 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1953 break;
1954 }
1955
1956 // Replace any software breakpoint opcodes that fall into this range back
1957 // into "buf" before we return
1958 if (bytes_read > 0)
1959 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1960 return bytes_read;
1961}
1962
Greg Clayton58a4c462010-12-16 20:01:20 +00001963uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001964Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00001965{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001966 Scalar scalar;
1967 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1968 return scalar.ULongLong(fail_value);
1969 return fail_value;
1970}
1971
1972addr_t
1973Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1974{
1975 Scalar scalar;
1976 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1977 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1978 return LLDB_INVALID_ADDRESS;
1979}
1980
1981
1982bool
1983Process::WritePointerToMemory (lldb::addr_t vm_addr,
1984 lldb::addr_t ptr_value,
1985 Error &error)
1986{
1987 Scalar scalar;
1988 const uint32_t addr_byte_size = GetAddressByteSize();
1989 if (addr_byte_size <= 4)
1990 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00001991 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001992 scalar = ptr_value;
1993 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00001994}
1995
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001996size_t
1997Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1998{
1999 size_t bytes_written = 0;
2000 const uint8_t *bytes = (const uint8_t *)buf;
2001
2002 while (bytes_written < size)
2003 {
2004 const size_t curr_size = size - bytes_written;
2005 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2006 bytes + bytes_written,
2007 curr_size,
2008 error);
2009 bytes_written += curr_bytes_written;
2010 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2011 break;
2012 }
2013 return bytes_written;
2014}
2015
2016size_t
2017Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2018{
Greg Clayton58be07b2011-01-07 06:08:19 +00002019#if defined (ENABLE_MEMORY_CACHING)
2020 m_memory_cache.Flush (addr, size);
2021#endif
2022
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002023 if (buf == NULL || size == 0)
2024 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002025
Jim Ingham4b536182011-08-09 02:12:22 +00002026 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002027
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002028 // We need to write any data that would go where any current software traps
2029 // (enabled software breakpoints) any software traps (breakpoints) that we
2030 // may have placed in our tasks memory.
2031
2032 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2033 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2034
2035 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002036 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002037
2038 BreakpointSiteList::collection::const_iterator pos;
2039 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002040 addr_t intersect_addr = 0;
2041 size_t intersect_size = 0;
2042 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002043 const uint8_t *ubuf = (const uint8_t *)buf;
2044
2045 for (pos = iter; pos != end; ++pos)
2046 {
2047 BreakpointSiteSP bp;
2048 bp = pos->second;
2049
2050 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2051 assert(addr <= intersect_addr && intersect_addr < addr + size);
2052 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2053 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2054
2055 // Check for bytes before this breakpoint
2056 const addr_t curr_addr = addr + bytes_written;
2057 if (intersect_addr > curr_addr)
2058 {
2059 // There are some bytes before this breakpoint that we need to
2060 // just write to memory
2061 size_t curr_size = intersect_addr - curr_addr;
2062 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2063 ubuf + bytes_written,
2064 curr_size,
2065 error);
2066 bytes_written += curr_bytes_written;
2067 if (curr_bytes_written != curr_size)
2068 {
2069 // We weren't able to write all of the requested bytes, we
2070 // are done looping and will return the number of bytes that
2071 // we have written so far.
2072 break;
2073 }
2074 }
2075
2076 // Now write any bytes that would cover up any software breakpoints
2077 // directly into the breakpoint opcode buffer
2078 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2079 bytes_written += intersect_size;
2080 }
2081
2082 // Write any remaining bytes after the last breakpoint if we have any left
2083 if (bytes_written < size)
2084 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2085 ubuf + bytes_written,
2086 size - bytes_written,
2087 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002088
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002089 return bytes_written;
2090}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002091
2092size_t
2093Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2094{
2095 if (byte_size == UINT32_MAX)
2096 byte_size = scalar.GetByteSize();
2097 if (byte_size > 0)
2098 {
2099 uint8_t buf[32];
2100 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2101 if (mem_size > 0)
2102 return WriteMemory(addr, buf, mem_size, error);
2103 else
2104 error.SetErrorString ("failed to get scalar as memory data");
2105 }
2106 else
2107 {
2108 error.SetErrorString ("invalid scalar value");
2109 }
2110 return 0;
2111}
2112
2113size_t
2114Process::ReadScalarIntegerFromMemory (addr_t addr,
2115 uint32_t byte_size,
2116 bool is_signed,
2117 Scalar &scalar,
2118 Error &error)
2119{
2120 uint64_t uval;
2121
2122 if (byte_size <= sizeof(uval))
2123 {
2124 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2125 if (bytes_read == byte_size)
2126 {
2127 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2128 uint32_t offset = 0;
2129 if (byte_size <= 4)
2130 scalar = data.GetMaxU32 (&offset, byte_size);
2131 else
2132 scalar = data.GetMaxU64 (&offset, byte_size);
2133
2134 if (is_signed)
2135 scalar.SignExtend(byte_size * 8);
2136 return bytes_read;
2137 }
2138 }
2139 else
2140 {
2141 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2142 }
2143 return 0;
2144}
2145
Greg Claytond495c532011-05-17 03:37:42 +00002146#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002147addr_t
2148Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2149{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002150 if (GetPrivateState() != eStateStopped)
2151 return LLDB_INVALID_ADDRESS;
2152
Greg Claytond495c532011-05-17 03:37:42 +00002153#if defined (USE_ALLOCATE_MEMORY_CACHE)
2154 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2155#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002156 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2157 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2158 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002159 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 +00002160 size,
Greg Claytond495c532011-05-17 03:37:42 +00002161 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002162 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002163 m_mod_id.GetStopID(),
2164 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002165 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002166#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002167}
2168
Sean Callanan90539452011-09-20 23:01:51 +00002169bool
2170Process::CanJIT ()
2171{
Sean Callanana7b443a2012-02-14 22:50:38 +00002172 if (m_can_jit == eCanJITDontKnow)
2173 {
2174 Error err;
2175
2176 uint64_t allocated_memory = AllocateMemory(8,
2177 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2178 err);
2179
2180 if (err.Success())
2181 m_can_jit = eCanJITYes;
2182 else
2183 m_can_jit = eCanJITNo;
2184
2185 DeallocateMemory (allocated_memory);
2186 }
2187
Sean Callanan90539452011-09-20 23:01:51 +00002188 return m_can_jit == eCanJITYes;
2189}
2190
2191void
2192Process::SetCanJIT (bool can_jit)
2193{
2194 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2195}
2196
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002197Error
2198Process::DeallocateMemory (addr_t ptr)
2199{
Greg Claytond495c532011-05-17 03:37:42 +00002200 Error error;
2201#if defined (USE_ALLOCATE_MEMORY_CACHE)
2202 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2203 {
2204 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2205 }
2206#else
2207 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002208
2209 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2210 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002211 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 +00002212 ptr,
2213 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002214 m_mod_id.GetStopID(),
2215 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002216#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002217 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002218}
2219
Greg Claytonc9660542012-02-05 02:38:54 +00002220ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002221Process::ReadModuleFromMemory (const FileSpec& file_spec,
2222 lldb::addr_t header_addr,
2223 bool add_image_to_target,
2224 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002225{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002226 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002227 if (module_sp)
2228 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002229 Error error;
2230 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2231 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002232 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002233 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002234 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002235 m_target.GetImages().Append(module_sp);
2236 if (load_sections_in_target)
2237 {
2238 bool changed = false;
2239 module_sp->SetLoadAddress (m_target, 0, changed);
2240 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002241 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002242 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002243 }
Greg Claytonc9660542012-02-05 02:38:54 +00002244 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002245 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002246}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002247
2248Error
Johnny Chen01a67862011-10-14 00:42:25 +00002249Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002250{
2251 Error error;
2252 error.SetErrorString("watchpoints are not supported");
2253 return error;
2254}
2255
2256Error
Johnny Chen01a67862011-10-14 00:42:25 +00002257Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002258{
2259 Error error;
2260 error.SetErrorString("watchpoints are not supported");
2261 return error;
2262}
2263
2264StateType
2265Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2266{
2267 StateType state;
2268 // Now wait for the process to launch and return control to us, and then
2269 // call DidLaunch:
2270 while (1)
2271 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002272 event_sp.reset();
2273 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2274
Greg Clayton2637f822011-11-17 01:23:07 +00002275 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002276 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002277
2278 // If state is invalid, then we timed out
2279 if (state == eStateInvalid)
2280 break;
2281
2282 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283 HandlePrivateEvent (event_sp);
2284 }
2285 return state;
2286}
2287
2288Error
Greg Clayton982c9762011-11-03 21:22:33 +00002289Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002290{
2291 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002293 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002294 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002295 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002296
Greg Claytonaa149cb2011-08-11 02:48:45 +00002297 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298 if (exe_module)
2299 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002300 char local_exec_file_path[PATH_MAX];
2301 char platform_exec_file_path[PATH_MAX];
2302 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2303 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002304 if (exe_module->GetFileSpec().Exists())
2305 {
Greg Clayton71337622011-02-24 22:24:29 +00002306 if (PrivateStateThreadIsValid ())
2307 PausePrivateStateThread ();
2308
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002309 error = WillLaunch (exe_module);
2310 if (error.Success())
2311 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002312 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002313 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002314
2315 // Now launch using these arguments.
Greg Clayton982c9762011-11-03 21:22:33 +00002316 error = DoLaunch (exe_module, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002317
2318 if (error.Fail())
2319 {
2320 if (GetID() != LLDB_INVALID_PROCESS_ID)
2321 {
2322 SetID (LLDB_INVALID_PROCESS_ID);
2323 const char *error_string = error.AsCString();
2324 if (error_string == NULL)
2325 error_string = "launch failed";
2326 SetExitStatus (-1, error_string);
2327 }
2328 }
2329 else
2330 {
2331 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002332 TimeValue timeout_time;
2333 timeout_time = TimeValue::Now();
2334 timeout_time.OffsetWithSeconds(10);
2335 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002336
Greg Clayton1a38ea72011-06-22 01:42:17 +00002337 if (state == eStateInvalid || event_sp.get() == NULL)
2338 {
2339 // We were able to launch the process, but we failed to
2340 // catch the initial stop.
2341 SetExitStatus (0, "failed to catch stop after launch");
2342 Destroy();
2343 }
2344 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002345 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002346
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002347 DidLaunch ();
2348
Greg Claytonc859e2d2012-02-13 23:10:39 +00002349 DynamicLoader *dyld = GetDynamicLoader ();
2350 if (dyld)
2351 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002352
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002353 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002354 // This delays passing the stopped event to listeners till DidLaunch gets
2355 // a chance to complete...
2356 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002357
2358 if (PrivateStateThreadIsValid ())
2359 ResumePrivateStateThread ();
2360 else
2361 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002362 }
2363 else if (state == eStateExited)
2364 {
2365 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2366 // not likely to work, and return an invalid pid.
2367 HandlePrivateEvent (event_sp);
2368 }
2369 }
2370 }
2371 }
2372 else
2373 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002374 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002375 }
2376 }
2377 return error;
2378}
2379
Greg Claytonc3776bf2012-02-09 06:16:32 +00002380
2381Error
2382Process::LoadCore ()
2383{
2384 Error error = DoLoadCore();
2385 if (error.Success())
2386 {
2387 if (PrivateStateThreadIsValid ())
2388 ResumePrivateStateThread ();
2389 else
2390 StartPrivateStateThread ();
2391
Greg Claytonc859e2d2012-02-13 23:10:39 +00002392 DynamicLoader *dyld = GetDynamicLoader ();
2393 if (dyld)
2394 dyld->DidAttach();
2395
2396 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002397 // We successfully loaded a core file, now pretend we stopped so we can
2398 // show all of the threads in the core file and explore the crashed
2399 // state.
2400 SetPrivateState (eStateStopped);
2401
2402 }
2403 return error;
2404}
2405
Greg Claytonc859e2d2012-02-13 23:10:39 +00002406DynamicLoader *
2407Process::GetDynamicLoader ()
2408{
2409 if (m_dyld_ap.get() == NULL)
2410 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2411 return m_dyld_ap.get();
2412}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002413
2414
Jim Inghambb3a2832011-01-29 01:49:25 +00002415Process::NextEventAction::EventActionResult
2416Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002417{
Jim Inghambb3a2832011-01-29 01:49:25 +00002418 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2419 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002420 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002421 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002422 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002423 return eEventActionRetry;
2424
2425 case eStateStopped:
2426 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002427 {
2428 // During attach, prior to sending the eStateStopped event,
2429 // lldb_private::Process subclasses must set the process must set
2430 // the new process ID.
2431 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2432 if (m_exec_count > 0)
2433 {
2434 --m_exec_count;
2435 m_process->Resume();
2436 return eEventActionRetry;
2437 }
2438 else
2439 {
2440 m_process->CompleteAttach ();
2441 return eEventActionSuccess;
2442 }
2443 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002444 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002445
Greg Clayton513c26c2011-01-29 07:10:55 +00002446 default:
2447 case eStateExited:
2448 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002449 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002450 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002451
2452 m_exit_string.assign ("No valid Process");
2453 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002454}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002455
Jim Inghambb3a2832011-01-29 01:49:25 +00002456Process::NextEventAction::EventActionResult
2457Process::AttachCompletionHandler::HandleBeingInterrupted()
2458{
2459 return eEventActionSuccess;
2460}
2461
2462const char *
2463Process::AttachCompletionHandler::GetExitString ()
2464{
2465 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002466}
2467
2468Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002469Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002470{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002471 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002472 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002473 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002474 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002475
Greg Clayton144f3a92011-11-15 03:53:30 +00002476 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002477 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002478 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002479 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002480 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002481
Greg Clayton144f3a92011-11-15 03:53:30 +00002482 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002483 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002484 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2485
2486 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002487 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002488 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2489 if (error.Success())
2490 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002491 m_should_detach = true;
2492
Greg Clayton144f3a92011-11-15 03:53:30 +00002493 SetPublicState (eStateAttaching);
Han Ming Ong84647042012-02-25 01:07:38 +00002494 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002495 if (error.Fail())
2496 {
2497 if (GetID() != LLDB_INVALID_PROCESS_ID)
2498 {
2499 SetID (LLDB_INVALID_PROCESS_ID);
2500 if (error.AsCString() == NULL)
2501 error.SetErrorString("attach failed");
2502
2503 SetExitStatus(-1, error.AsCString());
2504 }
2505 }
2506 else
2507 {
2508 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2509 StartPrivateStateThread();
2510 }
2511 return error;
2512 }
Greg Claytone996fd32011-03-08 22:40:15 +00002513 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002514 else
Greg Claytone996fd32011-03-08 22:40:15 +00002515 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002516 ProcessInstanceInfoList process_infos;
2517 PlatformSP platform_sp (m_target.GetPlatform ());
2518
2519 if (platform_sp)
2520 {
2521 ProcessInstanceInfoMatch match_info;
2522 match_info.GetProcessInfo() = attach_info;
2523 match_info.SetNameMatchType (eNameMatchEquals);
2524 platform_sp->FindProcesses (match_info, process_infos);
2525 const uint32_t num_matches = process_infos.GetSize();
2526 if (num_matches == 1)
2527 {
2528 attach_pid = process_infos.GetProcessIDAtIndex(0);
2529 // Fall through and attach using the above process ID
2530 }
2531 else
2532 {
2533 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2534 if (num_matches > 1)
2535 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2536 else
2537 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2538 }
2539 }
2540 else
2541 {
2542 error.SetErrorString ("invalid platform, can't find processes by name");
2543 return error;
2544 }
Greg Claytone996fd32011-03-08 22:40:15 +00002545 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002546 }
2547 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002548 {
2549 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002550 }
2551 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002552
2553 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002554 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002555 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002556 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002557 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002558 m_should_detach = true;
Greg Claytone996fd32011-03-08 22:40:15 +00002559 SetPublicState (eStateAttaching);
Greg Clayton144f3a92011-11-15 03:53:30 +00002560
Han Ming Ong84647042012-02-25 01:07:38 +00002561 error = DoAttachToProcessWithID (attach_pid, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002562 if (error.Success())
2563 {
2564
2565 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2566 StartPrivateStateThread();
2567 }
2568 else
Greg Claytone996fd32011-03-08 22:40:15 +00002569 {
2570 if (GetID() != LLDB_INVALID_PROCESS_ID)
2571 {
2572 SetID (LLDB_INVALID_PROCESS_ID);
2573 const char *error_string = error.AsCString();
2574 if (error_string == NULL)
2575 error_string = "attach failed";
2576
2577 SetExitStatus(-1, error_string);
2578 }
2579 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002580 }
2581 }
2582 return error;
2583}
2584
Greg Clayton144f3a92011-11-15 03:53:30 +00002585//Error
2586//Process::Attach (const char *process_name, bool wait_for_launch)
2587//{
2588// m_abi_sp.reset();
2589// m_process_input_reader.reset();
2590//
2591// // Find the process and its architecture. Make sure it matches the architecture
2592// // of the current Target, and if not adjust it.
2593// Error error;
2594//
2595// if (!wait_for_launch)
2596// {
2597// ProcessInstanceInfoList process_infos;
2598// PlatformSP platform_sp (m_target.GetPlatform ());
2599// assert (platform_sp.get());
2600//
2601// if (platform_sp)
2602// {
2603// ProcessInstanceInfoMatch match_info;
2604// match_info.GetProcessInfo().SetName(process_name);
2605// match_info.SetNameMatchType (eNameMatchEquals);
2606// platform_sp->FindProcesses (match_info, process_infos);
2607// if (process_infos.GetSize() > 1)
2608// {
2609// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2610// }
2611// else if (process_infos.GetSize() == 0)
2612// {
2613// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2614// }
2615// }
2616// else
2617// {
2618// error.SetErrorString ("invalid platform");
2619// }
2620// }
2621//
2622// if (error.Success())
2623// {
2624// m_dyld_ap.reset();
2625// m_os_ap.reset();
2626//
2627// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2628// if (error.Success())
2629// {
2630// SetPublicState (eStateAttaching);
2631// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2632// if (error.Fail())
2633// {
2634// if (GetID() != LLDB_INVALID_PROCESS_ID)
2635// {
2636// SetID (LLDB_INVALID_PROCESS_ID);
2637// const char *error_string = error.AsCString();
2638// if (error_string == NULL)
2639// error_string = "attach failed";
2640//
2641// SetExitStatus(-1, error_string);
2642// }
2643// }
2644// else
2645// {
2646// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2647// StartPrivateStateThread();
2648// }
2649// }
2650// }
2651// return error;
2652//}
2653
Greg Clayton93d3c8332011-02-16 04:46:07 +00002654void
2655Process::CompleteAttach ()
2656{
2657 // Let the process subclass figure out at much as it can about the process
2658 // before we go looking for a dynamic loader plug-in.
2659 DidAttach();
2660
Jim Ingham4299fdb2011-09-15 01:10:17 +00002661 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2662 // the same as the one we've already set, switch architectures.
2663 PlatformSP platform_sp (m_target.GetPlatform ());
2664 assert (platform_sp.get());
2665 if (platform_sp)
2666 {
2667 ProcessInstanceInfo process_info;
2668 platform_sp->GetProcessInfo (GetID(), process_info);
2669 const ArchSpec &process_arch = process_info.GetArchitecture();
2670 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2671 m_target.SetArchitecture (process_arch);
2672 }
2673
2674 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002675 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002676 DynamicLoader *dyld = GetDynamicLoader ();
2677 if (dyld)
2678 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002679
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002680 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002681 // Figure out which one is the executable, and set that in our target:
2682 ModuleList &modules = m_target.GetImages();
2683
2684 size_t num_modules = modules.GetSize();
2685 for (int i = 0; i < num_modules; i++)
2686 {
2687 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002688 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002689 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002690 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002691 m_target.SetExecutableModule (module_sp, false);
2692 break;
2693 }
2694 }
2695}
2696
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002697Error
Greg Claytonb766a732011-02-04 01:58:07 +00002698Process::ConnectRemote (const char *remote_url)
2699{
Greg Claytonb766a732011-02-04 01:58:07 +00002700 m_abi_sp.reset();
2701 m_process_input_reader.reset();
2702
2703 // Find the process and its architecture. Make sure it matches the architecture
2704 // of the current Target, and if not adjust it.
2705
2706 Error error (DoConnectRemote (remote_url));
2707 if (error.Success())
2708 {
Greg Clayton71337622011-02-24 22:24:29 +00002709 if (GetID() != LLDB_INVALID_PROCESS_ID)
2710 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002711 EventSP event_sp;
2712 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2713
2714 if (state == eStateStopped || state == eStateCrashed)
2715 {
2716 // If we attached and actually have a process on the other end, then
2717 // this ended up being the equivalent of an attach.
2718 CompleteAttach ();
2719
2720 // This delays passing the stopped event to listeners till
2721 // CompleteAttach gets a chance to complete...
2722 HandlePrivateEvent (event_sp);
2723
2724 }
Greg Clayton71337622011-02-24 22:24:29 +00002725 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002726
2727 if (PrivateStateThreadIsValid ())
2728 ResumePrivateStateThread ();
2729 else
2730 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002731 }
2732 return error;
2733}
2734
2735
2736Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002737Process::Resume ()
2738{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002739 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002740 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002741 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002742 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002743 StateAsCString(m_public_state.GetValue()),
2744 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002745
2746 Error error (WillResume());
2747 // Tell the process it is about to resume before the thread list
2748 if (error.Success())
2749 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002750 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002751 // can let all of our threads know that they are about to be
2752 // resumed. Threads will each be called with
2753 // Thread::WillResume(StateType) where StateType contains the state
2754 // that they are supposed to have when the process is resumed
2755 // (suspended/running/stepping). Threads should also check
2756 // their resume signal in lldb::Thread::GetResumeSignal()
2757 // to see if they are suppoed to start back up with a signal.
2758 if (m_thread_list.WillResume())
2759 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00002760 m_mod_id.BumpResumeID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002761 error = DoResume();
2762 if (error.Success())
2763 {
2764 DidResume();
2765 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00002766 if (log)
2767 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002768 }
2769 }
2770 else
2771 {
Jim Ingham444586b2011-01-24 06:34:17 +00002772 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002773 }
2774 }
Jim Ingham444586b2011-01-24 06:34:17 +00002775 else if (log)
2776 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002777 return error;
2778}
2779
2780Error
2781Process::Halt ()
2782{
Jim Inghambb3a2832011-01-29 01:49:25 +00002783 // Pause our private state thread so we can ensure no one else eats
2784 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002785 Listener halt_listener ("lldb.process.halt_listener");
2786 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002787
Jim Inghambb3a2832011-01-29 01:49:25 +00002788 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002789 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002790
Greg Clayton513c26c2011-01-29 07:10:55 +00002791 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002792 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002793
Greg Clayton513c26c2011-01-29 07:10:55 +00002794 bool caused_stop = false;
2795
2796 // Ask the process subclass to actually halt our process
2797 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002798 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002799 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002800 if (m_public_state.GetValue() == eStateAttaching)
2801 {
2802 SetExitStatus(SIGKILL, "Cancelled async attach.");
2803 Destroy ();
2804 }
2805 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002806 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002807 // If "caused_stop" is true, then DoHalt stopped the process. If
2808 // "caused_stop" is false, the process was already stopped.
2809 // If the DoHalt caused the process to stop, then we want to catch
2810 // this event and set the interrupted bool to true before we pass
2811 // this along so clients know that the process was interrupted by
2812 // a halt command.
2813 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002814 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002815 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002816 TimeValue timeout_time;
2817 timeout_time = TimeValue::Now();
2818 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002819 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2820 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002821
Jim Ingham0f16e732011-02-08 05:20:59 +00002822 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002823 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002824 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002825 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002826 }
2827 else
2828 {
Greg Clayton2637f822011-11-17 01:23:07 +00002829 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00002830 {
2831 // We caused the process to interrupt itself, so mark this
2832 // as such in the stop event so clients can tell an interrupted
2833 // process from a natural stop
2834 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2835 }
2836 else
2837 {
2838 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2839 if (log)
2840 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2841 error.SetErrorString ("Did not get stopped event after halt.");
2842 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002843 }
2844 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002845 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002846 }
2847 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002848 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002849 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002850 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002851
2852 // Post any event we might have consumed. If all goes well, we will have
2853 // stopped the process, intercepted the event and set the interrupted
2854 // bool in the event. Post it to the private event queue and that will end up
2855 // correctly setting the state.
2856 if (event_sp)
2857 m_private_state_broadcaster.BroadcastEvent(event_sp);
2858
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002859 return error;
2860}
2861
2862Error
2863Process::Detach ()
2864{
2865 Error error (WillDetach());
2866
2867 if (error.Success())
2868 {
2869 DisableAllBreakpointSites();
2870 error = DoDetach();
2871 if (error.Success())
2872 {
2873 DidDetach();
2874 StopPrivateStateThread();
2875 }
2876 }
2877 return error;
2878}
2879
2880Error
2881Process::Destroy ()
2882{
2883 Error error (WillDestroy());
2884 if (error.Success())
2885 {
2886 DisableAllBreakpointSites();
2887 error = DoDestroy();
2888 if (error.Success())
2889 {
2890 DidDestroy();
2891 StopPrivateStateThread();
2892 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002893 m_stdio_communication.StopReadThread();
2894 m_stdio_communication.Disconnect();
2895 if (m_process_input_reader && m_process_input_reader->IsActive())
2896 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2897 if (m_process_input_reader)
2898 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002899 }
2900 return error;
2901}
2902
2903Error
2904Process::Signal (int signal)
2905{
2906 Error error (WillSignal());
2907 if (error.Success())
2908 {
2909 error = DoSignal(signal);
2910 if (error.Success())
2911 DidSignal();
2912 }
2913 return error;
2914}
2915
Greg Clayton514487e2011-02-15 21:59:32 +00002916lldb::ByteOrder
2917Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002918{
Greg Clayton514487e2011-02-15 21:59:32 +00002919 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002920}
2921
2922uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002923Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002924{
Greg Clayton514487e2011-02-15 21:59:32 +00002925 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002926}
2927
Greg Clayton514487e2011-02-15 21:59:32 +00002928
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002929bool
2930Process::ShouldBroadcastEvent (Event *event_ptr)
2931{
2932 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2933 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002934 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002935
2936 switch (state)
2937 {
Greg Claytonb766a732011-02-04 01:58:07 +00002938 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002939 case eStateAttaching:
2940 case eStateLaunching:
2941 case eStateDetached:
2942 case eStateExited:
2943 case eStateUnloaded:
2944 // These events indicate changes in the state of the debugging session, always report them.
2945 return_value = true;
2946 break;
2947 case eStateInvalid:
2948 // We stopped for no apparent reason, don't report it.
2949 return_value = false;
2950 break;
2951 case eStateRunning:
2952 case eStateStepping:
2953 // If we've started the target running, we handle the cases where we
2954 // are already running and where there is a transition from stopped to
2955 // running differently.
2956 // running -> running: Automatically suppress extra running events
2957 // stopped -> running: Report except when there is one or more no votes
2958 // and no yes votes.
2959 SynchronouslyNotifyStateChanged (state);
2960 switch (m_public_state.GetValue())
2961 {
2962 case eStateRunning:
2963 case eStateStepping:
2964 // We always suppress multiple runnings with no PUBLIC stop in between.
2965 return_value = false;
2966 break;
2967 default:
2968 // TODO: make this work correctly. For now always report
2969 // run if we aren't running so we don't miss any runnning
2970 // events. If I run the lldb/test/thread/a.out file and
2971 // break at main.cpp:58, run and hit the breakpoints on
2972 // multiple threads, then somehow during the stepping over
2973 // of all breakpoints no run gets reported.
2974 return_value = true;
2975
2976 // This is a transition from stop to run.
2977 switch (m_thread_list.ShouldReportRun (event_ptr))
2978 {
2979 case eVoteYes:
2980 case eVoteNoOpinion:
2981 return_value = true;
2982 break;
2983 case eVoteNo:
2984 return_value = false;
2985 break;
2986 }
2987 break;
2988 }
2989 break;
2990 case eStateStopped:
2991 case eStateCrashed:
2992 case eStateSuspended:
2993 {
2994 // We've stopped. First see if we're going to restart the target.
2995 // If we are going to stop, then we always broadcast the event.
2996 // 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 +00002997 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002998 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003000 if (log)
3001 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003002 return true;
3003 }
3004 else
3005 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003006 RefreshStateAfterStop ();
3007
3008 if (m_thread_list.ShouldStop (event_ptr) == false)
3009 {
3010 switch (m_thread_list.ShouldReportStop (event_ptr))
3011 {
3012 case eVoteYes:
3013 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003014 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003015 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003016 case eVoteNo:
3017 return_value = false;
3018 break;
3019 }
3020
3021 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003022 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003023 Resume ();
3024 }
3025 else
3026 {
3027 return_value = true;
3028 SynchronouslyNotifyStateChanged (state);
3029 }
3030 }
3031 }
3032 }
3033
3034 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003035 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036 return return_value;
3037}
3038
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003039
3040bool
3041Process::StartPrivateStateThread ()
3042{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003043 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003044
Greg Clayton8b82f082011-04-12 05:54:46 +00003045 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003046 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003047 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3048
3049 if (already_running)
3050 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003051
3052 // Create a thread that watches our internal state and controls which
3053 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003054 char thread_name[1024];
Greg Clayton81c22f62011-10-19 18:09:39 +00003055 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Clayton3e06bd92011-01-09 21:07:35 +00003056 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00003057 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003058}
3059
3060void
3061Process::PausePrivateStateThread ()
3062{
3063 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3064}
3065
3066void
3067Process::ResumePrivateStateThread ()
3068{
3069 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3070}
3071
3072void
3073Process::StopPrivateStateThread ()
3074{
Greg Clayton8b82f082011-04-12 05:54:46 +00003075 if (PrivateStateThreadIsValid ())
3076 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003077}
3078
3079void
3080Process::ControlPrivateStateThread (uint32_t signal)
3081{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003082 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003083
3084 assert (signal == eBroadcastInternalStateControlStop ||
3085 signal == eBroadcastInternalStateControlPause ||
3086 signal == eBroadcastInternalStateControlResume);
3087
3088 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003089 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003090
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003091 // Signal the private state thread. First we should copy this is case the
3092 // thread starts exiting since the private state thread will NULL this out
3093 // when it exits
3094 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003095 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003096 {
3097 TimeValue timeout_time;
3098 bool timed_out;
3099
3100 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3101
3102 timeout_time = TimeValue::Now();
3103 timeout_time.OffsetWithSeconds(2);
3104 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3105 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3106
3107 if (signal == eBroadcastInternalStateControlStop)
3108 {
3109 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003110 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003111
3112 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003113 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003114 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115 }
3116 }
3117}
3118
3119void
3120Process::HandlePrivateEvent (EventSP &event_sp)
3121{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003122 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003123
Greg Clayton414f5d32011-01-25 02:58:48 +00003124 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003125
3126 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003127 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003128 {
Jim Ingham754ab982011-01-29 04:05:41 +00003129 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003130 switch (action_result)
3131 {
3132 case NextEventAction::eEventActionSuccess:
3133 SetNextEventAction(NULL);
3134 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003135
Jim Inghambb3a2832011-01-29 01:49:25 +00003136 case NextEventAction::eEventActionRetry:
3137 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003138
Jim Inghambb3a2832011-01-29 01:49:25 +00003139 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003140 // Handle Exiting Here. If we already got an exited event,
3141 // we should just propagate it. Otherwise, swallow this event,
3142 // and set our state to exit so the next event will kill us.
3143 if (new_state != eStateExited)
3144 {
3145 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003146 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003147 SetNextEventAction(NULL);
3148 return;
3149 }
3150 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003151 break;
3152 }
3153 }
3154
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003155 // See if we should broadcast this state to external clients?
3156 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003157
3158 if (should_broadcast)
3159 {
3160 if (log)
3161 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003162 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003163 __FUNCTION__,
3164 GetID(),
3165 StateAsCString(new_state),
3166 StateAsCString (GetState ()),
3167 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003168 }
Jim Ingham9575d842011-03-11 03:53:59 +00003169 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003170 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003171 PushProcessInputReader ();
3172 else
3173 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003174
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003175 BroadcastEvent (event_sp);
3176 }
3177 else
3178 {
3179 if (log)
3180 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003181 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003182 __FUNCTION__,
3183 GetID(),
3184 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003185 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003186 }
3187 }
3188}
3189
3190void *
3191Process::PrivateStateThread (void *arg)
3192{
3193 Process *proc = static_cast<Process*> (arg);
3194 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003195 return result;
3196}
3197
3198void *
3199Process::RunPrivateStateThread ()
3200{
3201 bool control_only = false;
3202 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3203
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003204 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003205 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003206 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003207
3208 bool exit_now = false;
3209 while (!exit_now)
3210 {
3211 EventSP event_sp;
3212 WaitForEventsPrivate (NULL, event_sp, control_only);
3213 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3214 {
3215 switch (event_sp->GetType())
3216 {
3217 case eBroadcastInternalStateControlStop:
3218 exit_now = true;
3219 continue; // Go to next loop iteration so we exit without
3220 break; // doing any internal state managment below
3221
3222 case eBroadcastInternalStateControlPause:
3223 control_only = true;
3224 break;
3225
3226 case eBroadcastInternalStateControlResume:
3227 control_only = false;
3228 break;
3229 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003230
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003231 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003232 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 +00003233
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003234 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003235 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003236 }
3237
3238
3239 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3240
3241 if (internal_state != eStateInvalid)
3242 {
3243 HandlePrivateEvent (event_sp);
3244 }
3245
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003246 if (internal_state == eStateInvalid ||
3247 internal_state == eStateExited ||
3248 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003249 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003250 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003251 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 +00003252
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003253 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003254 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003255 }
3256
Caroline Tice20ad3c42010-10-29 21:48:37 +00003257 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003258 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003259 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003260
Greg Clayton6ed95942011-01-22 07:12:45 +00003261 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3262 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003263 return NULL;
3264}
3265
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003266//------------------------------------------------------------------
3267// Process Event Data
3268//------------------------------------------------------------------
3269
3270Process::ProcessEventData::ProcessEventData () :
3271 EventData (),
3272 m_process_sp (),
3273 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003274 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003275 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003276 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003277{
3278}
3279
3280Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3281 EventData (),
3282 m_process_sp (process_sp),
3283 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003284 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003285 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003286 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287{
3288}
3289
3290Process::ProcessEventData::~ProcessEventData()
3291{
3292}
3293
3294const ConstString &
3295Process::ProcessEventData::GetFlavorString ()
3296{
3297 static ConstString g_flavor ("Process::ProcessEventData");
3298 return g_flavor;
3299}
3300
3301const ConstString &
3302Process::ProcessEventData::GetFlavor () const
3303{
3304 return ProcessEventData::GetFlavorString ();
3305}
3306
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003307void
3308Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3309{
3310 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003311 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3312 // the public event queue, then other times when we're pretending that this is where we stopped at the
3313 // end of expression evaluation. m_update_state is used to distinguish these
3314 // three cases; it is 0 when we're just pulling it off for private handling,
3315 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003316
Jim Inghama8604692011-05-22 21:45:01 +00003317 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003318 return;
3319
3320 m_process_sp->SetPublicState (m_state);
3321
3322 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3323 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003324 {
3325 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003326 uint32_t num_threads = curr_thread_list.GetSize();
3327 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003328
Jim Ingham4b536182011-08-09 02:12:22 +00003329 // The actions might change one of the thread's stop_info's opinions about whether we should
3330 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003331
3332 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3333 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3334 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3335 // 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
3336 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003337 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003338 for (idx = 0; idx < num_threads; ++idx)
3339 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3340
Jim Ingham4b536182011-08-09 02:12:22 +00003341 bool still_should_stop = true;
3342
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003343 for (idx = 0; idx < num_threads; ++idx)
3344 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003345 curr_thread_list = m_process_sp->GetThreadList();
3346 if (curr_thread_list.GetSize() != num_threads)
3347 {
3348 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003349 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003350 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 +00003351 break;
3352 }
3353
3354 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3355
3356 if (thread_sp->GetIndexID() != thread_index_array[idx])
3357 {
3358 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003359 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003360 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003361 idx,
3362 thread_index_array[idx],
3363 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003364 break;
3365 }
3366
Jim Inghamb15bfc72010-10-20 00:39:53 +00003367 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3368 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003369 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003370 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003371 // The stop action might restart the target. If it does, then we want to mark that in the
3372 // event so that whoever is receiving it will know to wait for the running event and reflect
3373 // that state appropriately.
3374 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003375
3376 // FIXME: we might have run.
3377 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003378 {
3379 SetRestarted (true);
3380 break;
3381 }
3382 else if (!stop_info_sp->ShouldStop(event_ptr))
3383 {
3384 still_should_stop = false;
3385 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003386 }
3387 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003388
Jim Ingham4b536182011-08-09 02:12:22 +00003389
3390 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003391 {
Jim Ingham4b536182011-08-09 02:12:22 +00003392 if (!still_should_stop)
3393 {
3394 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003395 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003396 m_process_sp->Resume();
3397 }
3398 else
3399 {
3400 // If we didn't restart, run the Stop Hooks here:
3401 // They might also restart the target, so watch for that.
3402 m_process_sp->GetTarget().RunStopHooks();
3403 if (m_process_sp->GetPrivateState() == eStateRunning)
3404 SetRestarted(true);
3405 }
Jim Ingham9575d842011-03-11 03:53:59 +00003406 }
3407
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003408 }
3409}
3410
3411void
3412Process::ProcessEventData::Dump (Stream *s) const
3413{
3414 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003415 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003416
Greg Clayton8b82f082011-04-12 05:54:46 +00003417 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003418}
3419
3420const Process::ProcessEventData *
3421Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3422{
3423 if (event_ptr)
3424 {
3425 const EventData *event_data = event_ptr->GetData();
3426 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3427 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3428 }
3429 return NULL;
3430}
3431
3432ProcessSP
3433Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3434{
3435 ProcessSP process_sp;
3436 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3437 if (data)
3438 process_sp = data->GetProcessSP();
3439 return process_sp;
3440}
3441
3442StateType
3443Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3444{
3445 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3446 if (data == NULL)
3447 return eStateInvalid;
3448 else
3449 return data->GetState();
3450}
3451
3452bool
3453Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3454{
3455 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3456 if (data == NULL)
3457 return false;
3458 else
3459 return data->GetRestarted();
3460}
3461
3462void
3463Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3464{
3465 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3466 if (data != NULL)
3467 data->SetRestarted(new_value);
3468}
3469
3470bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003471Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3472{
3473 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3474 if (data == NULL)
3475 return false;
3476 else
3477 return data->GetInterrupted ();
3478}
3479
3480void
3481Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3482{
3483 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3484 if (data != NULL)
3485 data->SetInterrupted(new_value);
3486}
3487
3488bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003489Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3490{
3491 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3492 if (data)
3493 {
3494 data->SetUpdateStateOnRemoval();
3495 return true;
3496 }
3497 return false;
3498}
3499
Greg Claytond9e416c2012-02-18 05:35:26 +00003500lldb::TargetSP
3501Process::CalculateTarget ()
3502{
3503 return m_target.shared_from_this();
3504}
3505
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003506void
Greg Clayton0603aa92010-10-04 01:05:56 +00003507Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003508{
Greg Claytonc14ee322011-09-22 04:58:26 +00003509 exe_ctx.SetTargetPtr (&m_target);
3510 exe_ctx.SetProcessPtr (this);
3511 exe_ctx.SetThreadPtr(NULL);
3512 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003513}
3514
Greg Claytone996fd32011-03-08 22:40:15 +00003515//uint32_t
3516//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3517//{
3518// return 0;
3519//}
3520//
3521//ArchSpec
3522//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3523//{
3524// return Host::GetArchSpecForExistingProcess (pid);
3525//}
3526//
3527//ArchSpec
3528//Process::GetArchSpecForExistingProcess (const char *process_name)
3529//{
3530// return Host::GetArchSpecForExistingProcess (process_name);
3531//}
3532//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003533void
3534Process::AppendSTDOUT (const char * s, size_t len)
3535{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003536 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003537 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003538 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003539}
3540
3541void
Greg Clayton93e86192011-11-13 04:45:22 +00003542Process::AppendSTDERR (const char * s, size_t len)
3543{
3544 Mutex::Locker locker (m_stdio_communication_mutex);
3545 m_stderr_data.append (s, len);
3546 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3547}
3548
3549//------------------------------------------------------------------
3550// Process STDIO
3551//------------------------------------------------------------------
3552
3553size_t
3554Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3555{
3556 Mutex::Locker locker(m_stdio_communication_mutex);
3557 size_t bytes_available = m_stdout_data.size();
3558 if (bytes_available > 0)
3559 {
3560 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3561 if (log)
3562 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3563 if (bytes_available > buf_size)
3564 {
3565 memcpy(buf, m_stdout_data.c_str(), buf_size);
3566 m_stdout_data.erase(0, buf_size);
3567 bytes_available = buf_size;
3568 }
3569 else
3570 {
3571 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3572 m_stdout_data.clear();
3573 }
3574 }
3575 return bytes_available;
3576}
3577
3578
3579size_t
3580Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3581{
3582 Mutex::Locker locker(m_stdio_communication_mutex);
3583 size_t bytes_available = m_stderr_data.size();
3584 if (bytes_available > 0)
3585 {
3586 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3587 if (log)
3588 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3589 if (bytes_available > buf_size)
3590 {
3591 memcpy(buf, m_stderr_data.c_str(), buf_size);
3592 m_stderr_data.erase(0, buf_size);
3593 bytes_available = buf_size;
3594 }
3595 else
3596 {
3597 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3598 m_stderr_data.clear();
3599 }
3600 }
3601 return bytes_available;
3602}
3603
3604void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003605Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3606{
3607 Process *process = (Process *) baton;
3608 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3609}
3610
3611size_t
3612Process::ProcessInputReaderCallback (void *baton,
3613 InputReader &reader,
3614 lldb::InputReaderAction notification,
3615 const char *bytes,
3616 size_t bytes_len)
3617{
3618 Process *process = (Process *) baton;
3619
3620 switch (notification)
3621 {
3622 case eInputReaderActivate:
3623 break;
3624
3625 case eInputReaderDeactivate:
3626 break;
3627
3628 case eInputReaderReactivate:
3629 break;
3630
Caroline Tice969ed3d2011-05-02 20:41:46 +00003631 case eInputReaderAsynchronousOutputWritten:
3632 break;
3633
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003634 case eInputReaderGotToken:
3635 {
3636 Error error;
3637 process->PutSTDIN (bytes, bytes_len, error);
3638 }
3639 break;
3640
Caroline Ticeefed6132010-11-19 20:47:54 +00003641 case eInputReaderInterrupt:
3642 process->Halt ();
3643 break;
3644
3645 case eInputReaderEndOfFile:
3646 process->AppendSTDOUT ("^D", 2);
3647 break;
3648
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003649 case eInputReaderDone:
3650 break;
3651
3652 }
3653
3654 return bytes_len;
3655}
3656
3657void
3658Process::ResetProcessInputReader ()
3659{
3660 m_process_input_reader.reset();
3661}
3662
3663void
Greg Claytonee95ed52011-11-17 22:14:31 +00003664Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003665{
3666 // First set up the Read Thread for reading/handling process I/O
3667
3668 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3669
3670 if (conn_ap.get())
3671 {
3672 m_stdio_communication.SetConnection (conn_ap.release());
3673 if (m_stdio_communication.IsConnected())
3674 {
3675 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3676 m_stdio_communication.StartReadThread();
3677
3678 // Now read thread is set up, set up input reader.
3679
3680 if (!m_process_input_reader.get())
3681 {
3682 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3683 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3684 this,
3685 eInputReaderGranularityByte,
3686 NULL,
3687 NULL,
3688 false));
3689
3690 if (err.Fail())
3691 m_process_input_reader.reset();
3692 }
3693 }
3694 }
3695}
3696
3697void
3698Process::PushProcessInputReader ()
3699{
3700 if (m_process_input_reader && !m_process_input_reader->IsActive())
3701 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3702}
3703
3704void
3705Process::PopProcessInputReader ()
3706{
3707 if (m_process_input_reader && m_process_input_reader->IsActive())
3708 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3709}
3710
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003711// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003712void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003713Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003714{
Greg Claytone0d378b2011-03-24 21:19:54 +00003715 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003716
3717 int i=0;
3718 const char *name;
3719 OptionEnumValueElement option_enum;
3720 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3721 {
3722 if (name)
3723 {
3724 option_enum.value = i;
3725 option_enum.string_value = name;
3726 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3727 g_plugins.push_back (option_enum);
3728 }
3729 ++i;
3730 }
3731 option_enum.value = 0;
3732 option_enum.string_value = NULL;
3733 option_enum.usage = NULL;
3734 g_plugins.push_back (option_enum);
3735
3736 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3737 {
3738 if (::strcmp (name, "plugin") == 0)
3739 {
3740 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3741 break;
3742 }
3743 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003744 UserSettingsControllerSP &usc = GetSettingsController();
3745 usc.reset (new SettingsController);
3746 UserSettingsController::InitializeSettingsController (usc,
3747 SettingsController::global_settings_table,
3748 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003749
3750 // Now call SettingsInitialize() for each 'child' of Process settings
3751 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003752}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003753
Greg Clayton99d0faf2010-11-18 23:32:35 +00003754void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003755Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003756{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003757 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3758
3759 Thread::SettingsTerminate ();
3760
3761 // Now terminate Process Settings.
3762
Greg Clayton99d0faf2010-11-18 23:32:35 +00003763 UserSettingsControllerSP &usc = GetSettingsController();
3764 UserSettingsController::FinalizeSettingsController (usc);
3765 usc.reset();
3766}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003767
Greg Clayton99d0faf2010-11-18 23:32:35 +00003768UserSettingsControllerSP &
3769Process::GetSettingsController ()
3770{
Greg Claytonb9556ac2012-01-30 07:41:31 +00003771 static UserSettingsControllerSP g_settings_controller_sp;
3772 if (!g_settings_controller_sp)
3773 {
3774 g_settings_controller_sp.reset (new Process::SettingsController);
3775 // The first shared pointer to Process::SettingsController in
3776 // g_settings_controller_sp must be fully created above so that
3777 // the TargetInstanceSettings can use a weak_ptr to refer back
3778 // to the master setttings controller
3779 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp,
3780 false,
3781 InstanceSettings::GetDefaultName().AsCString()));
3782 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
3783 }
3784 return g_settings_controller_sp;
3785
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003786}
3787
Caroline Tice1559a462010-09-27 00:30:10 +00003788void
3789Process::UpdateInstanceName ()
3790{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003791 Module *module = GetTarget().GetExecutableModulePointer();
Greg Claytone1cd1be2012-01-29 20:56:30 +00003792 if (module && module->GetFileSpec().GetFilename())
Caroline Tice1559a462010-09-27 00:30:10 +00003793 {
Greg Claytondbe54502010-11-19 03:46:01 +00003794 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytone1cd1be2012-01-29 20:56:30 +00003795 module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003796 }
3797}
3798
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003799ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003800Process::RunThreadPlan (ExecutionContext &exe_ctx,
3801 lldb::ThreadPlanSP &thread_plan_sp,
3802 bool stop_others,
3803 bool try_all_threads,
3804 bool discard_on_error,
3805 uint32_t single_thread_timeout_usec,
3806 Stream &errors)
3807{
3808 ExecutionResults return_value = eExecutionSetupError;
3809
Jim Ingham77787032011-01-20 02:03:18 +00003810 if (thread_plan_sp.get() == NULL)
3811 {
3812 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003813 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003814 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003815
3816 if (exe_ctx.GetProcessPtr() != this)
3817 {
3818 errors.Printf("RunThreadPlan called on wrong process.");
3819 return eExecutionSetupError;
3820 }
3821
3822 Thread *thread = exe_ctx.GetThreadPtr();
3823 if (thread == NULL)
3824 {
3825 errors.Printf("RunThreadPlan called with invalid thread.");
3826 return eExecutionSetupError;
3827 }
Jim Ingham77787032011-01-20 02:03:18 +00003828
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003829 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3830 // For that to be true the plan can't be private - since private plans suppress themselves in the
3831 // GetCompletedPlan call.
3832
3833 bool orig_plan_private = thread_plan_sp->GetPrivate();
3834 thread_plan_sp->SetPrivate(false);
3835
Jim Ingham444586b2011-01-24 06:34:17 +00003836 if (m_private_state.GetValue() != eStateStopped)
3837 {
3838 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003839 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003840 }
3841
Jim Ingham66243842011-08-13 00:56:10 +00003842 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00003843 const uint32_t thread_idx_id = thread->GetIndexID();
3844 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003845
3846 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3847 // so we should arrange to reset them as well.
3848
Greg Claytonc14ee322011-09-22 04:58:26 +00003849 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003850
Jim Ingham66243842011-08-13 00:56:10 +00003851 uint32_t selected_tid;
3852 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00003853 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00003854 {
3855 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003856 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003857 }
3858 else
3859 {
3860 selected_tid = LLDB_INVALID_THREAD_ID;
3861 }
3862
Greg Claytonc14ee322011-09-22 04:58:26 +00003863 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Inghamf48169b2010-11-30 02:22:11 +00003864
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003865 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003866
3867 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3868 // restored on exit to the function.
3869
3870 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003871
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003872 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003873 if (log)
3874 {
3875 StreamString s;
3876 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton81c22f62011-10-19 18:09:39 +00003877 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00003878 thread->GetIndexID(),
3879 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00003880 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003881 }
3882
Jim Ingham0f16e732011-02-08 05:20:59 +00003883 bool got_event;
3884 lldb::EventSP event_sp;
3885 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003886
3887 TimeValue* timeout_ptr = NULL;
3888 TimeValue real_timeout;
3889
Jim Ingham0f16e732011-02-08 05:20:59 +00003890 bool first_timeout = true;
3891 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003892
Jim Inghamf48169b2010-11-30 02:22:11 +00003893 while (1)
3894 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003895 // We usually want to resume the process if we get to the top of the loop.
3896 // The only exception is if we get two running events with no intervening
3897 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003898
Jim Ingham0f16e732011-02-08 05:20:59 +00003899 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003900 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003901 // Do the initial resume and wait for the running event before going further.
3902
Greg Claytonc14ee322011-09-22 04:58:26 +00003903 Error resume_error = Resume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00003904 if (!resume_error.Success())
3905 {
3906 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003907 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003908 break;
3909 }
3910
3911 real_timeout = TimeValue::Now();
3912 real_timeout.OffsetWithMicroSeconds(500000);
3913 timeout_ptr = &real_timeout;
3914
Sean Callananc1b312a2012-01-05 02:00:14 +00003915 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
Jim Ingham0f16e732011-02-08 05:20:59 +00003916 if (!got_event)
3917 {
3918 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003919 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003920
3921 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003922 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003923 break;
3924 }
3925
3926 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3927 if (stop_state != eStateRunning)
3928 {
3929 if (log)
3930 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3931
3932 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003933 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003934 break;
3935 }
3936
3937 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003938 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003939 // We need to call the function synchronously, so spin waiting for it to return.
3940 // If we get interrupted while executing, we're going to lose our context, and
3941 // won't be able to gather the result at this point.
3942 // We set the timeout AFTER the resume, since the resume takes some time and we
3943 // don't want to charge that to the timeout.
3944
3945 if (single_thread_timeout_usec != 0)
3946 {
3947 real_timeout = TimeValue::Now();
3948 if (first_timeout)
3949 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3950 else
3951 real_timeout.OffsetWithSeconds(10);
3952
3953 timeout_ptr = &real_timeout;
3954 }
3955 }
3956 else
3957 {
3958 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003959 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003960 do_resume = true;
3961 }
3962
3963 // Now wait for the process to stop again:
3964 stop_state = lldb::eStateInvalid;
3965 event_sp.reset();
3966 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3967
3968 if (got_event)
3969 {
3970 if (event_sp.get())
3971 {
3972 bool keep_going = false;
3973 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3974 if (log)
3975 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3976
3977 switch (stop_state)
3978 {
3979 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00003980 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003981 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00003982 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00003983 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00003984 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003985 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00003986 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00003987 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3988 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00003989 }
3990 else
3991 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003992 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3993 StopReason stop_reason = eStopReasonInvalid;
3994 if (stop_info_sp)
3995 stop_reason = stop_info_sp->GetStopReason();
3996 if (stop_reason == eStopReasonPlanComplete)
3997 {
3998 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003999 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004000 // Now mark this plan as private so it doesn't get reported as the stop reason
4001 // after this point.
4002 if (thread_plan_sp)
4003 thread_plan_sp->SetPrivate (orig_plan_private);
4004 return_value = eExecutionCompleted;
4005 }
4006 else
4007 {
4008 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004009 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004010
4011 return_value = eExecutionInterrupted;
4012 }
Jim Ingham160f78c2011-05-17 01:10:11 +00004013 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00004014 }
4015 break;
4016
Jim Ingham0f16e732011-02-08 05:20:59 +00004017 case lldb::eStateCrashed:
4018 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004019 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004020 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004021 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004022
Jim Ingham0f16e732011-02-08 05:20:59 +00004023 case lldb::eStateRunning:
4024 do_resume = false;
4025 keep_going = true;
4026 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004027
Jim Ingham0f16e732011-02-08 05:20:59 +00004028 default:
4029 if (log)
4030 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00004031
4032 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004033 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004034 break;
4035 }
4036 if (keep_going)
4037 continue;
4038 else
4039 break;
4040 }
4041 else
4042 {
4043 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004044 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00004045 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004046 break;
4047 }
4048 }
4049 else
4050 {
4051 // If we didn't get an event that means we've timed out...
4052 // We will interrupt the process here. Depending on what we were asked to do we will
4053 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00004054 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00004055
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004056 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00004057 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00004058 {
4059 if (first_timeout)
4060 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4061 "trying with all threads enabled.",
4062 single_thread_timeout_usec);
4063 else
4064 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4065 "and timeout: %d timed out.",
4066 single_thread_timeout_usec);
4067 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004068 else
Jim Ingham0f16e732011-02-08 05:20:59 +00004069 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4070 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00004071 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004072 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004073
Greg Claytonc14ee322011-09-22 04:58:26 +00004074 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00004075 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00004076 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004077 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004078 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004079
Jim Ingham0f16e732011-02-08 05:20:59 +00004080 // If halt succeeds, it always produces a stopped event. Wait for that:
4081
4082 real_timeout = TimeValue::Now();
4083 real_timeout.OffsetWithMicroSeconds(500000);
4084
4085 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004086
4087 if (got_event)
4088 {
4089 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4090 if (log)
4091 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004092 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00004093 if (stop_state == lldb::eStateStopped
4094 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00004095 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004096 }
4097
Jim Ingham0f16e732011-02-08 05:20:59 +00004098 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00004099 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004100 // Between the time we initiated the Halt and the time we delivered it, the process could have
4101 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00004102
Greg Claytonc14ee322011-09-22 04:58:26 +00004103 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004104 {
4105 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004106 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004107 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004108 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004109 break;
4110 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004111
Jim Ingham0f16e732011-02-08 05:20:59 +00004112 if (!try_all_threads)
4113 {
4114 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004115 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004116 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004117 break;
4118 }
4119
4120 if (first_timeout)
4121 {
4122 // Set all the other threads to run, and return to the top of the loop, which will continue;
4123 first_timeout = false;
4124 thread_plan_sp->SetStopOthers (false);
4125 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004126 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004127
4128 continue;
4129 }
4130 else
4131 {
4132 // Running all threads failed, so return Interrupted.
4133 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004134 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004135 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004136 break;
4137 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004138 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004139 }
4140 else
4141 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004142 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004143 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004144 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004145 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00004146 }
4147 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004148 else
4149 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004150 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4151 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00004152 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004153 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.",
4154 halt_error.AsCString());
4155 real_timeout = TimeValue::Now();
4156 real_timeout.OffsetWithMicroSeconds(500000);
4157 timeout_ptr = &real_timeout;
4158 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4159 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004160 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004161 // This is not going anywhere, bag out.
4162 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004163 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004164 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004165 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004166 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004167 else
4168 {
4169 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4170 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004171 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00004172 if (stop_state == lldb::eStateStopped)
4173 {
4174 // Between the time we initiated the Halt and the time we delivered it, the process could have
4175 // already finished its job. Check that here:
4176
Greg Claytonc14ee322011-09-22 04:58:26 +00004177 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004178 {
4179 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004180 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004181 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004182 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004183 break;
4184 }
4185
4186 if (first_timeout)
4187 {
4188 // Set all the other threads to run, and return to the top of the loop, which will continue;
4189 first_timeout = false;
4190 thread_plan_sp->SetStopOthers (false);
4191 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004192 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004193
4194 continue;
4195 }
4196 else
4197 {
4198 // Running all threads failed, so return Interrupted.
4199 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004200 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004201 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004202 break;
4203 }
4204 }
4205 else
4206 {
Sean Callanan39821ac2011-08-09 22:07:08 +00004207 if (log)
4208 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4209 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00004210 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004211 break;
4212 }
4213 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004214 }
4215
Jim Inghamf48169b2010-11-30 02:22:11 +00004216 }
4217
Jim Ingham0f16e732011-02-08 05:20:59 +00004218 } // END WAIT LOOP
4219
4220 // Now do some processing on the results of the run:
4221 if (return_value == eExecutionInterrupted)
4222 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004223 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004224 {
4225 StreamString s;
4226 if (event_sp)
4227 event_sp->Dump (&s);
4228 else
4229 {
Jim Ingham20829ac2011-08-09 22:24:33 +00004230 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004231 }
4232
4233 StreamString ts;
4234
Jim Ingham20829ac2011-08-09 22:24:33 +00004235 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00004236
4237 do
4238 {
4239 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4240
4241 if (!event_data)
4242 {
4243 event_explanation = "<no event data>";
4244 break;
4245 }
4246
4247 Process *process = event_data->GetProcessSP().get();
4248
4249 if (!process)
4250 {
4251 event_explanation = "<no process>";
4252 break;
4253 }
4254
4255 ThreadList &thread_list = process->GetThreadList();
4256
4257 uint32_t num_threads = thread_list.GetSize();
4258 uint32_t thread_index;
4259
4260 ts.Printf("<%u threads> ", num_threads);
4261
4262 for (thread_index = 0;
4263 thread_index < num_threads;
4264 ++thread_index)
4265 {
4266 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4267
4268 if (!thread)
4269 {
4270 ts.Printf("<?> ");
4271 continue;
4272 }
4273
Greg Clayton81c22f62011-10-19 18:09:39 +00004274 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Ingham0f16e732011-02-08 05:20:59 +00004275 RegisterContext *register_context = thread->GetRegisterContext().get();
4276
4277 if (register_context)
4278 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4279 else
4280 ts.Printf("[ip unknown] ");
4281
4282 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4283 if (stop_info_sp)
4284 {
4285 const char *stop_desc = stop_info_sp->GetDescription();
4286 if (stop_desc)
4287 ts.PutCString (stop_desc);
4288 }
4289 ts.Printf(">");
4290 }
4291
4292 event_explanation = ts.GetData();
4293 } while (0);
4294
4295 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004296 {
4297 if (event_explanation)
4298 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4299 else
4300 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4301 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004302
4303 if (discard_on_error && thread_plan_sp)
4304 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004305 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004306 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004307 }
4308 }
4309 }
4310 else if (return_value == eExecutionSetupError)
4311 {
4312 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004313 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004314
4315 if (discard_on_error && thread_plan_sp)
4316 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004317 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004318 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004319 }
4320 }
4321 else
4322 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004323 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004324 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004325 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004326 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00004327 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00004328 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004329 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004330 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004331 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004332 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00004333 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00004334 }
4335 else
4336 {
4337 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004338 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00004339 if (discard_on_error && thread_plan_sp)
4340 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004341 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004342 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00004343 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004344 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00004345 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004346 }
4347 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004348
Jim Inghamf48169b2010-11-30 02:22:11 +00004349 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00004350 // Check that it's still there, and if it is put it back in the context. Also restore the
4351 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00004352 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4353 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00004354 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004355 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00004356 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004357
4358 // Also restore the current process'es selected frame & thread, since this function calling may
4359 // be done behind the user's back.
4360
4361 if (selected_tid != LLDB_INVALID_THREAD_ID)
4362 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004363 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00004364 {
4365 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00004366 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00004367 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00004368 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004369 }
4370 }
4371
4372 return return_value;
4373}
4374
4375const char *
4376Process::ExecutionResultAsCString (ExecutionResults result)
4377{
4378 const char *result_name;
4379
4380 switch (result)
4381 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004382 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004383 result_name = "eExecutionCompleted";
4384 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004385 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004386 result_name = "eExecutionDiscarded";
4387 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004388 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004389 result_name = "eExecutionInterrupted";
4390 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004391 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004392 result_name = "eExecutionSetupError";
4393 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004394 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004395 result_name = "eExecutionTimedOut";
4396 break;
4397 }
4398 return result_name;
4399}
4400
Greg Clayton7260f622011-04-18 08:33:37 +00004401void
4402Process::GetStatus (Stream &strm)
4403{
4404 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00004405 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00004406 {
4407 if (state == eStateExited)
4408 {
4409 int exit_status = GetExitStatus();
4410 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004411 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004412 GetID(),
4413 exit_status,
4414 exit_status,
4415 exit_description ? exit_description : "");
4416 }
4417 else
4418 {
4419 if (state == eStateConnected)
4420 strm.Printf ("Connected to remote target.\n");
4421 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004422 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004423 }
4424 }
4425 else
4426 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004427 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004428 }
4429}
4430
4431size_t
4432Process::GetThreadStatus (Stream &strm,
4433 bool only_threads_with_stop_reason,
4434 uint32_t start_frame,
4435 uint32_t num_frames,
4436 uint32_t num_frames_with_source)
4437{
4438 size_t num_thread_infos_dumped = 0;
4439
4440 const size_t num_threads = GetThreadList().GetSize();
4441 for (uint32_t i = 0; i < num_threads; i++)
4442 {
4443 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4444 if (thread)
4445 {
4446 if (only_threads_with_stop_reason)
4447 {
4448 if (thread->GetStopInfo().get() == NULL)
4449 continue;
4450 }
4451 thread->GetStatus (strm,
4452 start_frame,
4453 num_frames,
4454 num_frames_with_source);
4455 ++num_thread_infos_dumped;
4456 }
4457 }
4458 return num_thread_infos_dumped;
4459}
4460
Greg Claytona9f40ad2012-02-22 04:37:26 +00004461void
4462Process::AddInvalidMemoryRegion (const LoadRange &region)
4463{
4464 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4465}
4466
4467bool
4468Process::RemoveInvalidMemoryRange (const LoadRange &region)
4469{
4470 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4471}
4472
4473
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004474//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004475// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004476//--------------------------------------------------------------
4477
Greg Clayton1b654882010-09-19 02:33:57 +00004478Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004479 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004480{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004481}
4482
Greg Clayton1b654882010-09-19 02:33:57 +00004483Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004484{
4485}
4486
4487lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004488Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004489{
Greg Claytonb9556ac2012-01-30 07:41:31 +00004490 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4491 false,
4492 instance_name));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004493 return new_settings_sp;
4494}
4495
4496//--------------------------------------------------------------
4497// class ProcessInstanceSettings
4498//--------------------------------------------------------------
4499
Greg Clayton85851dd2010-12-04 00:10:17 +00004500ProcessInstanceSettings::ProcessInstanceSettings
4501(
Greg Claytonb9556ac2012-01-30 07:41:31 +00004502 const UserSettingsControllerSP &owner_sp,
Greg Clayton85851dd2010-12-04 00:10:17 +00004503 bool live_instance,
4504 const char *name
4505) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004506 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004507{
Caroline Ticef20e8232010-09-09 18:26:37 +00004508 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4509 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4510 // 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 +00004511 // This is true for CreateInstanceName() too.
Greg Clayton1d885962011-11-08 02:43:13 +00004512
Caroline Tice9e41c152010-09-16 19:05:55 +00004513 if (GetInstanceName () == InstanceSettings::InvalidName())
4514 {
4515 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
Greg Claytonb9556ac2012-01-30 07:41:31 +00004516 owner_sp->RegisterInstanceSettings (this);
Caroline Tice9e41c152010-09-16 19:05:55 +00004517 }
Greg Clayton1d885962011-11-08 02:43:13 +00004518
Caroline Ticef20e8232010-09-09 18:26:37 +00004519 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004520 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004521 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004522 CopyInstanceSettings (pending_settings,false);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004523 }
4524}
4525
4526ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004527 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004528{
4529 if (m_instance_name != InstanceSettings::GetDefaultName())
4530 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004531 UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4532 if (owner_sp)
4533 {
4534 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4535 owner_sp->RemovePendingSettings (m_instance_name);
4536 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004537 }
4538}
4539
4540ProcessInstanceSettings::~ProcessInstanceSettings ()
4541{
4542}
4543
4544ProcessInstanceSettings&
4545ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4546{
4547 if (this != &rhs)
4548 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004549 }
4550
4551 return *this;
4552}
4553
4554
4555void
4556ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4557 const char *index_value,
4558 const char *value,
4559 const ConstString &instance_name,
4560 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004561 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004562 Error &err,
4563 bool pending)
4564{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004565}
4566
4567void
4568ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4569 bool pending)
4570{
Greg Clayton1d885962011-11-08 02:43:13 +00004571// if (new_settings.get() == NULL)
4572// return;
4573//
4574// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004575}
4576
Caroline Tice12cecd72010-09-20 21:37:42 +00004577bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004578ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4579 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004580 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004581 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004582{
Greg Clayton1d885962011-11-08 02:43:13 +00004583 if (err)
4584 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4585 return false;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004586}
4587
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004588const ConstString
4589ProcessInstanceSettings::CreateInstanceName ()
4590{
4591 static int instance_count = 1;
4592 StreamString sstr;
4593
4594 sstr.Printf ("process_%d", instance_count);
4595 ++instance_count;
4596
4597 const ConstString ret_val (sstr.GetData());
4598 return ret_val;
4599}
4600
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004601//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004602// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004603//--------------------------------------------------
4604
4605SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004606Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004607{
4608 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4609 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4610};
4611
4612
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004613SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004614Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004615{
Greg Clayton85851dd2010-12-04 00:10:17 +00004616 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton85851dd2010-12-04 00:10:17 +00004617 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004618};
4619
4620
Jim Ingham5aee1622010-08-09 23:31:02 +00004621
Greg Clayton1d885962011-11-08 02:43:13 +00004622