blob: fc498c6cd5aecf6f5459255051ff04e235bac881 [file] [log] [blame]
Chris Lattner24943d22010-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 Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-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 Clayton24bc5d92011-03-30 18:16:51 +000043void
Greg Claytonb72d0f02011-04-12 05:54:46 +000044ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +000045{
46 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +000047 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +000048 s.Printf (" pid = %llu\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +000049
50 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +000051 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +000060 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +000061 if (argc > 0)
62 {
63 for (uint32_t i=0; i<argc; i++)
64 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000065 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +000066 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +000067 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000068 else
Greg Claytonb72d0f02011-04-12 05:54:46 +000069 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000070 }
71 }
Greg Claytonb72d0f02011-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 Claytonff39f742011-04-01 00:29:43 +000086 if (m_arch.IsValid())
87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
88
Greg Claytonb72d0f02011-04-12 05:54:46 +000089 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000090 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000091 cstr = platform->GetUserName (m_uid);
92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000093 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000094 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000095 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000096 cstr = platform->GetGroupName (m_gid);
97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000098 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000099 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000100 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000101 cstr = platform->GetUserName (m_euid);
102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000103 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000104 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000105 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000106 cstr = platform->GetGroupName (m_egid);
107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000108 }
109}
110
111void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000112ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000113{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000114 const char *label;
115 if (show_args || verbose)
116 label = "ARGUMENTS";
117 else
118 label = "NAME";
119
Greg Claytonff39f742011-04-01 00:29:43 +0000120 if (verbose)
121 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
124 }
125 else
126 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000127 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000128 s.PutCString ("====== ====== ========== ======= ============================\n");
129 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000130}
131
132void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000133ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000134{
135 if (m_pid != LLDB_INVALID_PROCESS_ID)
136 {
137 const char *cstr;
Greg Claytond9919d32011-12-01 23:28:38 +0000138 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000139
Greg Clayton24bc5d92011-03-30 18:16:51 +0000140
Greg Claytonff39f742011-04-01 00:29:43 +0000141 if (verbose)
142 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000143 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000147 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000148
Greg Claytonb72d0f02011-04-12 05:54:46 +0000149 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000153 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000154
Greg Claytonb72d0f02011-04-12 05:54:46 +0000155 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000159 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000160
Greg Claytonb72d0f02011-04-12 05:54:46 +0000161 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000165 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000166 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
167 }
168 else
169 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000170 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000171 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000172 (int)m_arch.GetTriple().getArchName().size(),
173 m_arch.GetTriple().getArchName().data());
174 }
175
Greg Claytonb72d0f02011-04-12 05:54:46 +0000176 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000177 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000178 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-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 Claytonb72d0f02011-04-12 05:54:46 +0000185 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000186 }
187 }
188 }
189 else
190 {
191 s.PutCString (GetName());
192 }
193
194 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000195 }
196}
197
Greg Claytonb72d0f02011-04-12 05:54:46 +0000198
199void
Greg Clayton36bc5ea2011-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 Claytonb72d0f02011-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 Clayton36bc5ea2011-11-03 21:22:33 +0000236 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-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 Claytonabb33022011-11-08 02:43:13 +0000253void
Greg Clayton464c6162011-11-17 22:14:31 +0000254ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-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 Claytonabb33022011-11-08 02:43:13 +0000260 if (m_flags.Test(eLaunchFlagDisableSTDIO))
261 {
262 AppendSuppressFileAction (STDERR_FILENO, true , true );
263 AppendSuppressFileAction (STDIN_FILENO , true , false);
264 AppendSuppressFileAction (STDOUT_FILENO, false, true );
265 }
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 Clayton464c6162011-11-17 22:14:31 +0000272 const char *in_path = NULL;
273 const char *out_path = NULL;
274 const char *err_path = NULL;
Greg Claytonabb33022011-11-08 02:43:13 +0000275 if (target)
276 {
Greg Clayton464c6162011-11-17 22:14:31 +0000277 in_path = target->GetStandardErrorPath();
278 out_path = target->GetStandardInputPath();
279 err_path = target->GetStandardOutputPath();
280 }
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 Claytonabb33022011-11-08 02:43:13 +0000285 {
Greg Clayton464c6162011-11-17 22:14:31 +0000286 in_path = out_path = err_path = m_pty.GetSlaveName (NULL, 0);
Greg Claytonabb33022011-11-08 02:43:13 +0000287 }
288 }
289
Greg Clayton464c6162011-11-17 22:14:31 +0000290 if (in_path)
291 AppendOpenFileAction(STDERR_FILENO, in_path, true, true);
292
293 if (out_path)
294 AppendOpenFileAction(STDIN_FILENO, out_path, true, false);
295
296 if (err_path)
297 AppendOpenFileAction(STDOUT_FILENO, err_path, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000298 }
299 }
300}
301
Greg Clayton527154d2011-11-15 03:53:30 +0000302
303bool
304ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error, bool localhost)
305{
306 error.Clear();
307
308 if (GetFlags().Test (eLaunchFlagLaunchInShell))
309 {
310 const char *shell_executable = GetShell();
311 if (shell_executable)
312 {
313 char shell_resolved_path[PATH_MAX];
314
315 if (localhost)
316 {
317 FileSpec shell_filespec (shell_executable, true);
318
319 if (!shell_filespec.Exists())
320 {
321 // Resolve the path in case we just got "bash", "sh" or "tcsh"
322 if (!shell_filespec.ResolveExecutableLocation ())
323 {
324 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
325 return false;
326 }
327 }
328 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
329 shell_executable = shell_resolved_path;
330 }
331
332 Args shell_arguments;
333 std::string safe_arg;
334 shell_arguments.AppendArgument (shell_executable);
335 StreamString shell_command;
336 shell_arguments.AppendArgument ("-c");
337 shell_command.PutCString ("exec");
338 if (GetArchitecture().IsValid())
339 {
340 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
341 // Set the resume count to 2:
342 // 1 - stop in shell
343 // 2 - stop in /usr/bin/arch
344 // 3 - then we will stop in our program
345 SetResumeCount(2);
346 }
347 else
348 {
349 // Set the resume count to 1:
350 // 1 - stop in shell
351 // 2 - then we will stop in our program
352 SetResumeCount(1);
353 }
354
355 const char **argv = GetArguments().GetConstArgumentVector ();
356 if (argv)
357 {
358 for (size_t i=0; argv[i] != NULL; ++i)
359 {
360 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
361 shell_command.Printf(" %s", arg);
362 }
363 }
364 shell_arguments.AppendArgument (shell_command.GetString().c_str());
365
366 m_executable.SetFile(shell_executable, false);
367 m_arguments = shell_arguments;
368 return true;
369 }
370 else
371 {
372 error.SetErrorString ("invalid shell path");
373 }
374 }
375 else
376 {
377 error.SetErrorString ("not launching in shell");
378 }
379 return false;
380}
381
382
Greg Clayton24bc5d92011-03-30 18:16:51 +0000383bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000384ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
385{
386 if ((read || write) && fd >= 0 && path && path[0])
387 {
388 m_action = eFileActionOpen;
389 m_fd = fd;
390 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000391 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000392 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000393 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000394 else
Greg Clayton527154d2011-11-15 03:53:30 +0000395 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000396 m_path.assign (path);
397 return true;
398 }
399 else
400 {
401 Clear();
402 }
403 return false;
404}
405
406bool
407ProcessLaunchInfo::FileAction::Close (int fd)
408{
409 Clear();
410 if (fd >= 0)
411 {
412 m_action = eFileActionClose;
413 m_fd = fd;
414 }
415 return m_fd >= 0;
416}
417
418
419bool
420ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
421{
422 Clear();
423 if (fd >= 0 && dup_fd >= 0)
424 {
425 m_action = eFileActionDuplicate;
426 m_fd = fd;
427 m_arg = dup_fd;
428 }
429 return m_fd >= 0;
430}
431
432
433
434bool
435ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
436 const FileAction *info,
437 Log *log,
438 Error& error)
439{
440 if (info == NULL)
441 return false;
442
443 switch (info->m_action)
444 {
445 case eFileActionNone:
446 error.Clear();
447 break;
448
449 case eFileActionClose:
450 if (info->m_fd == -1)
451 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
452 else
453 {
454 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
455 eErrorTypePOSIX);
456 if (log && (error.Fail() || log))
457 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
458 file_actions, info->m_fd);
459 }
460 break;
461
462 case eFileActionDuplicate:
463 if (info->m_fd == -1)
464 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
465 else if (info->m_arg == -1)
466 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
467 else
468 {
469 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
470 eErrorTypePOSIX);
471 if (log && (error.Fail() || log))
472 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
473 file_actions, info->m_fd, info->m_arg);
474 }
475 break;
476
477 case eFileActionOpen:
478 if (info->m_fd == -1)
479 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
480 else
481 {
482 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000483
Greg Claytonb72d0f02011-04-12 05:54:46 +0000484 mode_t mode = 0;
485
Greg Clayton527154d2011-11-15 03:53:30 +0000486 if (oflag & O_CREAT)
487 mode = 0640;
488
Greg Claytonb72d0f02011-04-12 05:54:46 +0000489 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
490 info->m_fd,
491 info->m_path.c_str(),
492 oflag,
493 mode),
494 eErrorTypePOSIX);
495 if (error.Fail() || log)
496 error.PutToLog(log,
497 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
498 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
499 }
500 break;
501
502 default:
503 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
504 break;
505 }
506 return error.Success();
507}
508
509Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000510ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000511{
512 Error error;
513 char short_option = (char) m_getopt_table[option_idx].val;
514
515 switch (short_option)
516 {
517 case 's': // Stop at program entry point
518 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
519 break;
520
521 case 'e': // STDERR for read + write
522 {
523 ProcessLaunchInfo::FileAction action;
524 if (action.Open(STDERR_FILENO, option_arg, true, true))
525 launch_info.AppendFileAction (action);
526 }
527 break;
528
529 case 'i': // STDIN for read only
530 {
531 ProcessLaunchInfo::FileAction action;
532 if (action.Open(STDIN_FILENO, option_arg, true, false))
533 launch_info.AppendFileAction (action);
534 }
535 break;
536
537 case 'o': // Open STDOUT for write only
538 {
539 ProcessLaunchInfo::FileAction action;
540 if (action.Open(STDOUT_FILENO, option_arg, false, true))
541 launch_info.AppendFileAction (action);
542 }
543 break;
544
545 case 'p': // Process plug-in name
546 launch_info.SetProcessPluginName (option_arg);
547 break;
548
549 case 'n': // Disable STDIO
550 {
551 ProcessLaunchInfo::FileAction action;
552 if (action.Open(STDERR_FILENO, "/dev/null", true, true))
553 launch_info.AppendFileAction (action);
554 if (action.Open(STDOUT_FILENO, "/dev/null", false, true))
555 launch_info.AppendFileAction (action);
556 if (action.Open(STDIN_FILENO, "/dev/null", true, false))
557 launch_info.AppendFileAction (action);
558 }
559 break;
560
561 case 'w':
562 launch_info.SetWorkingDirectory (option_arg);
563 break;
564
565 case 't': // Open process in new terminal window
566 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
567 break;
568
569 case 'a':
570 launch_info.GetArchitecture().SetTriple (option_arg,
571 m_interpreter.GetPlatform(true).get());
572 break;
573
574 case 'A':
575 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
576 break;
577
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000578 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000579 if (option_arg && option_arg[0])
580 launch_info.SetShell (option_arg);
581 else
582 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000583 break;
584
Greg Claytonb72d0f02011-04-12 05:54:46 +0000585 case 'v':
586 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
587 break;
588
589 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000590 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000591 break;
592
593 }
594 return error;
595}
596
597OptionDefinition
598ProcessLaunchCommandOptions::g_option_table[] =
599{
600{ 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."},
601{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
602{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
603{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
604{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
605{ 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 Clayton527154d2011-11-15 03:53:30 +0000606{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypePath, "Run the process in a shell (not supported on all platforms)."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000607
608{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
609{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
610{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
611
612{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
613
614{ 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."},
615
616{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
617};
618
619
620
621bool
622ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000623{
624 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
625 return true;
626 const char *match_name = m_match_info.GetName();
627 if (!match_name)
628 return true;
629
630 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
631}
632
633bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000634ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000635{
636 if (!NameMatches (proc_info.GetName()))
637 return false;
638
639 if (m_match_info.ProcessIDIsValid() &&
640 m_match_info.GetProcessID() != proc_info.GetProcessID())
641 return false;
642
643 if (m_match_info.ParentProcessIDIsValid() &&
644 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
645 return false;
646
Greg Claytonb72d0f02011-04-12 05:54:46 +0000647 if (m_match_info.UserIDIsValid () &&
648 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000649 return false;
650
Greg Claytonb72d0f02011-04-12 05:54:46 +0000651 if (m_match_info.GroupIDIsValid () &&
652 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000653 return false;
654
655 if (m_match_info.EffectiveUserIDIsValid () &&
656 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
657 return false;
658
659 if (m_match_info.EffectiveGroupIDIsValid () &&
660 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
661 return false;
662
663 if (m_match_info.GetArchitecture().IsValid() &&
664 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
665 return false;
666 return true;
667}
668
669bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000670ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000671{
672 if (m_name_match_type != eNameMatchIgnore)
673 return false;
674
675 if (m_match_info.ProcessIDIsValid())
676 return false;
677
678 if (m_match_info.ParentProcessIDIsValid())
679 return false;
680
Greg Claytonb72d0f02011-04-12 05:54:46 +0000681 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000682 return false;
683
Greg Claytonb72d0f02011-04-12 05:54:46 +0000684 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000685 return false;
686
687 if (m_match_info.EffectiveUserIDIsValid ())
688 return false;
689
690 if (m_match_info.EffectiveGroupIDIsValid ())
691 return false;
692
693 if (m_match_info.GetArchitecture().IsValid())
694 return false;
695
696 if (m_match_all_users)
697 return false;
698
699 return true;
700
701}
702
703void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000704ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000705{
706 m_match_info.Clear();
707 m_name_match_type = eNameMatchIgnore;
708 m_match_all_users = false;
709}
Greg Claytonfd119992011-01-07 06:08:19 +0000710
Greg Clayton46c9a352012-02-09 06:16:32 +0000711ProcessSP
712Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000713{
Greg Clayton46c9a352012-02-09 06:16:32 +0000714 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000715 ProcessCreateInstance create_callback = NULL;
716 if (plugin_name)
717 {
718 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
719 if (create_callback)
720 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000721 process_sp = create_callback(target, listener, crash_file_path);
722 if (process_sp)
723 {
724 if (!process_sp->CanDebug(target, true))
725 process_sp.reset();
726 }
Chris Lattner24943d22010-06-08 16:52:24 +0000727 }
728 }
729 else
730 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000731 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000732 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000733 process_sp = create_callback(target, listener, crash_file_path);
734 if (process_sp)
735 {
736 if (!process_sp->CanDebug(target, false))
737 process_sp.reset();
738 else
739 break;
740 }
Chris Lattner24943d22010-06-08 16:52:24 +0000741 }
742 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000743 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000744}
745
Jim Ingham5a15e692012-02-16 06:50:00 +0000746ConstString &
747Process::GetStaticBroadcasterClass ()
748{
749 static ConstString class_name ("lldb.process");
750 return class_name;
751}
Chris Lattner24943d22010-06-08 16:52:24 +0000752
753//----------------------------------------------------------------------
754// Process constructor
755//----------------------------------------------------------------------
756Process::Process(Target &target, Listener &listener) :
757 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000758 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Greg Clayton334d33a2012-01-30 07:41:31 +0000759 ProcessInstanceSettings (GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000760 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000761 m_public_state (eStateUnloaded),
762 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000763 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
764 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000765 m_private_state_listener ("lldb.process.internal_state_listener"),
766 m_private_state_control_wait(),
767 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000768 m_mod_id (),
Chris Lattner24943d22010-06-08 16:52:24 +0000769 m_thread_index_id (0),
770 m_exit_status (-1),
771 m_exit_string (),
772 m_thread_list (this),
773 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000774 m_image_tokens (),
775 m_listener (listener),
776 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000777 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000778 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000779 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000780 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000781 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000782 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000783 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000784 m_stderr_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000785 m_memory_cache (*this),
786 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +0000787 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000788 m_next_event_action_ap(),
Sean Callanan04200f62012-02-14 22:50:38 +0000789 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +0000790{
Caroline Tice1ebef442010-09-27 00:30:10 +0000791 UpdateInstanceName();
Jim Ingham5a15e692012-02-16 06:50:00 +0000792
793 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +0000794
Greg Claytone005f2c2010-11-06 01:53:30 +0000795 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000796 if (log)
797 log->Printf ("%p Process::Process()", this);
798
Greg Clayton49ce6822010-10-31 03:01:06 +0000799 SetEventName (eBroadcastBitStateChanged, "state-changed");
800 SetEventName (eBroadcastBitInterrupt, "interrupt");
801 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
802 SetEventName (eBroadcastBitSTDERR, "stderr-available");
803
Chris Lattner24943d22010-06-08 16:52:24 +0000804 listener.StartListeningForEvents (this,
805 eBroadcastBitStateChanged |
806 eBroadcastBitInterrupt |
807 eBroadcastBitSTDOUT |
808 eBroadcastBitSTDERR);
809
810 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
811 eBroadcastBitStateChanged);
812
813 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
814 eBroadcastInternalStateControlStop |
815 eBroadcastInternalStateControlPause |
816 eBroadcastInternalStateControlResume);
817}
818
819//----------------------------------------------------------------------
820// Destructor
821//----------------------------------------------------------------------
822Process::~Process()
823{
Greg Claytone005f2c2010-11-06 01:53:30 +0000824 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000825 if (log)
826 log->Printf ("%p Process::~Process()", this);
827 StopPrivateStateThread();
828}
829
830void
831Process::Finalize()
832{
Greg Claytonffa43a62011-11-17 04:46:02 +0000833 switch (GetPrivateState())
834 {
835 case eStateConnected:
836 case eStateAttaching:
837 case eStateLaunching:
838 case eStateStopped:
839 case eStateRunning:
840 case eStateStepping:
841 case eStateCrashed:
842 case eStateSuspended:
843 if (GetShouldDetach())
844 Detach();
845 else
846 Destroy();
847 break;
848
849 case eStateInvalid:
850 case eStateUnloaded:
851 case eStateDetached:
852 case eStateExited:
853 break;
854 }
855
Greg Clayton2f57db02011-10-01 00:45:15 +0000856 // Clear our broadcaster before we proceed with destroying
857 Broadcaster::Clear();
858
Chris Lattner24943d22010-06-08 16:52:24 +0000859 // Do any cleanup needed prior to being destructed... Subclasses
860 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000861
862 // We need to destroy the loader before the derived Process class gets destroyed
863 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +0000864 m_dynamic_checkers_ap.reset();
865 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +0000866 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +0000867 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +0000868 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +0000869 std::vector<Notifications> empty_notifications;
870 m_notifications.swap(empty_notifications);
871 m_image_tokens.clear();
872 m_memory_cache.Clear();
873 m_allocated_memory_cache.Clear();
874 m_language_runtimes.clear();
875 m_next_event_action_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000876}
877
878void
879Process::RegisterNotificationCallbacks (const Notifications& callbacks)
880{
881 m_notifications.push_back(callbacks);
882 if (callbacks.initialize != NULL)
883 callbacks.initialize (callbacks.baton, this);
884}
885
886bool
887Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
888{
889 std::vector<Notifications>::iterator pos, end = m_notifications.end();
890 for (pos = m_notifications.begin(); pos != end; ++pos)
891 {
892 if (pos->baton == callbacks.baton &&
893 pos->initialize == callbacks.initialize &&
894 pos->process_state_changed == callbacks.process_state_changed)
895 {
896 m_notifications.erase(pos);
897 return true;
898 }
899 }
900 return false;
901}
902
903void
904Process::SynchronouslyNotifyStateChanged (StateType state)
905{
906 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
907 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
908 {
909 if (notification_pos->process_state_changed)
910 notification_pos->process_state_changed (notification_pos->baton, this, state);
911 }
912}
913
914// FIXME: We need to do some work on events before the general Listener sees them.
915// For instance if we are continuing from a breakpoint, we need to ensure that we do
916// the little "insert real insn, step & stop" trick. But we can't do that when the
917// event is delivered by the broadcaster - since that is done on the thread that is
918// waiting for new events, so if we needed more than one event for our handling, we would
919// stall. So instead we do it when we fetch the event off of the queue.
920//
921
922StateType
923Process::GetNextEvent (EventSP &event_sp)
924{
925 StateType state = eStateInvalid;
926
927 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
928 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
929
930 return state;
931}
932
933
934StateType
935Process::WaitForProcessToStop (const TimeValue *timeout)
936{
Jim Ingham21f37ad2011-08-09 02:12:22 +0000937 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
938 // We have to actually check each event, and in the case of a stopped event check the restarted flag
939 // on the event.
940 EventSP event_sp;
941 StateType state = GetState();
942 // If we are exited or detached, we won't ever get back to any
943 // other valid state...
944 if (state == eStateDetached || state == eStateExited)
945 return state;
946
947 while (state != eStateInvalid)
948 {
949 state = WaitForStateChangedEvents (timeout, event_sp);
950 switch (state)
951 {
952 case eStateCrashed:
953 case eStateDetached:
954 case eStateExited:
955 case eStateUnloaded:
956 return state;
957 case eStateStopped:
958 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
959 continue;
960 else
961 return state;
962 default:
963 continue;
964 }
965 }
966 return state;
Chris Lattner24943d22010-06-08 16:52:24 +0000967}
968
969
970StateType
971Process::WaitForState
972(
973 const TimeValue *timeout,
974 const StateType *match_states, const uint32_t num_match_states
975)
976{
977 EventSP event_sp;
978 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000979 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000980 while (state != eStateInvalid)
981 {
Greg Claytond8c62532010-10-07 04:19:01 +0000982 // If we are exited or detached, we won't ever get back to any
983 // other valid state...
984 if (state == eStateDetached || state == eStateExited)
985 return state;
986
Chris Lattner24943d22010-06-08 16:52:24 +0000987 state = WaitForStateChangedEvents (timeout, event_sp);
988
989 for (i=0; i<num_match_states; ++i)
990 {
991 if (match_states[i] == state)
992 return state;
993 }
994 }
995 return state;
996}
997
Jim Ingham63e24d72010-10-11 23:53:14 +0000998bool
999Process::HijackProcessEvents (Listener *listener)
1000{
1001 if (listener != NULL)
1002 {
1003 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
1004 }
1005 else
1006 return false;
1007}
1008
1009void
1010Process::RestoreProcessEvents ()
1011{
1012 RestoreBroadcaster();
1013}
1014
Jim Inghamf9f40c22011-02-08 05:20:59 +00001015bool
1016Process::HijackPrivateProcessEvents (Listener *listener)
1017{
1018 if (listener != NULL)
1019 {
1020 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
1021 }
1022 else
1023 return false;
1024}
1025
1026void
1027Process::RestorePrivateProcessEvents ()
1028{
1029 m_private_state_broadcaster.RestoreBroadcaster();
1030}
1031
Chris Lattner24943d22010-06-08 16:52:24 +00001032StateType
1033Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1034{
Greg Claytone005f2c2010-11-06 01:53:30 +00001035 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001036
1037 if (log)
1038 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1039
1040 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001041 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1042 this,
1043 eBroadcastBitStateChanged,
1044 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +00001045 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1046
1047 if (log)
1048 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1049 __FUNCTION__,
1050 timeout,
1051 StateAsCString(state));
1052 return state;
1053}
1054
1055Event *
1056Process::PeekAtStateChangedEvents ()
1057{
Greg Claytone005f2c2010-11-06 01:53:30 +00001058 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001059
1060 if (log)
1061 log->Printf ("Process::%s...", __FUNCTION__);
1062
1063 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001064 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1065 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001066 if (log)
1067 {
1068 if (event_ptr)
1069 {
1070 log->Printf ("Process::%s (event_ptr) => %s",
1071 __FUNCTION__,
1072 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1073 }
1074 else
1075 {
1076 log->Printf ("Process::%s no events found",
1077 __FUNCTION__);
1078 }
1079 }
1080 return event_ptr;
1081}
1082
1083StateType
1084Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1085{
Greg Claytone005f2c2010-11-06 01:53:30 +00001086 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001087
1088 if (log)
1089 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1090
1091 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001092 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1093 &m_private_state_broadcaster,
1094 eBroadcastBitStateChanged,
1095 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +00001096 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1097
1098 // This is a bit of a hack, but when we wait here we could very well return
1099 // to the command-line, and that could disable the log, which would render the
1100 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001101 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001102 {
1103 if (state == eStateInvalid)
1104 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1105 else
1106 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1107 }
Chris Lattner24943d22010-06-08 16:52:24 +00001108 return state;
1109}
1110
1111bool
1112Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1113{
Greg Claytone005f2c2010-11-06 01:53:30 +00001114 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001115
1116 if (log)
1117 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1118
1119 if (control_only)
1120 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1121 else
1122 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1123}
1124
1125bool
1126Process::IsRunning () const
1127{
1128 return StateIsRunningState (m_public_state.GetValue());
1129}
1130
1131int
1132Process::GetExitStatus ()
1133{
1134 if (m_public_state.GetValue() == eStateExited)
1135 return m_exit_status;
1136 return -1;
1137}
1138
Greg Clayton638351a2010-12-04 00:10:17 +00001139
Chris Lattner24943d22010-06-08 16:52:24 +00001140const char *
1141Process::GetExitDescription ()
1142{
1143 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1144 return m_exit_string.c_str();
1145 return NULL;
1146}
1147
Greg Clayton72e1c782011-01-22 23:43:18 +00001148bool
Chris Lattner24943d22010-06-08 16:52:24 +00001149Process::SetExitStatus (int status, const char *cstr)
1150{
Greg Clayton68ca8232011-01-25 02:58:48 +00001151 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1152 if (log)
1153 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1154 status, status,
1155 cstr ? "\"" : "",
1156 cstr ? cstr : "NULL",
1157 cstr ? "\"" : "");
1158
Greg Clayton72e1c782011-01-22 23:43:18 +00001159 // We were already in the exited state
1160 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001161 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001162 if (log)
1163 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001164 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001165 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001166
1167 m_exit_status = status;
1168 if (cstr)
1169 m_exit_string = cstr;
1170 else
1171 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001172
Greg Clayton72e1c782011-01-22 23:43:18 +00001173 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001174
Greg Clayton72e1c782011-01-22 23:43:18 +00001175 SetPrivateState (eStateExited);
1176 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001177}
1178
1179// This static callback can be used to watch for local child processes on
1180// the current host. The the child process exits, the process will be
1181// found in the global target list (we want to be completely sure that the
1182// lldb_private::Process doesn't go away before we can deliver the signal.
1183bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001184Process::SetProcessExitStatus (void *callback_baton,
1185 lldb::pid_t pid,
1186 bool exited,
1187 int signo, // Zero for no signal
1188 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001189)
1190{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001191 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1192 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00001193 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001194 callback_baton,
1195 pid,
1196 exited,
1197 signo,
1198 exit_status);
1199
1200 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001201 {
Greg Clayton63094e02010-06-23 01:19:29 +00001202 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001203 if (target_sp)
1204 {
1205 ProcessSP process_sp (target_sp->GetProcessSP());
1206 if (process_sp)
1207 {
1208 const char *signal_cstr = NULL;
1209 if (signo)
1210 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1211
1212 process_sp->SetExitStatus (exit_status, signal_cstr);
1213 }
1214 }
1215 return true;
1216 }
1217 return false;
1218}
1219
1220
Greg Clayton37f962e2011-08-22 02:49:39 +00001221void
1222Process::UpdateThreadListIfNeeded ()
1223{
1224 const uint32_t stop_id = GetStopID();
1225 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1226 {
Greg Clayton20206082011-11-17 01:23:07 +00001227 const StateType state = GetPrivateState();
1228 if (StateIsStoppedState (state, true))
1229 {
1230 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001231 // m_thread_list does have its own mutex, but we need to
1232 // hold onto the mutex between the call to UpdateThreadList(...)
1233 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001234 ThreadList new_thread_list(this);
1235 // Always update the thread list with the protocol specific
1236 // thread list
1237 UpdateThreadList (m_thread_list, new_thread_list);
1238 OperatingSystem *os = GetOperatingSystem ();
1239 if (os)
1240 os->UpdateThreadList (m_thread_list, new_thread_list);
1241 m_thread_list.Update (new_thread_list);
1242 m_thread_list.SetStopID (stop_id);
1243 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001244 }
1245}
1246
Chris Lattner24943d22010-06-08 16:52:24 +00001247uint32_t
1248Process::GetNextThreadIndexID ()
1249{
1250 return ++m_thread_index_id;
1251}
1252
1253StateType
1254Process::GetState()
1255{
1256 // If any other threads access this we will need a mutex for it
1257 return m_public_state.GetValue ();
1258}
1259
1260void
1261Process::SetPublicState (StateType new_state)
1262{
Greg Clayton68ca8232011-01-25 02:58:48 +00001263 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001264 if (log)
1265 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1266 m_public_state.SetValue (new_state);
1267}
1268
1269StateType
1270Process::GetPrivateState ()
1271{
1272 return m_private_state.GetValue();
1273}
1274
1275void
1276Process::SetPrivateState (StateType new_state)
1277{
Greg Clayton68ca8232011-01-25 02:58:48 +00001278 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001279 bool state_changed = false;
1280
1281 if (log)
1282 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1283
1284 Mutex::Locker locker(m_private_state.GetMutex());
1285
1286 const StateType old_state = m_private_state.GetValueNoLock ();
1287 state_changed = old_state != new_state;
1288 if (state_changed)
1289 {
1290 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001291 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001292 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001293 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001294 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001295 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001296 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001297 }
1298 // Use our target to get a shared pointer to ourselves...
1299 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1300 }
1301 else
1302 {
1303 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001304 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001305 }
1306}
1307
Jim Ingham0296fe72011-11-08 03:00:11 +00001308void
1309Process::SetRunningUserExpression (bool on)
1310{
1311 m_mod_id.SetRunningUserExpression (on);
1312}
1313
Chris Lattner24943d22010-06-08 16:52:24 +00001314addr_t
1315Process::GetImageInfoAddress()
1316{
1317 return LLDB_INVALID_ADDRESS;
1318}
1319
Greg Clayton0baa3942010-11-04 01:54:29 +00001320//----------------------------------------------------------------------
1321// LoadImage
1322//
1323// This function provides a default implementation that works for most
1324// unix variants. Any Process subclasses that need to do shared library
1325// loading differently should override LoadImage and UnloadImage and
1326// do what is needed.
1327//----------------------------------------------------------------------
1328uint32_t
1329Process::LoadImage (const FileSpec &image_spec, Error &error)
1330{
1331 DynamicLoader *loader = GetDynamicLoader();
1332 if (loader)
1333 {
1334 error = loader->CanLoadImage();
1335 if (error.Fail())
1336 return LLDB_INVALID_IMAGE_TOKEN;
1337 }
1338
1339 if (error.Success())
1340 {
1341 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001342
1343 if (thread_sp)
1344 {
1345 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1346
1347 if (frame_sp)
1348 {
1349 ExecutionContext exe_ctx;
1350 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001351 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001352 StreamString expr;
1353 char path[PATH_MAX];
1354 image_spec.GetPath(path, sizeof(path));
1355 expr.Printf("dlopen (\"%s\", 2)", path);
1356 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001357 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001358 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chenb14ec342011-09-09 00:01:43 +00001359 error = result_valobj_sp->GetError();
1360 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001361 {
1362 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001363 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001364 {
1365 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1366 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1367 {
1368 uint32_t image_token = m_image_tokens.size();
1369 m_image_tokens.push_back (image_ptr);
1370 return image_token;
1371 }
1372 }
1373 }
1374 }
1375 }
1376 }
1377 return LLDB_INVALID_IMAGE_TOKEN;
1378}
1379
1380//----------------------------------------------------------------------
1381// UnloadImage
1382//
1383// This function provides a default implementation that works for most
1384// unix variants. Any Process subclasses that need to do shared library
1385// loading differently should override LoadImage and UnloadImage and
1386// do what is needed.
1387//----------------------------------------------------------------------
1388Error
1389Process::UnloadImage (uint32_t image_token)
1390{
1391 Error error;
1392 if (image_token < m_image_tokens.size())
1393 {
1394 const addr_t image_addr = m_image_tokens[image_token];
1395 if (image_addr == LLDB_INVALID_ADDRESS)
1396 {
1397 error.SetErrorString("image already unloaded");
1398 }
1399 else
1400 {
1401 DynamicLoader *loader = GetDynamicLoader();
1402 if (loader)
1403 error = loader->CanLoadImage();
1404
1405 if (error.Success())
1406 {
1407 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001408
1409 if (thread_sp)
1410 {
1411 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1412
1413 if (frame_sp)
1414 {
1415 ExecutionContext exe_ctx;
1416 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001417 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001418 StreamString expr;
1419 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1420 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001421 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001422 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +00001423 if (result_valobj_sp->GetError().Success())
1424 {
1425 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001426 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001427 {
1428 if (scalar.UInt(1))
1429 {
1430 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1431 }
1432 else
1433 {
1434 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1435 }
1436 }
1437 }
1438 else
1439 {
1440 error = result_valobj_sp->GetError();
1441 }
1442 }
1443 }
1444 }
1445 }
1446 }
1447 else
1448 {
1449 error.SetErrorString("invalid image token");
1450 }
1451 return error;
1452}
1453
Greg Clayton75906e42011-05-11 18:39:18 +00001454const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001455Process::GetABI()
1456{
Greg Clayton75906e42011-05-11 18:39:18 +00001457 if (!m_abi_sp)
1458 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1459 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001460}
1461
Jim Ingham642036f2010-09-23 02:01:19 +00001462LanguageRuntime *
1463Process::GetLanguageRuntime(lldb::LanguageType language)
1464{
1465 LanguageRuntimeCollection::iterator pos;
1466 pos = m_language_runtimes.find (language);
1467 if (pos == m_language_runtimes.end())
1468 {
1469 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1470
1471 m_language_runtimes[language]
1472 = runtime;
1473 return runtime.get();
1474 }
1475 else
1476 return (*pos).second.get();
1477}
1478
1479CPPLanguageRuntime *
1480Process::GetCPPLanguageRuntime ()
1481{
1482 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1483 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1484 return static_cast<CPPLanguageRuntime *> (runtime);
1485 return NULL;
1486}
1487
1488ObjCLanguageRuntime *
1489Process::GetObjCLanguageRuntime ()
1490{
1491 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1492 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1493 return static_cast<ObjCLanguageRuntime *> (runtime);
1494 return NULL;
1495}
1496
Chris Lattner24943d22010-06-08 16:52:24 +00001497BreakpointSiteList &
1498Process::GetBreakpointSiteList()
1499{
1500 return m_breakpoint_site_list;
1501}
1502
1503const BreakpointSiteList &
1504Process::GetBreakpointSiteList() const
1505{
1506 return m_breakpoint_site_list;
1507}
1508
1509
1510void
1511Process::DisableAllBreakpointSites ()
1512{
1513 m_breakpoint_site_list.SetEnabledForAll (false);
1514}
1515
1516Error
1517Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1518{
1519 Error error (DisableBreakpointSiteByID (break_id));
1520
1521 if (error.Success())
1522 m_breakpoint_site_list.Remove(break_id);
1523
1524 return error;
1525}
1526
1527Error
1528Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1529{
1530 Error error;
1531 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1532 if (bp_site_sp)
1533 {
1534 if (bp_site_sp->IsEnabled())
1535 error = DisableBreakpoint (bp_site_sp.get());
1536 }
1537 else
1538 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001539 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001540 }
1541
1542 return error;
1543}
1544
1545Error
1546Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1547{
1548 Error error;
1549 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1550 if (bp_site_sp)
1551 {
1552 if (!bp_site_sp->IsEnabled())
1553 error = EnableBreakpoint (bp_site_sp.get());
1554 }
1555 else
1556 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001557 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001558 }
1559 return error;
1560}
1561
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001562lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001563Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001564{
Greg Clayton265ab332011-05-19 18:17:41 +00001565 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001566 if (load_addr != LLDB_INVALID_ADDRESS)
1567 {
1568 BreakpointSiteSP bp_site_sp;
1569
1570 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1571 // create a new breakpoint site and add it.
1572
1573 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1574
1575 if (bp_site_sp)
1576 {
1577 bp_site_sp->AddOwner (owner);
1578 owner->SetBreakpointSite (bp_site_sp);
1579 return bp_site_sp->GetID();
1580 }
1581 else
1582 {
1583 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1584 if (bp_site_sp)
1585 {
1586 if (EnableBreakpoint (bp_site_sp.get()).Success())
1587 {
1588 owner->SetBreakpointSite (bp_site_sp);
1589 return m_breakpoint_site_list.Add (bp_site_sp);
1590 }
1591 }
1592 }
1593 }
1594 // We failed to enable the breakpoint
1595 return LLDB_INVALID_BREAK_ID;
1596
1597}
1598
1599void
1600Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1601{
1602 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1603 if (num_owners == 0)
1604 {
1605 DisableBreakpoint(bp_site_sp.get());
1606 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1607 }
1608}
1609
1610
1611size_t
1612Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1613{
1614 size_t bytes_removed = 0;
1615 addr_t intersect_addr;
1616 size_t intersect_size;
1617 size_t opcode_offset;
1618 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001619 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001620 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001621
Jim Ingham82820f92011-06-29 19:42:28 +00001622 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001623 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001624 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001625 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001626 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001627 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001628 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001629 {
1630 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1631 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001632 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001633 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001634 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001635 }
Chris Lattner24943d22010-06-08 16:52:24 +00001636 }
1637 }
1638 }
1639 return bytes_removed;
1640}
1641
1642
Greg Claytonb1888f22011-03-19 01:12:21 +00001643
1644size_t
1645Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1646{
1647 PlatformSP platform_sp (m_target.GetPlatform());
1648 if (platform_sp)
1649 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1650 return 0;
1651}
1652
Chris Lattner24943d22010-06-08 16:52:24 +00001653Error
1654Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1655{
1656 Error error;
1657 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001658 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001659 const addr_t bp_addr = bp_site->GetLoadAddress();
1660 if (log)
1661 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1662 if (bp_site->IsEnabled())
1663 {
1664 if (log)
1665 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1666 return error;
1667 }
1668
1669 if (bp_addr == LLDB_INVALID_ADDRESS)
1670 {
1671 error.SetErrorString("BreakpointSite contains an invalid load address.");
1672 return error;
1673 }
1674 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1675 // trap for the breakpoint site
1676 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1677
1678 if (bp_opcode_size == 0)
1679 {
Greg Clayton9c236732011-10-26 00:56:27 +00001680 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001681 }
1682 else
1683 {
1684 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1685
1686 if (bp_opcode_bytes == NULL)
1687 {
1688 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1689 return error;
1690 }
1691
1692 // Save the original opcode by reading it
1693 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1694 {
1695 // Write a software breakpoint in place of the original opcode
1696 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1697 {
1698 uint8_t verify_bp_opcode_bytes[64];
1699 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1700 {
1701 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1702 {
1703 bp_site->SetEnabled(true);
1704 bp_site->SetType (BreakpointSite::eSoftware);
1705 if (log)
1706 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1707 bp_site->GetID(),
1708 (uint64_t)bp_addr);
1709 }
1710 else
Greg Clayton9c236732011-10-26 00:56:27 +00001711 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00001712 }
1713 else
1714 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1715 }
1716 else
1717 error.SetErrorString("Unable to write breakpoint trap to memory.");
1718 }
1719 else
1720 error.SetErrorString("Unable to read memory at breakpoint address.");
1721 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001722 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001723 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1724 bp_site->GetID(),
1725 (uint64_t)bp_addr,
1726 error.AsCString());
1727 return error;
1728}
1729
1730Error
1731Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1732{
1733 Error error;
1734 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001735 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001736 addr_t bp_addr = bp_site->GetLoadAddress();
1737 lldb::user_id_t breakID = bp_site->GetID();
1738 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001739 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001740
1741 if (bp_site->IsHardware())
1742 {
1743 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1744 }
1745 else if (bp_site->IsEnabled())
1746 {
1747 const size_t break_op_size = bp_site->GetByteSize();
1748 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1749 if (break_op_size > 0)
1750 {
1751 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001752 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001753 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001754 bool break_op_found = false;
1755
1756 // Read the breakpoint opcode
1757 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1758 {
1759 bool verify = false;
1760 // Make sure we have the a breakpoint opcode exists at this address
1761 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1762 {
1763 break_op_found = true;
1764 // We found a valid breakpoint opcode at this address, now restore
1765 // the saved opcode.
1766 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1767 {
1768 verify = true;
1769 }
1770 else
1771 error.SetErrorString("Memory write failed when restoring original opcode.");
1772 }
1773 else
1774 {
1775 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1776 // Set verify to true and so we can check if the original opcode has already been restored
1777 verify = true;
1778 }
1779
1780 if (verify)
1781 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001782 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001783 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001784 // Verify that our original opcode made it back to the inferior
1785 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1786 {
1787 // compare the memory we just read with the original opcode
1788 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1789 {
1790 // SUCCESS
1791 bp_site->SetEnabled(false);
1792 if (log)
1793 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1794 return error;
1795 }
1796 else
1797 {
1798 if (break_op_found)
1799 error.SetErrorString("Failed to restore original opcode.");
1800 }
1801 }
1802 else
1803 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1804 }
1805 }
1806 else
1807 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1808 }
1809 }
1810 else
1811 {
1812 if (log)
1813 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1814 return error;
1815 }
1816
1817 if (log)
1818 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1819 bp_site->GetID(),
1820 (uint64_t)bp_addr,
1821 error.AsCString());
1822 return error;
1823
1824}
1825
Greg Claytonfd119992011-01-07 06:08:19 +00001826// Comment out line below to disable memory caching
1827#define ENABLE_MEMORY_CACHING
1828// Uncomment to verify memory caching works after making changes to caching code
1829//#define VERIFY_MEMORY_READS
1830
1831#if defined (ENABLE_MEMORY_CACHING)
1832
1833#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001834
1835size_t
1836Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1837{
Greg Claytonfd119992011-01-07 06:08:19 +00001838 // Memory caching is enabled, with debug verification
1839 if (buf && size)
1840 {
1841 // Uncomment the line below to make sure memory caching is working.
1842 // I ran this through the test suite and got no assertions, so I am
1843 // pretty confident this is working well. If any changes are made to
1844 // memory caching, uncomment the line below and test your changes!
1845
1846 // Verify all memory reads by using the cache first, then redundantly
1847 // reading the same memory from the inferior and comparing to make sure
1848 // everything is exactly the same.
1849 std::string verify_buf (size, '\0');
1850 assert (verify_buf.size() == size);
1851 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1852 Error verify_error;
1853 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1854 assert (cache_bytes_read == verify_bytes_read);
1855 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1856 assert (verify_error.Success() == error.Success());
1857 return cache_bytes_read;
1858 }
1859 return 0;
1860}
1861
1862#else // #if defined (VERIFY_MEMORY_READS)
1863
1864size_t
1865Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1866{
1867 // Memory caching enabled, no verification
Greg Clayton613b8732011-05-17 03:37:42 +00001868 return m_memory_cache.Read (addr, buf, size, error);
Greg Claytonfd119992011-01-07 06:08:19 +00001869}
1870
1871#endif // #else for #if defined (VERIFY_MEMORY_READS)
1872
1873#else // #if defined (ENABLE_MEMORY_CACHING)
1874
1875size_t
1876Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1877{
1878 // Memory caching is disabled
1879 return ReadMemoryFromInferior (addr, buf, size, error);
1880}
1881
1882#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1883
1884
1885size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00001886Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001887{
1888 size_t total_cstr_len = 0;
1889 if (dst && dst_max_len)
1890 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00001891 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00001892 // NULL out everything just to be safe
1893 memset (dst, 0, dst_max_len);
1894 Error error;
1895 addr_t curr_addr = addr;
1896 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1897 size_t bytes_left = dst_max_len - 1;
1898 char *curr_dst = dst;
1899
1900 while (bytes_left > 0)
1901 {
1902 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1903 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1904 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1905
1906 if (bytes_read == 0)
1907 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00001908 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00001909 dst[total_cstr_len] = '\0';
1910 break;
1911 }
1912 const size_t len = strlen(curr_dst);
1913
1914 total_cstr_len += len;
1915
1916 if (len < bytes_to_read)
1917 break;
1918
1919 curr_dst += bytes_read;
1920 curr_addr += bytes_read;
1921 bytes_left -= bytes_read;
1922 }
1923 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00001924 else
1925 {
1926 if (dst == NULL)
1927 result_error.SetErrorString("invalid arguments");
1928 else
1929 result_error.Clear();
1930 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001931 return total_cstr_len;
1932}
1933
1934size_t
Greg Claytonfd119992011-01-07 06:08:19 +00001935Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1936{
Chris Lattner24943d22010-06-08 16:52:24 +00001937 if (buf == NULL || size == 0)
1938 return 0;
1939
1940 size_t bytes_read = 0;
1941 uint8_t *bytes = (uint8_t *)buf;
1942
1943 while (bytes_read < size)
1944 {
1945 const size_t curr_size = size - bytes_read;
1946 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1947 bytes + bytes_read,
1948 curr_size,
1949 error);
1950 bytes_read += curr_bytes_read;
1951 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1952 break;
1953 }
1954
1955 // Replace any software breakpoint opcodes that fall into this range back
1956 // into "buf" before we return
1957 if (bytes_read > 0)
1958 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1959 return bytes_read;
1960}
1961
Greg Claytonf72fdee2010-12-16 20:01:20 +00001962uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00001963Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00001964{
Greg Claytonc0fa5332011-05-22 22:46:53 +00001965 Scalar scalar;
1966 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1967 return scalar.ULongLong(fail_value);
1968 return fail_value;
1969}
1970
1971addr_t
1972Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1973{
1974 Scalar scalar;
1975 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1976 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1977 return LLDB_INVALID_ADDRESS;
1978}
1979
1980
1981bool
1982Process::WritePointerToMemory (lldb::addr_t vm_addr,
1983 lldb::addr_t ptr_value,
1984 Error &error)
1985{
1986 Scalar scalar;
1987 const uint32_t addr_byte_size = GetAddressByteSize();
1988 if (addr_byte_size <= 4)
1989 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001990 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00001991 scalar = ptr_value;
1992 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00001993}
1994
Chris Lattner24943d22010-06-08 16:52:24 +00001995size_t
1996Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1997{
1998 size_t bytes_written = 0;
1999 const uint8_t *bytes = (const uint8_t *)buf;
2000
2001 while (bytes_written < size)
2002 {
2003 const size_t curr_size = size - bytes_written;
2004 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2005 bytes + bytes_written,
2006 curr_size,
2007 error);
2008 bytes_written += curr_bytes_written;
2009 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2010 break;
2011 }
2012 return bytes_written;
2013}
2014
2015size_t
2016Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2017{
Greg Claytonfd119992011-01-07 06:08:19 +00002018#if defined (ENABLE_MEMORY_CACHING)
2019 m_memory_cache.Flush (addr, size);
2020#endif
2021
Chris Lattner24943d22010-06-08 16:52:24 +00002022 if (buf == NULL || size == 0)
2023 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002024
Jim Ingham21f37ad2011-08-09 02:12:22 +00002025 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002026
Chris Lattner24943d22010-06-08 16:52:24 +00002027 // We need to write any data that would go where any current software traps
2028 // (enabled software breakpoints) any software traps (breakpoints) that we
2029 // may have placed in our tasks memory.
2030
2031 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2032 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2033
2034 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002035 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002036
2037 BreakpointSiteList::collection::const_iterator pos;
2038 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002039 addr_t intersect_addr = 0;
2040 size_t intersect_size = 0;
2041 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002042 const uint8_t *ubuf = (const uint8_t *)buf;
2043
2044 for (pos = iter; pos != end; ++pos)
2045 {
2046 BreakpointSiteSP bp;
2047 bp = pos->second;
2048
2049 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2050 assert(addr <= intersect_addr && intersect_addr < addr + size);
2051 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2052 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2053
2054 // Check for bytes before this breakpoint
2055 const addr_t curr_addr = addr + bytes_written;
2056 if (intersect_addr > curr_addr)
2057 {
2058 // There are some bytes before this breakpoint that we need to
2059 // just write to memory
2060 size_t curr_size = intersect_addr - curr_addr;
2061 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2062 ubuf + bytes_written,
2063 curr_size,
2064 error);
2065 bytes_written += curr_bytes_written;
2066 if (curr_bytes_written != curr_size)
2067 {
2068 // We weren't able to write all of the requested bytes, we
2069 // are done looping and will return the number of bytes that
2070 // we have written so far.
2071 break;
2072 }
2073 }
2074
2075 // Now write any bytes that would cover up any software breakpoints
2076 // directly into the breakpoint opcode buffer
2077 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2078 bytes_written += intersect_size;
2079 }
2080
2081 // Write any remaining bytes after the last breakpoint if we have any left
2082 if (bytes_written < size)
2083 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2084 ubuf + bytes_written,
2085 size - bytes_written,
2086 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002087
Chris Lattner24943d22010-06-08 16:52:24 +00002088 return bytes_written;
2089}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002090
2091size_t
2092Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2093{
2094 if (byte_size == UINT32_MAX)
2095 byte_size = scalar.GetByteSize();
2096 if (byte_size > 0)
2097 {
2098 uint8_t buf[32];
2099 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2100 if (mem_size > 0)
2101 return WriteMemory(addr, buf, mem_size, error);
2102 else
2103 error.SetErrorString ("failed to get scalar as memory data");
2104 }
2105 else
2106 {
2107 error.SetErrorString ("invalid scalar value");
2108 }
2109 return 0;
2110}
2111
2112size_t
2113Process::ReadScalarIntegerFromMemory (addr_t addr,
2114 uint32_t byte_size,
2115 bool is_signed,
2116 Scalar &scalar,
2117 Error &error)
2118{
2119 uint64_t uval;
2120
2121 if (byte_size <= sizeof(uval))
2122 {
2123 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2124 if (bytes_read == byte_size)
2125 {
2126 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2127 uint32_t offset = 0;
2128 if (byte_size <= 4)
2129 scalar = data.GetMaxU32 (&offset, byte_size);
2130 else
2131 scalar = data.GetMaxU64 (&offset, byte_size);
2132
2133 if (is_signed)
2134 scalar.SignExtend(byte_size * 8);
2135 return bytes_read;
2136 }
2137 }
2138 else
2139 {
2140 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2141 }
2142 return 0;
2143}
2144
Greg Clayton613b8732011-05-17 03:37:42 +00002145#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002146addr_t
2147Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2148{
Jim Inghame6bd1422011-06-20 17:32:44 +00002149 if (GetPrivateState() != eStateStopped)
2150 return LLDB_INVALID_ADDRESS;
2151
Greg Clayton613b8732011-05-17 03:37:42 +00002152#if defined (USE_ALLOCATE_MEMORY_CACHE)
2153 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2154#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002155 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2156 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2157 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002158 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002159 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002160 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002161 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002162 m_mod_id.GetStopID(),
2163 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002164 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002165#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002166}
2167
Sean Callanan6cf6c472011-09-20 23:01:51 +00002168bool
2169Process::CanJIT ()
2170{
Sean Callanan04200f62012-02-14 22:50:38 +00002171 if (m_can_jit == eCanJITDontKnow)
2172 {
2173 Error err;
2174
2175 uint64_t allocated_memory = AllocateMemory(8,
2176 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2177 err);
2178
2179 if (err.Success())
2180 m_can_jit = eCanJITYes;
2181 else
2182 m_can_jit = eCanJITNo;
2183
2184 DeallocateMemory (allocated_memory);
2185 }
2186
Sean Callanan6cf6c472011-09-20 23:01:51 +00002187 return m_can_jit == eCanJITYes;
2188}
2189
2190void
2191Process::SetCanJIT (bool can_jit)
2192{
2193 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2194}
2195
Chris Lattner24943d22010-06-08 16:52:24 +00002196Error
2197Process::DeallocateMemory (addr_t ptr)
2198{
Greg Clayton613b8732011-05-17 03:37:42 +00002199 Error error;
2200#if defined (USE_ALLOCATE_MEMORY_CACHE)
2201 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2202 {
2203 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2204 }
2205#else
2206 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002207
2208 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2209 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002210 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002211 ptr,
2212 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002213 m_mod_id.GetStopID(),
2214 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002215#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002216 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002217}
2218
Greg Claytonb5a8f142012-02-05 02:38:54 +00002219ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002220Process::ReadModuleFromMemory (const FileSpec& file_spec,
2221 lldb::addr_t header_addr,
2222 bool add_image_to_target,
2223 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002224{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002225 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002226 if (module_sp)
2227 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002228 Error error;
2229 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2230 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002231 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002232 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002233 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002234 m_target.GetImages().Append(module_sp);
2235 if (load_sections_in_target)
2236 {
2237 bool changed = false;
2238 module_sp->SetLoadAddress (m_target, 0, changed);
2239 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002240 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002241 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002242 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002243 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002244 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002245}
Chris Lattner24943d22010-06-08 16:52:24 +00002246
2247Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002248Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002249{
2250 Error error;
2251 error.SetErrorString("watchpoints are not supported");
2252 return error;
2253}
2254
2255Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002256Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002257{
2258 Error error;
2259 error.SetErrorString("watchpoints are not supported");
2260 return error;
2261}
2262
2263StateType
2264Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2265{
2266 StateType state;
2267 // Now wait for the process to launch and return control to us, and then
2268 // call DidLaunch:
2269 while (1)
2270 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002271 event_sp.reset();
2272 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2273
Greg Clayton20206082011-11-17 01:23:07 +00002274 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002275 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002276
2277 // If state is invalid, then we timed out
2278 if (state == eStateInvalid)
2279 break;
2280
2281 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002282 HandlePrivateEvent (event_sp);
2283 }
2284 return state;
2285}
2286
2287Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002288Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002289{
2290 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002291 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002292 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002293 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002294 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002295
Greg Clayton5beb99d2011-08-11 02:48:45 +00002296 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002297 if (exe_module)
2298 {
Greg Clayton180546b2011-04-30 01:09:13 +00002299 char local_exec_file_path[PATH_MAX];
2300 char platform_exec_file_path[PATH_MAX];
2301 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2302 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002303 if (exe_module->GetFileSpec().Exists())
2304 {
Greg Claytona2f74232011-02-24 22:24:29 +00002305 if (PrivateStateThreadIsValid ())
2306 PausePrivateStateThread ();
2307
Chris Lattner24943d22010-06-08 16:52:24 +00002308 error = WillLaunch (exe_module);
2309 if (error.Success())
2310 {
Greg Claytond8c62532010-10-07 04:19:01 +00002311 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002312 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002313
2314 // Now launch using these arguments.
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002315 error = DoLaunch (exe_module, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +00002316
2317 if (error.Fail())
2318 {
2319 if (GetID() != LLDB_INVALID_PROCESS_ID)
2320 {
2321 SetID (LLDB_INVALID_PROCESS_ID);
2322 const char *error_string = error.AsCString();
2323 if (error_string == NULL)
2324 error_string = "launch failed";
2325 SetExitStatus (-1, error_string);
2326 }
2327 }
2328 else
2329 {
2330 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002331 TimeValue timeout_time;
2332 timeout_time = TimeValue::Now();
2333 timeout_time.OffsetWithSeconds(10);
2334 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002335
Greg Clayton49859592011-06-22 01:42:17 +00002336 if (state == eStateInvalid || event_sp.get() == NULL)
2337 {
2338 // We were able to launch the process, but we failed to
2339 // catch the initial stop.
2340 SetExitStatus (0, "failed to catch stop after launch");
2341 Destroy();
2342 }
2343 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002344 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002345
Chris Lattner24943d22010-06-08 16:52:24 +00002346 DidLaunch ();
2347
Greg Clayton9ce95382012-02-13 23:10:39 +00002348 DynamicLoader *dyld = GetDynamicLoader ();
2349 if (dyld)
2350 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002351
Greg Clayton37f962e2011-08-22 02:49:39 +00002352 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002353 // This delays passing the stopped event to listeners till DidLaunch gets
2354 // a chance to complete...
2355 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002356
2357 if (PrivateStateThreadIsValid ())
2358 ResumePrivateStateThread ();
2359 else
2360 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002361 }
2362 else if (state == eStateExited)
2363 {
2364 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2365 // not likely to work, and return an invalid pid.
2366 HandlePrivateEvent (event_sp);
2367 }
2368 }
2369 }
2370 }
2371 else
2372 {
Greg Clayton9c236732011-10-26 00:56:27 +00002373 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002374 }
2375 }
2376 return error;
2377}
2378
Greg Clayton46c9a352012-02-09 06:16:32 +00002379
2380Error
2381Process::LoadCore ()
2382{
2383 Error error = DoLoadCore();
2384 if (error.Success())
2385 {
2386 if (PrivateStateThreadIsValid ())
2387 ResumePrivateStateThread ();
2388 else
2389 StartPrivateStateThread ();
2390
Greg Clayton9ce95382012-02-13 23:10:39 +00002391 DynamicLoader *dyld = GetDynamicLoader ();
2392 if (dyld)
2393 dyld->DidAttach();
2394
2395 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002396 // We successfully loaded a core file, now pretend we stopped so we can
2397 // show all of the threads in the core file and explore the crashed
2398 // state.
2399 SetPrivateState (eStateStopped);
2400
2401 }
2402 return error;
2403}
2404
Greg Clayton9ce95382012-02-13 23:10:39 +00002405DynamicLoader *
2406Process::GetDynamicLoader ()
2407{
2408 if (m_dyld_ap.get() == NULL)
2409 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2410 return m_dyld_ap.get();
2411}
Greg Clayton46c9a352012-02-09 06:16:32 +00002412
2413
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002414Process::NextEventAction::EventActionResult
2415Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002416{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002417 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2418 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002419 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002420 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002421 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002422 return eEventActionRetry;
2423
2424 case eStateStopped:
2425 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002426 {
2427 // During attach, prior to sending the eStateStopped event,
2428 // lldb_private::Process subclasses must set the process must set
2429 // the new process ID.
2430 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2431 if (m_exec_count > 0)
2432 {
2433 --m_exec_count;
2434 m_process->Resume();
2435 return eEventActionRetry;
2436 }
2437 else
2438 {
2439 m_process->CompleteAttach ();
2440 return eEventActionSuccess;
2441 }
2442 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002443 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002444
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002445 default:
2446 case eStateExited:
2447 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002448 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002449 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002450
2451 m_exit_string.assign ("No valid Process");
2452 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002453}
Chris Lattner24943d22010-06-08 16:52:24 +00002454
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002455Process::NextEventAction::EventActionResult
2456Process::AttachCompletionHandler::HandleBeingInterrupted()
2457{
2458 return eEventActionSuccess;
2459}
2460
2461const char *
2462Process::AttachCompletionHandler::GetExitString ()
2463{
2464 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002465}
2466
2467Error
Greg Clayton527154d2011-11-15 03:53:30 +00002468Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002469{
Chris Lattner24943d22010-06-08 16:52:24 +00002470 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002471 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002472 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002473 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002474
Greg Clayton527154d2011-11-15 03:53:30 +00002475 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002476 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002477 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002478 {
Greg Clayton527154d2011-11-15 03:53:30 +00002479 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002480
Greg Clayton527154d2011-11-15 03:53:30 +00002481 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002482 {
Greg Clayton527154d2011-11-15 03:53:30 +00002483 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2484
2485 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002486 {
Greg Clayton527154d2011-11-15 03:53:30 +00002487 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2488 if (error.Success())
2489 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002490 m_should_detach = true;
2491
Greg Clayton527154d2011-11-15 03:53:30 +00002492 SetPublicState (eStateAttaching);
2493 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2494 if (error.Fail())
2495 {
2496 if (GetID() != LLDB_INVALID_PROCESS_ID)
2497 {
2498 SetID (LLDB_INVALID_PROCESS_ID);
2499 if (error.AsCString() == NULL)
2500 error.SetErrorString("attach failed");
2501
2502 SetExitStatus(-1, error.AsCString());
2503 }
2504 }
2505 else
2506 {
2507 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2508 StartPrivateStateThread();
2509 }
2510 return error;
2511 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002512 }
Greg Clayton527154d2011-11-15 03:53:30 +00002513 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002514 {
Greg Clayton527154d2011-11-15 03:53:30 +00002515 ProcessInstanceInfoList process_infos;
2516 PlatformSP platform_sp (m_target.GetPlatform ());
2517
2518 if (platform_sp)
2519 {
2520 ProcessInstanceInfoMatch match_info;
2521 match_info.GetProcessInfo() = attach_info;
2522 match_info.SetNameMatchType (eNameMatchEquals);
2523 platform_sp->FindProcesses (match_info, process_infos);
2524 const uint32_t num_matches = process_infos.GetSize();
2525 if (num_matches == 1)
2526 {
2527 attach_pid = process_infos.GetProcessIDAtIndex(0);
2528 // Fall through and attach using the above process ID
2529 }
2530 else
2531 {
2532 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2533 if (num_matches > 1)
2534 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2535 else
2536 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2537 }
2538 }
2539 else
2540 {
2541 error.SetErrorString ("invalid platform, can't find processes by name");
2542 return error;
2543 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002544 }
Chris Lattner24943d22010-06-08 16:52:24 +00002545 }
2546 else
Greg Clayton527154d2011-11-15 03:53:30 +00002547 {
2548 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002549 }
2550 }
Greg Clayton527154d2011-11-15 03:53:30 +00002551
2552 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002553 {
Greg Clayton527154d2011-11-15 03:53:30 +00002554 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002555 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002556 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002557 m_should_detach = true;
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002558 SetPublicState (eStateAttaching);
Greg Clayton527154d2011-11-15 03:53:30 +00002559
2560 error = DoAttachToProcessWithID (attach_pid);
2561 if (error.Success())
2562 {
2563
2564 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2565 StartPrivateStateThread();
2566 }
2567 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002568 {
2569 if (GetID() != LLDB_INVALID_PROCESS_ID)
2570 {
2571 SetID (LLDB_INVALID_PROCESS_ID);
2572 const char *error_string = error.AsCString();
2573 if (error_string == NULL)
2574 error_string = "attach failed";
2575
2576 SetExitStatus(-1, error_string);
2577 }
2578 }
Chris Lattner24943d22010-06-08 16:52:24 +00002579 }
2580 }
2581 return error;
2582}
2583
Greg Clayton527154d2011-11-15 03:53:30 +00002584//Error
2585//Process::Attach (const char *process_name, bool wait_for_launch)
2586//{
2587// m_abi_sp.reset();
2588// m_process_input_reader.reset();
2589//
2590// // Find the process and its architecture. Make sure it matches the architecture
2591// // of the current Target, and if not adjust it.
2592// Error error;
2593//
2594// if (!wait_for_launch)
2595// {
2596// ProcessInstanceInfoList process_infos;
2597// PlatformSP platform_sp (m_target.GetPlatform ());
2598// assert (platform_sp.get());
2599//
2600// if (platform_sp)
2601// {
2602// ProcessInstanceInfoMatch match_info;
2603// match_info.GetProcessInfo().SetName(process_name);
2604// match_info.SetNameMatchType (eNameMatchEquals);
2605// platform_sp->FindProcesses (match_info, process_infos);
2606// if (process_infos.GetSize() > 1)
2607// {
2608// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2609// }
2610// else if (process_infos.GetSize() == 0)
2611// {
2612// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2613// }
2614// }
2615// else
2616// {
2617// error.SetErrorString ("invalid platform");
2618// }
2619// }
2620//
2621// if (error.Success())
2622// {
2623// m_dyld_ap.reset();
2624// m_os_ap.reset();
2625//
2626// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2627// if (error.Success())
2628// {
2629// SetPublicState (eStateAttaching);
2630// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2631// if (error.Fail())
2632// {
2633// if (GetID() != LLDB_INVALID_PROCESS_ID)
2634// {
2635// SetID (LLDB_INVALID_PROCESS_ID);
2636// const char *error_string = error.AsCString();
2637// if (error_string == NULL)
2638// error_string = "attach failed";
2639//
2640// SetExitStatus(-1, error_string);
2641// }
2642// }
2643// else
2644// {
2645// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2646// StartPrivateStateThread();
2647// }
2648// }
2649// }
2650// return error;
2651//}
2652
Greg Clayton75c703d2011-02-16 04:46:07 +00002653void
2654Process::CompleteAttach ()
2655{
2656 // Let the process subclass figure out at much as it can about the process
2657 // before we go looking for a dynamic loader plug-in.
2658 DidAttach();
2659
Jim Ingham0d7f7772011-09-15 01:10:17 +00002660 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2661 // the same as the one we've already set, switch architectures.
2662 PlatformSP platform_sp (m_target.GetPlatform ());
2663 assert (platform_sp.get());
2664 if (platform_sp)
2665 {
2666 ProcessInstanceInfo process_info;
2667 platform_sp->GetProcessInfo (GetID(), process_info);
2668 const ArchSpec &process_arch = process_info.GetArchitecture();
2669 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2670 m_target.SetArchitecture (process_arch);
2671 }
2672
2673 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002674 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00002675 DynamicLoader *dyld = GetDynamicLoader ();
2676 if (dyld)
2677 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00002678
Greg Clayton37f962e2011-08-22 02:49:39 +00002679 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002680 // Figure out which one is the executable, and set that in our target:
2681 ModuleList &modules = m_target.GetImages();
2682
2683 size_t num_modules = modules.GetSize();
2684 for (int i = 0; i < num_modules; i++)
2685 {
2686 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002687 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002688 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002689 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton75c703d2011-02-16 04:46:07 +00002690 m_target.SetExecutableModule (module_sp, false);
2691 break;
2692 }
2693 }
2694}
2695
Chris Lattner24943d22010-06-08 16:52:24 +00002696Error
Greg Claytone71e2582011-02-04 01:58:07 +00002697Process::ConnectRemote (const char *remote_url)
2698{
Greg Claytone71e2582011-02-04 01:58:07 +00002699 m_abi_sp.reset();
2700 m_process_input_reader.reset();
2701
2702 // Find the process and its architecture. Make sure it matches the architecture
2703 // of the current Target, and if not adjust it.
2704
2705 Error error (DoConnectRemote (remote_url));
2706 if (error.Success())
2707 {
Greg Claytona2f74232011-02-24 22:24:29 +00002708 if (GetID() != LLDB_INVALID_PROCESS_ID)
2709 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002710 EventSP event_sp;
2711 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2712
2713 if (state == eStateStopped || state == eStateCrashed)
2714 {
2715 // If we attached and actually have a process on the other end, then
2716 // this ended up being the equivalent of an attach.
2717 CompleteAttach ();
2718
2719 // This delays passing the stopped event to listeners till
2720 // CompleteAttach gets a chance to complete...
2721 HandlePrivateEvent (event_sp);
2722
2723 }
Greg Claytona2f74232011-02-24 22:24:29 +00002724 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002725
2726 if (PrivateStateThreadIsValid ())
2727 ResumePrivateStateThread ();
2728 else
2729 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002730 }
2731 return error;
2732}
2733
2734
2735Error
Chris Lattner24943d22010-06-08 16:52:24 +00002736Process::Resume ()
2737{
Greg Claytone005f2c2010-11-06 01:53:30 +00002738 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002739 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002740 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002741 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002742 StateAsCString(m_public_state.GetValue()),
2743 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002744
2745 Error error (WillResume());
2746 // Tell the process it is about to resume before the thread list
2747 if (error.Success())
2748 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002749 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002750 // can let all of our threads know that they are about to be
2751 // resumed. Threads will each be called with
2752 // Thread::WillResume(StateType) where StateType contains the state
2753 // that they are supposed to have when the process is resumed
2754 // (suspended/running/stepping). Threads should also check
2755 // their resume signal in lldb::Thread::GetResumeSignal()
2756 // to see if they are suppoed to start back up with a signal.
2757 if (m_thread_list.WillResume())
2758 {
Jim Ingham0296fe72011-11-08 03:00:11 +00002759 m_mod_id.BumpResumeID();
Chris Lattner24943d22010-06-08 16:52:24 +00002760 error = DoResume();
2761 if (error.Success())
2762 {
2763 DidResume();
2764 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00002765 if (log)
2766 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00002767 }
2768 }
2769 else
2770 {
Jim Inghamac959662011-01-24 06:34:17 +00002771 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002772 }
2773 }
Jim Inghamac959662011-01-24 06:34:17 +00002774 else if (log)
2775 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002776 return error;
2777}
2778
2779Error
2780Process::Halt ()
2781{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002782 // Pause our private state thread so we can ensure no one else eats
2783 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002784 Listener halt_listener ("lldb.process.halt_listener");
2785 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002786
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002787 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002788 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002789
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002790 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002791 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002792
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002793 bool caused_stop = false;
2794
2795 // Ask the process subclass to actually halt our process
2796 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002797 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002798 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002799 if (m_public_state.GetValue() == eStateAttaching)
2800 {
2801 SetExitStatus(SIGKILL, "Cancelled async attach.");
2802 Destroy ();
2803 }
2804 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002805 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002806 // If "caused_stop" is true, then DoHalt stopped the process. If
2807 // "caused_stop" is false, the process was already stopped.
2808 // If the DoHalt caused the process to stop, then we want to catch
2809 // this event and set the interrupted bool to true before we pass
2810 // this along so clients know that the process was interrupted by
2811 // a halt command.
2812 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002813 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002814 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002815 TimeValue timeout_time;
2816 timeout_time = TimeValue::Now();
2817 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002818 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2819 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002820
Jim Inghamf9f40c22011-02-08 05:20:59 +00002821 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002822 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002823 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002824 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002825 }
2826 else
2827 {
Greg Clayton20206082011-11-17 01:23:07 +00002828 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002829 {
2830 // We caused the process to interrupt itself, so mark this
2831 // as such in the stop event so clients can tell an interrupted
2832 // process from a natural stop
2833 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2834 }
2835 else
2836 {
2837 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2838 if (log)
2839 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2840 error.SetErrorString ("Did not get stopped event after halt.");
2841 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002842 }
2843 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002844 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002845 }
2846 }
Chris Lattner24943d22010-06-08 16:52:24 +00002847 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002848 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002849 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002850
2851 // Post any event we might have consumed. If all goes well, we will have
2852 // stopped the process, intercepted the event and set the interrupted
2853 // bool in the event. Post it to the private event queue and that will end up
2854 // correctly setting the state.
2855 if (event_sp)
2856 m_private_state_broadcaster.BroadcastEvent(event_sp);
2857
Chris Lattner24943d22010-06-08 16:52:24 +00002858 return error;
2859}
2860
2861Error
2862Process::Detach ()
2863{
2864 Error error (WillDetach());
2865
2866 if (error.Success())
2867 {
2868 DisableAllBreakpointSites();
2869 error = DoDetach();
2870 if (error.Success())
2871 {
2872 DidDetach();
2873 StopPrivateStateThread();
2874 }
2875 }
2876 return error;
2877}
2878
2879Error
2880Process::Destroy ()
2881{
2882 Error error (WillDestroy());
2883 if (error.Success())
2884 {
2885 DisableAllBreakpointSites();
2886 error = DoDestroy();
2887 if (error.Success())
2888 {
2889 DidDestroy();
2890 StopPrivateStateThread();
2891 }
Caroline Tice861efb32010-11-16 05:07:41 +00002892 m_stdio_communication.StopReadThread();
2893 m_stdio_communication.Disconnect();
2894 if (m_process_input_reader && m_process_input_reader->IsActive())
2895 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2896 if (m_process_input_reader)
2897 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002898 }
2899 return error;
2900}
2901
2902Error
2903Process::Signal (int signal)
2904{
2905 Error error (WillSignal());
2906 if (error.Success())
2907 {
2908 error = DoSignal(signal);
2909 if (error.Success())
2910 DidSignal();
2911 }
2912 return error;
2913}
2914
Greg Clayton395fc332011-02-15 21:59:32 +00002915lldb::ByteOrder
2916Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002917{
Greg Clayton395fc332011-02-15 21:59:32 +00002918 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002919}
2920
2921uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002922Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002923{
Greg Clayton395fc332011-02-15 21:59:32 +00002924 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002925}
2926
Greg Clayton395fc332011-02-15 21:59:32 +00002927
Chris Lattner24943d22010-06-08 16:52:24 +00002928bool
2929Process::ShouldBroadcastEvent (Event *event_ptr)
2930{
2931 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2932 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002933 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002934
2935 switch (state)
2936 {
Greg Claytone71e2582011-02-04 01:58:07 +00002937 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002938 case eStateAttaching:
2939 case eStateLaunching:
2940 case eStateDetached:
2941 case eStateExited:
2942 case eStateUnloaded:
2943 // These events indicate changes in the state of the debugging session, always report them.
2944 return_value = true;
2945 break;
2946 case eStateInvalid:
2947 // We stopped for no apparent reason, don't report it.
2948 return_value = false;
2949 break;
2950 case eStateRunning:
2951 case eStateStepping:
2952 // If we've started the target running, we handle the cases where we
2953 // are already running and where there is a transition from stopped to
2954 // running differently.
2955 // running -> running: Automatically suppress extra running events
2956 // stopped -> running: Report except when there is one or more no votes
2957 // and no yes votes.
2958 SynchronouslyNotifyStateChanged (state);
2959 switch (m_public_state.GetValue())
2960 {
2961 case eStateRunning:
2962 case eStateStepping:
2963 // We always suppress multiple runnings with no PUBLIC stop in between.
2964 return_value = false;
2965 break;
2966 default:
2967 // TODO: make this work correctly. For now always report
2968 // run if we aren't running so we don't miss any runnning
2969 // events. If I run the lldb/test/thread/a.out file and
2970 // break at main.cpp:58, run and hit the breakpoints on
2971 // multiple threads, then somehow during the stepping over
2972 // of all breakpoints no run gets reported.
2973 return_value = true;
2974
2975 // This is a transition from stop to run.
2976 switch (m_thread_list.ShouldReportRun (event_ptr))
2977 {
2978 case eVoteYes:
2979 case eVoteNoOpinion:
2980 return_value = true;
2981 break;
2982 case eVoteNo:
2983 return_value = false;
2984 break;
2985 }
2986 break;
2987 }
2988 break;
2989 case eStateStopped:
2990 case eStateCrashed:
2991 case eStateSuspended:
2992 {
2993 // We've stopped. First see if we're going to restart the target.
2994 // If we are going to stop, then we always broadcast the event.
2995 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00002996 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002997 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002998 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002999 if (log)
3000 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003001 return true;
3002 }
3003 else
3004 {
Chris Lattner24943d22010-06-08 16:52:24 +00003005 RefreshStateAfterStop ();
3006
3007 if (m_thread_list.ShouldStop (event_ptr) == false)
3008 {
3009 switch (m_thread_list.ShouldReportStop (event_ptr))
3010 {
3011 case eVoteYes:
3012 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003013 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003014 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003015 case eVoteNo:
3016 return_value = false;
3017 break;
3018 }
3019
3020 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003021 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00003022 Resume ();
3023 }
3024 else
3025 {
3026 return_value = true;
3027 SynchronouslyNotifyStateChanged (state);
3028 }
3029 }
3030 }
3031 }
3032
3033 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003034 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003035 return return_value;
3036}
3037
Chris Lattner24943d22010-06-08 16:52:24 +00003038
3039bool
3040Process::StartPrivateStateThread ()
3041{
Greg Claytone005f2c2010-11-06 01:53:30 +00003042 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003043
Greg Claytonb72d0f02011-04-12 05:54:46 +00003044 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003045 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003046 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3047
3048 if (already_running)
3049 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003050
3051 // Create a thread that watches our internal state and controls which
3052 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003053 char thread_name[1024];
Greg Clayton444e35b2011-10-19 18:09:39 +00003054 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Claytona875b642011-01-09 21:07:35 +00003055 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00003056 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00003057}
3058
3059void
3060Process::PausePrivateStateThread ()
3061{
3062 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3063}
3064
3065void
3066Process::ResumePrivateStateThread ()
3067{
3068 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3069}
3070
3071void
3072Process::StopPrivateStateThread ()
3073{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003074 if (PrivateStateThreadIsValid ())
3075 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner24943d22010-06-08 16:52:24 +00003076}
3077
3078void
3079Process::ControlPrivateStateThread (uint32_t signal)
3080{
Greg Claytone005f2c2010-11-06 01:53:30 +00003081 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003082
3083 assert (signal == eBroadcastInternalStateControlStop ||
3084 signal == eBroadcastInternalStateControlPause ||
3085 signal == eBroadcastInternalStateControlResume);
3086
3087 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003088 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003089
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003090 // Signal the private state thread. First we should copy this is case the
3091 // thread starts exiting since the private state thread will NULL this out
3092 // when it exits
3093 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003094 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003095 {
3096 TimeValue timeout_time;
3097 bool timed_out;
3098
3099 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3100
3101 timeout_time = TimeValue::Now();
3102 timeout_time.OffsetWithSeconds(2);
3103 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3104 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3105
3106 if (signal == eBroadcastInternalStateControlStop)
3107 {
3108 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003109 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003110
3111 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003112 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003113 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003114 }
3115 }
3116}
3117
3118void
3119Process::HandlePrivateEvent (EventSP &event_sp)
3120{
Greg Claytone005f2c2010-11-06 01:53:30 +00003121 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003122
Greg Clayton68ca8232011-01-25 02:58:48 +00003123 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003124
3125 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003126 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003127 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003128 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003129 switch (action_result)
3130 {
3131 case NextEventAction::eEventActionSuccess:
3132 SetNextEventAction(NULL);
3133 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003134
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003135 case NextEventAction::eEventActionRetry:
3136 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003137
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003138 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003139 // Handle Exiting Here. If we already got an exited event,
3140 // we should just propagate it. Otherwise, swallow this event,
3141 // and set our state to exit so the next event will kill us.
3142 if (new_state != eStateExited)
3143 {
3144 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003145 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003146 SetNextEventAction(NULL);
3147 return;
3148 }
3149 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003150 break;
3151 }
3152 }
3153
Chris Lattner24943d22010-06-08 16:52:24 +00003154 // See if we should broadcast this state to external clients?
3155 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003156
3157 if (should_broadcast)
3158 {
3159 if (log)
3160 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003161 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003162 __FUNCTION__,
3163 GetID(),
3164 StateAsCString(new_state),
3165 StateAsCString (GetState ()),
3166 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003167 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003168 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003169 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003170 PushProcessInputReader ();
3171 else
3172 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003173
Chris Lattner24943d22010-06-08 16:52:24 +00003174 BroadcastEvent (event_sp);
3175 }
3176 else
3177 {
3178 if (log)
3179 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003180 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003181 __FUNCTION__,
3182 GetID(),
3183 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003184 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003185 }
3186 }
3187}
3188
3189void *
3190Process::PrivateStateThread (void *arg)
3191{
3192 Process *proc = static_cast<Process*> (arg);
3193 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003194 return result;
3195}
3196
3197void *
3198Process::RunPrivateStateThread ()
3199{
3200 bool control_only = false;
3201 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3202
Greg Claytone005f2c2010-11-06 01:53:30 +00003203 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003204 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003205 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003206
3207 bool exit_now = false;
3208 while (!exit_now)
3209 {
3210 EventSP event_sp;
3211 WaitForEventsPrivate (NULL, event_sp, control_only);
3212 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3213 {
3214 switch (event_sp->GetType())
3215 {
3216 case eBroadcastInternalStateControlStop:
3217 exit_now = true;
3218 continue; // Go to next loop iteration so we exit without
3219 break; // doing any internal state managment below
3220
3221 case eBroadcastInternalStateControlPause:
3222 control_only = true;
3223 break;
3224
3225 case eBroadcastInternalStateControlResume:
3226 control_only = false;
3227 break;
3228 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003229
Jim Ingham3ae449a2010-11-17 02:32:00 +00003230 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003231 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham3ae449a2010-11-17 02:32:00 +00003232
Chris Lattner24943d22010-06-08 16:52:24 +00003233 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003234 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003235 }
3236
3237
3238 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3239
3240 if (internal_state != eStateInvalid)
3241 {
3242 HandlePrivateEvent (event_sp);
3243 }
3244
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003245 if (internal_state == eStateInvalid ||
3246 internal_state == eStateExited ||
3247 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003248 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003249 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003250 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003251
Chris Lattner24943d22010-06-08 16:52:24 +00003252 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003253 }
Chris Lattner24943d22010-06-08 16:52:24 +00003254 }
3255
Caroline Tice926060e2010-10-29 21:48:37 +00003256 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003257 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003258 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003259
Greg Claytona4881d02011-01-22 07:12:45 +00003260 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3261 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003262 return NULL;
3263}
3264
Chris Lattner24943d22010-06-08 16:52:24 +00003265//------------------------------------------------------------------
3266// Process Event Data
3267//------------------------------------------------------------------
3268
3269Process::ProcessEventData::ProcessEventData () :
3270 EventData (),
3271 m_process_sp (),
3272 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003273 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003274 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003275 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003276{
3277}
3278
3279Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3280 EventData (),
3281 m_process_sp (process_sp),
3282 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003283 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003284 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003285 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003286{
3287}
3288
3289Process::ProcessEventData::~ProcessEventData()
3290{
3291}
3292
3293const ConstString &
3294Process::ProcessEventData::GetFlavorString ()
3295{
3296 static ConstString g_flavor ("Process::ProcessEventData");
3297 return g_flavor;
3298}
3299
3300const ConstString &
3301Process::ProcessEventData::GetFlavor () const
3302{
3303 return ProcessEventData::GetFlavorString ();
3304}
3305
Chris Lattner24943d22010-06-08 16:52:24 +00003306void
3307Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3308{
3309 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003310 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3311 // the public event queue, then other times when we're pretending that this is where we stopped at the
3312 // end of expression evaluation. m_update_state is used to distinguish these
3313 // three cases; it is 0 when we're just pulling it off for private handling,
3314 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003315
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003316 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003317 return;
3318
3319 m_process_sp->SetPublicState (m_state);
3320
3321 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3322 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003323 {
3324 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003325 uint32_t num_threads = curr_thread_list.GetSize();
3326 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003327
Jim Ingham21f37ad2011-08-09 02:12:22 +00003328 // The actions might change one of the thread's stop_info's opinions about whether we should
3329 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003330
3331 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3332 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3333 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3334 // 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
3335 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003336 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003337 for (idx = 0; idx < num_threads; ++idx)
3338 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3339
Jim Ingham21f37ad2011-08-09 02:12:22 +00003340 bool still_should_stop = true;
3341
Chris Lattner24943d22010-06-08 16:52:24 +00003342 for (idx = 0; idx < num_threads; ++idx)
3343 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003344 curr_thread_list = m_process_sp->GetThreadList();
3345 if (curr_thread_list.GetSize() != num_threads)
3346 {
3347 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003348 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003349 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0296fe72011-11-08 03:00:11 +00003350 break;
3351 }
3352
3353 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3354
3355 if (thread_sp->GetIndexID() != thread_index_array[idx])
3356 {
3357 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003358 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003359 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003360 idx,
3361 thread_index_array[idx],
3362 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003363 break;
3364 }
3365
Jim Ingham6297a3a2010-10-20 00:39:53 +00003366 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3367 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00003368 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003369 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003370 // The stop action might restart the target. If it does, then we want to mark that in the
3371 // event so that whoever is receiving it will know to wait for the running event and reflect
3372 // that state appropriately.
3373 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003374
3375 // FIXME: we might have run.
3376 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003377 {
3378 SetRestarted (true);
3379 break;
3380 }
3381 else if (!stop_info_sp->ShouldStop(event_ptr))
3382 {
3383 still_should_stop = false;
3384 }
Chris Lattner24943d22010-06-08 16:52:24 +00003385 }
3386 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003387
Jim Ingham21f37ad2011-08-09 02:12:22 +00003388
3389 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003390 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003391 if (!still_should_stop)
3392 {
3393 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003394 SetRestarted(true);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003395 m_process_sp->Resume();
3396 }
3397 else
3398 {
3399 // If we didn't restart, run the Stop Hooks here:
3400 // They might also restart the target, so watch for that.
3401 m_process_sp->GetTarget().RunStopHooks();
3402 if (m_process_sp->GetPrivateState() == eStateRunning)
3403 SetRestarted(true);
3404 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003405 }
3406
Chris Lattner24943d22010-06-08 16:52:24 +00003407 }
3408}
3409
3410void
3411Process::ProcessEventData::Dump (Stream *s) const
3412{
3413 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003414 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003415
Greg Claytonb72d0f02011-04-12 05:54:46 +00003416 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003417}
3418
3419const Process::ProcessEventData *
3420Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3421{
3422 if (event_ptr)
3423 {
3424 const EventData *event_data = event_ptr->GetData();
3425 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3426 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3427 }
3428 return NULL;
3429}
3430
3431ProcessSP
3432Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3433{
3434 ProcessSP process_sp;
3435 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3436 if (data)
3437 process_sp = data->GetProcessSP();
3438 return process_sp;
3439}
3440
3441StateType
3442Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3443{
3444 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3445 if (data == NULL)
3446 return eStateInvalid;
3447 else
3448 return data->GetState();
3449}
3450
3451bool
3452Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3453{
3454 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3455 if (data == NULL)
3456 return false;
3457 else
3458 return data->GetRestarted();
3459}
3460
3461void
3462Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3463{
3464 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3465 if (data != NULL)
3466 data->SetRestarted(new_value);
3467}
3468
3469bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003470Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3471{
3472 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3473 if (data == NULL)
3474 return false;
3475 else
3476 return data->GetInterrupted ();
3477}
3478
3479void
3480Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3481{
3482 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3483 if (data != NULL)
3484 data->SetInterrupted(new_value);
3485}
3486
3487bool
Chris Lattner24943d22010-06-08 16:52:24 +00003488Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3489{
3490 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3491 if (data)
3492 {
3493 data->SetUpdateStateOnRemoval();
3494 return true;
3495 }
3496 return false;
3497}
3498
Greg Clayton289afcb2012-02-18 05:35:26 +00003499lldb::TargetSP
3500Process::CalculateTarget ()
3501{
3502 return m_target.shared_from_this();
3503}
3504
Chris Lattner24943d22010-06-08 16:52:24 +00003505void
Greg Claytona830adb2010-10-04 01:05:56 +00003506Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003507{
Greg Clayton567e7f32011-09-22 04:58:26 +00003508 exe_ctx.SetTargetPtr (&m_target);
3509 exe_ctx.SetProcessPtr (this);
3510 exe_ctx.SetThreadPtr(NULL);
3511 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003512}
3513
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003514//uint32_t
3515//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3516//{
3517// return 0;
3518//}
3519//
3520//ArchSpec
3521//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3522//{
3523// return Host::GetArchSpecForExistingProcess (pid);
3524//}
3525//
3526//ArchSpec
3527//Process::GetArchSpecForExistingProcess (const char *process_name)
3528//{
3529// return Host::GetArchSpecForExistingProcess (process_name);
3530//}
3531//
Caroline Tice861efb32010-11-16 05:07:41 +00003532void
3533Process::AppendSTDOUT (const char * s, size_t len)
3534{
Greg Clayton20d338f2010-11-18 05:57:03 +00003535 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003536 m_stdout_data.append (s, len);
Greg Claytonb3781332010-12-05 19:16:56 +00003537 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003538}
3539
3540void
Greg Claytonbd06ff42011-11-13 04:45:22 +00003541Process::AppendSTDERR (const char * s, size_t len)
3542{
3543 Mutex::Locker locker (m_stdio_communication_mutex);
3544 m_stderr_data.append (s, len);
3545 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3546}
3547
3548//------------------------------------------------------------------
3549// Process STDIO
3550//------------------------------------------------------------------
3551
3552size_t
3553Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3554{
3555 Mutex::Locker locker(m_stdio_communication_mutex);
3556 size_t bytes_available = m_stdout_data.size();
3557 if (bytes_available > 0)
3558 {
3559 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3560 if (log)
3561 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3562 if (bytes_available > buf_size)
3563 {
3564 memcpy(buf, m_stdout_data.c_str(), buf_size);
3565 m_stdout_data.erase(0, buf_size);
3566 bytes_available = buf_size;
3567 }
3568 else
3569 {
3570 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3571 m_stdout_data.clear();
3572 }
3573 }
3574 return bytes_available;
3575}
3576
3577
3578size_t
3579Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3580{
3581 Mutex::Locker locker(m_stdio_communication_mutex);
3582 size_t bytes_available = m_stderr_data.size();
3583 if (bytes_available > 0)
3584 {
3585 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3586 if (log)
3587 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3588 if (bytes_available > buf_size)
3589 {
3590 memcpy(buf, m_stderr_data.c_str(), buf_size);
3591 m_stderr_data.erase(0, buf_size);
3592 bytes_available = buf_size;
3593 }
3594 else
3595 {
3596 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3597 m_stderr_data.clear();
3598 }
3599 }
3600 return bytes_available;
3601}
3602
3603void
Caroline Tice861efb32010-11-16 05:07:41 +00003604Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3605{
3606 Process *process = (Process *) baton;
3607 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3608}
3609
3610size_t
3611Process::ProcessInputReaderCallback (void *baton,
3612 InputReader &reader,
3613 lldb::InputReaderAction notification,
3614 const char *bytes,
3615 size_t bytes_len)
3616{
3617 Process *process = (Process *) baton;
3618
3619 switch (notification)
3620 {
3621 case eInputReaderActivate:
3622 break;
3623
3624 case eInputReaderDeactivate:
3625 break;
3626
3627 case eInputReaderReactivate:
3628 break;
3629
Caroline Tice4a348082011-05-02 20:41:46 +00003630 case eInputReaderAsynchronousOutputWritten:
3631 break;
3632
Caroline Tice861efb32010-11-16 05:07:41 +00003633 case eInputReaderGotToken:
3634 {
3635 Error error;
3636 process->PutSTDIN (bytes, bytes_len, error);
3637 }
3638 break;
3639
Caroline Ticec4f55fe2010-11-19 20:47:54 +00003640 case eInputReaderInterrupt:
3641 process->Halt ();
3642 break;
3643
3644 case eInputReaderEndOfFile:
3645 process->AppendSTDOUT ("^D", 2);
3646 break;
3647
Caroline Tice861efb32010-11-16 05:07:41 +00003648 case eInputReaderDone:
3649 break;
3650
3651 }
3652
3653 return bytes_len;
3654}
3655
3656void
3657Process::ResetProcessInputReader ()
3658{
3659 m_process_input_reader.reset();
3660}
3661
3662void
Greg Clayton464c6162011-11-17 22:14:31 +00003663Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00003664{
3665 // First set up the Read Thread for reading/handling process I/O
3666
3667 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3668
3669 if (conn_ap.get())
3670 {
3671 m_stdio_communication.SetConnection (conn_ap.release());
3672 if (m_stdio_communication.IsConnected())
3673 {
3674 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3675 m_stdio_communication.StartReadThread();
3676
3677 // Now read thread is set up, set up input reader.
3678
3679 if (!m_process_input_reader.get())
3680 {
3681 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3682 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3683 this,
3684 eInputReaderGranularityByte,
3685 NULL,
3686 NULL,
3687 false));
3688
3689 if (err.Fail())
3690 m_process_input_reader.reset();
3691 }
3692 }
3693 }
3694}
3695
3696void
3697Process::PushProcessInputReader ()
3698{
3699 if (m_process_input_reader && !m_process_input_reader->IsActive())
3700 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3701}
3702
3703void
3704Process::PopProcessInputReader ()
3705{
3706 if (m_process_input_reader && m_process_input_reader->IsActive())
3707 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3708}
3709
Greg Claytond284b662011-02-18 01:44:25 +00003710// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00003711void
Caroline Tice2a456812011-03-10 22:14:10 +00003712Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003713{
Greg Claytonb3448432011-03-24 21:19:54 +00003714 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00003715
3716 int i=0;
3717 const char *name;
3718 OptionEnumValueElement option_enum;
3719 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3720 {
3721 if (name)
3722 {
3723 option_enum.value = i;
3724 option_enum.string_value = name;
3725 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3726 g_plugins.push_back (option_enum);
3727 }
3728 ++i;
3729 }
3730 option_enum.value = 0;
3731 option_enum.string_value = NULL;
3732 option_enum.usage = NULL;
3733 g_plugins.push_back (option_enum);
3734
3735 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3736 {
3737 if (::strcmp (name, "plugin") == 0)
3738 {
3739 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3740 break;
3741 }
3742 }
Greg Clayton990de7b2010-11-18 23:32:35 +00003743 UserSettingsControllerSP &usc = GetSettingsController();
3744 usc.reset (new SettingsController);
3745 UserSettingsController::InitializeSettingsController (usc,
3746 SettingsController::global_settings_table,
3747 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00003748
3749 // Now call SettingsInitialize() for each 'child' of Process settings
3750 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00003751}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003752
Greg Clayton990de7b2010-11-18 23:32:35 +00003753void
Caroline Tice2a456812011-03-10 22:14:10 +00003754Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00003755{
Caroline Tice2a456812011-03-10 22:14:10 +00003756 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3757
3758 Thread::SettingsTerminate ();
3759
3760 // Now terminate Process Settings.
3761
Greg Clayton990de7b2010-11-18 23:32:35 +00003762 UserSettingsControllerSP &usc = GetSettingsController();
3763 UserSettingsController::FinalizeSettingsController (usc);
3764 usc.reset();
3765}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003766
Greg Clayton990de7b2010-11-18 23:32:35 +00003767UserSettingsControllerSP &
3768Process::GetSettingsController ()
3769{
Greg Clayton334d33a2012-01-30 07:41:31 +00003770 static UserSettingsControllerSP g_settings_controller_sp;
3771 if (!g_settings_controller_sp)
3772 {
3773 g_settings_controller_sp.reset (new Process::SettingsController);
3774 // The first shared pointer to Process::SettingsController in
3775 // g_settings_controller_sp must be fully created above so that
3776 // the TargetInstanceSettings can use a weak_ptr to refer back
3777 // to the master setttings controller
3778 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp,
3779 false,
3780 InstanceSettings::GetDefaultName().AsCString()));
3781 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
3782 }
3783 return g_settings_controller_sp;
3784
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003785}
3786
Caroline Tice1ebef442010-09-27 00:30:10 +00003787void
3788Process::UpdateInstanceName ()
3789{
Greg Clayton5beb99d2011-08-11 02:48:45 +00003790 Module *module = GetTarget().GetExecutableModulePointer();
Greg Clayton13d24fb2012-01-29 20:56:30 +00003791 if (module && module->GetFileSpec().GetFilename())
Caroline Tice1ebef442010-09-27 00:30:10 +00003792 {
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003793 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Clayton13d24fb2012-01-29 20:56:30 +00003794 module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1ebef442010-09-27 00:30:10 +00003795 }
3796}
3797
Greg Clayton427f2902010-12-14 02:59:59 +00003798ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00003799Process::RunThreadPlan (ExecutionContext &exe_ctx,
3800 lldb::ThreadPlanSP &thread_plan_sp,
3801 bool stop_others,
3802 bool try_all_threads,
3803 bool discard_on_error,
3804 uint32_t single_thread_timeout_usec,
3805 Stream &errors)
3806{
3807 ExecutionResults return_value = eExecutionSetupError;
3808
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003809 if (thread_plan_sp.get() == NULL)
3810 {
3811 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00003812 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003813 }
Greg Clayton567e7f32011-09-22 04:58:26 +00003814
3815 if (exe_ctx.GetProcessPtr() != this)
3816 {
3817 errors.Printf("RunThreadPlan called on wrong process.");
3818 return eExecutionSetupError;
3819 }
3820
3821 Thread *thread = exe_ctx.GetThreadPtr();
3822 if (thread == NULL)
3823 {
3824 errors.Printf("RunThreadPlan called with invalid thread.");
3825 return eExecutionSetupError;
3826 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003827
Jim Ingham5ab7fba2011-05-17 22:24:54 +00003828 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3829 // For that to be true the plan can't be private - since private plans suppress themselves in the
3830 // GetCompletedPlan call.
3831
3832 bool orig_plan_private = thread_plan_sp->GetPrivate();
3833 thread_plan_sp->SetPrivate(false);
3834
Jim Inghamac959662011-01-24 06:34:17 +00003835 if (m_private_state.GetValue() != eStateStopped)
3836 {
3837 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00003838 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00003839 }
3840
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003841 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00003842 const uint32_t thread_idx_id = thread->GetIndexID();
3843 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003844
3845 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3846 // so we should arrange to reset them as well.
3847
Greg Clayton567e7f32011-09-22 04:58:26 +00003848 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00003849
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003850 uint32_t selected_tid;
3851 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00003852 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00003853 {
3854 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003855 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003856 }
3857 else
3858 {
3859 selected_tid = LLDB_INVALID_THREAD_ID;
3860 }
3861
Greg Clayton567e7f32011-09-22 04:58:26 +00003862 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Ingham360f53f2010-11-30 02:22:11 +00003863
Jim Ingham6ae318c2011-01-23 21:14:08 +00003864 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003865
3866 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3867 // restored on exit to the function.
3868
3869 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00003870
Jim Ingham6ae318c2011-01-23 21:14:08 +00003871 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003872 if (log)
3873 {
3874 StreamString s;
3875 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton444e35b2011-10-19 18:09:39 +00003876 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Clayton567e7f32011-09-22 04:58:26 +00003877 thread->GetIndexID(),
3878 thread->GetID(),
Jim Inghamf9f40c22011-02-08 05:20:59 +00003879 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003880 }
3881
Jim Inghamf9f40c22011-02-08 05:20:59 +00003882 bool got_event;
3883 lldb::EventSP event_sp;
3884 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00003885
3886 TimeValue* timeout_ptr = NULL;
3887 TimeValue real_timeout;
3888
Jim Inghamf9f40c22011-02-08 05:20:59 +00003889 bool first_timeout = true;
3890 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00003891
Jim Ingham360f53f2010-11-30 02:22:11 +00003892 while (1)
3893 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003894 // We usually want to resume the process if we get to the top of the loop.
3895 // The only exception is if we get two running events with no intervening
3896 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00003897
Jim Inghamf9f40c22011-02-08 05:20:59 +00003898 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00003899 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003900 // Do the initial resume and wait for the running event before going further.
3901
Greg Clayton567e7f32011-09-22 04:58:26 +00003902 Error resume_error = Resume ();
Jim Inghamf9f40c22011-02-08 05:20:59 +00003903 if (!resume_error.Success())
3904 {
3905 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00003906 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003907 break;
3908 }
3909
3910 real_timeout = TimeValue::Now();
3911 real_timeout.OffsetWithMicroSeconds(500000);
3912 timeout_ptr = &real_timeout;
3913
Sean Callananfaf04782012-01-05 02:00:14 +00003914 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003915 if (!got_event)
3916 {
3917 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003918 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003919
3920 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003921 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003922 break;
3923 }
3924
3925 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3926 if (stop_state != eStateRunning)
3927 {
3928 if (log)
3929 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3930
3931 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003932 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003933 break;
3934 }
3935
3936 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003937 log->PutCString ("Resuming succeeded.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003938 // We need to call the function synchronously, so spin waiting for it to return.
3939 // If we get interrupted while executing, we're going to lose our context, and
3940 // won't be able to gather the result at this point.
3941 // We set the timeout AFTER the resume, since the resume takes some time and we
3942 // don't want to charge that to the timeout.
3943
3944 if (single_thread_timeout_usec != 0)
3945 {
3946 real_timeout = TimeValue::Now();
3947 if (first_timeout)
3948 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3949 else
3950 real_timeout.OffsetWithSeconds(10);
3951
3952 timeout_ptr = &real_timeout;
3953 }
3954 }
3955 else
3956 {
3957 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003958 log->PutCString ("Handled an extra running event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003959 do_resume = true;
3960 }
3961
3962 // Now wait for the process to stop again:
3963 stop_state = lldb::eStateInvalid;
3964 event_sp.reset();
3965 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3966
3967 if (got_event)
3968 {
3969 if (event_sp.get())
3970 {
3971 bool keep_going = false;
3972 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3973 if (log)
3974 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3975
3976 switch (stop_state)
3977 {
3978 case lldb::eStateStopped:
Jim Ingham2370a972011-05-17 01:10:11 +00003979 {
Greg Clayton43994462011-06-03 22:12:42 +00003980 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Clayton567e7f32011-09-22 04:58:26 +00003981 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton43994462011-06-03 22:12:42 +00003982 if (!thread_sp)
Jim Ingham2370a972011-05-17 01:10:11 +00003983 {
Greg Clayton43994462011-06-03 22:12:42 +00003984 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham2370a972011-05-17 01:10:11 +00003985 if (log)
Greg Clayton43994462011-06-03 22:12:42 +00003986 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3987 return_value = eExecutionInterrupted;
Jim Ingham2370a972011-05-17 01:10:11 +00003988 }
3989 else
3990 {
Greg Clayton43994462011-06-03 22:12:42 +00003991 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3992 StopReason stop_reason = eStopReasonInvalid;
3993 if (stop_info_sp)
3994 stop_reason = stop_info_sp->GetStopReason();
3995 if (stop_reason == eStopReasonPlanComplete)
3996 {
3997 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00003998 log->PutCString ("Execution completed successfully.");
Greg Clayton43994462011-06-03 22:12:42 +00003999 // Now mark this plan as private so it doesn't get reported as the stop reason
4000 // after this point.
4001 if (thread_plan_sp)
4002 thread_plan_sp->SetPrivate (orig_plan_private);
4003 return_value = eExecutionCompleted;
4004 }
4005 else
4006 {
4007 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004008 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton43994462011-06-03 22:12:42 +00004009
4010 return_value = eExecutionInterrupted;
4011 }
Jim Ingham2370a972011-05-17 01:10:11 +00004012 }
Greg Clayton43994462011-06-03 22:12:42 +00004013 }
4014 break;
4015
Jim Inghamf9f40c22011-02-08 05:20:59 +00004016 case lldb::eStateCrashed:
4017 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004018 log->PutCString ("Execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00004019 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004020 break;
Greg Clayton43994462011-06-03 22:12:42 +00004021
Jim Inghamf9f40c22011-02-08 05:20:59 +00004022 case lldb::eStateRunning:
4023 do_resume = false;
4024 keep_going = true;
4025 break;
Greg Clayton43994462011-06-03 22:12:42 +00004026
Jim Inghamf9f40c22011-02-08 05:20:59 +00004027 default:
4028 if (log)
4029 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham2370a972011-05-17 01:10:11 +00004030
4031 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytonb3448432011-03-24 21:19:54 +00004032 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004033 break;
4034 }
4035 if (keep_going)
4036 continue;
4037 else
4038 break;
4039 }
4040 else
4041 {
4042 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004043 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00004044 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004045 break;
4046 }
4047 }
4048 else
4049 {
4050 // If we didn't get an event that means we've timed out...
4051 // We will interrupt the process here. Depending on what we were asked to do we will
4052 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00004053 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00004054
Stephen Wilsonc2b98252011-01-12 04:20:03 +00004055 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00004056 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004057 {
4058 if (first_timeout)
4059 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4060 "trying with all threads enabled.",
4061 single_thread_timeout_usec);
4062 else
4063 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4064 "and timeout: %d timed out.",
4065 single_thread_timeout_usec);
4066 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004067 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00004068 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4069 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00004070 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00004071 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004072
Greg Clayton567e7f32011-09-22 04:58:26 +00004073 Error halt_error = Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00004074 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00004075 {
Jim Ingham360f53f2010-11-30 02:22:11 +00004076 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004077 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00004078
Jim Inghamf9f40c22011-02-08 05:20:59 +00004079 // If halt succeeds, it always produces a stopped event. Wait for that:
4080
4081 real_timeout = TimeValue::Now();
4082 real_timeout.OffsetWithMicroSeconds(500000);
4083
4084 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00004085
4086 if (got_event)
4087 {
4088 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4089 if (log)
4090 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004091 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00004092 if (stop_state == lldb::eStateStopped
4093 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf6d3d792011-08-09 22:24:33 +00004094 log->PutCString (" Event was the Halt interruption event.");
Jim Ingham360f53f2010-11-30 02:22:11 +00004095 }
4096
Jim Inghamf9f40c22011-02-08 05:20:59 +00004097 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00004098 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004099 // Between the time we initiated the Halt and the time we delivered it, the process could have
4100 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00004101
Greg Clayton567e7f32011-09-22 04:58:26 +00004102 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00004103 {
4104 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004105 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004106 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00004107 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004108 break;
4109 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004110
Jim Inghamf9f40c22011-02-08 05:20:59 +00004111 if (!try_all_threads)
4112 {
4113 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004114 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00004115 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004116 break;
4117 }
4118
4119 if (first_timeout)
4120 {
4121 // Set all the other threads to run, and return to the top of the loop, which will continue;
4122 first_timeout = false;
4123 thread_plan_sp->SetStopOthers (false);
4124 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004125 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004126
4127 continue;
4128 }
4129 else
4130 {
4131 // Running all threads failed, so return Interrupted.
4132 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004133 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00004134 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004135 break;
4136 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004137 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004138 }
4139 else
4140 { if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004141 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004142 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00004143 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004144 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00004145 }
4146 }
Jim Inghamc556b462011-01-22 01:30:53 +00004147 else
4148 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004149 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4150 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00004151 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004152 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.",
4153 halt_error.AsCString());
4154 real_timeout = TimeValue::Now();
4155 real_timeout.OffsetWithMicroSeconds(500000);
4156 timeout_ptr = &real_timeout;
4157 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4158 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00004159 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004160 // This is not going anywhere, bag out.
4161 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004162 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00004163 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004164 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00004165 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004166 else
4167 {
4168 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4169 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004170 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004171 if (stop_state == lldb::eStateStopped)
4172 {
4173 // Between the time we initiated the Halt and the time we delivered it, the process could have
4174 // already finished its job. Check that here:
4175
Greg Clayton567e7f32011-09-22 04:58:26 +00004176 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00004177 {
4178 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004179 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004180 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00004181 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004182 break;
4183 }
4184
4185 if (first_timeout)
4186 {
4187 // Set all the other threads to run, and return to the top of the loop, which will continue;
4188 first_timeout = false;
4189 thread_plan_sp->SetStopOthers (false);
4190 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004191 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004192
4193 continue;
4194 }
4195 else
4196 {
4197 // Running all threads failed, so return Interrupted.
4198 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004199 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00004200 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004201 break;
4202 }
4203 }
4204 else
4205 {
Sean Callananed3f86b2011-08-09 22:07:08 +00004206 if (log)
4207 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4208 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00004209 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004210 break;
4211 }
4212 }
Jim Inghamc556b462011-01-22 01:30:53 +00004213 }
4214
Jim Ingham360f53f2010-11-30 02:22:11 +00004215 }
4216
Jim Inghamf9f40c22011-02-08 05:20:59 +00004217 } // END WAIT LOOP
4218
4219 // Now do some processing on the results of the run:
4220 if (return_value == eExecutionInterrupted)
4221 {
Jim Ingham360f53f2010-11-30 02:22:11 +00004222 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004223 {
4224 StreamString s;
4225 if (event_sp)
4226 event_sp->Dump (&s);
4227 else
4228 {
Jim Inghamf6d3d792011-08-09 22:24:33 +00004229 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004230 }
4231
4232 StreamString ts;
4233
Jim Inghamf6d3d792011-08-09 22:24:33 +00004234 const char *event_explanation = NULL;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004235
4236 do
4237 {
4238 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4239
4240 if (!event_data)
4241 {
4242 event_explanation = "<no event data>";
4243 break;
4244 }
4245
4246 Process *process = event_data->GetProcessSP().get();
4247
4248 if (!process)
4249 {
4250 event_explanation = "<no process>";
4251 break;
4252 }
4253
4254 ThreadList &thread_list = process->GetThreadList();
4255
4256 uint32_t num_threads = thread_list.GetSize();
4257 uint32_t thread_index;
4258
4259 ts.Printf("<%u threads> ", num_threads);
4260
4261 for (thread_index = 0;
4262 thread_index < num_threads;
4263 ++thread_index)
4264 {
4265 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4266
4267 if (!thread)
4268 {
4269 ts.Printf("<?> ");
4270 continue;
4271 }
4272
Greg Clayton444e35b2011-10-19 18:09:39 +00004273 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Inghamf9f40c22011-02-08 05:20:59 +00004274 RegisterContext *register_context = thread->GetRegisterContext().get();
4275
4276 if (register_context)
4277 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4278 else
4279 ts.Printf("[ip unknown] ");
4280
4281 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4282 if (stop_info_sp)
4283 {
4284 const char *stop_desc = stop_info_sp->GetDescription();
4285 if (stop_desc)
4286 ts.PutCString (stop_desc);
4287 }
4288 ts.Printf(">");
4289 }
4290
4291 event_explanation = ts.GetData();
4292 } while (0);
4293
4294 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004295 {
4296 if (event_explanation)
4297 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4298 else
4299 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4300 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004301
4302 if (discard_on_error && thread_plan_sp)
4303 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004304 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004305 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004306 }
4307 }
4308 }
4309 else if (return_value == eExecutionSetupError)
4310 {
4311 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004312 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004313
4314 if (discard_on_error && thread_plan_sp)
4315 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004316 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004317 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004318 }
4319 }
4320 else
4321 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004322 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004323 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004324 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004325 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00004326 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00004327 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004328 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004329 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004330 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004331 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00004332 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00004333 }
4334 else
4335 {
4336 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004337 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00004338 if (discard_on_error && thread_plan_sp)
4339 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004340 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004341 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Clayton567e7f32011-09-22 04:58:26 +00004342 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004343 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham360f53f2010-11-30 02:22:11 +00004344 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004345 }
4346 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004347
Jim Ingham360f53f2010-11-30 02:22:11 +00004348 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004349 // Check that it's still there, and if it is put it back in the context. Also restore the
4350 // frame in the context if it is still present.
Greg Clayton567e7f32011-09-22 04:58:26 +00004351 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4352 if (thread)
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004353 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004354 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004355 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004356
4357 // Also restore the current process'es selected frame & thread, since this function calling may
4358 // be done behind the user's back.
4359
4360 if (selected_tid != LLDB_INVALID_THREAD_ID)
4361 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004362 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Ingham360f53f2010-11-30 02:22:11 +00004363 {
4364 // We were able to restore the selected thread, now restore the frame:
Greg Clayton567e7f32011-09-22 04:58:26 +00004365 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004366 if (old_frame_sp)
Greg Clayton567e7f32011-09-22 04:58:26 +00004367 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00004368 }
4369 }
4370
4371 return return_value;
4372}
4373
4374const char *
4375Process::ExecutionResultAsCString (ExecutionResults result)
4376{
4377 const char *result_name;
4378
4379 switch (result)
4380 {
Greg Claytonb3448432011-03-24 21:19:54 +00004381 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004382 result_name = "eExecutionCompleted";
4383 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004384 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00004385 result_name = "eExecutionDiscarded";
4386 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004387 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004388 result_name = "eExecutionInterrupted";
4389 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004390 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00004391 result_name = "eExecutionSetupError";
4392 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004393 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00004394 result_name = "eExecutionTimedOut";
4395 break;
4396 }
4397 return result_name;
4398}
4399
Greg Claytonabe0fed2011-04-18 08:33:37 +00004400void
4401Process::GetStatus (Stream &strm)
4402{
4403 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00004404 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00004405 {
4406 if (state == eStateExited)
4407 {
4408 int exit_status = GetExitStatus();
4409 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00004410 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00004411 GetID(),
4412 exit_status,
4413 exit_status,
4414 exit_description ? exit_description : "");
4415 }
4416 else
4417 {
4418 if (state == eStateConnected)
4419 strm.Printf ("Connected to remote target.\n");
4420 else
Greg Clayton444e35b2011-10-19 18:09:39 +00004421 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00004422 }
4423 }
4424 else
4425 {
Greg Clayton444e35b2011-10-19 18:09:39 +00004426 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004427 }
4428}
4429
4430size_t
4431Process::GetThreadStatus (Stream &strm,
4432 bool only_threads_with_stop_reason,
4433 uint32_t start_frame,
4434 uint32_t num_frames,
4435 uint32_t num_frames_with_source)
4436{
4437 size_t num_thread_infos_dumped = 0;
4438
4439 const size_t num_threads = GetThreadList().GetSize();
4440 for (uint32_t i = 0; i < num_threads; i++)
4441 {
4442 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4443 if (thread)
4444 {
4445 if (only_threads_with_stop_reason)
4446 {
4447 if (thread->GetStopInfo().get() == NULL)
4448 continue;
4449 }
4450 thread->GetStatus (strm,
4451 start_frame,
4452 num_frames,
4453 num_frames_with_source);
4454 ++num_thread_infos_dumped;
4455 }
4456 }
4457 return num_thread_infos_dumped;
4458}
4459
Greg Clayton76113302012-02-22 04:37:26 +00004460void
4461Process::AddInvalidMemoryRegion (const LoadRange &region)
4462{
4463 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4464}
4465
4466bool
4467Process::RemoveInvalidMemoryRange (const LoadRange &region)
4468{
4469 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4470}
4471
4472
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004473//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004474// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004475//--------------------------------------------------------------
4476
Greg Claytond0a5a232010-09-19 02:33:57 +00004477Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00004478 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004479{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004480}
4481
Greg Claytond0a5a232010-09-19 02:33:57 +00004482Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004483{
4484}
4485
4486lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00004487Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004488{
Greg Clayton334d33a2012-01-30 07:41:31 +00004489 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4490 false,
4491 instance_name));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004492 return new_settings_sp;
4493}
4494
4495//--------------------------------------------------------------
4496// class ProcessInstanceSettings
4497//--------------------------------------------------------------
4498
Greg Clayton638351a2010-12-04 00:10:17 +00004499ProcessInstanceSettings::ProcessInstanceSettings
4500(
Greg Clayton334d33a2012-01-30 07:41:31 +00004501 const UserSettingsControllerSP &owner_sp,
Greg Clayton638351a2010-12-04 00:10:17 +00004502 bool live_instance,
4503 const char *name
4504) :
Greg Clayton334d33a2012-01-30 07:41:31 +00004505 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004506{
Caroline Tice396704b2010-09-09 18:26:37 +00004507 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4508 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4509 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00004510 // This is true for CreateInstanceName() too.
Greg Claytonabb33022011-11-08 02:43:13 +00004511
Caroline Tice75b11a32010-09-16 19:05:55 +00004512 if (GetInstanceName () == InstanceSettings::InvalidName())
4513 {
4514 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
Greg Clayton334d33a2012-01-30 07:41:31 +00004515 owner_sp->RegisterInstanceSettings (this);
Caroline Tice75b11a32010-09-16 19:05:55 +00004516 }
Greg Claytonabb33022011-11-08 02:43:13 +00004517
Caroline Tice396704b2010-09-09 18:26:37 +00004518 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004519 {
Greg Clayton334d33a2012-01-30 07:41:31 +00004520 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004521 CopyInstanceSettings (pending_settings,false);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004522 }
4523}
4524
4525ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Clayton334d33a2012-01-30 07:41:31 +00004526 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004527{
4528 if (m_instance_name != InstanceSettings::GetDefaultName())
4529 {
Greg Clayton334d33a2012-01-30 07:41:31 +00004530 UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4531 if (owner_sp)
4532 {
4533 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4534 owner_sp->RemovePendingSettings (m_instance_name);
4535 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004536 }
4537}
4538
4539ProcessInstanceSettings::~ProcessInstanceSettings ()
4540{
4541}
4542
4543ProcessInstanceSettings&
4544ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4545{
4546 if (this != &rhs)
4547 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004548 }
4549
4550 return *this;
4551}
4552
4553
4554void
4555ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4556 const char *index_value,
4557 const char *value,
4558 const ConstString &instance_name,
4559 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00004560 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004561 Error &err,
4562 bool pending)
4563{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004564}
4565
4566void
4567ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4568 bool pending)
4569{
Greg Claytonabb33022011-11-08 02:43:13 +00004570// if (new_settings.get() == NULL)
4571// return;
4572//
4573// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004574}
4575
Caroline Ticebcb5b452010-09-20 21:37:42 +00004576bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004577ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4578 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00004579 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00004580 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004581{
Greg Claytonabb33022011-11-08 02:43:13 +00004582 if (err)
4583 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4584 return false;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004585}
4586
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004587const ConstString
4588ProcessInstanceSettings::CreateInstanceName ()
4589{
4590 static int instance_count = 1;
4591 StreamString sstr;
4592
4593 sstr.Printf ("process_%d", instance_count);
4594 ++instance_count;
4595
4596 const ConstString ret_val (sstr.GetData());
4597 return ret_val;
4598}
4599
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004600//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004601// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004602//--------------------------------------------------
4603
4604SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004605Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004606{
4607 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4608 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4609};
4610
4611
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004612SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004613Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004614{
Greg Clayton638351a2010-12-04 00:10:17 +00004615 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton638351a2010-12-04 00:10:17 +00004616 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004617};
4618
4619
Jim Ingham7508e732010-08-09 23:31:02 +00004620
Greg Claytonabb33022011-11-08 02:43:13 +00004621