blob: f6c598b5e40f4383294a25a20ba78eff4e67dc01 [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 *
1465Process::GetLanguageRuntime(lldb::LanguageType language)
1466{
1467 LanguageRuntimeCollection::iterator pos;
1468 pos = m_language_runtimes.find (language);
1469 if (pos == m_language_runtimes.end())
1470 {
1471 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1472
1473 m_language_runtimes[language]
1474 = runtime;
1475 return runtime.get();
1476 }
1477 else
1478 return (*pos).second.get();
1479}
1480
1481CPPLanguageRuntime *
1482Process::GetCPPLanguageRuntime ()
1483{
1484 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1485 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1486 return static_cast<CPPLanguageRuntime *> (runtime);
1487 return NULL;
1488}
1489
1490ObjCLanguageRuntime *
1491Process::GetObjCLanguageRuntime ()
1492{
1493 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1494 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1495 return static_cast<ObjCLanguageRuntime *> (runtime);
1496 return NULL;
1497}
1498
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001499BreakpointSiteList &
1500Process::GetBreakpointSiteList()
1501{
1502 return m_breakpoint_site_list;
1503}
1504
1505const BreakpointSiteList &
1506Process::GetBreakpointSiteList() const
1507{
1508 return m_breakpoint_site_list;
1509}
1510
1511
1512void
1513Process::DisableAllBreakpointSites ()
1514{
1515 m_breakpoint_site_list.SetEnabledForAll (false);
1516}
1517
1518Error
1519Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1520{
1521 Error error (DisableBreakpointSiteByID (break_id));
1522
1523 if (error.Success())
1524 m_breakpoint_site_list.Remove(break_id);
1525
1526 return error;
1527}
1528
1529Error
1530Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1531{
1532 Error error;
1533 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1534 if (bp_site_sp)
1535 {
1536 if (bp_site_sp->IsEnabled())
1537 error = DisableBreakpoint (bp_site_sp.get());
1538 }
1539 else
1540 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001541 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001542 }
1543
1544 return error;
1545}
1546
1547Error
1548Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1549{
1550 Error error;
1551 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1552 if (bp_site_sp)
1553 {
1554 if (!bp_site_sp->IsEnabled())
1555 error = EnableBreakpoint (bp_site_sp.get());
1556 }
1557 else
1558 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001559 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001560 }
1561 return error;
1562}
1563
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001564lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001565Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001566{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001567 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001568 if (load_addr != LLDB_INVALID_ADDRESS)
1569 {
1570 BreakpointSiteSP bp_site_sp;
1571
1572 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1573 // create a new breakpoint site and add it.
1574
1575 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1576
1577 if (bp_site_sp)
1578 {
1579 bp_site_sp->AddOwner (owner);
1580 owner->SetBreakpointSite (bp_site_sp);
1581 return bp_site_sp->GetID();
1582 }
1583 else
1584 {
1585 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1586 if (bp_site_sp)
1587 {
1588 if (EnableBreakpoint (bp_site_sp.get()).Success())
1589 {
1590 owner->SetBreakpointSite (bp_site_sp);
1591 return m_breakpoint_site_list.Add (bp_site_sp);
1592 }
1593 }
1594 }
1595 }
1596 // We failed to enable the breakpoint
1597 return LLDB_INVALID_BREAK_ID;
1598
1599}
1600
1601void
1602Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1603{
1604 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1605 if (num_owners == 0)
1606 {
1607 DisableBreakpoint(bp_site_sp.get());
1608 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1609 }
1610}
1611
1612
1613size_t
1614Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1615{
1616 size_t bytes_removed = 0;
1617 addr_t intersect_addr;
1618 size_t intersect_size;
1619 size_t opcode_offset;
1620 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001621 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001622 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001623
Jim Ingham20c77192011-06-29 19:42:28 +00001624 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001625 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001626 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001627 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001628 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001629 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001630 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001631 {
1632 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1633 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001634 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001635 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001636 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001637 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001638 }
1639 }
1640 }
1641 return bytes_removed;
1642}
1643
1644
Greg Claytonded470d2011-03-19 01:12:21 +00001645
1646size_t
1647Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1648{
1649 PlatformSP platform_sp (m_target.GetPlatform());
1650 if (platform_sp)
1651 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1652 return 0;
1653}
1654
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001655Error
1656Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1657{
1658 Error error;
1659 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001660 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001661 const addr_t bp_addr = bp_site->GetLoadAddress();
1662 if (log)
1663 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1664 if (bp_site->IsEnabled())
1665 {
1666 if (log)
1667 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1668 return error;
1669 }
1670
1671 if (bp_addr == LLDB_INVALID_ADDRESS)
1672 {
1673 error.SetErrorString("BreakpointSite contains an invalid load address.");
1674 return error;
1675 }
1676 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1677 // trap for the breakpoint site
1678 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1679
1680 if (bp_opcode_size == 0)
1681 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001682 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001683 }
1684 else
1685 {
1686 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1687
1688 if (bp_opcode_bytes == NULL)
1689 {
1690 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1691 return error;
1692 }
1693
1694 // Save the original opcode by reading it
1695 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1696 {
1697 // Write a software breakpoint in place of the original opcode
1698 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1699 {
1700 uint8_t verify_bp_opcode_bytes[64];
1701 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1702 {
1703 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1704 {
1705 bp_site->SetEnabled(true);
1706 bp_site->SetType (BreakpointSite::eSoftware);
1707 if (log)
1708 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1709 bp_site->GetID(),
1710 (uint64_t)bp_addr);
1711 }
1712 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001713 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001714 }
1715 else
1716 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1717 }
1718 else
1719 error.SetErrorString("Unable to write breakpoint trap to memory.");
1720 }
1721 else
1722 error.SetErrorString("Unable to read memory at breakpoint address.");
1723 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001724 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001725 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1726 bp_site->GetID(),
1727 (uint64_t)bp_addr,
1728 error.AsCString());
1729 return error;
1730}
1731
1732Error
1733Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1734{
1735 Error error;
1736 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001737 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001738 addr_t bp_addr = bp_site->GetLoadAddress();
1739 lldb::user_id_t breakID = bp_site->GetID();
1740 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001741 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001742
1743 if (bp_site->IsHardware())
1744 {
1745 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1746 }
1747 else if (bp_site->IsEnabled())
1748 {
1749 const size_t break_op_size = bp_site->GetByteSize();
1750 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1751 if (break_op_size > 0)
1752 {
1753 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001754 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001755 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001756 bool break_op_found = false;
1757
1758 // Read the breakpoint opcode
1759 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1760 {
1761 bool verify = false;
1762 // Make sure we have the a breakpoint opcode exists at this address
1763 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1764 {
1765 break_op_found = true;
1766 // We found a valid breakpoint opcode at this address, now restore
1767 // the saved opcode.
1768 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1769 {
1770 verify = true;
1771 }
1772 else
1773 error.SetErrorString("Memory write failed when restoring original opcode.");
1774 }
1775 else
1776 {
1777 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1778 // Set verify to true and so we can check if the original opcode has already been restored
1779 verify = true;
1780 }
1781
1782 if (verify)
1783 {
Greg Claytonc982c762010-07-09 20:39:50 +00001784 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001785 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001786 // Verify that our original opcode made it back to the inferior
1787 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1788 {
1789 // compare the memory we just read with the original opcode
1790 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1791 {
1792 // SUCCESS
1793 bp_site->SetEnabled(false);
1794 if (log)
1795 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1796 return error;
1797 }
1798 else
1799 {
1800 if (break_op_found)
1801 error.SetErrorString("Failed to restore original opcode.");
1802 }
1803 }
1804 else
1805 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1806 }
1807 }
1808 else
1809 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1810 }
1811 }
1812 else
1813 {
1814 if (log)
1815 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1816 return error;
1817 }
1818
1819 if (log)
1820 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1821 bp_site->GetID(),
1822 (uint64_t)bp_addr,
1823 error.AsCString());
1824 return error;
1825
1826}
1827
Greg Clayton58be07b2011-01-07 06:08:19 +00001828// Comment out line below to disable memory caching
1829#define ENABLE_MEMORY_CACHING
1830// Uncomment to verify memory caching works after making changes to caching code
1831//#define VERIFY_MEMORY_READS
1832
1833#if defined (ENABLE_MEMORY_CACHING)
1834
1835#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001836
1837size_t
1838Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1839{
Greg Clayton58be07b2011-01-07 06:08:19 +00001840 // Memory caching is enabled, with debug verification
1841 if (buf && size)
1842 {
1843 // Uncomment the line below to make sure memory caching is working.
1844 // I ran this through the test suite and got no assertions, so I am
1845 // pretty confident this is working well. If any changes are made to
1846 // memory caching, uncomment the line below and test your changes!
1847
1848 // Verify all memory reads by using the cache first, then redundantly
1849 // reading the same memory from the inferior and comparing to make sure
1850 // everything is exactly the same.
1851 std::string verify_buf (size, '\0');
1852 assert (verify_buf.size() == size);
1853 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1854 Error verify_error;
1855 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1856 assert (cache_bytes_read == verify_bytes_read);
1857 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1858 assert (verify_error.Success() == error.Success());
1859 return cache_bytes_read;
1860 }
1861 return 0;
1862}
1863
1864#else // #if defined (VERIFY_MEMORY_READS)
1865
1866size_t
1867Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1868{
1869 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001870 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001871}
1872
1873#endif // #else for #if defined (VERIFY_MEMORY_READS)
1874
1875#else // #if defined (ENABLE_MEMORY_CACHING)
1876
1877size_t
1878Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1879{
1880 // Memory caching is disabled
1881 return ReadMemoryFromInferior (addr, buf, size, error);
1882}
1883
1884#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1885
1886
1887size_t
Greg Claytone91b7952011-12-15 03:14:23 +00001888Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00001889{
1890 size_t total_cstr_len = 0;
1891 if (dst && dst_max_len)
1892 {
Greg Claytone91b7952011-12-15 03:14:23 +00001893 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00001894 // NULL out everything just to be safe
1895 memset (dst, 0, dst_max_len);
1896 Error error;
1897 addr_t curr_addr = addr;
1898 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1899 size_t bytes_left = dst_max_len - 1;
1900 char *curr_dst = dst;
1901
1902 while (bytes_left > 0)
1903 {
1904 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1905 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1906 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1907
1908 if (bytes_read == 0)
1909 {
Greg Claytone91b7952011-12-15 03:14:23 +00001910 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001911 dst[total_cstr_len] = '\0';
1912 break;
1913 }
1914 const size_t len = strlen(curr_dst);
1915
1916 total_cstr_len += len;
1917
1918 if (len < bytes_to_read)
1919 break;
1920
1921 curr_dst += bytes_read;
1922 curr_addr += bytes_read;
1923 bytes_left -= bytes_read;
1924 }
1925 }
Greg Claytone91b7952011-12-15 03:14:23 +00001926 else
1927 {
1928 if (dst == NULL)
1929 result_error.SetErrorString("invalid arguments");
1930 else
1931 result_error.Clear();
1932 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001933 return total_cstr_len;
1934}
1935
1936size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00001937Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1938{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001939 if (buf == NULL || size == 0)
1940 return 0;
1941
1942 size_t bytes_read = 0;
1943 uint8_t *bytes = (uint8_t *)buf;
1944
1945 while (bytes_read < size)
1946 {
1947 const size_t curr_size = size - bytes_read;
1948 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1949 bytes + bytes_read,
1950 curr_size,
1951 error);
1952 bytes_read += curr_bytes_read;
1953 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1954 break;
1955 }
1956
1957 // Replace any software breakpoint opcodes that fall into this range back
1958 // into "buf" before we return
1959 if (bytes_read > 0)
1960 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1961 return bytes_read;
1962}
1963
Greg Clayton58a4c462010-12-16 20:01:20 +00001964uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001965Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00001966{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001967 Scalar scalar;
1968 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1969 return scalar.ULongLong(fail_value);
1970 return fail_value;
1971}
1972
1973addr_t
1974Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1975{
1976 Scalar scalar;
1977 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1978 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1979 return LLDB_INVALID_ADDRESS;
1980}
1981
1982
1983bool
1984Process::WritePointerToMemory (lldb::addr_t vm_addr,
1985 lldb::addr_t ptr_value,
1986 Error &error)
1987{
1988 Scalar scalar;
1989 const uint32_t addr_byte_size = GetAddressByteSize();
1990 if (addr_byte_size <= 4)
1991 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00001992 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001993 scalar = ptr_value;
1994 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00001995}
1996
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001997size_t
1998Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1999{
2000 size_t bytes_written = 0;
2001 const uint8_t *bytes = (const uint8_t *)buf;
2002
2003 while (bytes_written < size)
2004 {
2005 const size_t curr_size = size - bytes_written;
2006 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2007 bytes + bytes_written,
2008 curr_size,
2009 error);
2010 bytes_written += curr_bytes_written;
2011 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2012 break;
2013 }
2014 return bytes_written;
2015}
2016
2017size_t
2018Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2019{
Greg Clayton58be07b2011-01-07 06:08:19 +00002020#if defined (ENABLE_MEMORY_CACHING)
2021 m_memory_cache.Flush (addr, size);
2022#endif
2023
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002024 if (buf == NULL || size == 0)
2025 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002026
Jim Ingham4b536182011-08-09 02:12:22 +00002027 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002028
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002029 // We need to write any data that would go where any current software traps
2030 // (enabled software breakpoints) any software traps (breakpoints) that we
2031 // may have placed in our tasks memory.
2032
2033 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2034 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2035
2036 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002037 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002038
2039 BreakpointSiteList::collection::const_iterator pos;
2040 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002041 addr_t intersect_addr = 0;
2042 size_t intersect_size = 0;
2043 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002044 const uint8_t *ubuf = (const uint8_t *)buf;
2045
2046 for (pos = iter; pos != end; ++pos)
2047 {
2048 BreakpointSiteSP bp;
2049 bp = pos->second;
2050
2051 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2052 assert(addr <= intersect_addr && intersect_addr < addr + size);
2053 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2054 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2055
2056 // Check for bytes before this breakpoint
2057 const addr_t curr_addr = addr + bytes_written;
2058 if (intersect_addr > curr_addr)
2059 {
2060 // There are some bytes before this breakpoint that we need to
2061 // just write to memory
2062 size_t curr_size = intersect_addr - curr_addr;
2063 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2064 ubuf + bytes_written,
2065 curr_size,
2066 error);
2067 bytes_written += curr_bytes_written;
2068 if (curr_bytes_written != curr_size)
2069 {
2070 // We weren't able to write all of the requested bytes, we
2071 // are done looping and will return the number of bytes that
2072 // we have written so far.
2073 break;
2074 }
2075 }
2076
2077 // Now write any bytes that would cover up any software breakpoints
2078 // directly into the breakpoint opcode buffer
2079 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2080 bytes_written += intersect_size;
2081 }
2082
2083 // Write any remaining bytes after the last breakpoint if we have any left
2084 if (bytes_written < size)
2085 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2086 ubuf + bytes_written,
2087 size - bytes_written,
2088 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002089
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002090 return bytes_written;
2091}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002092
2093size_t
2094Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2095{
2096 if (byte_size == UINT32_MAX)
2097 byte_size = scalar.GetByteSize();
2098 if (byte_size > 0)
2099 {
2100 uint8_t buf[32];
2101 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2102 if (mem_size > 0)
2103 return WriteMemory(addr, buf, mem_size, error);
2104 else
2105 error.SetErrorString ("failed to get scalar as memory data");
2106 }
2107 else
2108 {
2109 error.SetErrorString ("invalid scalar value");
2110 }
2111 return 0;
2112}
2113
2114size_t
2115Process::ReadScalarIntegerFromMemory (addr_t addr,
2116 uint32_t byte_size,
2117 bool is_signed,
2118 Scalar &scalar,
2119 Error &error)
2120{
2121 uint64_t uval;
2122
2123 if (byte_size <= sizeof(uval))
2124 {
2125 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2126 if (bytes_read == byte_size)
2127 {
2128 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2129 uint32_t offset = 0;
2130 if (byte_size <= 4)
2131 scalar = data.GetMaxU32 (&offset, byte_size);
2132 else
2133 scalar = data.GetMaxU64 (&offset, byte_size);
2134
2135 if (is_signed)
2136 scalar.SignExtend(byte_size * 8);
2137 return bytes_read;
2138 }
2139 }
2140 else
2141 {
2142 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2143 }
2144 return 0;
2145}
2146
Greg Claytond495c532011-05-17 03:37:42 +00002147#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002148addr_t
2149Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2150{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002151 if (GetPrivateState() != eStateStopped)
2152 return LLDB_INVALID_ADDRESS;
2153
Greg Claytond495c532011-05-17 03:37:42 +00002154#if defined (USE_ALLOCATE_MEMORY_CACHE)
2155 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2156#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002157 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2158 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2159 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002160 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 +00002161 size,
Greg Claytond495c532011-05-17 03:37:42 +00002162 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002163 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002164 m_mod_id.GetStopID(),
2165 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002166 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002167#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002168}
2169
Sean Callanan90539452011-09-20 23:01:51 +00002170bool
2171Process::CanJIT ()
2172{
Sean Callanana7b443a2012-02-14 22:50:38 +00002173 if (m_can_jit == eCanJITDontKnow)
2174 {
2175 Error err;
2176
2177 uint64_t allocated_memory = AllocateMemory(8,
2178 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2179 err);
2180
2181 if (err.Success())
2182 m_can_jit = eCanJITYes;
2183 else
2184 m_can_jit = eCanJITNo;
2185
2186 DeallocateMemory (allocated_memory);
2187 }
2188
Sean Callanan90539452011-09-20 23:01:51 +00002189 return m_can_jit == eCanJITYes;
2190}
2191
2192void
2193Process::SetCanJIT (bool can_jit)
2194{
2195 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2196}
2197
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002198Error
2199Process::DeallocateMemory (addr_t ptr)
2200{
Greg Claytond495c532011-05-17 03:37:42 +00002201 Error error;
2202#if defined (USE_ALLOCATE_MEMORY_CACHE)
2203 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2204 {
2205 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2206 }
2207#else
2208 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002209
2210 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2211 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002212 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 +00002213 ptr,
2214 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002215 m_mod_id.GetStopID(),
2216 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002217#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002218 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002219}
2220
Greg Claytonc9660542012-02-05 02:38:54 +00002221ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002222Process::ReadModuleFromMemory (const FileSpec& file_spec,
2223 lldb::addr_t header_addr,
2224 bool add_image_to_target,
2225 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002226{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002227 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002228 if (module_sp)
2229 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002230 Error error;
2231 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2232 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002233 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002234 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002235 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002236 m_target.GetImages().Append(module_sp);
2237 if (load_sections_in_target)
2238 {
2239 bool changed = false;
2240 module_sp->SetLoadAddress (m_target, 0, changed);
2241 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002242 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002243 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002244 }
Greg Claytonc9660542012-02-05 02:38:54 +00002245 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002246 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002247}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002248
2249Error
Johnny Chen01a67862011-10-14 00:42:25 +00002250Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251{
2252 Error error;
2253 error.SetErrorString("watchpoints are not supported");
2254 return error;
2255}
2256
2257Error
Johnny Chen01a67862011-10-14 00:42:25 +00002258Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002259{
2260 Error error;
2261 error.SetErrorString("watchpoints are not supported");
2262 return error;
2263}
2264
2265StateType
2266Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2267{
2268 StateType state;
2269 // Now wait for the process to launch and return control to us, and then
2270 // call DidLaunch:
2271 while (1)
2272 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002273 event_sp.reset();
2274 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2275
Greg Clayton2637f822011-11-17 01:23:07 +00002276 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002277 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002278
2279 // If state is invalid, then we timed out
2280 if (state == eStateInvalid)
2281 break;
2282
2283 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002284 HandlePrivateEvent (event_sp);
2285 }
2286 return state;
2287}
2288
2289Error
Greg Clayton982c9762011-11-03 21:22:33 +00002290Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002291{
2292 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002293 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002294 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002295 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002296 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002297
Greg Claytonaa149cb2011-08-11 02:48:45 +00002298 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299 if (exe_module)
2300 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002301 char local_exec_file_path[PATH_MAX];
2302 char platform_exec_file_path[PATH_MAX];
2303 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2304 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002305 if (exe_module->GetFileSpec().Exists())
2306 {
Greg Clayton71337622011-02-24 22:24:29 +00002307 if (PrivateStateThreadIsValid ())
2308 PausePrivateStateThread ();
2309
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002310 error = WillLaunch (exe_module);
2311 if (error.Success())
2312 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002313 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002314 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002315
2316 // Now launch using these arguments.
Greg Clayton982c9762011-11-03 21:22:33 +00002317 error = DoLaunch (exe_module, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002318
2319 if (error.Fail())
2320 {
2321 if (GetID() != LLDB_INVALID_PROCESS_ID)
2322 {
2323 SetID (LLDB_INVALID_PROCESS_ID);
2324 const char *error_string = error.AsCString();
2325 if (error_string == NULL)
2326 error_string = "launch failed";
2327 SetExitStatus (-1, error_string);
2328 }
2329 }
2330 else
2331 {
2332 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002333 TimeValue timeout_time;
2334 timeout_time = TimeValue::Now();
2335 timeout_time.OffsetWithSeconds(10);
2336 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337
Greg Clayton1a38ea72011-06-22 01:42:17 +00002338 if (state == eStateInvalid || event_sp.get() == NULL)
2339 {
2340 // We were able to launch the process, but we failed to
2341 // catch the initial stop.
2342 SetExitStatus (0, "failed to catch stop after launch");
2343 Destroy();
2344 }
2345 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002346 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002347
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002348 DidLaunch ();
2349
Greg Claytonc859e2d2012-02-13 23:10:39 +00002350 DynamicLoader *dyld = GetDynamicLoader ();
2351 if (dyld)
2352 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002353
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002354 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002355 // This delays passing the stopped event to listeners till DidLaunch gets
2356 // a chance to complete...
2357 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002358
2359 if (PrivateStateThreadIsValid ())
2360 ResumePrivateStateThread ();
2361 else
2362 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002363 }
2364 else if (state == eStateExited)
2365 {
2366 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2367 // not likely to work, and return an invalid pid.
2368 HandlePrivateEvent (event_sp);
2369 }
2370 }
2371 }
2372 }
2373 else
2374 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002375 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376 }
2377 }
2378 return error;
2379}
2380
Greg Claytonc3776bf2012-02-09 06:16:32 +00002381
2382Error
2383Process::LoadCore ()
2384{
2385 Error error = DoLoadCore();
2386 if (error.Success())
2387 {
2388 if (PrivateStateThreadIsValid ())
2389 ResumePrivateStateThread ();
2390 else
2391 StartPrivateStateThread ();
2392
Greg Claytonc859e2d2012-02-13 23:10:39 +00002393 DynamicLoader *dyld = GetDynamicLoader ();
2394 if (dyld)
2395 dyld->DidAttach();
2396
2397 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002398 // We successfully loaded a core file, now pretend we stopped so we can
2399 // show all of the threads in the core file and explore the crashed
2400 // state.
2401 SetPrivateState (eStateStopped);
2402
2403 }
2404 return error;
2405}
2406
Greg Claytonc859e2d2012-02-13 23:10:39 +00002407DynamicLoader *
2408Process::GetDynamicLoader ()
2409{
2410 if (m_dyld_ap.get() == NULL)
2411 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2412 return m_dyld_ap.get();
2413}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002414
2415
Jim Inghambb3a2832011-01-29 01:49:25 +00002416Process::NextEventAction::EventActionResult
2417Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002418{
Jim Inghambb3a2832011-01-29 01:49:25 +00002419 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2420 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002421 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002422 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002423 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002424 return eEventActionRetry;
2425
2426 case eStateStopped:
2427 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002428 {
2429 // During attach, prior to sending the eStateStopped event,
2430 // lldb_private::Process subclasses must set the process must set
2431 // the new process ID.
2432 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2433 if (m_exec_count > 0)
2434 {
2435 --m_exec_count;
2436 m_process->Resume();
2437 return eEventActionRetry;
2438 }
2439 else
2440 {
2441 m_process->CompleteAttach ();
2442 return eEventActionSuccess;
2443 }
2444 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002445 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002446
Greg Clayton513c26c2011-01-29 07:10:55 +00002447 default:
2448 case eStateExited:
2449 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002450 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002451 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002452
2453 m_exit_string.assign ("No valid Process");
2454 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002455}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002456
Jim Inghambb3a2832011-01-29 01:49:25 +00002457Process::NextEventAction::EventActionResult
2458Process::AttachCompletionHandler::HandleBeingInterrupted()
2459{
2460 return eEventActionSuccess;
2461}
2462
2463const char *
2464Process::AttachCompletionHandler::GetExitString ()
2465{
2466 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002467}
2468
2469Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002470Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002471{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002472 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002473 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002474 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002475 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002476
Greg Clayton144f3a92011-11-15 03:53:30 +00002477 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002478 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002479 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002480 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002481 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002482
Greg Clayton144f3a92011-11-15 03:53:30 +00002483 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002484 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002485 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2486
2487 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002488 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002489 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2490 if (error.Success())
2491 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002492 m_should_detach = true;
2493
Greg Clayton144f3a92011-11-15 03:53:30 +00002494 SetPublicState (eStateAttaching);
Han Ming Ong84647042012-02-25 01:07:38 +00002495 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002496 if (error.Fail())
2497 {
2498 if (GetID() != LLDB_INVALID_PROCESS_ID)
2499 {
2500 SetID (LLDB_INVALID_PROCESS_ID);
2501 if (error.AsCString() == NULL)
2502 error.SetErrorString("attach failed");
2503
2504 SetExitStatus(-1, error.AsCString());
2505 }
2506 }
2507 else
2508 {
2509 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2510 StartPrivateStateThread();
2511 }
2512 return error;
2513 }
Greg Claytone996fd32011-03-08 22:40:15 +00002514 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002515 else
Greg Claytone996fd32011-03-08 22:40:15 +00002516 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002517 ProcessInstanceInfoList process_infos;
2518 PlatformSP platform_sp (m_target.GetPlatform ());
2519
2520 if (platform_sp)
2521 {
2522 ProcessInstanceInfoMatch match_info;
2523 match_info.GetProcessInfo() = attach_info;
2524 match_info.SetNameMatchType (eNameMatchEquals);
2525 platform_sp->FindProcesses (match_info, process_infos);
2526 const uint32_t num_matches = process_infos.GetSize();
2527 if (num_matches == 1)
2528 {
2529 attach_pid = process_infos.GetProcessIDAtIndex(0);
2530 // Fall through and attach using the above process ID
2531 }
2532 else
2533 {
2534 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2535 if (num_matches > 1)
2536 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2537 else
2538 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2539 }
2540 }
2541 else
2542 {
2543 error.SetErrorString ("invalid platform, can't find processes by name");
2544 return error;
2545 }
Greg Claytone996fd32011-03-08 22:40:15 +00002546 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002547 }
2548 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002549 {
2550 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002551 }
2552 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002553
2554 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002555 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002556 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002557 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002558 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002559 m_should_detach = true;
Greg Claytone996fd32011-03-08 22:40:15 +00002560 SetPublicState (eStateAttaching);
Greg Clayton144f3a92011-11-15 03:53:30 +00002561
Han Ming Ong84647042012-02-25 01:07:38 +00002562 error = DoAttachToProcessWithID (attach_pid, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002563 if (error.Success())
2564 {
2565
2566 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2567 StartPrivateStateThread();
2568 }
2569 else
Greg Claytone996fd32011-03-08 22:40:15 +00002570 {
2571 if (GetID() != LLDB_INVALID_PROCESS_ID)
2572 {
2573 SetID (LLDB_INVALID_PROCESS_ID);
2574 const char *error_string = error.AsCString();
2575 if (error_string == NULL)
2576 error_string = "attach failed";
2577
2578 SetExitStatus(-1, error_string);
2579 }
2580 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002581 }
2582 }
2583 return error;
2584}
2585
Greg Clayton144f3a92011-11-15 03:53:30 +00002586//Error
2587//Process::Attach (const char *process_name, bool wait_for_launch)
2588//{
2589// m_abi_sp.reset();
2590// m_process_input_reader.reset();
2591//
2592// // Find the process and its architecture. Make sure it matches the architecture
2593// // of the current Target, and if not adjust it.
2594// Error error;
2595//
2596// if (!wait_for_launch)
2597// {
2598// ProcessInstanceInfoList process_infos;
2599// PlatformSP platform_sp (m_target.GetPlatform ());
2600// assert (platform_sp.get());
2601//
2602// if (platform_sp)
2603// {
2604// ProcessInstanceInfoMatch match_info;
2605// match_info.GetProcessInfo().SetName(process_name);
2606// match_info.SetNameMatchType (eNameMatchEquals);
2607// platform_sp->FindProcesses (match_info, process_infos);
2608// if (process_infos.GetSize() > 1)
2609// {
2610// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2611// }
2612// else if (process_infos.GetSize() == 0)
2613// {
2614// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2615// }
2616// }
2617// else
2618// {
2619// error.SetErrorString ("invalid platform");
2620// }
2621// }
2622//
2623// if (error.Success())
2624// {
2625// m_dyld_ap.reset();
2626// m_os_ap.reset();
2627//
2628// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2629// if (error.Success())
2630// {
2631// SetPublicState (eStateAttaching);
2632// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2633// if (error.Fail())
2634// {
2635// if (GetID() != LLDB_INVALID_PROCESS_ID)
2636// {
2637// SetID (LLDB_INVALID_PROCESS_ID);
2638// const char *error_string = error.AsCString();
2639// if (error_string == NULL)
2640// error_string = "attach failed";
2641//
2642// SetExitStatus(-1, error_string);
2643// }
2644// }
2645// else
2646// {
2647// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2648// StartPrivateStateThread();
2649// }
2650// }
2651// }
2652// return error;
2653//}
2654
Greg Clayton93d3c8332011-02-16 04:46:07 +00002655void
2656Process::CompleteAttach ()
2657{
2658 // Let the process subclass figure out at much as it can about the process
2659 // before we go looking for a dynamic loader plug-in.
2660 DidAttach();
2661
Jim Ingham4299fdb2011-09-15 01:10:17 +00002662 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2663 // the same as the one we've already set, switch architectures.
2664 PlatformSP platform_sp (m_target.GetPlatform ());
2665 assert (platform_sp.get());
2666 if (platform_sp)
2667 {
2668 ProcessInstanceInfo process_info;
2669 platform_sp->GetProcessInfo (GetID(), process_info);
2670 const ArchSpec &process_arch = process_info.GetArchitecture();
2671 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2672 m_target.SetArchitecture (process_arch);
2673 }
2674
2675 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002676 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002677 DynamicLoader *dyld = GetDynamicLoader ();
2678 if (dyld)
2679 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002680
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002681 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002682 // Figure out which one is the executable, and set that in our target:
2683 ModuleList &modules = m_target.GetImages();
2684
2685 size_t num_modules = modules.GetSize();
2686 for (int i = 0; i < num_modules; i++)
2687 {
2688 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002689 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002690 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002691 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002692 m_target.SetExecutableModule (module_sp, false);
2693 break;
2694 }
2695 }
2696}
2697
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002698Error
Greg Claytonb766a732011-02-04 01:58:07 +00002699Process::ConnectRemote (const char *remote_url)
2700{
Greg Claytonb766a732011-02-04 01:58:07 +00002701 m_abi_sp.reset();
2702 m_process_input_reader.reset();
2703
2704 // Find the process and its architecture. Make sure it matches the architecture
2705 // of the current Target, and if not adjust it.
2706
2707 Error error (DoConnectRemote (remote_url));
2708 if (error.Success())
2709 {
Greg Clayton71337622011-02-24 22:24:29 +00002710 if (GetID() != LLDB_INVALID_PROCESS_ID)
2711 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002712 EventSP event_sp;
2713 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2714
2715 if (state == eStateStopped || state == eStateCrashed)
2716 {
2717 // If we attached and actually have a process on the other end, then
2718 // this ended up being the equivalent of an attach.
2719 CompleteAttach ();
2720
2721 // This delays passing the stopped event to listeners till
2722 // CompleteAttach gets a chance to complete...
2723 HandlePrivateEvent (event_sp);
2724
2725 }
Greg Clayton71337622011-02-24 22:24:29 +00002726 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002727
2728 if (PrivateStateThreadIsValid ())
2729 ResumePrivateStateThread ();
2730 else
2731 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002732 }
2733 return error;
2734}
2735
2736
2737Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738Process::Resume ()
2739{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002740 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002741 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002742 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002743 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002744 StateAsCString(m_public_state.GetValue()),
2745 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002746
2747 Error error (WillResume());
2748 // Tell the process it is about to resume before the thread list
2749 if (error.Success())
2750 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002751 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002752 // can let all of our threads know that they are about to be
2753 // resumed. Threads will each be called with
2754 // Thread::WillResume(StateType) where StateType contains the state
2755 // that they are supposed to have when the process is resumed
2756 // (suspended/running/stepping). Threads should also check
2757 // their resume signal in lldb::Thread::GetResumeSignal()
2758 // to see if they are suppoed to start back up with a signal.
2759 if (m_thread_list.WillResume())
2760 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00002761 m_mod_id.BumpResumeID();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762 error = DoResume();
2763 if (error.Success())
2764 {
2765 DidResume();
2766 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00002767 if (log)
2768 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002769 }
2770 }
2771 else
2772 {
Jim Ingham444586b2011-01-24 06:34:17 +00002773 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002774 }
2775 }
Jim Ingham444586b2011-01-24 06:34:17 +00002776 else if (log)
2777 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002778 return error;
2779}
2780
2781Error
2782Process::Halt ()
2783{
Jim Inghambb3a2832011-01-29 01:49:25 +00002784 // Pause our private state thread so we can ensure no one else eats
2785 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002786 Listener halt_listener ("lldb.process.halt_listener");
2787 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002788
Jim Inghambb3a2832011-01-29 01:49:25 +00002789 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002790 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002791
Greg Clayton513c26c2011-01-29 07:10:55 +00002792 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002793 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002794
Greg Clayton513c26c2011-01-29 07:10:55 +00002795 bool caused_stop = false;
2796
2797 // Ask the process subclass to actually halt our process
2798 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002799 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002800 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002801 if (m_public_state.GetValue() == eStateAttaching)
2802 {
2803 SetExitStatus(SIGKILL, "Cancelled async attach.");
2804 Destroy ();
2805 }
2806 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002807 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002808 // If "caused_stop" is true, then DoHalt stopped the process. If
2809 // "caused_stop" is false, the process was already stopped.
2810 // If the DoHalt caused the process to stop, then we want to catch
2811 // this event and set the interrupted bool to true before we pass
2812 // this along so clients know that the process was interrupted by
2813 // a halt command.
2814 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002815 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002816 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002817 TimeValue timeout_time;
2818 timeout_time = TimeValue::Now();
2819 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002820 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2821 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002822
Jim Ingham0f16e732011-02-08 05:20:59 +00002823 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002824 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002825 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002826 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002827 }
2828 else
2829 {
Greg Clayton2637f822011-11-17 01:23:07 +00002830 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00002831 {
2832 // We caused the process to interrupt itself, so mark this
2833 // as such in the stop event so clients can tell an interrupted
2834 // process from a natural stop
2835 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2836 }
2837 else
2838 {
2839 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2840 if (log)
2841 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2842 error.SetErrorString ("Did not get stopped event after halt.");
2843 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002844 }
2845 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002846 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002847 }
2848 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002849 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002850 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002851 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002852
2853 // Post any event we might have consumed. If all goes well, we will have
2854 // stopped the process, intercepted the event and set the interrupted
2855 // bool in the event. Post it to the private event queue and that will end up
2856 // correctly setting the state.
2857 if (event_sp)
2858 m_private_state_broadcaster.BroadcastEvent(event_sp);
2859
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002860 return error;
2861}
2862
2863Error
2864Process::Detach ()
2865{
2866 Error error (WillDetach());
2867
2868 if (error.Success())
2869 {
2870 DisableAllBreakpointSites();
2871 error = DoDetach();
2872 if (error.Success())
2873 {
2874 DidDetach();
2875 StopPrivateStateThread();
2876 }
2877 }
2878 return error;
2879}
2880
2881Error
2882Process::Destroy ()
2883{
2884 Error error (WillDestroy());
2885 if (error.Success())
2886 {
2887 DisableAllBreakpointSites();
2888 error = DoDestroy();
2889 if (error.Success())
2890 {
2891 DidDestroy();
2892 StopPrivateStateThread();
2893 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002894 m_stdio_communication.StopReadThread();
2895 m_stdio_communication.Disconnect();
2896 if (m_process_input_reader && m_process_input_reader->IsActive())
2897 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2898 if (m_process_input_reader)
2899 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002900 }
2901 return error;
2902}
2903
2904Error
2905Process::Signal (int signal)
2906{
2907 Error error (WillSignal());
2908 if (error.Success())
2909 {
2910 error = DoSignal(signal);
2911 if (error.Success())
2912 DidSignal();
2913 }
2914 return error;
2915}
2916
Greg Clayton514487e2011-02-15 21:59:32 +00002917lldb::ByteOrder
2918Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919{
Greg Clayton514487e2011-02-15 21:59:32 +00002920 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002921}
2922
2923uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002924Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002925{
Greg Clayton514487e2011-02-15 21:59:32 +00002926 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002927}
2928
Greg Clayton514487e2011-02-15 21:59:32 +00002929
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002930bool
2931Process::ShouldBroadcastEvent (Event *event_ptr)
2932{
2933 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2934 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002935 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002936
2937 switch (state)
2938 {
Greg Claytonb766a732011-02-04 01:58:07 +00002939 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002940 case eStateAttaching:
2941 case eStateLaunching:
2942 case eStateDetached:
2943 case eStateExited:
2944 case eStateUnloaded:
2945 // These events indicate changes in the state of the debugging session, always report them.
2946 return_value = true;
2947 break;
2948 case eStateInvalid:
2949 // We stopped for no apparent reason, don't report it.
2950 return_value = false;
2951 break;
2952 case eStateRunning:
2953 case eStateStepping:
2954 // If we've started the target running, we handle the cases where we
2955 // are already running and where there is a transition from stopped to
2956 // running differently.
2957 // running -> running: Automatically suppress extra running events
2958 // stopped -> running: Report except when there is one or more no votes
2959 // and no yes votes.
2960 SynchronouslyNotifyStateChanged (state);
2961 switch (m_public_state.GetValue())
2962 {
2963 case eStateRunning:
2964 case eStateStepping:
2965 // We always suppress multiple runnings with no PUBLIC stop in between.
2966 return_value = false;
2967 break;
2968 default:
2969 // TODO: make this work correctly. For now always report
2970 // run if we aren't running so we don't miss any runnning
2971 // events. If I run the lldb/test/thread/a.out file and
2972 // break at main.cpp:58, run and hit the breakpoints on
2973 // multiple threads, then somehow during the stepping over
2974 // of all breakpoints no run gets reported.
2975 return_value = true;
2976
2977 // This is a transition from stop to run.
2978 switch (m_thread_list.ShouldReportRun (event_ptr))
2979 {
2980 case eVoteYes:
2981 case eVoteNoOpinion:
2982 return_value = true;
2983 break;
2984 case eVoteNo:
2985 return_value = false;
2986 break;
2987 }
2988 break;
2989 }
2990 break;
2991 case eStateStopped:
2992 case eStateCrashed:
2993 case eStateSuspended:
2994 {
2995 // We've stopped. First see if we're going to restart the target.
2996 // If we are going to stop, then we always broadcast the event.
2997 // 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 +00002998 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002999 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003000 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003001 if (log)
3002 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003003 return true;
3004 }
3005 else
3006 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003007 RefreshStateAfterStop ();
3008
3009 if (m_thread_list.ShouldStop (event_ptr) == false)
3010 {
3011 switch (m_thread_list.ShouldReportStop (event_ptr))
3012 {
3013 case eVoteYes:
3014 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003015 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003016 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003017 case eVoteNo:
3018 return_value = false;
3019 break;
3020 }
3021
3022 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003023 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003024 Resume ();
3025 }
3026 else
3027 {
3028 return_value = true;
3029 SynchronouslyNotifyStateChanged (state);
3030 }
3031 }
3032 }
3033 }
3034
3035 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003036 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003037 return return_value;
3038}
3039
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003040
3041bool
3042Process::StartPrivateStateThread ()
3043{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003044 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045
Greg Clayton8b82f082011-04-12 05:54:46 +00003046 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003047 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003048 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3049
3050 if (already_running)
3051 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003052
3053 // Create a thread that watches our internal state and controls which
3054 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003055 char thread_name[1024];
Greg Clayton81c22f62011-10-19 18:09:39 +00003056 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Clayton3e06bd92011-01-09 21:07:35 +00003057 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00003058 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003059}
3060
3061void
3062Process::PausePrivateStateThread ()
3063{
3064 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3065}
3066
3067void
3068Process::ResumePrivateStateThread ()
3069{
3070 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3071}
3072
3073void
3074Process::StopPrivateStateThread ()
3075{
Greg Clayton8b82f082011-04-12 05:54:46 +00003076 if (PrivateStateThreadIsValid ())
3077 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003078}
3079
3080void
3081Process::ControlPrivateStateThread (uint32_t signal)
3082{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003083 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003084
3085 assert (signal == eBroadcastInternalStateControlStop ||
3086 signal == eBroadcastInternalStateControlPause ||
3087 signal == eBroadcastInternalStateControlResume);
3088
3089 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003090 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003091
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003092 // Signal the private state thread. First we should copy this is case the
3093 // thread starts exiting since the private state thread will NULL this out
3094 // when it exits
3095 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003096 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003097 {
3098 TimeValue timeout_time;
3099 bool timed_out;
3100
3101 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3102
3103 timeout_time = TimeValue::Now();
3104 timeout_time.OffsetWithSeconds(2);
3105 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3106 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3107
3108 if (signal == eBroadcastInternalStateControlStop)
3109 {
3110 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003111 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003112
3113 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003114 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003115 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003116 }
3117 }
3118}
3119
3120void
3121Process::HandlePrivateEvent (EventSP &event_sp)
3122{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003123 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003124
Greg Clayton414f5d32011-01-25 02:58:48 +00003125 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003126
3127 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003128 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003129 {
Jim Ingham754ab982011-01-29 04:05:41 +00003130 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003131 switch (action_result)
3132 {
3133 case NextEventAction::eEventActionSuccess:
3134 SetNextEventAction(NULL);
3135 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003136
Jim Inghambb3a2832011-01-29 01:49:25 +00003137 case NextEventAction::eEventActionRetry:
3138 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003139
Jim Inghambb3a2832011-01-29 01:49:25 +00003140 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003141 // Handle Exiting Here. If we already got an exited event,
3142 // we should just propagate it. Otherwise, swallow this event,
3143 // and set our state to exit so the next event will kill us.
3144 if (new_state != eStateExited)
3145 {
3146 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003147 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003148 SetNextEventAction(NULL);
3149 return;
3150 }
3151 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003152 break;
3153 }
3154 }
3155
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003156 // See if we should broadcast this state to external clients?
3157 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003158
3159 if (should_broadcast)
3160 {
3161 if (log)
3162 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003163 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003164 __FUNCTION__,
3165 GetID(),
3166 StateAsCString(new_state),
3167 StateAsCString (GetState ()),
3168 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003169 }
Jim Ingham9575d842011-03-11 03:53:59 +00003170 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003171 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003172 PushProcessInputReader ();
3173 else
3174 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003175
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003176 BroadcastEvent (event_sp);
3177 }
3178 else
3179 {
3180 if (log)
3181 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003182 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003183 __FUNCTION__,
3184 GetID(),
3185 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003186 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187 }
3188 }
3189}
3190
3191void *
3192Process::PrivateStateThread (void *arg)
3193{
3194 Process *proc = static_cast<Process*> (arg);
3195 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003196 return result;
3197}
3198
3199void *
3200Process::RunPrivateStateThread ()
3201{
3202 bool control_only = false;
3203 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3204
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003205 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003206 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003207 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003208
3209 bool exit_now = false;
3210 while (!exit_now)
3211 {
3212 EventSP event_sp;
3213 WaitForEventsPrivate (NULL, event_sp, control_only);
3214 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3215 {
3216 switch (event_sp->GetType())
3217 {
3218 case eBroadcastInternalStateControlStop:
3219 exit_now = true;
3220 continue; // Go to next loop iteration so we exit without
3221 break; // doing any internal state managment below
3222
3223 case eBroadcastInternalStateControlPause:
3224 control_only = true;
3225 break;
3226
3227 case eBroadcastInternalStateControlResume:
3228 control_only = false;
3229 break;
3230 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003231
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003232 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003233 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 +00003234
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003235 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003236 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003237 }
3238
3239
3240 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3241
3242 if (internal_state != eStateInvalid)
3243 {
3244 HandlePrivateEvent (event_sp);
3245 }
3246
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003247 if (internal_state == eStateInvalid ||
3248 internal_state == eStateExited ||
3249 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003250 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003251 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003252 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 +00003253
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003254 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003255 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003256 }
3257
Caroline Tice20ad3c42010-10-29 21:48:37 +00003258 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003259 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003260 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003261
Greg Clayton6ed95942011-01-22 07:12:45 +00003262 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3263 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003264 return NULL;
3265}
3266
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003267//------------------------------------------------------------------
3268// Process Event Data
3269//------------------------------------------------------------------
3270
3271Process::ProcessEventData::ProcessEventData () :
3272 EventData (),
3273 m_process_sp (),
3274 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003275 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003276 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003277 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003278{
3279}
3280
3281Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3282 EventData (),
3283 m_process_sp (process_sp),
3284 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003285 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003286 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003287 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003288{
3289}
3290
3291Process::ProcessEventData::~ProcessEventData()
3292{
3293}
3294
3295const ConstString &
3296Process::ProcessEventData::GetFlavorString ()
3297{
3298 static ConstString g_flavor ("Process::ProcessEventData");
3299 return g_flavor;
3300}
3301
3302const ConstString &
3303Process::ProcessEventData::GetFlavor () const
3304{
3305 return ProcessEventData::GetFlavorString ();
3306}
3307
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003308void
3309Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3310{
3311 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003312 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3313 // the public event queue, then other times when we're pretending that this is where we stopped at the
3314 // end of expression evaluation. m_update_state is used to distinguish these
3315 // three cases; it is 0 when we're just pulling it off for private handling,
3316 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003317
Jim Inghama8604692011-05-22 21:45:01 +00003318 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003319 return;
3320
3321 m_process_sp->SetPublicState (m_state);
3322
3323 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3324 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003325 {
3326 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003327 uint32_t num_threads = curr_thread_list.GetSize();
3328 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003329
Jim Ingham4b536182011-08-09 02:12:22 +00003330 // The actions might change one of the thread's stop_info's opinions about whether we should
3331 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003332
3333 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3334 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3335 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3336 // 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
3337 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003338 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003339 for (idx = 0; idx < num_threads; ++idx)
3340 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3341
Jim Ingham4b536182011-08-09 02:12:22 +00003342 bool still_should_stop = true;
3343
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003344 for (idx = 0; idx < num_threads; ++idx)
3345 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003346 curr_thread_list = m_process_sp->GetThreadList();
3347 if (curr_thread_list.GetSize() != num_threads)
3348 {
3349 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003350 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003351 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 +00003352 break;
3353 }
3354
3355 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3356
3357 if (thread_sp->GetIndexID() != thread_index_array[idx])
3358 {
3359 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003360 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003361 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003362 idx,
3363 thread_index_array[idx],
3364 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003365 break;
3366 }
3367
Jim Inghamb15bfc72010-10-20 00:39:53 +00003368 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3369 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003370 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003371 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003372 // The stop action might restart the target. If it does, then we want to mark that in the
3373 // event so that whoever is receiving it will know to wait for the running event and reflect
3374 // that state appropriately.
3375 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003376
3377 // FIXME: we might have run.
3378 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003379 {
3380 SetRestarted (true);
3381 break;
3382 }
3383 else if (!stop_info_sp->ShouldStop(event_ptr))
3384 {
3385 still_should_stop = false;
3386 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003387 }
3388 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003389
Jim Ingham4b536182011-08-09 02:12:22 +00003390
3391 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003392 {
Jim Ingham4b536182011-08-09 02:12:22 +00003393 if (!still_should_stop)
3394 {
3395 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003396 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003397 m_process_sp->Resume();
3398 }
3399 else
3400 {
3401 // If we didn't restart, run the Stop Hooks here:
3402 // They might also restart the target, so watch for that.
3403 m_process_sp->GetTarget().RunStopHooks();
3404 if (m_process_sp->GetPrivateState() == eStateRunning)
3405 SetRestarted(true);
3406 }
Jim Ingham9575d842011-03-11 03:53:59 +00003407 }
3408
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003409 }
3410}
3411
3412void
3413Process::ProcessEventData::Dump (Stream *s) const
3414{
3415 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003416 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003417
Greg Clayton8b82f082011-04-12 05:54:46 +00003418 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003419}
3420
3421const Process::ProcessEventData *
3422Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3423{
3424 if (event_ptr)
3425 {
3426 const EventData *event_data = event_ptr->GetData();
3427 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3428 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3429 }
3430 return NULL;
3431}
3432
3433ProcessSP
3434Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3435{
3436 ProcessSP process_sp;
3437 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3438 if (data)
3439 process_sp = data->GetProcessSP();
3440 return process_sp;
3441}
3442
3443StateType
3444Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3445{
3446 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3447 if (data == NULL)
3448 return eStateInvalid;
3449 else
3450 return data->GetState();
3451}
3452
3453bool
3454Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3455{
3456 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3457 if (data == NULL)
3458 return false;
3459 else
3460 return data->GetRestarted();
3461}
3462
3463void
3464Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3465{
3466 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3467 if (data != NULL)
3468 data->SetRestarted(new_value);
3469}
3470
3471bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003472Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3473{
3474 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3475 if (data == NULL)
3476 return false;
3477 else
3478 return data->GetInterrupted ();
3479}
3480
3481void
3482Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3483{
3484 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3485 if (data != NULL)
3486 data->SetInterrupted(new_value);
3487}
3488
3489bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003490Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3491{
3492 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3493 if (data)
3494 {
3495 data->SetUpdateStateOnRemoval();
3496 return true;
3497 }
3498 return false;
3499}
3500
Greg Claytond9e416c2012-02-18 05:35:26 +00003501lldb::TargetSP
3502Process::CalculateTarget ()
3503{
3504 return m_target.shared_from_this();
3505}
3506
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003507void
Greg Clayton0603aa92010-10-04 01:05:56 +00003508Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003509{
Greg Claytonc14ee322011-09-22 04:58:26 +00003510 exe_ctx.SetTargetPtr (&m_target);
3511 exe_ctx.SetProcessPtr (this);
3512 exe_ctx.SetThreadPtr(NULL);
3513 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003514}
3515
Greg Claytone996fd32011-03-08 22:40:15 +00003516//uint32_t
3517//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3518//{
3519// return 0;
3520//}
3521//
3522//ArchSpec
3523//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3524//{
3525// return Host::GetArchSpecForExistingProcess (pid);
3526//}
3527//
3528//ArchSpec
3529//Process::GetArchSpecForExistingProcess (const char *process_name)
3530//{
3531// return Host::GetArchSpecForExistingProcess (process_name);
3532//}
3533//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003534void
3535Process::AppendSTDOUT (const char * s, size_t len)
3536{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003537 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003538 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003539 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003540}
3541
3542void
Greg Clayton93e86192011-11-13 04:45:22 +00003543Process::AppendSTDERR (const char * s, size_t len)
3544{
3545 Mutex::Locker locker (m_stdio_communication_mutex);
3546 m_stderr_data.append (s, len);
3547 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3548}
3549
3550//------------------------------------------------------------------
3551// Process STDIO
3552//------------------------------------------------------------------
3553
3554size_t
3555Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3556{
3557 Mutex::Locker locker(m_stdio_communication_mutex);
3558 size_t bytes_available = m_stdout_data.size();
3559 if (bytes_available > 0)
3560 {
3561 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3562 if (log)
3563 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3564 if (bytes_available > buf_size)
3565 {
3566 memcpy(buf, m_stdout_data.c_str(), buf_size);
3567 m_stdout_data.erase(0, buf_size);
3568 bytes_available = buf_size;
3569 }
3570 else
3571 {
3572 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3573 m_stdout_data.clear();
3574 }
3575 }
3576 return bytes_available;
3577}
3578
3579
3580size_t
3581Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3582{
3583 Mutex::Locker locker(m_stdio_communication_mutex);
3584 size_t bytes_available = m_stderr_data.size();
3585 if (bytes_available > 0)
3586 {
3587 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3588 if (log)
3589 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3590 if (bytes_available > buf_size)
3591 {
3592 memcpy(buf, m_stderr_data.c_str(), buf_size);
3593 m_stderr_data.erase(0, buf_size);
3594 bytes_available = buf_size;
3595 }
3596 else
3597 {
3598 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3599 m_stderr_data.clear();
3600 }
3601 }
3602 return bytes_available;
3603}
3604
3605void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003606Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3607{
3608 Process *process = (Process *) baton;
3609 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3610}
3611
3612size_t
3613Process::ProcessInputReaderCallback (void *baton,
3614 InputReader &reader,
3615 lldb::InputReaderAction notification,
3616 const char *bytes,
3617 size_t bytes_len)
3618{
3619 Process *process = (Process *) baton;
3620
3621 switch (notification)
3622 {
3623 case eInputReaderActivate:
3624 break;
3625
3626 case eInputReaderDeactivate:
3627 break;
3628
3629 case eInputReaderReactivate:
3630 break;
3631
Caroline Tice969ed3d2011-05-02 20:41:46 +00003632 case eInputReaderAsynchronousOutputWritten:
3633 break;
3634
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003635 case eInputReaderGotToken:
3636 {
3637 Error error;
3638 process->PutSTDIN (bytes, bytes_len, error);
3639 }
3640 break;
3641
Caroline Ticeefed6132010-11-19 20:47:54 +00003642 case eInputReaderInterrupt:
3643 process->Halt ();
3644 break;
3645
3646 case eInputReaderEndOfFile:
3647 process->AppendSTDOUT ("^D", 2);
3648 break;
3649
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003650 case eInputReaderDone:
3651 break;
3652
3653 }
3654
3655 return bytes_len;
3656}
3657
3658void
3659Process::ResetProcessInputReader ()
3660{
3661 m_process_input_reader.reset();
3662}
3663
3664void
Greg Claytonee95ed52011-11-17 22:14:31 +00003665Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003666{
3667 // First set up the Read Thread for reading/handling process I/O
3668
3669 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3670
3671 if (conn_ap.get())
3672 {
3673 m_stdio_communication.SetConnection (conn_ap.release());
3674 if (m_stdio_communication.IsConnected())
3675 {
3676 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3677 m_stdio_communication.StartReadThread();
3678
3679 // Now read thread is set up, set up input reader.
3680
3681 if (!m_process_input_reader.get())
3682 {
3683 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3684 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3685 this,
3686 eInputReaderGranularityByte,
3687 NULL,
3688 NULL,
3689 false));
3690
3691 if (err.Fail())
3692 m_process_input_reader.reset();
3693 }
3694 }
3695 }
3696}
3697
3698void
3699Process::PushProcessInputReader ()
3700{
3701 if (m_process_input_reader && !m_process_input_reader->IsActive())
3702 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3703}
3704
3705void
3706Process::PopProcessInputReader ()
3707{
3708 if (m_process_input_reader && m_process_input_reader->IsActive())
3709 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3710}
3711
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003712// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003713void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003714Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003715{
Greg Claytone0d378b2011-03-24 21:19:54 +00003716 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003717
3718 int i=0;
3719 const char *name;
3720 OptionEnumValueElement option_enum;
3721 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3722 {
3723 if (name)
3724 {
3725 option_enum.value = i;
3726 option_enum.string_value = name;
3727 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3728 g_plugins.push_back (option_enum);
3729 }
3730 ++i;
3731 }
3732 option_enum.value = 0;
3733 option_enum.string_value = NULL;
3734 option_enum.usage = NULL;
3735 g_plugins.push_back (option_enum);
3736
3737 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3738 {
3739 if (::strcmp (name, "plugin") == 0)
3740 {
3741 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3742 break;
3743 }
3744 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003745 UserSettingsControllerSP &usc = GetSettingsController();
3746 usc.reset (new SettingsController);
3747 UserSettingsController::InitializeSettingsController (usc,
3748 SettingsController::global_settings_table,
3749 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003750
3751 // Now call SettingsInitialize() for each 'child' of Process settings
3752 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003753}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003754
Greg Clayton99d0faf2010-11-18 23:32:35 +00003755void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003756Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003757{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003758 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3759
3760 Thread::SettingsTerminate ();
3761
3762 // Now terminate Process Settings.
3763
Greg Clayton99d0faf2010-11-18 23:32:35 +00003764 UserSettingsControllerSP &usc = GetSettingsController();
3765 UserSettingsController::FinalizeSettingsController (usc);
3766 usc.reset();
3767}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003768
Greg Clayton99d0faf2010-11-18 23:32:35 +00003769UserSettingsControllerSP &
3770Process::GetSettingsController ()
3771{
Greg Claytonb9556ac2012-01-30 07:41:31 +00003772 static UserSettingsControllerSP g_settings_controller_sp;
3773 if (!g_settings_controller_sp)
3774 {
3775 g_settings_controller_sp.reset (new Process::SettingsController);
3776 // The first shared pointer to Process::SettingsController in
3777 // g_settings_controller_sp must be fully created above so that
3778 // the TargetInstanceSettings can use a weak_ptr to refer back
3779 // to the master setttings controller
3780 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp,
3781 false,
3782 InstanceSettings::GetDefaultName().AsCString()));
3783 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
3784 }
3785 return g_settings_controller_sp;
3786
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003787}
3788
Caroline Tice1559a462010-09-27 00:30:10 +00003789void
3790Process::UpdateInstanceName ()
3791{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003792 Module *module = GetTarget().GetExecutableModulePointer();
Greg Claytone1cd1be2012-01-29 20:56:30 +00003793 if (module && module->GetFileSpec().GetFilename())
Caroline Tice1559a462010-09-27 00:30:10 +00003794 {
Greg Claytondbe54502010-11-19 03:46:01 +00003795 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytone1cd1be2012-01-29 20:56:30 +00003796 module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003797 }
3798}
3799
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003800ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003801Process::RunThreadPlan (ExecutionContext &exe_ctx,
3802 lldb::ThreadPlanSP &thread_plan_sp,
3803 bool stop_others,
3804 bool try_all_threads,
3805 bool discard_on_error,
3806 uint32_t single_thread_timeout_usec,
3807 Stream &errors)
3808{
3809 ExecutionResults return_value = eExecutionSetupError;
3810
Jim Ingham77787032011-01-20 02:03:18 +00003811 if (thread_plan_sp.get() == NULL)
3812 {
3813 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003814 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003815 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003816
3817 if (exe_ctx.GetProcessPtr() != this)
3818 {
3819 errors.Printf("RunThreadPlan called on wrong process.");
3820 return eExecutionSetupError;
3821 }
3822
3823 Thread *thread = exe_ctx.GetThreadPtr();
3824 if (thread == NULL)
3825 {
3826 errors.Printf("RunThreadPlan called with invalid thread.");
3827 return eExecutionSetupError;
3828 }
Jim Ingham77787032011-01-20 02:03:18 +00003829
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003830 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3831 // For that to be true the plan can't be private - since private plans suppress themselves in the
3832 // GetCompletedPlan call.
3833
3834 bool orig_plan_private = thread_plan_sp->GetPrivate();
3835 thread_plan_sp->SetPrivate(false);
3836
Jim Ingham444586b2011-01-24 06:34:17 +00003837 if (m_private_state.GetValue() != eStateStopped)
3838 {
3839 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003840 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003841 }
3842
Jim Ingham66243842011-08-13 00:56:10 +00003843 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00003844 const uint32_t thread_idx_id = thread->GetIndexID();
3845 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003846
3847 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3848 // so we should arrange to reset them as well.
3849
Greg Claytonc14ee322011-09-22 04:58:26 +00003850 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003851
Jim Ingham66243842011-08-13 00:56:10 +00003852 uint32_t selected_tid;
3853 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00003854 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00003855 {
3856 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003857 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003858 }
3859 else
3860 {
3861 selected_tid = LLDB_INVALID_THREAD_ID;
3862 }
3863
Greg Claytonc14ee322011-09-22 04:58:26 +00003864 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Inghamf48169b2010-11-30 02:22:11 +00003865
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003866 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003867
3868 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3869 // restored on exit to the function.
3870
3871 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003872
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003873 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003874 if (log)
3875 {
3876 StreamString s;
3877 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton81c22f62011-10-19 18:09:39 +00003878 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00003879 thread->GetIndexID(),
3880 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00003881 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003882 }
3883
Jim Ingham0f16e732011-02-08 05:20:59 +00003884 bool got_event;
3885 lldb::EventSP event_sp;
3886 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003887
3888 TimeValue* timeout_ptr = NULL;
3889 TimeValue real_timeout;
3890
Jim Ingham0f16e732011-02-08 05:20:59 +00003891 bool first_timeout = true;
3892 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003893
Jim Inghamf48169b2010-11-30 02:22:11 +00003894 while (1)
3895 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003896 // We usually want to resume the process if we get to the top of the loop.
3897 // The only exception is if we get two running events with no intervening
3898 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003899
Jim Ingham0f16e732011-02-08 05:20:59 +00003900 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003901 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003902 // Do the initial resume and wait for the running event before going further.
3903
Greg Claytonc14ee322011-09-22 04:58:26 +00003904 Error resume_error = Resume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00003905 if (!resume_error.Success())
3906 {
3907 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003908 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003909 break;
3910 }
3911
3912 real_timeout = TimeValue::Now();
3913 real_timeout.OffsetWithMicroSeconds(500000);
3914 timeout_ptr = &real_timeout;
3915
Sean Callananc1b312a2012-01-05 02:00:14 +00003916 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
Jim Ingham0f16e732011-02-08 05:20:59 +00003917 if (!got_event)
3918 {
3919 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003920 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003921
3922 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003923 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003924 break;
3925 }
3926
3927 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3928 if (stop_state != eStateRunning)
3929 {
3930 if (log)
3931 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3932
3933 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003934 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003935 break;
3936 }
3937
3938 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003939 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003940 // We need to call the function synchronously, so spin waiting for it to return.
3941 // If we get interrupted while executing, we're going to lose our context, and
3942 // won't be able to gather the result at this point.
3943 // We set the timeout AFTER the resume, since the resume takes some time and we
3944 // don't want to charge that to the timeout.
3945
3946 if (single_thread_timeout_usec != 0)
3947 {
3948 real_timeout = TimeValue::Now();
3949 if (first_timeout)
3950 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3951 else
3952 real_timeout.OffsetWithSeconds(10);
3953
3954 timeout_ptr = &real_timeout;
3955 }
3956 }
3957 else
3958 {
3959 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003960 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003961 do_resume = true;
3962 }
3963
3964 // Now wait for the process to stop again:
3965 stop_state = lldb::eStateInvalid;
3966 event_sp.reset();
3967 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3968
3969 if (got_event)
3970 {
3971 if (event_sp.get())
3972 {
3973 bool keep_going = false;
3974 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3975 if (log)
3976 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3977
3978 switch (stop_state)
3979 {
3980 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00003981 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003982 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00003983 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00003984 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00003985 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003986 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00003987 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00003988 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3989 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00003990 }
3991 else
3992 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003993 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3994 StopReason stop_reason = eStopReasonInvalid;
3995 if (stop_info_sp)
3996 stop_reason = stop_info_sp->GetStopReason();
3997 if (stop_reason == eStopReasonPlanComplete)
3998 {
3999 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004000 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004001 // Now mark this plan as private so it doesn't get reported as the stop reason
4002 // after this point.
4003 if (thread_plan_sp)
4004 thread_plan_sp->SetPrivate (orig_plan_private);
4005 return_value = eExecutionCompleted;
4006 }
4007 else
4008 {
4009 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004010 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004011
4012 return_value = eExecutionInterrupted;
4013 }
Jim Ingham160f78c2011-05-17 01:10:11 +00004014 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00004015 }
4016 break;
4017
Jim Ingham0f16e732011-02-08 05:20:59 +00004018 case lldb::eStateCrashed:
4019 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004020 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004021 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004022 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004023
Jim Ingham0f16e732011-02-08 05:20:59 +00004024 case lldb::eStateRunning:
4025 do_resume = false;
4026 keep_going = true;
4027 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004028
Jim Ingham0f16e732011-02-08 05:20:59 +00004029 default:
4030 if (log)
4031 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00004032
4033 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004034 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004035 break;
4036 }
4037 if (keep_going)
4038 continue;
4039 else
4040 break;
4041 }
4042 else
4043 {
4044 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004045 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00004046 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004047 break;
4048 }
4049 }
4050 else
4051 {
4052 // If we didn't get an event that means we've timed out...
4053 // We will interrupt the process here. Depending on what we were asked to do we will
4054 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00004055 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00004056
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004057 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00004058 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00004059 {
4060 if (first_timeout)
4061 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4062 "trying with all threads enabled.",
4063 single_thread_timeout_usec);
4064 else
4065 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4066 "and timeout: %d timed out.",
4067 single_thread_timeout_usec);
4068 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004069 else
Jim Ingham0f16e732011-02-08 05:20:59 +00004070 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4071 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00004072 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004073 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004074
Greg Claytonc14ee322011-09-22 04:58:26 +00004075 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00004076 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00004077 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004078 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004079 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004080
Jim Ingham0f16e732011-02-08 05:20:59 +00004081 // If halt succeeds, it always produces a stopped event. Wait for that:
4082
4083 real_timeout = TimeValue::Now();
4084 real_timeout.OffsetWithMicroSeconds(500000);
4085
4086 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004087
4088 if (got_event)
4089 {
4090 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4091 if (log)
4092 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004093 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00004094 if (stop_state == lldb::eStateStopped
4095 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00004096 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004097 }
4098
Jim Ingham0f16e732011-02-08 05:20:59 +00004099 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00004100 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004101 // Between the time we initiated the Halt and the time we delivered it, the process could have
4102 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00004103
Greg Claytonc14ee322011-09-22 04:58:26 +00004104 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004105 {
4106 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004107 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004108 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004109 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004110 break;
4111 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004112
Jim Ingham0f16e732011-02-08 05:20:59 +00004113 if (!try_all_threads)
4114 {
4115 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004116 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004117 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004118 break;
4119 }
4120
4121 if (first_timeout)
4122 {
4123 // Set all the other threads to run, and return to the top of the loop, which will continue;
4124 first_timeout = false;
4125 thread_plan_sp->SetStopOthers (false);
4126 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004127 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004128
4129 continue;
4130 }
4131 else
4132 {
4133 // Running all threads failed, so return Interrupted.
4134 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004135 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004136 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004137 break;
4138 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004139 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004140 }
4141 else
4142 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004143 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004144 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004145 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004146 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00004147 }
4148 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004149 else
4150 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004151 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4152 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00004153 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004154 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.",
4155 halt_error.AsCString());
4156 real_timeout = TimeValue::Now();
4157 real_timeout.OffsetWithMicroSeconds(500000);
4158 timeout_ptr = &real_timeout;
4159 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4160 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004161 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004162 // This is not going anywhere, bag out.
4163 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004164 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004165 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004166 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004167 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004168 else
4169 {
4170 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4171 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004172 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00004173 if (stop_state == lldb::eStateStopped)
4174 {
4175 // Between the time we initiated the Halt and the time we delivered it, the process could have
4176 // already finished its job. Check that here:
4177
Greg Claytonc14ee322011-09-22 04:58:26 +00004178 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004179 {
4180 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004181 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004182 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004183 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004184 break;
4185 }
4186
4187 if (first_timeout)
4188 {
4189 // Set all the other threads to run, and return to the top of the loop, which will continue;
4190 first_timeout = false;
4191 thread_plan_sp->SetStopOthers (false);
4192 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004193 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004194
4195 continue;
4196 }
4197 else
4198 {
4199 // Running all threads failed, so return Interrupted.
4200 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004201 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004202 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004203 break;
4204 }
4205 }
4206 else
4207 {
Sean Callanan39821ac2011-08-09 22:07:08 +00004208 if (log)
4209 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4210 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00004211 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004212 break;
4213 }
4214 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004215 }
4216
Jim Inghamf48169b2010-11-30 02:22:11 +00004217 }
4218
Jim Ingham0f16e732011-02-08 05:20:59 +00004219 } // END WAIT LOOP
4220
4221 // Now do some processing on the results of the run:
4222 if (return_value == eExecutionInterrupted)
4223 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004224 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004225 {
4226 StreamString s;
4227 if (event_sp)
4228 event_sp->Dump (&s);
4229 else
4230 {
Jim Ingham20829ac2011-08-09 22:24:33 +00004231 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004232 }
4233
4234 StreamString ts;
4235
Jim Ingham20829ac2011-08-09 22:24:33 +00004236 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00004237
4238 do
4239 {
4240 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4241
4242 if (!event_data)
4243 {
4244 event_explanation = "<no event data>";
4245 break;
4246 }
4247
4248 Process *process = event_data->GetProcessSP().get();
4249
4250 if (!process)
4251 {
4252 event_explanation = "<no process>";
4253 break;
4254 }
4255
4256 ThreadList &thread_list = process->GetThreadList();
4257
4258 uint32_t num_threads = thread_list.GetSize();
4259 uint32_t thread_index;
4260
4261 ts.Printf("<%u threads> ", num_threads);
4262
4263 for (thread_index = 0;
4264 thread_index < num_threads;
4265 ++thread_index)
4266 {
4267 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4268
4269 if (!thread)
4270 {
4271 ts.Printf("<?> ");
4272 continue;
4273 }
4274
Greg Clayton81c22f62011-10-19 18:09:39 +00004275 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Ingham0f16e732011-02-08 05:20:59 +00004276 RegisterContext *register_context = thread->GetRegisterContext().get();
4277
4278 if (register_context)
4279 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4280 else
4281 ts.Printf("[ip unknown] ");
4282
4283 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4284 if (stop_info_sp)
4285 {
4286 const char *stop_desc = stop_info_sp->GetDescription();
4287 if (stop_desc)
4288 ts.PutCString (stop_desc);
4289 }
4290 ts.Printf(">");
4291 }
4292
4293 event_explanation = ts.GetData();
4294 } while (0);
4295
4296 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004297 {
4298 if (event_explanation)
4299 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4300 else
4301 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4302 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004303
4304 if (discard_on_error && thread_plan_sp)
4305 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004306 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004307 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004308 }
4309 }
4310 }
4311 else if (return_value == eExecutionSetupError)
4312 {
4313 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004314 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004315
4316 if (discard_on_error && thread_plan_sp)
4317 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004318 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004319 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004320 }
4321 }
4322 else
4323 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004324 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004325 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004326 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004327 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00004328 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00004329 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004330 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004331 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004332 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004333 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00004334 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00004335 }
4336 else
4337 {
4338 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004339 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00004340 if (discard_on_error && thread_plan_sp)
4341 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004342 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004343 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00004344 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004345 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00004346 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004347 }
4348 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004349
Jim Inghamf48169b2010-11-30 02:22:11 +00004350 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00004351 // Check that it's still there, and if it is put it back in the context. Also restore the
4352 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00004353 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4354 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00004355 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004356 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00004357 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004358
4359 // Also restore the current process'es selected frame & thread, since this function calling may
4360 // be done behind the user's back.
4361
4362 if (selected_tid != LLDB_INVALID_THREAD_ID)
4363 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004364 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00004365 {
4366 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00004367 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00004368 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00004369 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004370 }
4371 }
4372
4373 return return_value;
4374}
4375
4376const char *
4377Process::ExecutionResultAsCString (ExecutionResults result)
4378{
4379 const char *result_name;
4380
4381 switch (result)
4382 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004383 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004384 result_name = "eExecutionCompleted";
4385 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004386 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004387 result_name = "eExecutionDiscarded";
4388 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004389 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004390 result_name = "eExecutionInterrupted";
4391 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004392 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004393 result_name = "eExecutionSetupError";
4394 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004395 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004396 result_name = "eExecutionTimedOut";
4397 break;
4398 }
4399 return result_name;
4400}
4401
Greg Clayton7260f622011-04-18 08:33:37 +00004402void
4403Process::GetStatus (Stream &strm)
4404{
4405 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00004406 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00004407 {
4408 if (state == eStateExited)
4409 {
4410 int exit_status = GetExitStatus();
4411 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004412 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004413 GetID(),
4414 exit_status,
4415 exit_status,
4416 exit_description ? exit_description : "");
4417 }
4418 else
4419 {
4420 if (state == eStateConnected)
4421 strm.Printf ("Connected to remote target.\n");
4422 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004423 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004424 }
4425 }
4426 else
4427 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004428 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004429 }
4430}
4431
4432size_t
4433Process::GetThreadStatus (Stream &strm,
4434 bool only_threads_with_stop_reason,
4435 uint32_t start_frame,
4436 uint32_t num_frames,
4437 uint32_t num_frames_with_source)
4438{
4439 size_t num_thread_infos_dumped = 0;
4440
4441 const size_t num_threads = GetThreadList().GetSize();
4442 for (uint32_t i = 0; i < num_threads; i++)
4443 {
4444 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4445 if (thread)
4446 {
4447 if (only_threads_with_stop_reason)
4448 {
4449 if (thread->GetStopInfo().get() == NULL)
4450 continue;
4451 }
4452 thread->GetStatus (strm,
4453 start_frame,
4454 num_frames,
4455 num_frames_with_source);
4456 ++num_thread_infos_dumped;
4457 }
4458 }
4459 return num_thread_infos_dumped;
4460}
4461
Greg Claytona9f40ad2012-02-22 04:37:26 +00004462void
4463Process::AddInvalidMemoryRegion (const LoadRange &region)
4464{
4465 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4466}
4467
4468bool
4469Process::RemoveInvalidMemoryRange (const LoadRange &region)
4470{
4471 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4472}
4473
4474
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004475//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004476// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004477//--------------------------------------------------------------
4478
Greg Clayton1b654882010-09-19 02:33:57 +00004479Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004480 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004481{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004482}
4483
Greg Clayton1b654882010-09-19 02:33:57 +00004484Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004485{
4486}
4487
4488lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004489Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004490{
Greg Claytonb9556ac2012-01-30 07:41:31 +00004491 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4492 false,
4493 instance_name));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004494 return new_settings_sp;
4495}
4496
4497//--------------------------------------------------------------
4498// class ProcessInstanceSettings
4499//--------------------------------------------------------------
4500
Greg Clayton85851dd2010-12-04 00:10:17 +00004501ProcessInstanceSettings::ProcessInstanceSettings
4502(
Greg Claytonb9556ac2012-01-30 07:41:31 +00004503 const UserSettingsControllerSP &owner_sp,
Greg Clayton85851dd2010-12-04 00:10:17 +00004504 bool live_instance,
4505 const char *name
4506) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004507 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004508{
Caroline Ticef20e8232010-09-09 18:26:37 +00004509 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4510 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4511 // 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 +00004512 // This is true for CreateInstanceName() too.
Greg Clayton1d885962011-11-08 02:43:13 +00004513
Caroline Tice9e41c152010-09-16 19:05:55 +00004514 if (GetInstanceName () == InstanceSettings::InvalidName())
4515 {
4516 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
Greg Claytonb9556ac2012-01-30 07:41:31 +00004517 owner_sp->RegisterInstanceSettings (this);
Caroline Tice9e41c152010-09-16 19:05:55 +00004518 }
Greg Clayton1d885962011-11-08 02:43:13 +00004519
Caroline Ticef20e8232010-09-09 18:26:37 +00004520 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004521 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004522 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004523 CopyInstanceSettings (pending_settings,false);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004524 }
4525}
4526
4527ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004528 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004529{
4530 if (m_instance_name != InstanceSettings::GetDefaultName())
4531 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004532 UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4533 if (owner_sp)
4534 {
4535 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4536 owner_sp->RemovePendingSettings (m_instance_name);
4537 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004538 }
4539}
4540
4541ProcessInstanceSettings::~ProcessInstanceSettings ()
4542{
4543}
4544
4545ProcessInstanceSettings&
4546ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4547{
4548 if (this != &rhs)
4549 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004550 }
4551
4552 return *this;
4553}
4554
4555
4556void
4557ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4558 const char *index_value,
4559 const char *value,
4560 const ConstString &instance_name,
4561 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004562 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004563 Error &err,
4564 bool pending)
4565{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004566}
4567
4568void
4569ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4570 bool pending)
4571{
Greg Clayton1d885962011-11-08 02:43:13 +00004572// if (new_settings.get() == NULL)
4573// return;
4574//
4575// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004576}
4577
Caroline Tice12cecd72010-09-20 21:37:42 +00004578bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004579ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4580 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004581 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004582 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004583{
Greg Clayton1d885962011-11-08 02:43:13 +00004584 if (err)
4585 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4586 return false;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004587}
4588
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004589const ConstString
4590ProcessInstanceSettings::CreateInstanceName ()
4591{
4592 static int instance_count = 1;
4593 StreamString sstr;
4594
4595 sstr.Printf ("process_%d", instance_count);
4596 ++instance_count;
4597
4598 const ConstString ret_val (sstr.GetData());
4599 return ret_val;
4600}
4601
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004602//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004603// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004604//--------------------------------------------------
4605
4606SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004607Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004608{
4609 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4610 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4611};
4612
4613
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004614SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004615Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004616{
Greg Clayton85851dd2010-12-04 00:10:17 +00004617 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton85851dd2010-12-04 00:10:17 +00004618 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004619};
4620
4621
Jim Ingham5aee1622010-08-09 23:31:02 +00004622
Greg Clayton1d885962011-11-08 02:43:13 +00004623