blob: fceeafd7ab01b4d7db766ee96d9da936bbfa4e8a [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"
Jim Inghamd21d98b2012-04-10 01:21:57 +000039#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
41using namespace lldb;
42using namespace lldb_private;
43
Greg Clayton24bc5d92011-03-30 18:16:51 +000044void
Greg Claytonb72d0f02011-04-12 05:54:46 +000045ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +000046{
47 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +000048 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +000049 s.Printf (" pid = %llu\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +000050
51 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +000052 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +000053
54 if (m_executable)
55 {
56 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
57 s.PutCString (" file = ");
58 m_executable.Dump(&s);
59 s.EOL();
60 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000061 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +000062 if (argc > 0)
63 {
64 for (uint32_t i=0; i<argc; i++)
65 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000066 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +000067 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +000068 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000069 else
Greg Claytonb72d0f02011-04-12 05:54:46 +000070 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000071 }
72 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000073
74 const uint32_t envc = m_environment.GetArgumentCount();
75 if (envc > 0)
76 {
77 for (uint32_t i=0; i<envc; i++)
78 {
79 const char *env = m_environment.GetArgumentAtIndex(i);
80 if (i < 10)
81 s.Printf (" env[%u] = %s\n", i, env);
82 else
83 s.Printf ("env[%u] = %s\n", i, env);
84 }
85 }
86
Greg Claytonff39f742011-04-01 00:29:43 +000087 if (m_arch.IsValid())
88 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
89
Greg Claytonb72d0f02011-04-12 05:54:46 +000090 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000091 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000092 cstr = platform->GetUserName (m_uid);
93 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000094 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000095 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000096 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000097 cstr = platform->GetGroupName (m_gid);
98 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000099 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000100 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000101 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000102 cstr = platform->GetUserName (m_euid);
103 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000104 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000105 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000106 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000107 cstr = platform->GetGroupName (m_egid);
108 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000109 }
110}
111
112void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000113ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000114{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000115 const char *label;
116 if (show_args || verbose)
117 label = "ARGUMENTS";
118 else
119 label = "NAME";
120
Greg Claytonff39f742011-04-01 00:29:43 +0000121 if (verbose)
122 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000123 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000124 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
125 }
126 else
127 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000128 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000129 s.PutCString ("====== ====== ========== ======= ============================\n");
130 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000131}
132
133void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000134ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000135{
136 if (m_pid != LLDB_INVALID_PROCESS_ID)
137 {
138 const char *cstr;
Greg Claytond9919d32011-12-01 23:28:38 +0000139 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000140
Greg Clayton24bc5d92011-03-30 18:16:51 +0000141
Greg Claytonff39f742011-04-01 00:29:43 +0000142 if (verbose)
143 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000144 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000145 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
146 s.Printf ("%-10s ", cstr);
147 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000148 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000149
Greg Claytonb72d0f02011-04-12 05:54:46 +0000150 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000151 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
152 s.Printf ("%-10s ", cstr);
153 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000154 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000155
Greg Claytonb72d0f02011-04-12 05:54:46 +0000156 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000157 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
158 s.Printf ("%-10s ", cstr);
159 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000160 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000161
Greg Claytonb72d0f02011-04-12 05:54:46 +0000162 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000163 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
164 s.Printf ("%-10s ", cstr);
165 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000166 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000167 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
168 }
169 else
170 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000171 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000172 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000173 (int)m_arch.GetTriple().getArchName().size(),
174 m_arch.GetTriple().getArchName().data());
175 }
176
Greg Claytonb72d0f02011-04-12 05:54:46 +0000177 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000178 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000179 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000180 if (argc > 0)
181 {
182 for (uint32_t i=0; i<argc; i++)
183 {
184 if (i > 0)
185 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000186 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000187 }
188 }
189 }
190 else
191 {
192 s.PutCString (GetName());
193 }
194
195 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000196 }
197}
198
Greg Claytonb72d0f02011-04-12 05:54:46 +0000199
200void
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000201ProcessInfo::SetArguments (char const **argv,
202 bool first_arg_is_executable,
203 bool first_arg_is_executable_and_argument)
204{
205 m_arguments.SetArguments (argv);
206
207 // Is the first argument the executable?
208 if (first_arg_is_executable)
209 {
210 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
211 if (first_arg)
212 {
213 // Yes the first argument is an executable, set it as the executable
214 // in the launch options. Don't resolve the file path as the path
215 // could be a remote platform path
216 const bool resolve = false;
217 m_executable.SetFile(first_arg, resolve);
218
219 // If argument zero is an executable and shouldn't be included
220 // in the arguments, remove it from the front of the arguments
221 if (first_arg_is_executable_and_argument == false)
222 m_arguments.DeleteArgumentAtIndex (0);
223 }
224 }
225}
226void
227ProcessInfo::SetArguments (const Args& args,
228 bool first_arg_is_executable,
229 bool first_arg_is_executable_and_argument)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000230{
231 // Copy all arguments
232 m_arguments = args;
233
234 // Is the first argument the executable?
235 if (first_arg_is_executable)
236 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000237 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000238 if (first_arg)
239 {
240 // Yes the first argument is an executable, set it as the executable
241 // in the launch options. Don't resolve the file path as the path
242 // could be a remote platform path
243 const bool resolve = false;
244 m_executable.SetFile(first_arg, resolve);
245
246 // If argument zero is an executable and shouldn't be included
247 // in the arguments, remove it from the front of the arguments
248 if (first_arg_is_executable_and_argument == false)
249 m_arguments.DeleteArgumentAtIndex (0);
250 }
251 }
252}
253
Greg Claytonabb33022011-11-08 02:43:13 +0000254void
Greg Clayton464c6162011-11-17 22:14:31 +0000255ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000256{
257 // If notthing was specified, then check the process for any default
258 // settings that were set with "settings set"
259 if (m_file_actions.empty())
260 {
Greg Claytonabb33022011-11-08 02:43:13 +0000261 if (m_flags.Test(eLaunchFlagDisableSTDIO))
262 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000263 AppendSuppressFileAction (STDIN_FILENO , true, false);
264 AppendSuppressFileAction (STDOUT_FILENO, false, true);
265 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000266 }
267 else
268 {
269 // Check for any values that might have gotten set with any of:
270 // (lldb) settings set target.input-path
271 // (lldb) settings set target.output-path
272 // (lldb) settings set target.error-path
Greg Clayton464c6162011-11-17 22:14:31 +0000273 const char *in_path = NULL;
274 const char *out_path = NULL;
275 const char *err_path = NULL;
Greg Claytonabb33022011-11-08 02:43:13 +0000276 if (target)
277 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000278 in_path = target->GetStandardInputPath();
279 out_path = target->GetStandardOutputPath();
280 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000281 }
282
283 if (default_to_use_pty && (!in_path && !out_path && !err_path))
284 {
285 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000286 {
Greg Clayton464c6162011-11-17 22:14:31 +0000287 in_path = out_path = err_path = m_pty.GetSlaveName (NULL, 0);
Greg Claytonabb33022011-11-08 02:43:13 +0000288 }
289 }
290
Greg Clayton464c6162011-11-17 22:14:31 +0000291 if (in_path)
Greg Clayton95ec1682012-03-06 04:01:04 +0000292 AppendOpenFileAction(STDIN_FILENO, in_path, true, false);
293
Greg Clayton464c6162011-11-17 22:14:31 +0000294 if (out_path)
Greg Clayton95ec1682012-03-06 04:01:04 +0000295 AppendOpenFileAction(STDOUT_FILENO, out_path, false, true);
Greg Clayton464c6162011-11-17 22:14:31 +0000296
297 if (err_path)
Greg Clayton95ec1682012-03-06 04:01:04 +0000298 AppendOpenFileAction(STDERR_FILENO, err_path, false, true);
299
Greg Claytonabb33022011-11-08 02:43:13 +0000300 }
301 }
302}
303
Greg Clayton527154d2011-11-15 03:53:30 +0000304
305bool
Greg Clayton97471182012-04-14 01:42:46 +0000306ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error,
307 bool localhost,
308 bool will_debug,
309 bool first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000310{
311 error.Clear();
312
313 if (GetFlags().Test (eLaunchFlagLaunchInShell))
314 {
315 const char *shell_executable = GetShell();
316 if (shell_executable)
317 {
318 char shell_resolved_path[PATH_MAX];
319
320 if (localhost)
321 {
322 FileSpec shell_filespec (shell_executable, true);
323
324 if (!shell_filespec.Exists())
325 {
326 // Resolve the path in case we just got "bash", "sh" or "tcsh"
327 if (!shell_filespec.ResolveExecutableLocation ())
328 {
329 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
330 return false;
331 }
332 }
333 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
334 shell_executable = shell_resolved_path;
335 }
336
337 Args shell_arguments;
338 std::string safe_arg;
339 shell_arguments.AppendArgument (shell_executable);
Greg Clayton527154d2011-11-15 03:53:30 +0000340 shell_arguments.AppendArgument ("-c");
Greg Clayton97471182012-04-14 01:42:46 +0000341
342 StreamString shell_command;
343 if (will_debug)
Greg Clayton527154d2011-11-15 03:53:30 +0000344 {
Greg Clayton97471182012-04-14 01:42:46 +0000345 shell_command.PutCString ("exec");
346 if (GetArchitecture().IsValid())
347 {
348 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
349 // Set the resume count to 2:
350 // 1 - stop in shell
351 // 2 - stop in /usr/bin/arch
352 // 3 - then we will stop in our program
353 SetResumeCount(2);
354 }
355 else
356 {
357 // Set the resume count to 1:
358 // 1 - stop in shell
359 // 2 - then we will stop in our program
360 SetResumeCount(1);
361 }
Greg Clayton527154d2011-11-15 03:53:30 +0000362 }
363
364 const char **argv = GetArguments().GetConstArgumentVector ();
365 if (argv)
366 {
Greg Clayton97471182012-04-14 01:42:46 +0000367 if (first_arg_is_full_shell_command)
Greg Clayton527154d2011-11-15 03:53:30 +0000368 {
Greg Clayton97471182012-04-14 01:42:46 +0000369 // There should only be one argument that is the shell command itself to be used as is
370 if (argv[0] && !argv[1])
371 shell_command.Printf("%s", argv[0]);
372 else
373 return false;
Greg Clayton527154d2011-11-15 03:53:30 +0000374 }
Greg Clayton97471182012-04-14 01:42:46 +0000375 else
376 {
377 for (size_t i=0; argv[i] != NULL; ++i)
378 {
379 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
380 shell_command.Printf(" %s", arg);
381 }
382 }
383 shell_arguments.AppendArgument (shell_command.GetString().c_str());
Greg Clayton527154d2011-11-15 03:53:30 +0000384 }
Greg Clayton97471182012-04-14 01:42:46 +0000385 else
386 {
387 return false;
388 }
389
Greg Clayton527154d2011-11-15 03:53:30 +0000390 m_executable.SetFile(shell_executable, false);
391 m_arguments = shell_arguments;
392 return true;
393 }
394 else
395 {
396 error.SetErrorString ("invalid shell path");
397 }
398 }
399 else
400 {
401 error.SetErrorString ("not launching in shell");
402 }
403 return false;
404}
405
406
Greg Clayton24bc5d92011-03-30 18:16:51 +0000407bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000408ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
409{
410 if ((read || write) && fd >= 0 && path && path[0])
411 {
412 m_action = eFileActionOpen;
413 m_fd = fd;
414 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000415 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000416 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000417 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000418 else
Greg Clayton527154d2011-11-15 03:53:30 +0000419 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000420 m_path.assign (path);
421 return true;
422 }
423 else
424 {
425 Clear();
426 }
427 return false;
428}
429
430bool
431ProcessLaunchInfo::FileAction::Close (int fd)
432{
433 Clear();
434 if (fd >= 0)
435 {
436 m_action = eFileActionClose;
437 m_fd = fd;
438 }
439 return m_fd >= 0;
440}
441
442
443bool
444ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
445{
446 Clear();
447 if (fd >= 0 && dup_fd >= 0)
448 {
449 m_action = eFileActionDuplicate;
450 m_fd = fd;
451 m_arg = dup_fd;
452 }
453 return m_fd >= 0;
454}
455
456
457
458bool
459ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
460 const FileAction *info,
461 Log *log,
462 Error& error)
463{
464 if (info == NULL)
465 return false;
466
467 switch (info->m_action)
468 {
469 case eFileActionNone:
470 error.Clear();
471 break;
472
473 case eFileActionClose:
474 if (info->m_fd == -1)
475 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
476 else
477 {
478 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
479 eErrorTypePOSIX);
480 if (log && (error.Fail() || log))
481 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
482 file_actions, info->m_fd);
483 }
484 break;
485
486 case eFileActionDuplicate:
487 if (info->m_fd == -1)
488 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
489 else if (info->m_arg == -1)
490 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
491 else
492 {
493 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
494 eErrorTypePOSIX);
495 if (log && (error.Fail() || log))
496 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
497 file_actions, info->m_fd, info->m_arg);
498 }
499 break;
500
501 case eFileActionOpen:
502 if (info->m_fd == -1)
503 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
504 else
505 {
506 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000507
Greg Claytonb72d0f02011-04-12 05:54:46 +0000508 mode_t mode = 0;
509
Greg Clayton527154d2011-11-15 03:53:30 +0000510 if (oflag & O_CREAT)
511 mode = 0640;
512
Greg Claytonb72d0f02011-04-12 05:54:46 +0000513 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
514 info->m_fd,
515 info->m_path.c_str(),
516 oflag,
517 mode),
518 eErrorTypePOSIX);
519 if (error.Fail() || log)
520 error.PutToLog(log,
521 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
522 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
523 }
524 break;
525
526 default:
527 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
528 break;
529 }
530 return error.Success();
531}
532
533Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000534ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000535{
536 Error error;
537 char short_option = (char) m_getopt_table[option_idx].val;
538
539 switch (short_option)
540 {
541 case 's': // Stop at program entry point
542 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
543 break;
544
Greg Claytonb72d0f02011-04-12 05:54:46 +0000545 case 'i': // STDIN for read only
546 {
547 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000548 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000549 launch_info.AppendFileAction (action);
550 }
551 break;
552
553 case 'o': // Open STDOUT for write only
554 {
555 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000556 if (action.Open (STDOUT_FILENO, option_arg, false, true))
557 launch_info.AppendFileAction (action);
558 }
559 break;
560
561 case 'e': // STDERR for write only
562 {
563 ProcessLaunchInfo::FileAction action;
564 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000565 launch_info.AppendFileAction (action);
566 }
567 break;
568
Greg Clayton95ec1682012-03-06 04:01:04 +0000569
Greg Claytonb72d0f02011-04-12 05:54:46 +0000570 case 'p': // Process plug-in name
571 launch_info.SetProcessPluginName (option_arg);
572 break;
573
574 case 'n': // Disable STDIO
575 {
576 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000577 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000578 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000579 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000580 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000581 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000582 launch_info.AppendFileAction (action);
583 }
584 break;
585
586 case 'w':
587 launch_info.SetWorkingDirectory (option_arg);
588 break;
589
590 case 't': // Open process in new terminal window
591 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
592 break;
593
594 case 'a':
Greg Claytonb170aee2012-05-08 01:45:38 +0000595 if (!launch_info.GetArchitecture().SetTriple (option_arg, m_interpreter.GetPlatform(true).get()))
596 launch_info.GetArchitecture().SetTriple (option_arg);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000597 break;
598
599 case 'A':
600 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
601 break;
602
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000603 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000604 if (option_arg && option_arg[0])
605 launch_info.SetShell (option_arg);
606 else
607 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000608 break;
609
Greg Claytonb72d0f02011-04-12 05:54:46 +0000610 case 'v':
611 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
612 break;
613
614 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000615 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000616 break;
617
618 }
619 return error;
620}
621
622OptionDefinition
623ProcessLaunchCommandOptions::g_option_table[] =
624{
625{ 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."},
626{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
627{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
628{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
629{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
630{ 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 +0000631{ 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 +0000632
633{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
634{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
635{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
636
637{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
638
639{ 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."},
640
641{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
642};
643
644
645
646bool
647ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000648{
649 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
650 return true;
651 const char *match_name = m_match_info.GetName();
652 if (!match_name)
653 return true;
654
655 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
656}
657
658bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000659ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000660{
661 if (!NameMatches (proc_info.GetName()))
662 return false;
663
664 if (m_match_info.ProcessIDIsValid() &&
665 m_match_info.GetProcessID() != proc_info.GetProcessID())
666 return false;
667
668 if (m_match_info.ParentProcessIDIsValid() &&
669 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
670 return false;
671
Greg Claytonb72d0f02011-04-12 05:54:46 +0000672 if (m_match_info.UserIDIsValid () &&
673 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000674 return false;
675
Greg Claytonb72d0f02011-04-12 05:54:46 +0000676 if (m_match_info.GroupIDIsValid () &&
677 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000678 return false;
679
680 if (m_match_info.EffectiveUserIDIsValid () &&
681 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
682 return false;
683
684 if (m_match_info.EffectiveGroupIDIsValid () &&
685 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
686 return false;
687
688 if (m_match_info.GetArchitecture().IsValid() &&
689 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
690 return false;
691 return true;
692}
693
694bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000695ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000696{
697 if (m_name_match_type != eNameMatchIgnore)
698 return false;
699
700 if (m_match_info.ProcessIDIsValid())
701 return false;
702
703 if (m_match_info.ParentProcessIDIsValid())
704 return false;
705
Greg Claytonb72d0f02011-04-12 05:54:46 +0000706 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000707 return false;
708
Greg Claytonb72d0f02011-04-12 05:54:46 +0000709 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000710 return false;
711
712 if (m_match_info.EffectiveUserIDIsValid ())
713 return false;
714
715 if (m_match_info.EffectiveGroupIDIsValid ())
716 return false;
717
718 if (m_match_info.GetArchitecture().IsValid())
719 return false;
720
721 if (m_match_all_users)
722 return false;
723
724 return true;
725
726}
727
728void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000729ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000730{
731 m_match_info.Clear();
732 m_name_match_type = eNameMatchIgnore;
733 m_match_all_users = false;
734}
Greg Claytonfd119992011-01-07 06:08:19 +0000735
Greg Clayton46c9a352012-02-09 06:16:32 +0000736ProcessSP
737Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000738{
Greg Clayton46c9a352012-02-09 06:16:32 +0000739 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000740 ProcessCreateInstance create_callback = NULL;
741 if (plugin_name)
742 {
743 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
744 if (create_callback)
745 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000746 process_sp = create_callback(target, listener, crash_file_path);
747 if (process_sp)
748 {
749 if (!process_sp->CanDebug(target, true))
750 process_sp.reset();
751 }
Chris Lattner24943d22010-06-08 16:52:24 +0000752 }
753 }
754 else
755 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000756 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000757 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000758 process_sp = create_callback(target, listener, crash_file_path);
759 if (process_sp)
760 {
761 if (!process_sp->CanDebug(target, false))
762 process_sp.reset();
763 else
764 break;
765 }
Chris Lattner24943d22010-06-08 16:52:24 +0000766 }
767 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000768 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000769}
770
Jim Ingham5a15e692012-02-16 06:50:00 +0000771ConstString &
772Process::GetStaticBroadcasterClass ()
773{
774 static ConstString class_name ("lldb.process");
775 return class_name;
776}
Chris Lattner24943d22010-06-08 16:52:24 +0000777
778//----------------------------------------------------------------------
779// Process constructor
780//----------------------------------------------------------------------
781Process::Process(Target &target, Listener &listener) :
782 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000783 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Greg Clayton334d33a2012-01-30 07:41:31 +0000784 ProcessInstanceSettings (GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000785 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000786 m_public_state (eStateUnloaded),
787 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000788 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
789 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000790 m_private_state_listener ("lldb.process.internal_state_listener"),
791 m_private_state_control_wait(),
792 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000793 m_mod_id (),
Chris Lattner24943d22010-06-08 16:52:24 +0000794 m_thread_index_id (0),
795 m_exit_status (-1),
796 m_exit_string (),
797 m_thread_list (this),
798 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000799 m_image_tokens (),
800 m_listener (listener),
801 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000802 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000803 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000804 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000805 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000806 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000807 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000808 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000809 m_stderr_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000810 m_memory_cache (*this),
811 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +0000812 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000813 m_next_event_action_ap(),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000814 m_run_lock (),
Jim Ingham43892562012-06-06 00:29:30 +0000815 m_currently_handling_event(false),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000816 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +0000817{
Caroline Tice1ebef442010-09-27 00:30:10 +0000818 UpdateInstanceName();
Jim Ingham5a15e692012-02-16 06:50:00 +0000819
820 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +0000821
Greg Claytone005f2c2010-11-06 01:53:30 +0000822 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000823 if (log)
824 log->Printf ("%p Process::Process()", this);
825
Greg Clayton49ce6822010-10-31 03:01:06 +0000826 SetEventName (eBroadcastBitStateChanged, "state-changed");
827 SetEventName (eBroadcastBitInterrupt, "interrupt");
828 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
829 SetEventName (eBroadcastBitSTDERR, "stderr-available");
830
Chris Lattner24943d22010-06-08 16:52:24 +0000831 listener.StartListeningForEvents (this,
832 eBroadcastBitStateChanged |
833 eBroadcastBitInterrupt |
834 eBroadcastBitSTDOUT |
835 eBroadcastBitSTDERR);
836
837 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
838 eBroadcastBitStateChanged);
839
840 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
841 eBroadcastInternalStateControlStop |
842 eBroadcastInternalStateControlPause |
843 eBroadcastInternalStateControlResume);
844}
845
846//----------------------------------------------------------------------
847// Destructor
848//----------------------------------------------------------------------
849Process::~Process()
850{
Greg Claytone005f2c2010-11-06 01:53:30 +0000851 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000852 if (log)
853 log->Printf ("%p Process::~Process()", this);
854 StopPrivateStateThread();
855}
856
857void
858Process::Finalize()
859{
Greg Claytonffa43a62011-11-17 04:46:02 +0000860 switch (GetPrivateState())
861 {
862 case eStateConnected:
863 case eStateAttaching:
864 case eStateLaunching:
865 case eStateStopped:
866 case eStateRunning:
867 case eStateStepping:
868 case eStateCrashed:
869 case eStateSuspended:
870 if (GetShouldDetach())
871 Detach();
872 else
873 Destroy();
874 break;
875
876 case eStateInvalid:
877 case eStateUnloaded:
878 case eStateDetached:
879 case eStateExited:
880 break;
881 }
882
Greg Clayton2f57db02011-10-01 00:45:15 +0000883 // Clear our broadcaster before we proceed with destroying
884 Broadcaster::Clear();
885
Chris Lattner24943d22010-06-08 16:52:24 +0000886 // Do any cleanup needed prior to being destructed... Subclasses
887 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000888
889 // We need to destroy the loader before the derived Process class gets destroyed
890 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +0000891 m_dynamic_checkers_ap.reset();
892 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +0000893 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +0000894 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +0000895 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +0000896 std::vector<Notifications> empty_notifications;
897 m_notifications.swap(empty_notifications);
898 m_image_tokens.clear();
899 m_memory_cache.Clear();
900 m_allocated_memory_cache.Clear();
901 m_language_runtimes.clear();
902 m_next_event_action_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000903}
904
905void
906Process::RegisterNotificationCallbacks (const Notifications& callbacks)
907{
908 m_notifications.push_back(callbacks);
909 if (callbacks.initialize != NULL)
910 callbacks.initialize (callbacks.baton, this);
911}
912
913bool
914Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
915{
916 std::vector<Notifications>::iterator pos, end = m_notifications.end();
917 for (pos = m_notifications.begin(); pos != end; ++pos)
918 {
919 if (pos->baton == callbacks.baton &&
920 pos->initialize == callbacks.initialize &&
921 pos->process_state_changed == callbacks.process_state_changed)
922 {
923 m_notifications.erase(pos);
924 return true;
925 }
926 }
927 return false;
928}
929
930void
931Process::SynchronouslyNotifyStateChanged (StateType state)
932{
933 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
934 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
935 {
936 if (notification_pos->process_state_changed)
937 notification_pos->process_state_changed (notification_pos->baton, this, state);
938 }
939}
940
941// FIXME: We need to do some work on events before the general Listener sees them.
942// For instance if we are continuing from a breakpoint, we need to ensure that we do
943// the little "insert real insn, step & stop" trick. But we can't do that when the
944// event is delivered by the broadcaster - since that is done on the thread that is
945// waiting for new events, so if we needed more than one event for our handling, we would
946// stall. So instead we do it when we fetch the event off of the queue.
947//
948
949StateType
950Process::GetNextEvent (EventSP &event_sp)
951{
952 StateType state = eStateInvalid;
953
954 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
955 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
956
957 return state;
958}
959
960
961StateType
962Process::WaitForProcessToStop (const TimeValue *timeout)
963{
Jim Ingham21f37ad2011-08-09 02:12:22 +0000964 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
965 // We have to actually check each event, and in the case of a stopped event check the restarted flag
966 // on the event.
967 EventSP event_sp;
968 StateType state = GetState();
969 // If we are exited or detached, we won't ever get back to any
970 // other valid state...
971 if (state == eStateDetached || state == eStateExited)
972 return state;
973
974 while (state != eStateInvalid)
975 {
976 state = WaitForStateChangedEvents (timeout, event_sp);
977 switch (state)
978 {
979 case eStateCrashed:
980 case eStateDetached:
981 case eStateExited:
982 case eStateUnloaded:
983 return state;
984 case eStateStopped:
985 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
986 continue;
987 else
988 return state;
989 default:
990 continue;
991 }
992 }
993 return state;
Chris Lattner24943d22010-06-08 16:52:24 +0000994}
995
996
997StateType
998Process::WaitForState
999(
1000 const TimeValue *timeout,
1001 const StateType *match_states, const uint32_t num_match_states
1002)
1003{
1004 EventSP event_sp;
1005 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001006 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001007 while (state != eStateInvalid)
1008 {
Greg Claytond8c62532010-10-07 04:19:01 +00001009 // If we are exited or detached, we won't ever get back to any
1010 // other valid state...
1011 if (state == eStateDetached || state == eStateExited)
1012 return state;
1013
Chris Lattner24943d22010-06-08 16:52:24 +00001014 state = WaitForStateChangedEvents (timeout, event_sp);
1015
1016 for (i=0; i<num_match_states; ++i)
1017 {
1018 if (match_states[i] == state)
1019 return state;
1020 }
1021 }
1022 return state;
1023}
1024
Jim Ingham63e24d72010-10-11 23:53:14 +00001025bool
1026Process::HijackProcessEvents (Listener *listener)
1027{
1028 if (listener != NULL)
1029 {
1030 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
1031 }
1032 else
1033 return false;
1034}
1035
1036void
1037Process::RestoreProcessEvents ()
1038{
1039 RestoreBroadcaster();
1040}
1041
Jim Inghamf9f40c22011-02-08 05:20:59 +00001042bool
1043Process::HijackPrivateProcessEvents (Listener *listener)
1044{
1045 if (listener != NULL)
1046 {
1047 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
1048 }
1049 else
1050 return false;
1051}
1052
1053void
1054Process::RestorePrivateProcessEvents ()
1055{
1056 m_private_state_broadcaster.RestoreBroadcaster();
1057}
1058
Chris Lattner24943d22010-06-08 16:52:24 +00001059StateType
1060Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1061{
Greg Claytone005f2c2010-11-06 01:53:30 +00001062 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001063
1064 if (log)
1065 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1066
1067 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001068 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1069 this,
1070 eBroadcastBitStateChanged,
1071 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +00001072 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1073
1074 if (log)
1075 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1076 __FUNCTION__,
1077 timeout,
1078 StateAsCString(state));
1079 return state;
1080}
1081
1082Event *
1083Process::PeekAtStateChangedEvents ()
1084{
Greg Claytone005f2c2010-11-06 01:53:30 +00001085 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001086
1087 if (log)
1088 log->Printf ("Process::%s...", __FUNCTION__);
1089
1090 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001091 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1092 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001093 if (log)
1094 {
1095 if (event_ptr)
1096 {
1097 log->Printf ("Process::%s (event_ptr) => %s",
1098 __FUNCTION__,
1099 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1100 }
1101 else
1102 {
1103 log->Printf ("Process::%s no events found",
1104 __FUNCTION__);
1105 }
1106 }
1107 return event_ptr;
1108}
1109
1110StateType
1111Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1112{
Greg Claytone005f2c2010-11-06 01:53:30 +00001113 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001114
1115 if (log)
1116 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1117
1118 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001119 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1120 &m_private_state_broadcaster,
1121 eBroadcastBitStateChanged,
1122 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +00001123 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1124
1125 // This is a bit of a hack, but when we wait here we could very well return
1126 // to the command-line, and that could disable the log, which would render the
1127 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001128 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001129 {
1130 if (state == eStateInvalid)
1131 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1132 else
1133 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1134 }
Chris Lattner24943d22010-06-08 16:52:24 +00001135 return state;
1136}
1137
1138bool
1139Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1140{
Greg Claytone005f2c2010-11-06 01:53:30 +00001141 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001142
1143 if (log)
1144 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1145
1146 if (control_only)
1147 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1148 else
1149 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1150}
1151
1152bool
1153Process::IsRunning () const
1154{
1155 return StateIsRunningState (m_public_state.GetValue());
1156}
1157
1158int
1159Process::GetExitStatus ()
1160{
1161 if (m_public_state.GetValue() == eStateExited)
1162 return m_exit_status;
1163 return -1;
1164}
1165
Greg Clayton638351a2010-12-04 00:10:17 +00001166
Chris Lattner24943d22010-06-08 16:52:24 +00001167const char *
1168Process::GetExitDescription ()
1169{
1170 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1171 return m_exit_string.c_str();
1172 return NULL;
1173}
1174
Greg Clayton72e1c782011-01-22 23:43:18 +00001175bool
Chris Lattner24943d22010-06-08 16:52:24 +00001176Process::SetExitStatus (int status, const char *cstr)
1177{
Greg Clayton68ca8232011-01-25 02:58:48 +00001178 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1179 if (log)
1180 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1181 status, status,
1182 cstr ? "\"" : "",
1183 cstr ? cstr : "NULL",
1184 cstr ? "\"" : "");
1185
Greg Clayton72e1c782011-01-22 23:43:18 +00001186 // We were already in the exited state
1187 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001188 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001189 if (log)
1190 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001191 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001192 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001193
1194 m_exit_status = status;
1195 if (cstr)
1196 m_exit_string = cstr;
1197 else
1198 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001199
Greg Clayton72e1c782011-01-22 23:43:18 +00001200 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001201
Greg Clayton72e1c782011-01-22 23:43:18 +00001202 SetPrivateState (eStateExited);
1203 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001204}
1205
1206// This static callback can be used to watch for local child processes on
1207// the current host. The the child process exits, the process will be
1208// found in the global target list (we want to be completely sure that the
1209// lldb_private::Process doesn't go away before we can deliver the signal.
1210bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001211Process::SetProcessExitStatus (void *callback_baton,
1212 lldb::pid_t pid,
1213 bool exited,
1214 int signo, // Zero for no signal
1215 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001216)
1217{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001218 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1219 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00001220 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001221 callback_baton,
1222 pid,
1223 exited,
1224 signo,
1225 exit_status);
1226
1227 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001228 {
Greg Clayton63094e02010-06-23 01:19:29 +00001229 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001230 if (target_sp)
1231 {
1232 ProcessSP process_sp (target_sp->GetProcessSP());
1233 if (process_sp)
1234 {
1235 const char *signal_cstr = NULL;
1236 if (signo)
1237 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1238
1239 process_sp->SetExitStatus (exit_status, signal_cstr);
1240 }
1241 }
1242 return true;
1243 }
1244 return false;
1245}
1246
1247
Greg Clayton37f962e2011-08-22 02:49:39 +00001248void
1249Process::UpdateThreadListIfNeeded ()
1250{
1251 const uint32_t stop_id = GetStopID();
1252 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1253 {
Greg Clayton20206082011-11-17 01:23:07 +00001254 const StateType state = GetPrivateState();
1255 if (StateIsStoppedState (state, true))
1256 {
1257 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001258 // m_thread_list does have its own mutex, but we need to
1259 // hold onto the mutex between the call to UpdateThreadList(...)
1260 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001261 ThreadList new_thread_list(this);
1262 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001263 // thread list, but only update if "true" is returned
1264 if (UpdateThreadList (m_thread_list, new_thread_list))
1265 {
1266 OperatingSystem *os = GetOperatingSystem ();
1267 if (os)
1268 os->UpdateThreadList (m_thread_list, new_thread_list);
1269 m_thread_list.Update (new_thread_list);
1270 m_thread_list.SetStopID (stop_id);
1271 }
Greg Clayton20206082011-11-17 01:23:07 +00001272 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001273 }
1274}
1275
Chris Lattner24943d22010-06-08 16:52:24 +00001276uint32_t
1277Process::GetNextThreadIndexID ()
1278{
1279 return ++m_thread_index_id;
1280}
1281
1282StateType
1283Process::GetState()
1284{
1285 // If any other threads access this we will need a mutex for it
1286 return m_public_state.GetValue ();
1287}
1288
1289void
1290Process::SetPublicState (StateType new_state)
1291{
Greg Clayton68ca8232011-01-25 02:58:48 +00001292 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001293 if (log)
1294 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001295 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001296 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001297
1298 // On the transition from Run to Stopped, we unlock the writer end of the
1299 // run lock. The lock gets locked in Resume, which is the public API
1300 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001301 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1302 {
Sean Callanana3772862012-06-02 01:16:20 +00001303 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001304 {
Sean Callanana3772862012-06-02 01:16:20 +00001305 if (log)
1306 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1307 m_run_lock.WriteUnlock();
1308 }
1309 else
1310 {
1311 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1312 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1313 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001314 {
Sean Callanana3772862012-06-02 01:16:20 +00001315 if (new_state_is_stopped)
1316 {
1317 if (log)
1318 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1319 m_run_lock.WriteUnlock();
1320 }
Greg Claytona894fe72012-04-05 16:12:35 +00001321 }
Greg Claytona894fe72012-04-05 16:12:35 +00001322 }
1323 }
Chris Lattner24943d22010-06-08 16:52:24 +00001324}
1325
Jim Ingham027aaa72012-04-19 01:40:33 +00001326Error
1327Process::Resume ()
1328{
1329 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1330 if (log)
1331 log->Printf("Process::Resume -- locking run lock");
1332 if (!m_run_lock.WriteTryLock())
1333 {
1334 Error error("Resume request failed - process still running.");
1335 if (log)
1336 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1337 return error;
1338 }
1339 return PrivateResume();
1340}
1341
Chris Lattner24943d22010-06-08 16:52:24 +00001342StateType
1343Process::GetPrivateState ()
1344{
1345 return m_private_state.GetValue();
1346}
1347
1348void
1349Process::SetPrivateState (StateType new_state)
1350{
Greg Clayton68ca8232011-01-25 02:58:48 +00001351 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001352 bool state_changed = false;
1353
1354 if (log)
1355 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1356
1357 Mutex::Locker locker(m_private_state.GetMutex());
1358
1359 const StateType old_state = m_private_state.GetValueNoLock ();
1360 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001361 // This code is left commented out in case we ever need to control
1362 // the private process state with another run lock. Right now it doesn't
1363 // seem like we need to do this, but if we ever do, we can uncomment and
1364 // use this code.
1365// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1366// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1367// if (old_state_is_stopped != new_state_is_stopped)
1368// {
1369// if (new_state_is_stopped)
1370// m_private_run_lock.WriteUnlock();
1371// else
1372// m_private_run_lock.WriteLock();
1373// }
1374
Chris Lattner24943d22010-06-08 16:52:24 +00001375 if (state_changed)
1376 {
1377 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001378 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001379 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001380 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001381 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001382 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001383 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001384 }
1385 // Use our target to get a shared pointer to ourselves...
1386 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1387 }
1388 else
1389 {
1390 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001391 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001392 }
1393}
1394
Jim Ingham0296fe72011-11-08 03:00:11 +00001395void
1396Process::SetRunningUserExpression (bool on)
1397{
1398 m_mod_id.SetRunningUserExpression (on);
1399}
1400
Chris Lattner24943d22010-06-08 16:52:24 +00001401addr_t
1402Process::GetImageInfoAddress()
1403{
1404 return LLDB_INVALID_ADDRESS;
1405}
1406
Greg Clayton0baa3942010-11-04 01:54:29 +00001407//----------------------------------------------------------------------
1408// LoadImage
1409//
1410// This function provides a default implementation that works for most
1411// unix variants. Any Process subclasses that need to do shared library
1412// loading differently should override LoadImage and UnloadImage and
1413// do what is needed.
1414//----------------------------------------------------------------------
1415uint32_t
1416Process::LoadImage (const FileSpec &image_spec, Error &error)
1417{
Greg Clayton77d40712012-04-18 00:05:19 +00001418 char path[PATH_MAX];
1419 image_spec.GetPath(path, sizeof(path));
1420
Greg Clayton0baa3942010-11-04 01:54:29 +00001421 DynamicLoader *loader = GetDynamicLoader();
1422 if (loader)
1423 {
1424 error = loader->CanLoadImage();
1425 if (error.Fail())
1426 return LLDB_INVALID_IMAGE_TOKEN;
1427 }
1428
1429 if (error.Success())
1430 {
1431 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001432
1433 if (thread_sp)
1434 {
1435 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1436
1437 if (frame_sp)
1438 {
1439 ExecutionContext exe_ctx;
1440 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001441 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001442 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001443 expr.Printf("dlopen (\"%s\", 2)", path);
1444 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001445 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001446 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 +00001447 error = result_valobj_sp->GetError();
1448 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001449 {
1450 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001451 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001452 {
1453 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1454 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1455 {
1456 uint32_t image_token = m_image_tokens.size();
1457 m_image_tokens.push_back (image_ptr);
1458 return image_token;
1459 }
1460 }
1461 }
1462 }
1463 }
1464 }
Greg Clayton77d40712012-04-18 00:05:19 +00001465 if (!error.AsCString())
1466 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001467 return LLDB_INVALID_IMAGE_TOKEN;
1468}
1469
1470//----------------------------------------------------------------------
1471// UnloadImage
1472//
1473// This function provides a default implementation that works for most
1474// unix variants. Any Process subclasses that need to do shared library
1475// loading differently should override LoadImage and UnloadImage and
1476// do what is needed.
1477//----------------------------------------------------------------------
1478Error
1479Process::UnloadImage (uint32_t image_token)
1480{
1481 Error error;
1482 if (image_token < m_image_tokens.size())
1483 {
1484 const addr_t image_addr = m_image_tokens[image_token];
1485 if (image_addr == LLDB_INVALID_ADDRESS)
1486 {
1487 error.SetErrorString("image already unloaded");
1488 }
1489 else
1490 {
1491 DynamicLoader *loader = GetDynamicLoader();
1492 if (loader)
1493 error = loader->CanLoadImage();
1494
1495 if (error.Success())
1496 {
1497 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001498
1499 if (thread_sp)
1500 {
1501 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1502
1503 if (frame_sp)
1504 {
1505 ExecutionContext exe_ctx;
1506 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001507 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001508 StreamString expr;
1509 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1510 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001511 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001512 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 +00001513 if (result_valobj_sp->GetError().Success())
1514 {
1515 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001516 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001517 {
1518 if (scalar.UInt(1))
1519 {
1520 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1521 }
1522 else
1523 {
1524 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1525 }
1526 }
1527 }
1528 else
1529 {
1530 error = result_valobj_sp->GetError();
1531 }
1532 }
1533 }
1534 }
1535 }
1536 }
1537 else
1538 {
1539 error.SetErrorString("invalid image token");
1540 }
1541 return error;
1542}
1543
Greg Clayton75906e42011-05-11 18:39:18 +00001544const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001545Process::GetABI()
1546{
Greg Clayton75906e42011-05-11 18:39:18 +00001547 if (!m_abi_sp)
1548 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1549 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001550}
1551
Jim Ingham642036f2010-09-23 02:01:19 +00001552LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001553Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001554{
1555 LanguageRuntimeCollection::iterator pos;
1556 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001557 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001558 {
Jim Inghame3117662012-03-10 00:22:19 +00001559 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001560
Jim Inghame3117662012-03-10 00:22:19 +00001561 m_language_runtimes[language] = runtime_sp;
1562 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001563 }
1564 else
1565 return (*pos).second.get();
1566}
1567
1568CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001569Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001570{
Jim Inghame3117662012-03-10 00:22:19 +00001571 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001572 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1573 return static_cast<CPPLanguageRuntime *> (runtime);
1574 return NULL;
1575}
1576
1577ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001578Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001579{
Jim Inghame3117662012-03-10 00:22:19 +00001580 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001581 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1582 return static_cast<ObjCLanguageRuntime *> (runtime);
1583 return NULL;
1584}
1585
Enrico Granata6b1763b2012-05-21 16:51:35 +00001586bool
1587Process::IsPossibleDynamicValue (ValueObject& in_value)
1588{
1589 if (in_value.IsDynamic())
1590 return false;
1591 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1592
1593 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1594 {
1595 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1596 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1597 }
1598
1599 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1600 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1601 return true;
1602
1603 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1604 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1605}
1606
Chris Lattner24943d22010-06-08 16:52:24 +00001607BreakpointSiteList &
1608Process::GetBreakpointSiteList()
1609{
1610 return m_breakpoint_site_list;
1611}
1612
1613const BreakpointSiteList &
1614Process::GetBreakpointSiteList() const
1615{
1616 return m_breakpoint_site_list;
1617}
1618
1619
1620void
1621Process::DisableAllBreakpointSites ()
1622{
1623 m_breakpoint_site_list.SetEnabledForAll (false);
1624}
1625
1626Error
1627Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1628{
1629 Error error (DisableBreakpointSiteByID (break_id));
1630
1631 if (error.Success())
1632 m_breakpoint_site_list.Remove(break_id);
1633
1634 return error;
1635}
1636
1637Error
1638Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1639{
1640 Error error;
1641 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1642 if (bp_site_sp)
1643 {
1644 if (bp_site_sp->IsEnabled())
1645 error = DisableBreakpoint (bp_site_sp.get());
1646 }
1647 else
1648 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001649 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001650 }
1651
1652 return error;
1653}
1654
1655Error
1656Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1657{
1658 Error error;
1659 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1660 if (bp_site_sp)
1661 {
1662 if (!bp_site_sp->IsEnabled())
1663 error = EnableBreakpoint (bp_site_sp.get());
1664 }
1665 else
1666 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001667 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001668 }
1669 return error;
1670}
1671
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001672lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001673Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001674{
Greg Clayton265ab332011-05-19 18:17:41 +00001675 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001676 if (load_addr != LLDB_INVALID_ADDRESS)
1677 {
1678 BreakpointSiteSP bp_site_sp;
1679
1680 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1681 // create a new breakpoint site and add it.
1682
1683 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1684
1685 if (bp_site_sp)
1686 {
1687 bp_site_sp->AddOwner (owner);
1688 owner->SetBreakpointSite (bp_site_sp);
1689 return bp_site_sp->GetID();
1690 }
1691 else
1692 {
1693 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1694 if (bp_site_sp)
1695 {
1696 if (EnableBreakpoint (bp_site_sp.get()).Success())
1697 {
1698 owner->SetBreakpointSite (bp_site_sp);
1699 return m_breakpoint_site_list.Add (bp_site_sp);
1700 }
1701 }
1702 }
1703 }
1704 // We failed to enable the breakpoint
1705 return LLDB_INVALID_BREAK_ID;
1706
1707}
1708
1709void
1710Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1711{
1712 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1713 if (num_owners == 0)
1714 {
1715 DisableBreakpoint(bp_site_sp.get());
1716 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1717 }
1718}
1719
1720
1721size_t
1722Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1723{
1724 size_t bytes_removed = 0;
1725 addr_t intersect_addr;
1726 size_t intersect_size;
1727 size_t opcode_offset;
1728 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001729 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001730 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001731
Jim Ingham82820f92011-06-29 19:42:28 +00001732 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001733 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001734 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001735 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001736 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001737 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001738 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001739 {
1740 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1741 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001742 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001743 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001744 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001745 }
Chris Lattner24943d22010-06-08 16:52:24 +00001746 }
1747 }
1748 }
1749 return bytes_removed;
1750}
1751
1752
Greg Claytonb1888f22011-03-19 01:12:21 +00001753
1754size_t
1755Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1756{
1757 PlatformSP platform_sp (m_target.GetPlatform());
1758 if (platform_sp)
1759 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1760 return 0;
1761}
1762
Chris Lattner24943d22010-06-08 16:52:24 +00001763Error
1764Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1765{
1766 Error error;
1767 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001768 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001769 const addr_t bp_addr = bp_site->GetLoadAddress();
1770 if (log)
1771 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1772 if (bp_site->IsEnabled())
1773 {
1774 if (log)
1775 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1776 return error;
1777 }
1778
1779 if (bp_addr == LLDB_INVALID_ADDRESS)
1780 {
1781 error.SetErrorString("BreakpointSite contains an invalid load address.");
1782 return error;
1783 }
1784 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1785 // trap for the breakpoint site
1786 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1787
1788 if (bp_opcode_size == 0)
1789 {
Greg Clayton9c236732011-10-26 00:56:27 +00001790 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001791 }
1792 else
1793 {
1794 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1795
1796 if (bp_opcode_bytes == NULL)
1797 {
1798 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1799 return error;
1800 }
1801
1802 // Save the original opcode by reading it
1803 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1804 {
1805 // Write a software breakpoint in place of the original opcode
1806 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1807 {
1808 uint8_t verify_bp_opcode_bytes[64];
1809 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1810 {
1811 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1812 {
1813 bp_site->SetEnabled(true);
1814 bp_site->SetType (BreakpointSite::eSoftware);
1815 if (log)
1816 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1817 bp_site->GetID(),
1818 (uint64_t)bp_addr);
1819 }
1820 else
Greg Clayton9c236732011-10-26 00:56:27 +00001821 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00001822 }
1823 else
1824 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1825 }
1826 else
1827 error.SetErrorString("Unable to write breakpoint trap to memory.");
1828 }
1829 else
1830 error.SetErrorString("Unable to read memory at breakpoint address.");
1831 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001832 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001833 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1834 bp_site->GetID(),
1835 (uint64_t)bp_addr,
1836 error.AsCString());
1837 return error;
1838}
1839
1840Error
1841Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1842{
1843 Error error;
1844 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001845 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001846 addr_t bp_addr = bp_site->GetLoadAddress();
1847 lldb::user_id_t breakID = bp_site->GetID();
1848 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001849 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001850
1851 if (bp_site->IsHardware())
1852 {
1853 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1854 }
1855 else if (bp_site->IsEnabled())
1856 {
1857 const size_t break_op_size = bp_site->GetByteSize();
1858 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1859 if (break_op_size > 0)
1860 {
1861 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001862 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001863 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001864 bool break_op_found = false;
1865
1866 // Read the breakpoint opcode
1867 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1868 {
1869 bool verify = false;
1870 // Make sure we have the a breakpoint opcode exists at this address
1871 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1872 {
1873 break_op_found = true;
1874 // We found a valid breakpoint opcode at this address, now restore
1875 // the saved opcode.
1876 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1877 {
1878 verify = true;
1879 }
1880 else
1881 error.SetErrorString("Memory write failed when restoring original opcode.");
1882 }
1883 else
1884 {
1885 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1886 // Set verify to true and so we can check if the original opcode has already been restored
1887 verify = true;
1888 }
1889
1890 if (verify)
1891 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001892 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001893 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001894 // Verify that our original opcode made it back to the inferior
1895 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1896 {
1897 // compare the memory we just read with the original opcode
1898 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1899 {
1900 // SUCCESS
1901 bp_site->SetEnabled(false);
1902 if (log)
1903 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1904 return error;
1905 }
1906 else
1907 {
1908 if (break_op_found)
1909 error.SetErrorString("Failed to restore original opcode.");
1910 }
1911 }
1912 else
1913 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1914 }
1915 }
1916 else
1917 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1918 }
1919 }
1920 else
1921 {
1922 if (log)
1923 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1924 return error;
1925 }
1926
1927 if (log)
1928 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1929 bp_site->GetID(),
1930 (uint64_t)bp_addr,
1931 error.AsCString());
1932 return error;
1933
1934}
1935
Sean Callananf90b5f32012-06-07 22:26:42 +00001936// Comment out line below to disable memory caching, overriding the process setting
1937// target.process.disable-memory-cache
Greg Claytonfd119992011-01-07 06:08:19 +00001938#define ENABLE_MEMORY_CACHING
1939// Uncomment to verify memory caching works after making changes to caching code
1940//#define VERIFY_MEMORY_READS
1941
Sean Callananf90b5f32012-06-07 22:26:42 +00001942size_t
1943Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1944{
1945 if (!GetDisableMemoryCache())
1946 {
Greg Claytonfd119992011-01-07 06:08:19 +00001947#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00001948 // Memory caching is enabled, with debug verification
1949
1950 if (buf && size)
1951 {
1952 // Uncomment the line below to make sure memory caching is working.
1953 // I ran this through the test suite and got no assertions, so I am
1954 // pretty confident this is working well. If any changes are made to
1955 // memory caching, uncomment the line below and test your changes!
1956
1957 // Verify all memory reads by using the cache first, then redundantly
1958 // reading the same memory from the inferior and comparing to make sure
1959 // everything is exactly the same.
1960 std::string verify_buf (size, '\0');
1961 assert (verify_buf.size() == size);
1962 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1963 Error verify_error;
1964 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1965 assert (cache_bytes_read == verify_bytes_read);
1966 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1967 assert (verify_error.Success() == error.Success());
1968 return cache_bytes_read;
1969 }
1970 return 0;
1971#else // !defined(VERIFY_MEMORY_READS)
1972 // Memory caching is enabled, without debug verification
1973
1974 return m_memory_cache.Read (addr, buf, size, error);
1975#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00001976 }
Sean Callananf90b5f32012-06-07 22:26:42 +00001977 else
1978 {
1979 // Memory caching is disabled
1980
1981 return ReadMemoryFromInferior (addr, buf, size, error);
1982 }
Greg Claytonfd119992011-01-07 06:08:19 +00001983}
Greg Claytonfd119992011-01-07 06:08:19 +00001984
Greg Claytondd29b972012-05-18 23:20:01 +00001985size_t
1986Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
1987{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00001988 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00001989 out_str.clear();
1990 addr_t curr_addr = addr;
1991 while (1)
1992 {
1993 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
1994 if (length == 0)
1995 break;
1996 out_str.append(buf, length);
1997 // If we got "length - 1" bytes, we didn't get the whole C string, we
1998 // need to read some more characters
1999 if (length == sizeof(buf) - 1)
2000 curr_addr += length;
2001 else
2002 break;
2003 }
2004 return out_str.size();
2005}
2006
Greg Claytonfd119992011-01-07 06:08:19 +00002007
2008size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002009Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002010{
2011 size_t total_cstr_len = 0;
2012 if (dst && dst_max_len)
2013 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002014 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002015 // NULL out everything just to be safe
2016 memset (dst, 0, dst_max_len);
2017 Error error;
2018 addr_t curr_addr = addr;
2019 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2020 size_t bytes_left = dst_max_len - 1;
2021 char *curr_dst = dst;
2022
2023 while (bytes_left > 0)
2024 {
2025 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2026 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2027 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2028
2029 if (bytes_read == 0)
2030 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002031 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002032 dst[total_cstr_len] = '\0';
2033 break;
2034 }
2035 const size_t len = strlen(curr_dst);
2036
2037 total_cstr_len += len;
2038
2039 if (len < bytes_to_read)
2040 break;
2041
2042 curr_dst += bytes_read;
2043 curr_addr += bytes_read;
2044 bytes_left -= bytes_read;
2045 }
2046 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002047 else
2048 {
2049 if (dst == NULL)
2050 result_error.SetErrorString("invalid arguments");
2051 else
2052 result_error.Clear();
2053 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002054 return total_cstr_len;
2055}
2056
2057size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002058Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2059{
Chris Lattner24943d22010-06-08 16:52:24 +00002060 if (buf == NULL || size == 0)
2061 return 0;
2062
2063 size_t bytes_read = 0;
2064 uint8_t *bytes = (uint8_t *)buf;
2065
2066 while (bytes_read < size)
2067 {
2068 const size_t curr_size = size - bytes_read;
2069 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2070 bytes + bytes_read,
2071 curr_size,
2072 error);
2073 bytes_read += curr_bytes_read;
2074 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2075 break;
2076 }
2077
2078 // Replace any software breakpoint opcodes that fall into this range back
2079 // into "buf" before we return
2080 if (bytes_read > 0)
2081 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2082 return bytes_read;
2083}
2084
Greg Claytonf72fdee2010-12-16 20:01:20 +00002085uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002086Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002087{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002088 Scalar scalar;
2089 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2090 return scalar.ULongLong(fail_value);
2091 return fail_value;
2092}
2093
2094addr_t
2095Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2096{
2097 Scalar scalar;
2098 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2099 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2100 return LLDB_INVALID_ADDRESS;
2101}
2102
2103
2104bool
2105Process::WritePointerToMemory (lldb::addr_t vm_addr,
2106 lldb::addr_t ptr_value,
2107 Error &error)
2108{
2109 Scalar scalar;
2110 const uint32_t addr_byte_size = GetAddressByteSize();
2111 if (addr_byte_size <= 4)
2112 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002113 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002114 scalar = ptr_value;
2115 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002116}
2117
Chris Lattner24943d22010-06-08 16:52:24 +00002118size_t
2119Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2120{
2121 size_t bytes_written = 0;
2122 const uint8_t *bytes = (const uint8_t *)buf;
2123
2124 while (bytes_written < size)
2125 {
2126 const size_t curr_size = size - bytes_written;
2127 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2128 bytes + bytes_written,
2129 curr_size,
2130 error);
2131 bytes_written += curr_bytes_written;
2132 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2133 break;
2134 }
2135 return bytes_written;
2136}
2137
2138size_t
2139Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2140{
Greg Claytonfd119992011-01-07 06:08:19 +00002141#if defined (ENABLE_MEMORY_CACHING)
2142 m_memory_cache.Flush (addr, size);
2143#endif
2144
Chris Lattner24943d22010-06-08 16:52:24 +00002145 if (buf == NULL || size == 0)
2146 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002147
Jim Ingham21f37ad2011-08-09 02:12:22 +00002148 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002149
Chris Lattner24943d22010-06-08 16:52:24 +00002150 // We need to write any data that would go where any current software traps
2151 // (enabled software breakpoints) any software traps (breakpoints) that we
2152 // may have placed in our tasks memory.
2153
2154 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2155 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2156
2157 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002158 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002159
2160 BreakpointSiteList::collection::const_iterator pos;
2161 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002162 addr_t intersect_addr = 0;
2163 size_t intersect_size = 0;
2164 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002165 const uint8_t *ubuf = (const uint8_t *)buf;
2166
2167 for (pos = iter; pos != end; ++pos)
2168 {
2169 BreakpointSiteSP bp;
2170 bp = pos->second;
2171
2172 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2173 assert(addr <= intersect_addr && intersect_addr < addr + size);
2174 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2175 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2176
2177 // Check for bytes before this breakpoint
2178 const addr_t curr_addr = addr + bytes_written;
2179 if (intersect_addr > curr_addr)
2180 {
2181 // There are some bytes before this breakpoint that we need to
2182 // just write to memory
2183 size_t curr_size = intersect_addr - curr_addr;
2184 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2185 ubuf + bytes_written,
2186 curr_size,
2187 error);
2188 bytes_written += curr_bytes_written;
2189 if (curr_bytes_written != curr_size)
2190 {
2191 // We weren't able to write all of the requested bytes, we
2192 // are done looping and will return the number of bytes that
2193 // we have written so far.
2194 break;
2195 }
2196 }
2197
2198 // Now write any bytes that would cover up any software breakpoints
2199 // directly into the breakpoint opcode buffer
2200 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2201 bytes_written += intersect_size;
2202 }
2203
2204 // Write any remaining bytes after the last breakpoint if we have any left
2205 if (bytes_written < size)
2206 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2207 ubuf + bytes_written,
2208 size - bytes_written,
2209 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002210
Chris Lattner24943d22010-06-08 16:52:24 +00002211 return bytes_written;
2212}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002213
2214size_t
2215Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2216{
2217 if (byte_size == UINT32_MAX)
2218 byte_size = scalar.GetByteSize();
2219 if (byte_size > 0)
2220 {
2221 uint8_t buf[32];
2222 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2223 if (mem_size > 0)
2224 return WriteMemory(addr, buf, mem_size, error);
2225 else
2226 error.SetErrorString ("failed to get scalar as memory data");
2227 }
2228 else
2229 {
2230 error.SetErrorString ("invalid scalar value");
2231 }
2232 return 0;
2233}
2234
2235size_t
2236Process::ReadScalarIntegerFromMemory (addr_t addr,
2237 uint32_t byte_size,
2238 bool is_signed,
2239 Scalar &scalar,
2240 Error &error)
2241{
2242 uint64_t uval;
2243
2244 if (byte_size <= sizeof(uval))
2245 {
2246 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2247 if (bytes_read == byte_size)
2248 {
2249 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2250 uint32_t offset = 0;
2251 if (byte_size <= 4)
2252 scalar = data.GetMaxU32 (&offset, byte_size);
2253 else
2254 scalar = data.GetMaxU64 (&offset, byte_size);
2255
2256 if (is_signed)
2257 scalar.SignExtend(byte_size * 8);
2258 return bytes_read;
2259 }
2260 }
2261 else
2262 {
2263 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2264 }
2265 return 0;
2266}
2267
Greg Clayton613b8732011-05-17 03:37:42 +00002268#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002269addr_t
2270Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2271{
Jim Inghame6bd1422011-06-20 17:32:44 +00002272 if (GetPrivateState() != eStateStopped)
2273 return LLDB_INVALID_ADDRESS;
2274
Greg Clayton613b8732011-05-17 03:37:42 +00002275#if defined (USE_ALLOCATE_MEMORY_CACHE)
2276 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2277#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002278 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2279 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2280 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002281 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 +00002282 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002283 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002284 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002285 m_mod_id.GetStopID(),
2286 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002287 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002288#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002289}
2290
Sean Callanan6cf6c472011-09-20 23:01:51 +00002291bool
2292Process::CanJIT ()
2293{
Sean Callanan04200f62012-02-14 22:50:38 +00002294 if (m_can_jit == eCanJITDontKnow)
2295 {
2296 Error err;
2297
2298 uint64_t allocated_memory = AllocateMemory(8,
2299 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2300 err);
2301
2302 if (err.Success())
2303 m_can_jit = eCanJITYes;
2304 else
2305 m_can_jit = eCanJITNo;
2306
2307 DeallocateMemory (allocated_memory);
2308 }
2309
Sean Callanan6cf6c472011-09-20 23:01:51 +00002310 return m_can_jit == eCanJITYes;
2311}
2312
2313void
2314Process::SetCanJIT (bool can_jit)
2315{
2316 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2317}
2318
Chris Lattner24943d22010-06-08 16:52:24 +00002319Error
2320Process::DeallocateMemory (addr_t ptr)
2321{
Greg Clayton613b8732011-05-17 03:37:42 +00002322 Error error;
2323#if defined (USE_ALLOCATE_MEMORY_CACHE)
2324 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2325 {
2326 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2327 }
2328#else
2329 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002330
2331 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2332 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002333 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 +00002334 ptr,
2335 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002336 m_mod_id.GetStopID(),
2337 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002338#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002339 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002340}
2341
Greg Claytonb5a8f142012-02-05 02:38:54 +00002342ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002343Process::ReadModuleFromMemory (const FileSpec& file_spec,
2344 lldb::addr_t header_addr,
2345 bool add_image_to_target,
2346 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002347{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002348 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002349 if (module_sp)
2350 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002351 Error error;
2352 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2353 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002354 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002355 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002356 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002357 m_target.GetImages().Append(module_sp);
2358 if (load_sections_in_target)
2359 {
2360 bool changed = false;
2361 module_sp->SetLoadAddress (m_target, 0, changed);
2362 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002363 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002364 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002365 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002366 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002367 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002368}
Chris Lattner24943d22010-06-08 16:52:24 +00002369
2370Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002371Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002372{
2373 Error error;
2374 error.SetErrorString("watchpoints are not supported");
2375 return error;
2376}
2377
2378Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002379Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002380{
2381 Error error;
2382 error.SetErrorString("watchpoints are not supported");
2383 return error;
2384}
2385
2386StateType
2387Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2388{
2389 StateType state;
2390 // Now wait for the process to launch and return control to us, and then
2391 // call DidLaunch:
2392 while (1)
2393 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002394 event_sp.reset();
2395 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2396
Greg Clayton20206082011-11-17 01:23:07 +00002397 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002398 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002399
2400 // If state is invalid, then we timed out
2401 if (state == eStateInvalid)
2402 break;
2403
2404 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002405 HandlePrivateEvent (event_sp);
2406 }
2407 return state;
2408}
2409
2410Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002411Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002412{
2413 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002414 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002415 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002416 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002417 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002418
Greg Clayton5beb99d2011-08-11 02:48:45 +00002419 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002420 if (exe_module)
2421 {
Greg Clayton180546b2011-04-30 01:09:13 +00002422 char local_exec_file_path[PATH_MAX];
2423 char platform_exec_file_path[PATH_MAX];
2424 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2425 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002426 if (exe_module->GetFileSpec().Exists())
2427 {
Greg Claytona2f74232011-02-24 22:24:29 +00002428 if (PrivateStateThreadIsValid ())
2429 PausePrivateStateThread ();
2430
Chris Lattner24943d22010-06-08 16:52:24 +00002431 error = WillLaunch (exe_module);
2432 if (error.Success())
2433 {
Greg Claytond8c62532010-10-07 04:19:01 +00002434 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002435 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002436
2437 // Now launch using these arguments.
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002438 error = DoLaunch (exe_module, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +00002439
2440 if (error.Fail())
2441 {
2442 if (GetID() != LLDB_INVALID_PROCESS_ID)
2443 {
2444 SetID (LLDB_INVALID_PROCESS_ID);
2445 const char *error_string = error.AsCString();
2446 if (error_string == NULL)
2447 error_string = "launch failed";
2448 SetExitStatus (-1, error_string);
2449 }
2450 }
2451 else
2452 {
2453 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002454 TimeValue timeout_time;
2455 timeout_time = TimeValue::Now();
2456 timeout_time.OffsetWithSeconds(10);
2457 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002458
Greg Clayton49859592011-06-22 01:42:17 +00002459 if (state == eStateInvalid || event_sp.get() == NULL)
2460 {
2461 // We were able to launch the process, but we failed to
2462 // catch the initial stop.
2463 SetExitStatus (0, "failed to catch stop after launch");
2464 Destroy();
2465 }
2466 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002467 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002468
Chris Lattner24943d22010-06-08 16:52:24 +00002469 DidLaunch ();
2470
Greg Clayton9ce95382012-02-13 23:10:39 +00002471 DynamicLoader *dyld = GetDynamicLoader ();
2472 if (dyld)
2473 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002474
Greg Clayton37f962e2011-08-22 02:49:39 +00002475 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002476 // This delays passing the stopped event to listeners till DidLaunch gets
2477 // a chance to complete...
2478 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002479
2480 if (PrivateStateThreadIsValid ())
2481 ResumePrivateStateThread ();
2482 else
2483 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002484 }
2485 else if (state == eStateExited)
2486 {
2487 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2488 // not likely to work, and return an invalid pid.
2489 HandlePrivateEvent (event_sp);
2490 }
2491 }
2492 }
2493 }
2494 else
2495 {
Greg Clayton9c236732011-10-26 00:56:27 +00002496 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002497 }
2498 }
2499 return error;
2500}
2501
Greg Clayton46c9a352012-02-09 06:16:32 +00002502
2503Error
2504Process::LoadCore ()
2505{
2506 Error error = DoLoadCore();
2507 if (error.Success())
2508 {
2509 if (PrivateStateThreadIsValid ())
2510 ResumePrivateStateThread ();
2511 else
2512 StartPrivateStateThread ();
2513
Greg Clayton9ce95382012-02-13 23:10:39 +00002514 DynamicLoader *dyld = GetDynamicLoader ();
2515 if (dyld)
2516 dyld->DidAttach();
2517
2518 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002519 // We successfully loaded a core file, now pretend we stopped so we can
2520 // show all of the threads in the core file and explore the crashed
2521 // state.
2522 SetPrivateState (eStateStopped);
2523
2524 }
2525 return error;
2526}
2527
Greg Clayton9ce95382012-02-13 23:10:39 +00002528DynamicLoader *
2529Process::GetDynamicLoader ()
2530{
2531 if (m_dyld_ap.get() == NULL)
2532 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2533 return m_dyld_ap.get();
2534}
Greg Clayton46c9a352012-02-09 06:16:32 +00002535
2536
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002537Process::NextEventAction::EventActionResult
2538Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002539{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002540 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2541 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002542 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002543 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002544 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002545 return eEventActionRetry;
2546
2547 case eStateStopped:
2548 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002549 {
2550 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002551 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002552 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2553 if (m_exec_count > 0)
2554 {
2555 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002556 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002557 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002558 return eEventActionRetry;
2559 }
2560 else
2561 {
2562 m_process->CompleteAttach ();
2563 return eEventActionSuccess;
2564 }
2565 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002566 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002567
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002568 default:
2569 case eStateExited:
2570 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002571 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002572 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002573
2574 m_exit_string.assign ("No valid Process");
2575 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002576}
Chris Lattner24943d22010-06-08 16:52:24 +00002577
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002578Process::NextEventAction::EventActionResult
2579Process::AttachCompletionHandler::HandleBeingInterrupted()
2580{
2581 return eEventActionSuccess;
2582}
2583
2584const char *
2585Process::AttachCompletionHandler::GetExitString ()
2586{
2587 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002588}
2589
2590Error
Greg Clayton527154d2011-11-15 03:53:30 +00002591Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002592{
Chris Lattner24943d22010-06-08 16:52:24 +00002593 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002594 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002595 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002596 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002597
Greg Clayton527154d2011-11-15 03:53:30 +00002598 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002599 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002600 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002601 {
Greg Clayton527154d2011-11-15 03:53:30 +00002602 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002603
Greg Clayton527154d2011-11-15 03:53:30 +00002604 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002605 {
Greg Clayton527154d2011-11-15 03:53:30 +00002606 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2607
2608 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002609 {
Greg Clayton527154d2011-11-15 03:53:30 +00002610 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2611 if (error.Success())
2612 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002613 m_should_detach = true;
2614
Greg Clayton527154d2011-11-15 03:53:30 +00002615 SetPublicState (eStateAttaching);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002616 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
Greg Clayton527154d2011-11-15 03:53:30 +00002617 if (error.Fail())
2618 {
2619 if (GetID() != LLDB_INVALID_PROCESS_ID)
2620 {
2621 SetID (LLDB_INVALID_PROCESS_ID);
2622 if (error.AsCString() == NULL)
2623 error.SetErrorString("attach failed");
2624
2625 SetExitStatus(-1, error.AsCString());
2626 }
2627 }
2628 else
2629 {
2630 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2631 StartPrivateStateThread();
2632 }
2633 return error;
2634 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002635 }
Greg Clayton527154d2011-11-15 03:53:30 +00002636 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002637 {
Greg Clayton527154d2011-11-15 03:53:30 +00002638 ProcessInstanceInfoList process_infos;
2639 PlatformSP platform_sp (m_target.GetPlatform ());
2640
2641 if (platform_sp)
2642 {
2643 ProcessInstanceInfoMatch match_info;
2644 match_info.GetProcessInfo() = attach_info;
2645 match_info.SetNameMatchType (eNameMatchEquals);
2646 platform_sp->FindProcesses (match_info, process_infos);
2647 const uint32_t num_matches = process_infos.GetSize();
2648 if (num_matches == 1)
2649 {
2650 attach_pid = process_infos.GetProcessIDAtIndex(0);
2651 // Fall through and attach using the above process ID
2652 }
2653 else
2654 {
2655 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2656 if (num_matches > 1)
2657 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2658 else
2659 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2660 }
2661 }
2662 else
2663 {
2664 error.SetErrorString ("invalid platform, can't find processes by name");
2665 return error;
2666 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002667 }
Chris Lattner24943d22010-06-08 16:52:24 +00002668 }
2669 else
Greg Clayton527154d2011-11-15 03:53:30 +00002670 {
2671 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002672 }
2673 }
Greg Clayton527154d2011-11-15 03:53:30 +00002674
2675 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002676 {
Greg Clayton527154d2011-11-15 03:53:30 +00002677 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002678 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002679 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002680 m_should_detach = true;
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002681 SetPublicState (eStateAttaching);
Greg Clayton527154d2011-11-15 03:53:30 +00002682
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002683 error = DoAttachToProcessWithID (attach_pid, attach_info);
Greg Clayton527154d2011-11-15 03:53:30 +00002684 if (error.Success())
2685 {
2686
2687 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2688 StartPrivateStateThread();
2689 }
2690 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002691 {
2692 if (GetID() != LLDB_INVALID_PROCESS_ID)
2693 {
2694 SetID (LLDB_INVALID_PROCESS_ID);
2695 const char *error_string = error.AsCString();
2696 if (error_string == NULL)
2697 error_string = "attach failed";
2698
2699 SetExitStatus(-1, error_string);
2700 }
2701 }
Chris Lattner24943d22010-06-08 16:52:24 +00002702 }
2703 }
2704 return error;
2705}
2706
Greg Clayton527154d2011-11-15 03:53:30 +00002707//Error
2708//Process::Attach (const char *process_name, bool wait_for_launch)
2709//{
2710// m_abi_sp.reset();
2711// m_process_input_reader.reset();
2712//
2713// // Find the process and its architecture. Make sure it matches the architecture
2714// // of the current Target, and if not adjust it.
2715// Error error;
2716//
2717// if (!wait_for_launch)
2718// {
2719// ProcessInstanceInfoList process_infos;
2720// PlatformSP platform_sp (m_target.GetPlatform ());
2721// assert (platform_sp.get());
2722//
2723// if (platform_sp)
2724// {
2725// ProcessInstanceInfoMatch match_info;
2726// match_info.GetProcessInfo().SetName(process_name);
2727// match_info.SetNameMatchType (eNameMatchEquals);
2728// platform_sp->FindProcesses (match_info, process_infos);
2729// if (process_infos.GetSize() > 1)
2730// {
2731// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2732// }
2733// else if (process_infos.GetSize() == 0)
2734// {
2735// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2736// }
2737// }
2738// else
2739// {
2740// error.SetErrorString ("invalid platform");
2741// }
2742// }
2743//
2744// if (error.Success())
2745// {
2746// m_dyld_ap.reset();
2747// m_os_ap.reset();
2748//
2749// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2750// if (error.Success())
2751// {
2752// SetPublicState (eStateAttaching);
2753// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2754// if (error.Fail())
2755// {
2756// if (GetID() != LLDB_INVALID_PROCESS_ID)
2757// {
2758// SetID (LLDB_INVALID_PROCESS_ID);
2759// const char *error_string = error.AsCString();
2760// if (error_string == NULL)
2761// error_string = "attach failed";
2762//
2763// SetExitStatus(-1, error_string);
2764// }
2765// }
2766// else
2767// {
2768// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2769// StartPrivateStateThread();
2770// }
2771// }
2772// }
2773// return error;
2774//}
2775
Greg Clayton75c703d2011-02-16 04:46:07 +00002776void
2777Process::CompleteAttach ()
2778{
2779 // Let the process subclass figure out at much as it can about the process
2780 // before we go looking for a dynamic loader plug-in.
2781 DidAttach();
2782
Jim Ingham0d7f7772011-09-15 01:10:17 +00002783 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2784 // the same as the one we've already set, switch architectures.
2785 PlatformSP platform_sp (m_target.GetPlatform ());
2786 assert (platform_sp.get());
2787 if (platform_sp)
2788 {
Greg Claytonb170aee2012-05-08 01:45:38 +00002789 const ArchSpec &target_arch = m_target.GetArchitecture();
2790 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2791 {
2792 ArchSpec platform_arch;
2793 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2794 if (platform_sp)
2795 {
2796 m_target.SetPlatform (platform_sp);
2797 m_target.SetArchitecture(platform_arch);
2798 }
2799 }
2800 else
2801 {
2802 ProcessInstanceInfo process_info;
2803 platform_sp->GetProcessInfo (GetID(), process_info);
2804 const ArchSpec &process_arch = process_info.GetArchitecture();
2805 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2806 m_target.SetArchitecture (process_arch);
2807 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00002808 }
2809
2810 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002811 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00002812 DynamicLoader *dyld = GetDynamicLoader ();
2813 if (dyld)
2814 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00002815
Greg Clayton37f962e2011-08-22 02:49:39 +00002816 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002817 // Figure out which one is the executable, and set that in our target:
Jim Ingham93367902012-05-30 02:19:25 +00002818 ModuleList &target_modules = m_target.GetImages();
2819 Mutex::Locker modules_locker(target_modules.GetMutex());
2820 size_t num_modules = target_modules.GetSize();
2821 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00002822
Greg Clayton75c703d2011-02-16 04:46:07 +00002823 for (int i = 0; i < num_modules; i++)
2824 {
Jim Ingham93367902012-05-30 02:19:25 +00002825 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002826 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002827 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002828 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00002829 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00002830 break;
2831 }
2832 }
Jim Ingham93367902012-05-30 02:19:25 +00002833 if (new_executable_module_sp)
2834 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00002835}
2836
Chris Lattner24943d22010-06-08 16:52:24 +00002837Error
Greg Claytone71e2582011-02-04 01:58:07 +00002838Process::ConnectRemote (const char *remote_url)
2839{
Greg Claytone71e2582011-02-04 01:58:07 +00002840 m_abi_sp.reset();
2841 m_process_input_reader.reset();
2842
2843 // Find the process and its architecture. Make sure it matches the architecture
2844 // of the current Target, and if not adjust it.
2845
2846 Error error (DoConnectRemote (remote_url));
2847 if (error.Success())
2848 {
Greg Claytona2f74232011-02-24 22:24:29 +00002849 if (GetID() != LLDB_INVALID_PROCESS_ID)
2850 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002851 EventSP event_sp;
2852 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2853
2854 if (state == eStateStopped || state == eStateCrashed)
2855 {
2856 // If we attached and actually have a process on the other end, then
2857 // this ended up being the equivalent of an attach.
2858 CompleteAttach ();
2859
2860 // This delays passing the stopped event to listeners till
2861 // CompleteAttach gets a chance to complete...
2862 HandlePrivateEvent (event_sp);
2863
2864 }
Greg Claytona2f74232011-02-24 22:24:29 +00002865 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002866
2867 if (PrivateStateThreadIsValid ())
2868 ResumePrivateStateThread ();
2869 else
2870 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002871 }
2872 return error;
2873}
2874
2875
2876Error
Jim Ingham027aaa72012-04-19 01:40:33 +00002877Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00002878{
Greg Claytone005f2c2010-11-06 01:53:30 +00002879 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002880 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002881 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002882 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002883 StateAsCString(m_public_state.GetValue()),
2884 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002885
2886 Error error (WillResume());
2887 // Tell the process it is about to resume before the thread list
2888 if (error.Success())
2889 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002890 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002891 // can let all of our threads know that they are about to be
2892 // resumed. Threads will each be called with
2893 // Thread::WillResume(StateType) where StateType contains the state
2894 // that they are supposed to have when the process is resumed
2895 // (suspended/running/stepping). Threads should also check
2896 // their resume signal in lldb::Thread::GetResumeSignal()
2897 // to see if they are suppoed to start back up with a signal.
2898 if (m_thread_list.WillResume())
2899 {
Jim Ingham1831e782012-04-07 00:00:41 +00002900 // Last thing, do the PreResumeActions.
2901 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00002902 {
Jim Ingham1831e782012-04-07 00:00:41 +00002903 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
2904 }
2905 else
2906 {
2907 m_mod_id.BumpResumeID();
2908 error = DoResume();
2909 if (error.Success())
2910 {
2911 DidResume();
2912 m_thread_list.DidResume();
2913 if (log)
2914 log->Printf ("Process thinks the process has resumed.");
2915 }
Chris Lattner24943d22010-06-08 16:52:24 +00002916 }
2917 }
2918 else
2919 {
Jim Inghamac959662011-01-24 06:34:17 +00002920 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002921 }
2922 }
Jim Inghamac959662011-01-24 06:34:17 +00002923 else if (log)
2924 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002925 return error;
2926}
2927
2928Error
2929Process::Halt ()
2930{
Jim Ingham43892562012-06-06 00:29:30 +00002931 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
2932 // we could just straightaway get another event. It just narrows the window...
2933 m_currently_handling_event.WaitForValueEqualTo(false);
2934
2935
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002936 // Pause our private state thread so we can ensure no one else eats
2937 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002938 Listener halt_listener ("lldb.process.halt_listener");
2939 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002940
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002941 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002942 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002943
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002944 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002945 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002946
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002947 bool caused_stop = false;
2948
2949 // Ask the process subclass to actually halt our process
2950 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002951 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002952 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002953 if (m_public_state.GetValue() == eStateAttaching)
2954 {
2955 SetExitStatus(SIGKILL, "Cancelled async attach.");
2956 Destroy ();
2957 }
2958 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002959 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002960 // If "caused_stop" is true, then DoHalt stopped the process. If
2961 // "caused_stop" is false, the process was already stopped.
2962 // If the DoHalt caused the process to stop, then we want to catch
2963 // this event and set the interrupted bool to true before we pass
2964 // this along so clients know that the process was interrupted by
2965 // a halt command.
2966 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002967 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002968 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002969 TimeValue timeout_time;
2970 timeout_time = TimeValue::Now();
2971 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002972 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2973 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002974
Jim Inghamf9f40c22011-02-08 05:20:59 +00002975 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002976 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002977 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002978 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002979 }
2980 else
2981 {
Greg Clayton20206082011-11-17 01:23:07 +00002982 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002983 {
2984 // We caused the process to interrupt itself, so mark this
2985 // as such in the stop event so clients can tell an interrupted
2986 // process from a natural stop
2987 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2988 }
2989 else
2990 {
2991 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2992 if (log)
2993 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2994 error.SetErrorString ("Did not get stopped event after halt.");
2995 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002996 }
2997 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002998 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002999 }
3000 }
Chris Lattner24943d22010-06-08 16:52:24 +00003001 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003002 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003003 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003004
3005 // Post any event we might have consumed. If all goes well, we will have
3006 // stopped the process, intercepted the event and set the interrupted
3007 // bool in the event. Post it to the private event queue and that will end up
3008 // correctly setting the state.
3009 if (event_sp)
3010 m_private_state_broadcaster.BroadcastEvent(event_sp);
3011
Chris Lattner24943d22010-06-08 16:52:24 +00003012 return error;
3013}
3014
3015Error
3016Process::Detach ()
3017{
3018 Error error (WillDetach());
3019
3020 if (error.Success())
3021 {
3022 DisableAllBreakpointSites();
3023 error = DoDetach();
3024 if (error.Success())
3025 {
3026 DidDetach();
3027 StopPrivateStateThread();
3028 }
3029 }
3030 return error;
3031}
3032
3033Error
3034Process::Destroy ()
3035{
3036 Error error (WillDestroy());
3037 if (error.Success())
3038 {
Jim Inghamf4928de2012-05-23 15:46:31 +00003039 if (m_public_state.GetValue() == eStateRunning)
3040 {
Jim Ingham43892562012-06-06 00:29:30 +00003041 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TEMPORARY));
3042 if (log)
3043 log->Printf("Process::Destroy() About to halt.");
Jim Inghamf4928de2012-05-23 15:46:31 +00003044 error = Halt();
3045 if (error.Success())
3046 {
3047 // Consume the halt event.
3048 EventSP stop_event;
3049 TimeValue timeout (TimeValue::Now());
Jim Ingham43892562012-06-06 00:29:30 +00003050 timeout.OffsetWithSeconds(1);
Jim Inghamf4928de2012-05-23 15:46:31 +00003051 StateType state = WaitForProcessToStop (&timeout);
3052 if (state != eStateStopped)
3053 {
Jim Ingham43892562012-06-06 00:29:30 +00003054 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TEMPORARY));
Jim Inghamf4928de2012-05-23 15:46:31 +00003055 if (log)
3056 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Ingham43892562012-06-06 00:29:30 +00003057 // If we really couldn't stop the process then we should just error out here, but if the
3058 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3059 StateType private_state = m_private_state.GetValue();
3060 if (private_state != eStateStopped && private_state != eStateExited)
3061 {
3062 return error;
3063 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003064 }
3065 }
3066 else
3067 {
Jim Ingham43892562012-06-06 00:29:30 +00003068 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TEMPORARY));
Jim Inghamf4928de2012-05-23 15:46:31 +00003069 if (log)
3070 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
Jim Ingham43892562012-06-06 00:29:30 +00003071 return error;
Jim Inghamf4928de2012-05-23 15:46:31 +00003072 }
3073 }
Jim Ingham43892562012-06-06 00:29:30 +00003074
3075 if (m_public_state.GetValue() != eStateRunning)
3076 {
3077 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3078 // kill it, we don't want it hitting a breakpoint...
3079 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3080 // we're not going to have much luck doing this now.
3081 m_thread_list.DiscardThreadPlans();
3082 DisableAllBreakpointSites();
3083 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003084
Chris Lattner24943d22010-06-08 16:52:24 +00003085 error = DoDestroy();
3086 if (error.Success())
3087 {
3088 DidDestroy();
3089 StopPrivateStateThread();
3090 }
Caroline Tice861efb32010-11-16 05:07:41 +00003091 m_stdio_communication.StopReadThread();
3092 m_stdio_communication.Disconnect();
3093 if (m_process_input_reader && m_process_input_reader->IsActive())
3094 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3095 if (m_process_input_reader)
3096 m_process_input_reader.reset();
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003097
3098 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3099 // the last events through the event system, in which case we might strand the write lock. Unlock
3100 // it here so when we do to tear down the process we don't get an error destroying the lock.
3101 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003102 }
3103 return error;
3104}
3105
3106Error
3107Process::Signal (int signal)
3108{
3109 Error error (WillSignal());
3110 if (error.Success())
3111 {
3112 error = DoSignal(signal);
3113 if (error.Success())
3114 DidSignal();
3115 }
3116 return error;
3117}
3118
Greg Clayton395fc332011-02-15 21:59:32 +00003119lldb::ByteOrder
3120Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003121{
Greg Clayton395fc332011-02-15 21:59:32 +00003122 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003123}
3124
3125uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003126Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003127{
Greg Clayton395fc332011-02-15 21:59:32 +00003128 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003129}
3130
Greg Clayton395fc332011-02-15 21:59:32 +00003131
Chris Lattner24943d22010-06-08 16:52:24 +00003132bool
3133Process::ShouldBroadcastEvent (Event *event_ptr)
3134{
3135 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3136 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00003137 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003138
3139 switch (state)
3140 {
Greg Claytone71e2582011-02-04 01:58:07 +00003141 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003142 case eStateAttaching:
3143 case eStateLaunching:
3144 case eStateDetached:
3145 case eStateExited:
3146 case eStateUnloaded:
3147 // These events indicate changes in the state of the debugging session, always report them.
3148 return_value = true;
3149 break;
3150 case eStateInvalid:
3151 // We stopped for no apparent reason, don't report it.
3152 return_value = false;
3153 break;
3154 case eStateRunning:
3155 case eStateStepping:
3156 // If we've started the target running, we handle the cases where we
3157 // are already running and where there is a transition from stopped to
3158 // running differently.
3159 // running -> running: Automatically suppress extra running events
3160 // stopped -> running: Report except when there is one or more no votes
3161 // and no yes votes.
3162 SynchronouslyNotifyStateChanged (state);
3163 switch (m_public_state.GetValue())
3164 {
3165 case eStateRunning:
3166 case eStateStepping:
3167 // We always suppress multiple runnings with no PUBLIC stop in between.
3168 return_value = false;
3169 break;
3170 default:
3171 // TODO: make this work correctly. For now always report
3172 // run if we aren't running so we don't miss any runnning
3173 // events. If I run the lldb/test/thread/a.out file and
3174 // break at main.cpp:58, run and hit the breakpoints on
3175 // multiple threads, then somehow during the stepping over
3176 // of all breakpoints no run gets reported.
3177 return_value = true;
3178
3179 // This is a transition from stop to run.
3180 switch (m_thread_list.ShouldReportRun (event_ptr))
3181 {
3182 case eVoteYes:
3183 case eVoteNoOpinion:
3184 return_value = true;
3185 break;
3186 case eVoteNo:
3187 return_value = false;
3188 break;
3189 }
3190 break;
3191 }
3192 break;
3193 case eStateStopped:
3194 case eStateCrashed:
3195 case eStateSuspended:
3196 {
3197 // We've stopped. First see if we're going to restart the target.
3198 // If we are going to stop, then we always broadcast the event.
3199 // 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 +00003200 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003201
3202 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003203 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003204 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003205 if (log)
3206 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003207 return true;
3208 }
3209 else
3210 {
Chris Lattner24943d22010-06-08 16:52:24 +00003211
3212 if (m_thread_list.ShouldStop (event_ptr) == false)
3213 {
3214 switch (m_thread_list.ShouldReportStop (event_ptr))
3215 {
3216 case eVoteYes:
3217 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003218 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003219 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003220 case eVoteNo:
3221 return_value = false;
3222 break;
3223 }
3224
3225 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003226 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham027aaa72012-04-19 01:40:33 +00003227 PrivateResume ();
Chris Lattner24943d22010-06-08 16:52:24 +00003228 }
3229 else
3230 {
3231 return_value = true;
3232 SynchronouslyNotifyStateChanged (state);
3233 }
3234 }
3235 }
3236 }
3237
3238 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003239 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003240 return return_value;
3241}
3242
Chris Lattner24943d22010-06-08 16:52:24 +00003243
3244bool
Jim Ingham1831e782012-04-07 00:00:41 +00003245Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003246{
Greg Claytone005f2c2010-11-06 01:53:30 +00003247 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003248
Greg Claytonb72d0f02011-04-12 05:54:46 +00003249 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003250 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003251 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3252
Jim Ingham1831e782012-04-07 00:00:41 +00003253 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003254 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003255
3256 // Create a thread that watches our internal state and controls which
3257 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003258 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003259 if (already_running)
3260 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3261 else
3262 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003263
3264 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003265 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003266 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3267 if (success)
3268 {
3269 ResumePrivateStateThread();
3270 return true;
3271 }
3272 else
3273 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003274}
3275
3276void
3277Process::PausePrivateStateThread ()
3278{
3279 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3280}
3281
3282void
3283Process::ResumePrivateStateThread ()
3284{
3285 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3286}
3287
3288void
3289Process::StopPrivateStateThread ()
3290{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003291 if (PrivateStateThreadIsValid ())
3292 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003293 else
3294 {
3295 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3296 if (log)
3297 printf ("Went to stop the private state thread, but it was already invalid.");
3298 }
Chris Lattner24943d22010-06-08 16:52:24 +00003299}
3300
3301void
3302Process::ControlPrivateStateThread (uint32_t signal)
3303{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003304 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003305
3306 assert (signal == eBroadcastInternalStateControlStop ||
3307 signal == eBroadcastInternalStateControlPause ||
3308 signal == eBroadcastInternalStateControlResume);
3309
3310 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003311 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003312
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003313 // Signal the private state thread. First we should copy this is case the
3314 // thread starts exiting since the private state thread will NULL this out
3315 // when it exits
3316 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003317 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003318 {
3319 TimeValue timeout_time;
3320 bool timed_out;
3321
3322 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3323
3324 timeout_time = TimeValue::Now();
3325 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003326 if (log)
3327 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003328 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3329 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3330
3331 if (signal == eBroadcastInternalStateControlStop)
3332 {
3333 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003334 {
3335 Error error;
3336 Host::ThreadCancel (private_state_thread, &error);
3337 if (log)
3338 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3339 }
3340 else
3341 {
3342 if (log)
3343 log->Printf ("The control event killed the private state thread without having to cancel.");
3344 }
Chris Lattner24943d22010-06-08 16:52:24 +00003345
3346 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003347 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003348 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003349 }
3350 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003351 else
3352 {
3353 if (log)
3354 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3355 }
Chris Lattner24943d22010-06-08 16:52:24 +00003356}
3357
3358void
3359Process::HandlePrivateEvent (EventSP &event_sp)
3360{
Greg Claytone005f2c2010-11-06 01:53:30 +00003361 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003362 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003363
Greg Clayton68ca8232011-01-25 02:58:48 +00003364 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003365
3366 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003367 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003368 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003369 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003370 switch (action_result)
3371 {
3372 case NextEventAction::eEventActionSuccess:
3373 SetNextEventAction(NULL);
3374 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003375
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003376 case NextEventAction::eEventActionRetry:
3377 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003378
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003379 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003380 // Handle Exiting Here. If we already got an exited event,
3381 // we should just propagate it. Otherwise, swallow this event,
3382 // and set our state to exit so the next event will kill us.
3383 if (new_state != eStateExited)
3384 {
3385 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003386 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003387 SetNextEventAction(NULL);
3388 return;
3389 }
3390 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003391 break;
3392 }
3393 }
3394
Chris Lattner24943d22010-06-08 16:52:24 +00003395 // See if we should broadcast this state to external clients?
3396 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003397
3398 if (should_broadcast)
3399 {
3400 if (log)
3401 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003402 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003403 __FUNCTION__,
3404 GetID(),
3405 StateAsCString(new_state),
3406 StateAsCString (GetState ()),
3407 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003408 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003409 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003410 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003411 PushProcessInputReader ();
3412 else
3413 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003414
Chris Lattner24943d22010-06-08 16:52:24 +00003415 BroadcastEvent (event_sp);
3416 }
3417 else
3418 {
3419 if (log)
3420 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003421 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003422 __FUNCTION__,
3423 GetID(),
3424 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003425 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003426 }
3427 }
Jim Ingham43892562012-06-06 00:29:30 +00003428 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003429}
3430
3431void *
3432Process::PrivateStateThread (void *arg)
3433{
3434 Process *proc = static_cast<Process*> (arg);
3435 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003436 return result;
3437}
3438
3439void *
3440Process::RunPrivateStateThread ()
3441{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003442 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003443 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003444
Greg Claytone005f2c2010-11-06 01:53:30 +00003445 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003446 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003447 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003448
3449 bool exit_now = false;
3450 while (!exit_now)
3451 {
3452 EventSP event_sp;
3453 WaitForEventsPrivate (NULL, event_sp, control_only);
3454 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3455 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003456 if (log)
3457 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3458
Chris Lattner24943d22010-06-08 16:52:24 +00003459 switch (event_sp->GetType())
3460 {
3461 case eBroadcastInternalStateControlStop:
3462 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003463 break; // doing any internal state managment below
3464
3465 case eBroadcastInternalStateControlPause:
3466 control_only = true;
3467 break;
3468
3469 case eBroadcastInternalStateControlResume:
3470 control_only = false;
3471 break;
3472 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003473
Chris Lattner24943d22010-06-08 16:52:24 +00003474 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003475 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003476 }
3477
3478
3479 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3480
3481 if (internal_state != eStateInvalid)
3482 {
3483 HandlePrivateEvent (event_sp);
3484 }
3485
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003486 if (internal_state == eStateInvalid ||
3487 internal_state == eStateExited ||
3488 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003489 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003490 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003491 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 +00003492
Chris Lattner24943d22010-06-08 16:52:24 +00003493 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003494 }
Chris Lattner24943d22010-06-08 16:52:24 +00003495 }
3496
Caroline Tice926060e2010-10-29 21:48:37 +00003497 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003498 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003499 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003500
Greg Claytona4881d02011-01-22 07:12:45 +00003501 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3502 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003503 return NULL;
3504}
3505
Chris Lattner24943d22010-06-08 16:52:24 +00003506//------------------------------------------------------------------
3507// Process Event Data
3508//------------------------------------------------------------------
3509
3510Process::ProcessEventData::ProcessEventData () :
3511 EventData (),
3512 m_process_sp (),
3513 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003514 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003515 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003516 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003517{
3518}
3519
3520Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3521 EventData (),
3522 m_process_sp (process_sp),
3523 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003524 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003525 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003526 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003527{
3528}
3529
3530Process::ProcessEventData::~ProcessEventData()
3531{
3532}
3533
3534const ConstString &
3535Process::ProcessEventData::GetFlavorString ()
3536{
3537 static ConstString g_flavor ("Process::ProcessEventData");
3538 return g_flavor;
3539}
3540
3541const ConstString &
3542Process::ProcessEventData::GetFlavor () const
3543{
3544 return ProcessEventData::GetFlavorString ();
3545}
3546
Chris Lattner24943d22010-06-08 16:52:24 +00003547void
3548Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3549{
3550 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003551 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3552 // the public event queue, then other times when we're pretending that this is where we stopped at the
3553 // end of expression evaluation. m_update_state is used to distinguish these
3554 // three cases; it is 0 when we're just pulling it off for private handling,
3555 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003556
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003557 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003558 return;
3559
3560 m_process_sp->SetPublicState (m_state);
3561
3562 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3563 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003564 {
3565 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003566 uint32_t num_threads = curr_thread_list.GetSize();
3567 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003568
Jim Ingham21f37ad2011-08-09 02:12:22 +00003569 // The actions might change one of the thread's stop_info's opinions about whether we should
3570 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003571
3572 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3573 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3574 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3575 // 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
3576 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003577 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003578 for (idx = 0; idx < num_threads; ++idx)
3579 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3580
Jim Ingham21f37ad2011-08-09 02:12:22 +00003581 bool still_should_stop = true;
3582
Chris Lattner24943d22010-06-08 16:52:24 +00003583 for (idx = 0; idx < num_threads; ++idx)
3584 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003585 curr_thread_list = m_process_sp->GetThreadList();
3586 if (curr_thread_list.GetSize() != num_threads)
3587 {
3588 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003589 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003590 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 +00003591 break;
3592 }
3593
3594 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3595
3596 if (thread_sp->GetIndexID() != thread_index_array[idx])
3597 {
3598 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003599 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003600 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003601 idx,
3602 thread_index_array[idx],
3603 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003604 break;
3605 }
3606
Jim Ingham6297a3a2010-10-20 00:39:53 +00003607 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3608 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00003609 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003610 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003611 // The stop action might restart the target. If it does, then we want to mark that in the
3612 // event so that whoever is receiving it will know to wait for the running event and reflect
3613 // that state appropriately.
3614 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003615
3616 // FIXME: we might have run.
3617 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003618 {
3619 SetRestarted (true);
3620 break;
3621 }
3622 else if (!stop_info_sp->ShouldStop(event_ptr))
3623 {
3624 still_should_stop = false;
3625 }
Chris Lattner24943d22010-06-08 16:52:24 +00003626 }
3627 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003628
Jim Ingham21f37ad2011-08-09 02:12:22 +00003629
3630 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003631 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003632 if (!still_should_stop)
3633 {
3634 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003635 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00003636 // Use the public resume method here, since this is just
3637 // extending a public resume.
Jim Ingham21f37ad2011-08-09 02:12:22 +00003638 m_process_sp->Resume();
3639 }
3640 else
3641 {
3642 // If we didn't restart, run the Stop Hooks here:
3643 // They might also restart the target, so watch for that.
3644 m_process_sp->GetTarget().RunStopHooks();
3645 if (m_process_sp->GetPrivateState() == eStateRunning)
3646 SetRestarted(true);
3647 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003648 }
3649
Chris Lattner24943d22010-06-08 16:52:24 +00003650 }
3651}
3652
3653void
3654Process::ProcessEventData::Dump (Stream *s) const
3655{
3656 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003657 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003658
Greg Claytonb72d0f02011-04-12 05:54:46 +00003659 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003660}
3661
3662const Process::ProcessEventData *
3663Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3664{
3665 if (event_ptr)
3666 {
3667 const EventData *event_data = event_ptr->GetData();
3668 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3669 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3670 }
3671 return NULL;
3672}
3673
3674ProcessSP
3675Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3676{
3677 ProcessSP process_sp;
3678 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3679 if (data)
3680 process_sp = data->GetProcessSP();
3681 return process_sp;
3682}
3683
3684StateType
3685Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3686{
3687 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3688 if (data == NULL)
3689 return eStateInvalid;
3690 else
3691 return data->GetState();
3692}
3693
3694bool
3695Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3696{
3697 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3698 if (data == NULL)
3699 return false;
3700 else
3701 return data->GetRestarted();
3702}
3703
3704void
3705Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3706{
3707 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3708 if (data != NULL)
3709 data->SetRestarted(new_value);
3710}
3711
3712bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003713Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3714{
3715 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3716 if (data == NULL)
3717 return false;
3718 else
3719 return data->GetInterrupted ();
3720}
3721
3722void
3723Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3724{
3725 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3726 if (data != NULL)
3727 data->SetInterrupted(new_value);
3728}
3729
3730bool
Chris Lattner24943d22010-06-08 16:52:24 +00003731Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3732{
3733 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3734 if (data)
3735 {
3736 data->SetUpdateStateOnRemoval();
3737 return true;
3738 }
3739 return false;
3740}
3741
Greg Clayton289afcb2012-02-18 05:35:26 +00003742lldb::TargetSP
3743Process::CalculateTarget ()
3744{
3745 return m_target.shared_from_this();
3746}
3747
Chris Lattner24943d22010-06-08 16:52:24 +00003748void
Greg Claytona830adb2010-10-04 01:05:56 +00003749Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003750{
Greg Clayton567e7f32011-09-22 04:58:26 +00003751 exe_ctx.SetTargetPtr (&m_target);
3752 exe_ctx.SetProcessPtr (this);
3753 exe_ctx.SetThreadPtr(NULL);
3754 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003755}
3756
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003757//uint32_t
3758//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3759//{
3760// return 0;
3761//}
3762//
3763//ArchSpec
3764//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3765//{
3766// return Host::GetArchSpecForExistingProcess (pid);
3767//}
3768//
3769//ArchSpec
3770//Process::GetArchSpecForExistingProcess (const char *process_name)
3771//{
3772// return Host::GetArchSpecForExistingProcess (process_name);
3773//}
3774//
Caroline Tice861efb32010-11-16 05:07:41 +00003775void
3776Process::AppendSTDOUT (const char * s, size_t len)
3777{
Greg Clayton20d338f2010-11-18 05:57:03 +00003778 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003779 m_stdout_data.append (s, len);
Greg Claytonb3781332010-12-05 19:16:56 +00003780 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003781}
3782
3783void
Greg Claytonbd06ff42011-11-13 04:45:22 +00003784Process::AppendSTDERR (const char * s, size_t len)
3785{
3786 Mutex::Locker locker (m_stdio_communication_mutex);
3787 m_stderr_data.append (s, len);
3788 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3789}
3790
3791//------------------------------------------------------------------
3792// Process STDIO
3793//------------------------------------------------------------------
3794
3795size_t
3796Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3797{
3798 Mutex::Locker locker(m_stdio_communication_mutex);
3799 size_t bytes_available = m_stdout_data.size();
3800 if (bytes_available > 0)
3801 {
3802 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3803 if (log)
3804 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3805 if (bytes_available > buf_size)
3806 {
3807 memcpy(buf, m_stdout_data.c_str(), buf_size);
3808 m_stdout_data.erase(0, buf_size);
3809 bytes_available = buf_size;
3810 }
3811 else
3812 {
3813 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3814 m_stdout_data.clear();
3815 }
3816 }
3817 return bytes_available;
3818}
3819
3820
3821size_t
3822Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3823{
3824 Mutex::Locker locker(m_stdio_communication_mutex);
3825 size_t bytes_available = m_stderr_data.size();
3826 if (bytes_available > 0)
3827 {
3828 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3829 if (log)
3830 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3831 if (bytes_available > buf_size)
3832 {
3833 memcpy(buf, m_stderr_data.c_str(), buf_size);
3834 m_stderr_data.erase(0, buf_size);
3835 bytes_available = buf_size;
3836 }
3837 else
3838 {
3839 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3840 m_stderr_data.clear();
3841 }
3842 }
3843 return bytes_available;
3844}
3845
3846void
Caroline Tice861efb32010-11-16 05:07:41 +00003847Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3848{
3849 Process *process = (Process *) baton;
3850 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3851}
3852
3853size_t
3854Process::ProcessInputReaderCallback (void *baton,
3855 InputReader &reader,
3856 lldb::InputReaderAction notification,
3857 const char *bytes,
3858 size_t bytes_len)
3859{
3860 Process *process = (Process *) baton;
3861
3862 switch (notification)
3863 {
3864 case eInputReaderActivate:
3865 break;
3866
3867 case eInputReaderDeactivate:
3868 break;
3869
3870 case eInputReaderReactivate:
3871 break;
3872
Caroline Tice4a348082011-05-02 20:41:46 +00003873 case eInputReaderAsynchronousOutputWritten:
3874 break;
3875
Caroline Tice861efb32010-11-16 05:07:41 +00003876 case eInputReaderGotToken:
3877 {
3878 Error error;
3879 process->PutSTDIN (bytes, bytes_len, error);
3880 }
3881 break;
3882
Caroline Ticec4f55fe2010-11-19 20:47:54 +00003883 case eInputReaderInterrupt:
3884 process->Halt ();
3885 break;
3886
3887 case eInputReaderEndOfFile:
3888 process->AppendSTDOUT ("^D", 2);
3889 break;
3890
Caroline Tice861efb32010-11-16 05:07:41 +00003891 case eInputReaderDone:
3892 break;
3893
3894 }
3895
3896 return bytes_len;
3897}
3898
3899void
3900Process::ResetProcessInputReader ()
3901{
3902 m_process_input_reader.reset();
3903}
3904
3905void
Greg Clayton464c6162011-11-17 22:14:31 +00003906Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00003907{
3908 // First set up the Read Thread for reading/handling process I/O
3909
3910 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3911
3912 if (conn_ap.get())
3913 {
3914 m_stdio_communication.SetConnection (conn_ap.release());
3915 if (m_stdio_communication.IsConnected())
3916 {
3917 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3918 m_stdio_communication.StartReadThread();
3919
3920 // Now read thread is set up, set up input reader.
3921
3922 if (!m_process_input_reader.get())
3923 {
3924 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3925 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3926 this,
3927 eInputReaderGranularityByte,
3928 NULL,
3929 NULL,
3930 false));
3931
3932 if (err.Fail())
3933 m_process_input_reader.reset();
3934 }
3935 }
3936 }
3937}
3938
3939void
3940Process::PushProcessInputReader ()
3941{
3942 if (m_process_input_reader && !m_process_input_reader->IsActive())
3943 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3944}
3945
3946void
3947Process::PopProcessInputReader ()
3948{
3949 if (m_process_input_reader && m_process_input_reader->IsActive())
3950 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3951}
3952
Greg Claytond284b662011-02-18 01:44:25 +00003953// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00003954void
Caroline Tice2a456812011-03-10 22:14:10 +00003955Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003956{
Greg Claytonb3448432011-03-24 21:19:54 +00003957 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00003958
3959 int i=0;
3960 const char *name;
3961 OptionEnumValueElement option_enum;
3962 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3963 {
3964 if (name)
3965 {
3966 option_enum.value = i;
3967 option_enum.string_value = name;
3968 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3969 g_plugins.push_back (option_enum);
3970 }
3971 ++i;
3972 }
3973 option_enum.value = 0;
3974 option_enum.string_value = NULL;
3975 option_enum.usage = NULL;
3976 g_plugins.push_back (option_enum);
3977
3978 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3979 {
3980 if (::strcmp (name, "plugin") == 0)
3981 {
3982 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3983 break;
3984 }
3985 }
Greg Clayton990de7b2010-11-18 23:32:35 +00003986 UserSettingsControllerSP &usc = GetSettingsController();
Greg Clayton990de7b2010-11-18 23:32:35 +00003987 UserSettingsController::InitializeSettingsController (usc,
3988 SettingsController::global_settings_table,
3989 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00003990
3991 // Now call SettingsInitialize() for each 'child' of Process settings
3992 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00003993}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003994
Greg Clayton990de7b2010-11-18 23:32:35 +00003995void
Caroline Tice2a456812011-03-10 22:14:10 +00003996Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00003997{
Caroline Tice2a456812011-03-10 22:14:10 +00003998 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3999
4000 Thread::SettingsTerminate ();
4001
4002 // Now terminate Process Settings.
4003
Greg Clayton990de7b2010-11-18 23:32:35 +00004004 UserSettingsControllerSP &usc = GetSettingsController();
4005 UserSettingsController::FinalizeSettingsController (usc);
4006 usc.reset();
4007}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004008
Greg Clayton990de7b2010-11-18 23:32:35 +00004009UserSettingsControllerSP &
4010Process::GetSettingsController ()
4011{
Greg Clayton334d33a2012-01-30 07:41:31 +00004012 static UserSettingsControllerSP g_settings_controller_sp;
4013 if (!g_settings_controller_sp)
4014 {
4015 g_settings_controller_sp.reset (new Process::SettingsController);
4016 // The first shared pointer to Process::SettingsController in
4017 // g_settings_controller_sp must be fully created above so that
4018 // the TargetInstanceSettings can use a weak_ptr to refer back
4019 // to the master setttings controller
4020 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp,
4021 false,
4022 InstanceSettings::GetDefaultName().AsCString()));
4023 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
4024 }
4025 return g_settings_controller_sp;
4026
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004027}
4028
Caroline Tice1ebef442010-09-27 00:30:10 +00004029void
4030Process::UpdateInstanceName ()
4031{
Greg Clayton5beb99d2011-08-11 02:48:45 +00004032 Module *module = GetTarget().GetExecutableModulePointer();
Greg Clayton13d24fb2012-01-29 20:56:30 +00004033 if (module && module->GetFileSpec().GetFilename())
Caroline Tice1ebef442010-09-27 00:30:10 +00004034 {
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00004035 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Clayton13d24fb2012-01-29 20:56:30 +00004036 module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1ebef442010-09-27 00:30:10 +00004037 }
4038}
4039
Greg Clayton427f2902010-12-14 02:59:59 +00004040ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004041Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004042 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004043 bool stop_others,
4044 bool try_all_threads,
4045 bool discard_on_error,
4046 uint32_t single_thread_timeout_usec,
4047 Stream &errors)
4048{
4049 ExecutionResults return_value = eExecutionSetupError;
4050
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004051 if (thread_plan_sp.get() == NULL)
4052 {
4053 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004054 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004055 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004056
4057 if (exe_ctx.GetProcessPtr() != this)
4058 {
4059 errors.Printf("RunThreadPlan called on wrong process.");
4060 return eExecutionSetupError;
4061 }
4062
4063 Thread *thread = exe_ctx.GetThreadPtr();
4064 if (thread == NULL)
4065 {
4066 errors.Printf("RunThreadPlan called with invalid thread.");
4067 return eExecutionSetupError;
4068 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004069
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004070 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4071 // For that to be true the plan can't be private - since private plans suppress themselves in the
4072 // GetCompletedPlan call.
4073
4074 bool orig_plan_private = thread_plan_sp->GetPrivate();
4075 thread_plan_sp->SetPrivate(false);
4076
Jim Inghamac959662011-01-24 06:34:17 +00004077 if (m_private_state.GetValue() != eStateStopped)
4078 {
4079 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004080 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004081 }
4082
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004083 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004084 const uint32_t thread_idx_id = thread->GetIndexID();
4085 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004086
4087 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4088 // so we should arrange to reset them as well.
4089
Greg Clayton567e7f32011-09-22 04:58:26 +00004090 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004091
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004092 uint32_t selected_tid;
4093 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004094 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004095 {
4096 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004097 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004098 }
4099 else
4100 {
4101 selected_tid = LLDB_INVALID_THREAD_ID;
4102 }
4103
Jim Ingham1831e782012-04-07 00:00:41 +00004104 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004105 lldb::StateType old_state;
4106 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004107
Jim Inghamd21d98b2012-04-10 01:21:57 +00004108 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004109 if (Host::GetCurrentThread() == m_private_state_thread)
4110 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004111 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4112 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004113 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Inghamd21d98b2012-04-10 01:21:57 +00004114 // we are fielding public events here.
4115 if (log)
4116 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4117
4118
Jim Ingham1831e782012-04-07 00:00:41 +00004119 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004120
4121 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4122 // returning control here.
4123 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4124 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4125 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4126 // do just what we want.
4127 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4128 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4129 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4130 old_state = m_public_state.GetValue();
4131 m_public_state.SetValueNoLock(eStateStopped);
4132
4133 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004134 StartPrivateStateThread(true);
4135 }
4136
4137 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004138
Jim Ingham6ae318c2011-01-23 21:14:08 +00004139 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004140
4141 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4142 // restored on exit to the function.
4143
4144 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00004145
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004146 if (log)
4147 {
4148 StreamString s;
4149 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton444e35b2011-10-19 18:09:39 +00004150 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Clayton567e7f32011-09-22 04:58:26 +00004151 thread->GetIndexID(),
4152 thread->GetID(),
Jim Inghamf9f40c22011-02-08 05:20:59 +00004153 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004154 }
4155
Jim Inghamf9f40c22011-02-08 05:20:59 +00004156 bool got_event;
4157 lldb::EventSP event_sp;
4158 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00004159
4160 TimeValue* timeout_ptr = NULL;
4161 TimeValue real_timeout;
4162
Jim Inghamf9f40c22011-02-08 05:20:59 +00004163 bool first_timeout = true;
4164 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00004165
Jim Ingham360f53f2010-11-30 02:22:11 +00004166 while (1)
4167 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004168 // We usually want to resume the process if we get to the top of the loop.
4169 // The only exception is if we get two running events with no intervening
4170 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00004171
Jim Inghamf9f40c22011-02-08 05:20:59 +00004172 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00004173 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004174 // Do the initial resume and wait for the running event before going further.
4175
Jim Ingham027aaa72012-04-19 01:40:33 +00004176 Error resume_error = PrivateResume ();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004177 if (!resume_error.Success())
4178 {
4179 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00004180 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004181 break;
4182 }
4183
4184 real_timeout = TimeValue::Now();
4185 real_timeout.OffsetWithMicroSeconds(500000);
4186 timeout_ptr = &real_timeout;
4187
Sean Callananfaf04782012-01-05 02:00:14 +00004188 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
Jim Inghamd21d98b2012-04-10 01:21:57 +00004189 if (!got_event)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004190 {
4191 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004192 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004193
4194 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00004195 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004196 break;
4197 }
4198
4199 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4200 if (stop_state != eStateRunning)
4201 {
4202 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004203 log->Printf("Process::RunThreadPlan(): didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00004204
4205 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00004206 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004207 break;
4208 }
4209
4210 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004211 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004212 // We need to call the function synchronously, so spin waiting for it to return.
4213 // If we get interrupted while executing, we're going to lose our context, and
4214 // won't be able to gather the result at this point.
4215 // We set the timeout AFTER the resume, since the resume takes some time and we
4216 // don't want to charge that to the timeout.
4217
4218 if (single_thread_timeout_usec != 0)
4219 {
4220 real_timeout = TimeValue::Now();
Jim Inghamf641af32012-04-13 23:09:49 +00004221 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004222
4223 timeout_ptr = &real_timeout;
4224 }
4225 }
4226 else
4227 {
4228 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004229 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004230 do_resume = true;
4231 }
4232
4233 // Now wait for the process to stop again:
4234 stop_state = lldb::eStateInvalid;
4235 event_sp.reset();
Jim Inghamf641af32012-04-13 23:09:49 +00004236
4237 if (log)
4238 {
4239 if (timeout_ptr)
4240 {
4241 StreamString s;
4242 s.Printf ("about to wait - timeout is:\n ");
4243 timeout_ptr->Dump (&s, 120);
4244 s.Printf ("\nNow is:\n ");
4245 TimeValue::Now().Dump (&s, 120);
4246 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4247 }
4248 else
4249 {
4250 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4251 }
4252 }
4253
Jim Inghamf9f40c22011-02-08 05:20:59 +00004254 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4255
4256 if (got_event)
4257 {
4258 if (event_sp.get())
4259 {
4260 bool keep_going = false;
4261 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4262 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004263 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00004264
4265 switch (stop_state)
4266 {
4267 case lldb::eStateStopped:
Jim Ingham2370a972011-05-17 01:10:11 +00004268 {
Greg Clayton43994462011-06-03 22:12:42 +00004269 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Clayton567e7f32011-09-22 04:58:26 +00004270 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton43994462011-06-03 22:12:42 +00004271 if (!thread_sp)
Jim Ingham2370a972011-05-17 01:10:11 +00004272 {
Greg Clayton43994462011-06-03 22:12:42 +00004273 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham2370a972011-05-17 01:10:11 +00004274 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004275 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Greg Clayton43994462011-06-03 22:12:42 +00004276 return_value = eExecutionInterrupted;
Jim Ingham2370a972011-05-17 01:10:11 +00004277 }
4278 else
4279 {
Greg Clayton43994462011-06-03 22:12:42 +00004280 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4281 StopReason stop_reason = eStopReasonInvalid;
4282 if (stop_info_sp)
4283 stop_reason = stop_info_sp->GetStopReason();
4284 if (stop_reason == eStopReasonPlanComplete)
4285 {
4286 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004287 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
Greg Clayton43994462011-06-03 22:12:42 +00004288 // Now mark this plan as private so it doesn't get reported as the stop reason
4289 // after this point.
4290 if (thread_plan_sp)
4291 thread_plan_sp->SetPrivate (orig_plan_private);
4292 return_value = eExecutionCompleted;
4293 }
4294 else
4295 {
4296 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004297 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Greg Clayton43994462011-06-03 22:12:42 +00004298
4299 return_value = eExecutionInterrupted;
4300 }
Jim Ingham2370a972011-05-17 01:10:11 +00004301 }
Greg Clayton43994462011-06-03 22:12:42 +00004302 }
4303 break;
4304
Jim Inghamf9f40c22011-02-08 05:20:59 +00004305 case lldb::eStateCrashed:
4306 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004307 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00004308 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004309 break;
Greg Clayton43994462011-06-03 22:12:42 +00004310
Jim Inghamf9f40c22011-02-08 05:20:59 +00004311 case lldb::eStateRunning:
4312 do_resume = false;
4313 keep_going = true;
4314 break;
Greg Clayton43994462011-06-03 22:12:42 +00004315
Jim Inghamf9f40c22011-02-08 05:20:59 +00004316 default:
4317 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004318 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham2370a972011-05-17 01:10:11 +00004319
4320 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytonb3448432011-03-24 21:19:54 +00004321 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004322 break;
4323 }
4324 if (keep_going)
4325 continue;
4326 else
4327 break;
4328 }
4329 else
4330 {
4331 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004332 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00004333 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004334 break;
4335 }
4336 }
4337 else
4338 {
4339 // If we didn't get an event that means we've timed out...
4340 // We will interrupt the process here. Depending on what we were asked to do we will
4341 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00004342 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00004343
Stephen Wilsonc2b98252011-01-12 04:20:03 +00004344 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00004345 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004346 {
4347 if (first_timeout)
4348 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4349 "trying with all threads enabled.",
4350 single_thread_timeout_usec);
4351 else
4352 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4353 "and timeout: %d timed out.",
4354 single_thread_timeout_usec);
4355 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004356 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00004357 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4358 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00004359 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00004360 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004361
Greg Clayton567e7f32011-09-22 04:58:26 +00004362 Error halt_error = Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00004363 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00004364 {
Jim Ingham360f53f2010-11-30 02:22:11 +00004365 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004366 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00004367
Jim Inghamf9f40c22011-02-08 05:20:59 +00004368 // If halt succeeds, it always produces a stopped event. Wait for that:
4369
4370 real_timeout = TimeValue::Now();
4371 real_timeout.OffsetWithMicroSeconds(500000);
4372
4373 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00004374
4375 if (got_event)
4376 {
4377 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4378 if (log)
4379 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004380 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00004381 if (stop_state == lldb::eStateStopped
4382 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf6d3d792011-08-09 22:24:33 +00004383 log->PutCString (" Event was the Halt interruption event.");
Jim Ingham360f53f2010-11-30 02:22:11 +00004384 }
4385
Jim Inghamf9f40c22011-02-08 05:20:59 +00004386 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00004387 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004388 // Between the time we initiated the Halt and the time we delivered it, the process could have
4389 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00004390
Greg Clayton567e7f32011-09-22 04:58:26 +00004391 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00004392 {
4393 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004394 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004395 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00004396 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004397 break;
4398 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004399
Jim Inghamf9f40c22011-02-08 05:20:59 +00004400 if (!try_all_threads)
4401 {
4402 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004403 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00004404 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004405 break;
4406 }
4407
4408 if (first_timeout)
4409 {
4410 // Set all the other threads to run, and return to the top of the loop, which will continue;
4411 first_timeout = false;
4412 thread_plan_sp->SetStopOthers (false);
4413 if (log)
Jim Inghamf641af32012-04-13 23:09:49 +00004414 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004415
4416 continue;
4417 }
4418 else
4419 {
4420 // Running all threads failed, so return Interrupted.
4421 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004422 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00004423 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004424 break;
4425 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004426 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004427 }
4428 else
4429 { if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004430 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004431 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00004432 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004433 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00004434 }
4435 }
Jim Inghamc556b462011-01-22 01:30:53 +00004436 else
4437 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004438 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4439 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00004440 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004441 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.",
4442 halt_error.AsCString());
4443 real_timeout = TimeValue::Now();
4444 real_timeout.OffsetWithMicroSeconds(500000);
4445 timeout_ptr = &real_timeout;
4446 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4447 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00004448 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004449 // This is not going anywhere, bag out.
4450 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004451 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00004452 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004453 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00004454 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004455 else
4456 {
4457 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4458 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004459 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004460 if (stop_state == lldb::eStateStopped)
4461 {
4462 // Between the time we initiated the Halt and the time we delivered it, the process could have
4463 // already finished its job. Check that here:
4464
Greg Clayton567e7f32011-09-22 04:58:26 +00004465 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00004466 {
4467 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004468 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004469 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00004470 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004471 break;
4472 }
4473
4474 if (first_timeout)
4475 {
4476 // Set all the other threads to run, and return to the top of the loop, which will continue;
4477 first_timeout = false;
4478 thread_plan_sp->SetStopOthers (false);
4479 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004480 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004481
4482 continue;
4483 }
4484 else
4485 {
4486 // Running all threads failed, so return Interrupted.
4487 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004488 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00004489 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004490 break;
4491 }
4492 }
4493 else
4494 {
Sean Callananed3f86b2011-08-09 22:07:08 +00004495 if (log)
4496 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4497 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00004498 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004499 break;
4500 }
4501 }
Jim Inghamc556b462011-01-22 01:30:53 +00004502 }
4503
Jim Ingham360f53f2010-11-30 02:22:11 +00004504 }
4505
Jim Inghamf9f40c22011-02-08 05:20:59 +00004506 } // END WAIT LOOP
4507
Jim Ingham1831e782012-04-07 00:00:41 +00004508 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4509 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4510 {
4511 StopPrivateStateThread();
Jim Ingham1831e782012-04-07 00:00:41 +00004512 Error error;
Jim Ingham1831e782012-04-07 00:00:41 +00004513 m_private_state_thread = backup_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004514 if (stopper_base_plan_sp != NULL)
4515 {
4516 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4517 }
4518 m_public_state.SetValueNoLock(old_state);
4519
Jim Ingham1831e782012-04-07 00:00:41 +00004520 }
4521
4522
Jim Inghamf9f40c22011-02-08 05:20:59 +00004523 // Now do some processing on the results of the run:
4524 if (return_value == eExecutionInterrupted)
4525 {
Jim Ingham360f53f2010-11-30 02:22:11 +00004526 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004527 {
4528 StreamString s;
4529 if (event_sp)
4530 event_sp->Dump (&s);
4531 else
4532 {
Jim Inghamf6d3d792011-08-09 22:24:33 +00004533 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004534 }
4535
4536 StreamString ts;
4537
Jim Inghamf6d3d792011-08-09 22:24:33 +00004538 const char *event_explanation = NULL;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004539
4540 do
4541 {
4542 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4543
4544 if (!event_data)
4545 {
4546 event_explanation = "<no event data>";
4547 break;
4548 }
4549
4550 Process *process = event_data->GetProcessSP().get();
4551
4552 if (!process)
4553 {
4554 event_explanation = "<no process>";
4555 break;
4556 }
4557
4558 ThreadList &thread_list = process->GetThreadList();
4559
4560 uint32_t num_threads = thread_list.GetSize();
4561 uint32_t thread_index;
4562
4563 ts.Printf("<%u threads> ", num_threads);
4564
4565 for (thread_index = 0;
4566 thread_index < num_threads;
4567 ++thread_index)
4568 {
4569 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4570
4571 if (!thread)
4572 {
4573 ts.Printf("<?> ");
4574 continue;
4575 }
4576
Greg Clayton444e35b2011-10-19 18:09:39 +00004577 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Inghamf9f40c22011-02-08 05:20:59 +00004578 RegisterContext *register_context = thread->GetRegisterContext().get();
4579
4580 if (register_context)
4581 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4582 else
4583 ts.Printf("[ip unknown] ");
4584
4585 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4586 if (stop_info_sp)
4587 {
4588 const char *stop_desc = stop_info_sp->GetDescription();
4589 if (stop_desc)
4590 ts.PutCString (stop_desc);
4591 }
4592 ts.Printf(">");
4593 }
4594
4595 event_explanation = ts.GetData();
4596 } while (0);
4597
4598 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004599 {
4600 if (event_explanation)
4601 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4602 else
4603 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4604 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004605
4606 if (discard_on_error && thread_plan_sp)
4607 {
Jim Inghamf641af32012-04-13 23:09:49 +00004608 if (log)
4609 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
Greg Clayton567e7f32011-09-22 04:58:26 +00004610 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004611 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004612 }
Jim Inghamf641af32012-04-13 23:09:49 +00004613 else
4614 {
4615 if (log)
4616 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
4617
4618 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004619 }
4620 }
4621 else if (return_value == eExecutionSetupError)
4622 {
4623 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004624 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004625
4626 if (discard_on_error && thread_plan_sp)
4627 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004628 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004629 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004630 }
4631 }
4632 else
4633 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004634 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004635 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004636 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004637 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00004638 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00004639 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004640 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004641 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004642 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004643 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00004644 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00004645 }
4646 else
4647 {
4648 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004649 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00004650 if (discard_on_error && thread_plan_sp)
4651 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004652 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004653 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Clayton567e7f32011-09-22 04:58:26 +00004654 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004655 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham360f53f2010-11-30 02:22:11 +00004656 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004657 }
4658 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004659
Jim Ingham360f53f2010-11-30 02:22:11 +00004660 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004661 // Check that it's still there, and if it is put it back in the context. Also restore the
4662 // frame in the context if it is still present.
Greg Clayton567e7f32011-09-22 04:58:26 +00004663 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4664 if (thread)
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004665 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004666 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004667 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004668
4669 // Also restore the current process'es selected frame & thread, since this function calling may
4670 // be done behind the user's back.
4671
4672 if (selected_tid != LLDB_INVALID_THREAD_ID)
4673 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004674 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Ingham360f53f2010-11-30 02:22:11 +00004675 {
4676 // We were able to restore the selected thread, now restore the frame:
Greg Clayton567e7f32011-09-22 04:58:26 +00004677 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004678 if (old_frame_sp)
Greg Clayton567e7f32011-09-22 04:58:26 +00004679 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00004680 }
4681 }
4682
4683 return return_value;
4684}
4685
4686const char *
4687Process::ExecutionResultAsCString (ExecutionResults result)
4688{
4689 const char *result_name;
4690
4691 switch (result)
4692 {
Greg Claytonb3448432011-03-24 21:19:54 +00004693 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004694 result_name = "eExecutionCompleted";
4695 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004696 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00004697 result_name = "eExecutionDiscarded";
4698 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004699 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004700 result_name = "eExecutionInterrupted";
4701 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004702 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00004703 result_name = "eExecutionSetupError";
4704 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004705 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00004706 result_name = "eExecutionTimedOut";
4707 break;
4708 }
4709 return result_name;
4710}
4711
Greg Claytonabe0fed2011-04-18 08:33:37 +00004712void
4713Process::GetStatus (Stream &strm)
4714{
4715 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00004716 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00004717 {
4718 if (state == eStateExited)
4719 {
4720 int exit_status = GetExitStatus();
4721 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00004722 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00004723 GetID(),
4724 exit_status,
4725 exit_status,
4726 exit_description ? exit_description : "");
4727 }
4728 else
4729 {
4730 if (state == eStateConnected)
4731 strm.Printf ("Connected to remote target.\n");
4732 else
Greg Clayton444e35b2011-10-19 18:09:39 +00004733 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00004734 }
4735 }
4736 else
4737 {
Greg Clayton444e35b2011-10-19 18:09:39 +00004738 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004739 }
4740}
4741
4742size_t
4743Process::GetThreadStatus (Stream &strm,
4744 bool only_threads_with_stop_reason,
4745 uint32_t start_frame,
4746 uint32_t num_frames,
4747 uint32_t num_frames_with_source)
4748{
4749 size_t num_thread_infos_dumped = 0;
4750
4751 const size_t num_threads = GetThreadList().GetSize();
4752 for (uint32_t i = 0; i < num_threads; i++)
4753 {
4754 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4755 if (thread)
4756 {
4757 if (only_threads_with_stop_reason)
4758 {
4759 if (thread->GetStopInfo().get() == NULL)
4760 continue;
4761 }
4762 thread->GetStatus (strm,
4763 start_frame,
4764 num_frames,
4765 num_frames_with_source);
4766 ++num_thread_infos_dumped;
4767 }
4768 }
4769 return num_thread_infos_dumped;
4770}
4771
Greg Clayton76113302012-02-22 04:37:26 +00004772void
4773Process::AddInvalidMemoryRegion (const LoadRange &region)
4774{
4775 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4776}
4777
4778bool
4779Process::RemoveInvalidMemoryRange (const LoadRange &region)
4780{
4781 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4782}
4783
Jim Ingham1831e782012-04-07 00:00:41 +00004784void
4785Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4786{
4787 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4788}
4789
4790bool
4791Process::RunPreResumeActions ()
4792{
4793 bool result = true;
4794 while (!m_pre_resume_actions.empty())
4795 {
4796 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
4797 m_pre_resume_actions.pop_back();
4798 bool this_result = action.callback (action.baton);
4799 if (result == true) result = this_result;
4800 }
4801 return result;
4802}
4803
4804void
4805Process::ClearPreResumeActions ()
4806{
4807 m_pre_resume_actions.clear();
4808}
Greg Clayton76113302012-02-22 04:37:26 +00004809
Greg Claytoncf5927e2012-05-18 02:38:05 +00004810void
4811Process::Flush ()
4812{
4813 m_thread_list.Flush();
4814}
4815
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004816//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004817// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004818//--------------------------------------------------------------
4819
Greg Claytond0a5a232010-09-19 02:33:57 +00004820Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00004821 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004822{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004823}
4824
Greg Claytond0a5a232010-09-19 02:33:57 +00004825Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004826{
4827}
4828
4829lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00004830Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004831{
Greg Clayton334d33a2012-01-30 07:41:31 +00004832 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4833 false,
4834 instance_name));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004835 return new_settings_sp;
4836}
4837
4838//--------------------------------------------------------------
4839// class ProcessInstanceSettings
4840//--------------------------------------------------------------
4841
Greg Clayton638351a2010-12-04 00:10:17 +00004842ProcessInstanceSettings::ProcessInstanceSettings
4843(
Greg Clayton334d33a2012-01-30 07:41:31 +00004844 const UserSettingsControllerSP &owner_sp,
Greg Clayton638351a2010-12-04 00:10:17 +00004845 bool live_instance,
4846 const char *name
4847) :
Greg Clayton334d33a2012-01-30 07:41:31 +00004848 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004849{
Caroline Tice396704b2010-09-09 18:26:37 +00004850 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4851 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4852 // 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 +00004853 // This is true for CreateInstanceName() too.
Greg Claytonabb33022011-11-08 02:43:13 +00004854
Caroline Tice75b11a32010-09-16 19:05:55 +00004855 if (GetInstanceName () == InstanceSettings::InvalidName())
4856 {
4857 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
Greg Clayton334d33a2012-01-30 07:41:31 +00004858 owner_sp->RegisterInstanceSettings (this);
Caroline Tice75b11a32010-09-16 19:05:55 +00004859 }
Greg Claytonabb33022011-11-08 02:43:13 +00004860
Caroline Tice396704b2010-09-09 18:26:37 +00004861 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004862 {
Greg Clayton334d33a2012-01-30 07:41:31 +00004863 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004864 CopyInstanceSettings (pending_settings,false);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004865 }
4866}
4867
4868ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Clayton334d33a2012-01-30 07:41:31 +00004869 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004870{
4871 if (m_instance_name != InstanceSettings::GetDefaultName())
4872 {
Greg Clayton334d33a2012-01-30 07:41:31 +00004873 UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4874 if (owner_sp)
4875 {
4876 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4877 owner_sp->RemovePendingSettings (m_instance_name);
4878 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004879 }
4880}
4881
4882ProcessInstanceSettings::~ProcessInstanceSettings ()
4883{
4884}
4885
4886ProcessInstanceSettings&
4887ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4888{
4889 if (this != &rhs)
4890 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004891 }
4892
4893 return *this;
4894}
4895
4896
4897void
4898ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4899 const char *index_value,
4900 const char *value,
4901 const ConstString &instance_name,
4902 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00004903 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004904 Error &err,
4905 bool pending)
4906{
Sean Callananf90b5f32012-06-07 22:26:42 +00004907 if (var_name == GetDisableMemoryCacheVarName())
4908 {
4909 bool success;
4910 bool result = Args::StringToBoolean(value, false, &success);
4911
4912 if (success)
4913 {
4914 m_disable_memory_cache = result;
4915 }
4916 else
4917 {
4918 err.SetErrorStringWithFormat ("Bad value \"%s\" for %s, should be Boolean.", value, GetDisableMemoryCacheVarName().AsCString());
4919 }
4920
4921 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004922}
4923
4924void
4925ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4926 bool pending)
4927{
Sean Callananf90b5f32012-06-07 22:26:42 +00004928 if (new_settings.get() == NULL)
4929 return;
4930
4931 ProcessInstanceSettings *new_settings_ptr = static_cast <ProcessInstanceSettings *> (new_settings.get());
4932
4933 if (!new_settings_ptr)
4934 return;
4935
4936 *this = *new_settings_ptr;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004937}
4938
Caroline Ticebcb5b452010-09-20 21:37:42 +00004939bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004940ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4941 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00004942 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00004943 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004944{
Sean Callananf90b5f32012-06-07 22:26:42 +00004945 if (var_name == GetDisableMemoryCacheVarName())
4946 {
4947 value.AppendString(m_disable_memory_cache ? "true" : "false");
4948 return true;
4949 }
4950 else
4951 {
4952 if (err)
4953 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4954 return false;
4955 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004956}
4957
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004958const ConstString
4959ProcessInstanceSettings::CreateInstanceName ()
4960{
4961 static int instance_count = 1;
4962 StreamString sstr;
4963
4964 sstr.Printf ("process_%d", instance_count);
4965 ++instance_count;
4966
4967 const ConstString ret_val (sstr.GetData());
4968 return ret_val;
4969}
4970
Sean Callananf90b5f32012-06-07 22:26:42 +00004971const ConstString &
4972ProcessInstanceSettings::GetDisableMemoryCacheVarName () const
4973{
4974 static ConstString disable_memory_cache_var_name ("disable-memory-cache");
4975
4976 return disable_memory_cache_var_name;
4977}
4978
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004979//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004980// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004981//--------------------------------------------------
4982
4983SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004984Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004985{
4986 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4987 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4988};
4989
4990
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004991SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004992Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004993{
Greg Clayton638351a2010-12-04 00:10:17 +00004994 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Sean Callananf90b5f32012-06-07 22:26:42 +00004995 { "disable-memory-cache", eSetVarTypeBoolean,
4996#ifdef ENABLE_MEMORY_CACHING
4997 "false",
4998#else
4999 "true",
5000#endif
5001 NULL, false, false, "Disable reading and caching of memory in fixed-size units." },
Greg Clayton638351a2010-12-04 00:10:17 +00005002 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00005003};
5004
5005
Jim Ingham7508e732010-08-09 23:31:02 +00005006
Greg Claytonabb33022011-11-08 02:43:13 +00005007