blob: 993d9809250ab0badc02bd4c817d3aa8f6093bd9 [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,
Jim Ingham5d90ade2012-07-27 23:57:19 +0000838 eBroadcastBitStateChanged |
839 eBroadcastBitInterrupt);
Chris Lattner24943d22010-06-08 16:52:24 +0000840
841 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
842 eBroadcastInternalStateControlStop |
843 eBroadcastInternalStateControlPause |
844 eBroadcastInternalStateControlResume);
845}
846
847//----------------------------------------------------------------------
848// Destructor
849//----------------------------------------------------------------------
850Process::~Process()
851{
Greg Claytone005f2c2010-11-06 01:53:30 +0000852 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000853 if (log)
854 log->Printf ("%p Process::~Process()", this);
855 StopPrivateStateThread();
856}
857
858void
859Process::Finalize()
860{
Greg Claytonffa43a62011-11-17 04:46:02 +0000861 switch (GetPrivateState())
862 {
863 case eStateConnected:
864 case eStateAttaching:
865 case eStateLaunching:
866 case eStateStopped:
867 case eStateRunning:
868 case eStateStepping:
869 case eStateCrashed:
870 case eStateSuspended:
871 if (GetShouldDetach())
872 Detach();
873 else
874 Destroy();
875 break;
876
877 case eStateInvalid:
878 case eStateUnloaded:
879 case eStateDetached:
880 case eStateExited:
881 break;
882 }
883
Greg Clayton2f57db02011-10-01 00:45:15 +0000884 // Clear our broadcaster before we proceed with destroying
885 Broadcaster::Clear();
886
Chris Lattner24943d22010-06-08 16:52:24 +0000887 // Do any cleanup needed prior to being destructed... Subclasses
888 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000889
890 // We need to destroy the loader before the derived Process class gets destroyed
891 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +0000892 m_dynamic_checkers_ap.reset();
893 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +0000894 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +0000895 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +0000896 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +0000897 std::vector<Notifications> empty_notifications;
898 m_notifications.swap(empty_notifications);
899 m_image_tokens.clear();
900 m_memory_cache.Clear();
901 m_allocated_memory_cache.Clear();
902 m_language_runtimes.clear();
903 m_next_event_action_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000904}
905
906void
907Process::RegisterNotificationCallbacks (const Notifications& callbacks)
908{
909 m_notifications.push_back(callbacks);
910 if (callbacks.initialize != NULL)
911 callbacks.initialize (callbacks.baton, this);
912}
913
914bool
915Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
916{
917 std::vector<Notifications>::iterator pos, end = m_notifications.end();
918 for (pos = m_notifications.begin(); pos != end; ++pos)
919 {
920 if (pos->baton == callbacks.baton &&
921 pos->initialize == callbacks.initialize &&
922 pos->process_state_changed == callbacks.process_state_changed)
923 {
924 m_notifications.erase(pos);
925 return true;
926 }
927 }
928 return false;
929}
930
931void
932Process::SynchronouslyNotifyStateChanged (StateType state)
933{
934 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
935 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
936 {
937 if (notification_pos->process_state_changed)
938 notification_pos->process_state_changed (notification_pos->baton, this, state);
939 }
940}
941
942// FIXME: We need to do some work on events before the general Listener sees them.
943// For instance if we are continuing from a breakpoint, we need to ensure that we do
944// the little "insert real insn, step & stop" trick. But we can't do that when the
945// event is delivered by the broadcaster - since that is done on the thread that is
946// waiting for new events, so if we needed more than one event for our handling, we would
947// stall. So instead we do it when we fetch the event off of the queue.
948//
949
950StateType
951Process::GetNextEvent (EventSP &event_sp)
952{
953 StateType state = eStateInvalid;
954
955 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
956 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
957
958 return state;
959}
960
961
962StateType
963Process::WaitForProcessToStop (const TimeValue *timeout)
964{
Jim Ingham21f37ad2011-08-09 02:12:22 +0000965 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
966 // We have to actually check each event, and in the case of a stopped event check the restarted flag
967 // on the event.
968 EventSP event_sp;
969 StateType state = GetState();
970 // If we are exited or detached, we won't ever get back to any
971 // other valid state...
972 if (state == eStateDetached || state == eStateExited)
973 return state;
974
975 while (state != eStateInvalid)
976 {
977 state = WaitForStateChangedEvents (timeout, event_sp);
978 switch (state)
979 {
980 case eStateCrashed:
981 case eStateDetached:
982 case eStateExited:
983 case eStateUnloaded:
984 return state;
985 case eStateStopped:
986 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
987 continue;
988 else
989 return state;
990 default:
991 continue;
992 }
993 }
994 return state;
Chris Lattner24943d22010-06-08 16:52:24 +0000995}
996
997
998StateType
999Process::WaitForState
1000(
1001 const TimeValue *timeout,
1002 const StateType *match_states, const uint32_t num_match_states
1003)
1004{
1005 EventSP event_sp;
1006 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +00001007 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +00001008 while (state != eStateInvalid)
1009 {
Greg Claytond8c62532010-10-07 04:19:01 +00001010 // If we are exited or detached, we won't ever get back to any
1011 // other valid state...
1012 if (state == eStateDetached || state == eStateExited)
1013 return state;
1014
Chris Lattner24943d22010-06-08 16:52:24 +00001015 state = WaitForStateChangedEvents (timeout, event_sp);
1016
1017 for (i=0; i<num_match_states; ++i)
1018 {
1019 if (match_states[i] == state)
1020 return state;
1021 }
1022 }
1023 return state;
1024}
1025
Jim Ingham63e24d72010-10-11 23:53:14 +00001026bool
1027Process::HijackProcessEvents (Listener *listener)
1028{
1029 if (listener != NULL)
1030 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001031 return HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Ingham63e24d72010-10-11 23:53:14 +00001032 }
1033 else
1034 return false;
1035}
1036
1037void
1038Process::RestoreProcessEvents ()
1039{
1040 RestoreBroadcaster();
1041}
1042
Jim Inghamf9f40c22011-02-08 05:20:59 +00001043bool
1044Process::HijackPrivateProcessEvents (Listener *listener)
1045{
1046 if (listener != NULL)
1047 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00001048 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged | eBroadcastBitInterrupt);
Jim Inghamf9f40c22011-02-08 05:20:59 +00001049 }
1050 else
1051 return false;
1052}
1053
1054void
1055Process::RestorePrivateProcessEvents ()
1056{
1057 m_private_state_broadcaster.RestoreBroadcaster();
1058}
1059
Chris Lattner24943d22010-06-08 16:52:24 +00001060StateType
1061Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1062{
Greg Claytone005f2c2010-11-06 01:53:30 +00001063 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001064
1065 if (log)
1066 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1067
1068 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001069 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1070 this,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001071 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton36f63a92010-10-19 03:25:40 +00001072 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001073 {
1074 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1075 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1076 else if (log)
1077 log->Printf ("Process::%s got no event or was interrupted.", __FUNCTION__);
1078 }
Chris Lattner24943d22010-06-08 16:52:24 +00001079
1080 if (log)
1081 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1082 __FUNCTION__,
1083 timeout,
1084 StateAsCString(state));
1085 return state;
1086}
1087
1088Event *
1089Process::PeekAtStateChangedEvents ()
1090{
Greg Claytone005f2c2010-11-06 01:53:30 +00001091 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001092
1093 if (log)
1094 log->Printf ("Process::%s...", __FUNCTION__);
1095
1096 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001097 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1098 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001099 if (log)
1100 {
1101 if (event_ptr)
1102 {
1103 log->Printf ("Process::%s (event_ptr) => %s",
1104 __FUNCTION__,
1105 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1106 }
1107 else
1108 {
1109 log->Printf ("Process::%s no events found",
1110 __FUNCTION__);
1111 }
1112 }
1113 return event_ptr;
1114}
1115
1116StateType
1117Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1118{
Greg Claytone005f2c2010-11-06 01:53:30 +00001119 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001120
1121 if (log)
1122 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1123
1124 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001125 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1126 &m_private_state_broadcaster,
Jim Ingham5d90ade2012-07-27 23:57:19 +00001127 eBroadcastBitStateChanged | eBroadcastBitInterrupt,
Greg Clayton72e1c782011-01-22 23:43:18 +00001128 event_sp))
Jim Ingham5d90ade2012-07-27 23:57:19 +00001129 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1130 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00001131
1132 // This is a bit of a hack, but when we wait here we could very well return
1133 // to the command-line, and that could disable the log, which would render the
1134 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001135 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001136 {
1137 if (state == eStateInvalid)
1138 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1139 else
1140 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1141 }
Chris Lattner24943d22010-06-08 16:52:24 +00001142 return state;
1143}
1144
1145bool
1146Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1147{
Greg Claytone005f2c2010-11-06 01:53:30 +00001148 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001149
1150 if (log)
1151 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1152
1153 if (control_only)
1154 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1155 else
1156 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1157}
1158
1159bool
1160Process::IsRunning () const
1161{
1162 return StateIsRunningState (m_public_state.GetValue());
1163}
1164
1165int
1166Process::GetExitStatus ()
1167{
1168 if (m_public_state.GetValue() == eStateExited)
1169 return m_exit_status;
1170 return -1;
1171}
1172
Greg Clayton638351a2010-12-04 00:10:17 +00001173
Chris Lattner24943d22010-06-08 16:52:24 +00001174const char *
1175Process::GetExitDescription ()
1176{
1177 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1178 return m_exit_string.c_str();
1179 return NULL;
1180}
1181
Greg Clayton72e1c782011-01-22 23:43:18 +00001182bool
Chris Lattner24943d22010-06-08 16:52:24 +00001183Process::SetExitStatus (int status, const char *cstr)
1184{
Greg Clayton68ca8232011-01-25 02:58:48 +00001185 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1186 if (log)
1187 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1188 status, status,
1189 cstr ? "\"" : "",
1190 cstr ? cstr : "NULL",
1191 cstr ? "\"" : "");
1192
Greg Clayton72e1c782011-01-22 23:43:18 +00001193 // We were already in the exited state
1194 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001195 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001196 if (log)
1197 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001198 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001199 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001200
1201 m_exit_status = status;
1202 if (cstr)
1203 m_exit_string = cstr;
1204 else
1205 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001206
Greg Clayton72e1c782011-01-22 23:43:18 +00001207 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001208
Greg Clayton72e1c782011-01-22 23:43:18 +00001209 SetPrivateState (eStateExited);
1210 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001211}
1212
1213// This static callback can be used to watch for local child processes on
1214// the current host. The the child process exits, the process will be
1215// found in the global target list (we want to be completely sure that the
1216// lldb_private::Process doesn't go away before we can deliver the signal.
1217bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001218Process::SetProcessExitStatus (void *callback_baton,
1219 lldb::pid_t pid,
1220 bool exited,
1221 int signo, // Zero for no signal
1222 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001223)
1224{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001225 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1226 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00001227 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001228 callback_baton,
1229 pid,
1230 exited,
1231 signo,
1232 exit_status);
1233
1234 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001235 {
Greg Clayton63094e02010-06-23 01:19:29 +00001236 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001237 if (target_sp)
1238 {
1239 ProcessSP process_sp (target_sp->GetProcessSP());
1240 if (process_sp)
1241 {
1242 const char *signal_cstr = NULL;
1243 if (signo)
1244 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1245
1246 process_sp->SetExitStatus (exit_status, signal_cstr);
1247 }
1248 }
1249 return true;
1250 }
1251 return false;
1252}
1253
1254
Greg Clayton37f962e2011-08-22 02:49:39 +00001255void
1256Process::UpdateThreadListIfNeeded ()
1257{
1258 const uint32_t stop_id = GetStopID();
1259 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1260 {
Greg Clayton20206082011-11-17 01:23:07 +00001261 const StateType state = GetPrivateState();
1262 if (StateIsStoppedState (state, true))
1263 {
1264 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001265 // m_thread_list does have its own mutex, but we need to
1266 // hold onto the mutex between the call to UpdateThreadList(...)
1267 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001268 ThreadList new_thread_list(this);
1269 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001270 // thread list, but only update if "true" is returned
1271 if (UpdateThreadList (m_thread_list, new_thread_list))
1272 {
1273 OperatingSystem *os = GetOperatingSystem ();
1274 if (os)
1275 os->UpdateThreadList (m_thread_list, new_thread_list);
1276 m_thread_list.Update (new_thread_list);
1277 m_thread_list.SetStopID (stop_id);
1278 }
Greg Clayton20206082011-11-17 01:23:07 +00001279 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001280 }
1281}
1282
Chris Lattner24943d22010-06-08 16:52:24 +00001283uint32_t
1284Process::GetNextThreadIndexID ()
1285{
1286 return ++m_thread_index_id;
1287}
1288
1289StateType
1290Process::GetState()
1291{
1292 // If any other threads access this we will need a mutex for it
1293 return m_public_state.GetValue ();
1294}
1295
1296void
1297Process::SetPublicState (StateType new_state)
1298{
Greg Clayton68ca8232011-01-25 02:58:48 +00001299 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001300 if (log)
1301 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001302 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001303 m_public_state.SetValue (new_state);
Jim Ingham027aaa72012-04-19 01:40:33 +00001304
1305 // On the transition from Run to Stopped, we unlock the writer end of the
1306 // run lock. The lock gets locked in Resume, which is the public API
1307 // to tell the program to run.
Greg Claytona894fe72012-04-05 16:12:35 +00001308 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1309 {
Sean Callanana3772862012-06-02 01:16:20 +00001310 if (new_state == eStateDetached)
Greg Claytona894fe72012-04-05 16:12:35 +00001311 {
Sean Callanana3772862012-06-02 01:16:20 +00001312 if (log)
1313 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1314 m_run_lock.WriteUnlock();
1315 }
1316 else
1317 {
1318 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1319 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1320 if (old_state_is_stopped != new_state_is_stopped)
Greg Claytona894fe72012-04-05 16:12:35 +00001321 {
Sean Callanana3772862012-06-02 01:16:20 +00001322 if (new_state_is_stopped)
1323 {
1324 if (log)
1325 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1326 m_run_lock.WriteUnlock();
1327 }
Greg Claytona894fe72012-04-05 16:12:35 +00001328 }
Greg Claytona894fe72012-04-05 16:12:35 +00001329 }
1330 }
Chris Lattner24943d22010-06-08 16:52:24 +00001331}
1332
Jim Ingham027aaa72012-04-19 01:40:33 +00001333Error
1334Process::Resume ()
1335{
1336 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1337 if (log)
1338 log->Printf("Process::Resume -- locking run lock");
1339 if (!m_run_lock.WriteTryLock())
1340 {
1341 Error error("Resume request failed - process still running.");
1342 if (log)
1343 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1344 return error;
1345 }
1346 return PrivateResume();
1347}
1348
Chris Lattner24943d22010-06-08 16:52:24 +00001349StateType
1350Process::GetPrivateState ()
1351{
1352 return m_private_state.GetValue();
1353}
1354
1355void
1356Process::SetPrivateState (StateType new_state)
1357{
Greg Clayton68ca8232011-01-25 02:58:48 +00001358 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001359 bool state_changed = false;
1360
1361 if (log)
1362 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1363
1364 Mutex::Locker locker(m_private_state.GetMutex());
1365
1366 const StateType old_state = m_private_state.GetValueNoLock ();
1367 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001368 // This code is left commented out in case we ever need to control
1369 // the private process state with another run lock. Right now it doesn't
1370 // seem like we need to do this, but if we ever do, we can uncomment and
1371 // use this code.
1372// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1373// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1374// if (old_state_is_stopped != new_state_is_stopped)
1375// {
1376// if (new_state_is_stopped)
1377// m_private_run_lock.WriteUnlock();
1378// else
1379// m_private_run_lock.WriteLock();
1380// }
1381
Chris Lattner24943d22010-06-08 16:52:24 +00001382 if (state_changed)
1383 {
1384 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001385 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001386 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001387 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001388 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001389 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001390 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001391 }
1392 // Use our target to get a shared pointer to ourselves...
1393 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1394 }
1395 else
1396 {
1397 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001398 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001399 }
1400}
1401
Jim Ingham0296fe72011-11-08 03:00:11 +00001402void
1403Process::SetRunningUserExpression (bool on)
1404{
1405 m_mod_id.SetRunningUserExpression (on);
1406}
1407
Chris Lattner24943d22010-06-08 16:52:24 +00001408addr_t
1409Process::GetImageInfoAddress()
1410{
1411 return LLDB_INVALID_ADDRESS;
1412}
1413
Greg Clayton0baa3942010-11-04 01:54:29 +00001414//----------------------------------------------------------------------
1415// LoadImage
1416//
1417// This function provides a default implementation that works for most
1418// unix variants. Any Process subclasses that need to do shared library
1419// loading differently should override LoadImage and UnloadImage and
1420// do what is needed.
1421//----------------------------------------------------------------------
1422uint32_t
1423Process::LoadImage (const FileSpec &image_spec, Error &error)
1424{
Greg Clayton77d40712012-04-18 00:05:19 +00001425 char path[PATH_MAX];
1426 image_spec.GetPath(path, sizeof(path));
1427
Greg Clayton0baa3942010-11-04 01:54:29 +00001428 DynamicLoader *loader = GetDynamicLoader();
1429 if (loader)
1430 {
1431 error = loader->CanLoadImage();
1432 if (error.Fail())
1433 return LLDB_INVALID_IMAGE_TOKEN;
1434 }
1435
1436 if (error.Success())
1437 {
1438 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001439
1440 if (thread_sp)
1441 {
1442 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1443
1444 if (frame_sp)
1445 {
1446 ExecutionContext exe_ctx;
1447 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001448 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001449 StreamString expr;
Greg Clayton0baa3942010-11-04 01:54:29 +00001450 expr.Printf("dlopen (\"%s\", 2)", path);
1451 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001452 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001453 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 +00001454 error = result_valobj_sp->GetError();
1455 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001456 {
1457 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001458 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001459 {
1460 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1461 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1462 {
1463 uint32_t image_token = m_image_tokens.size();
1464 m_image_tokens.push_back (image_ptr);
1465 return image_token;
1466 }
1467 }
1468 }
1469 }
1470 }
1471 }
Greg Clayton77d40712012-04-18 00:05:19 +00001472 if (!error.AsCString())
1473 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton0baa3942010-11-04 01:54:29 +00001474 return LLDB_INVALID_IMAGE_TOKEN;
1475}
1476
1477//----------------------------------------------------------------------
1478// UnloadImage
1479//
1480// This function provides a default implementation that works for most
1481// unix variants. Any Process subclasses that need to do shared library
1482// loading differently should override LoadImage and UnloadImage and
1483// do what is needed.
1484//----------------------------------------------------------------------
1485Error
1486Process::UnloadImage (uint32_t image_token)
1487{
1488 Error error;
1489 if (image_token < m_image_tokens.size())
1490 {
1491 const addr_t image_addr = m_image_tokens[image_token];
1492 if (image_addr == LLDB_INVALID_ADDRESS)
1493 {
1494 error.SetErrorString("image already unloaded");
1495 }
1496 else
1497 {
1498 DynamicLoader *loader = GetDynamicLoader();
1499 if (loader)
1500 error = loader->CanLoadImage();
1501
1502 if (error.Success())
1503 {
1504 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001505
1506 if (thread_sp)
1507 {
1508 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1509
1510 if (frame_sp)
1511 {
1512 ExecutionContext exe_ctx;
1513 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001514 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001515 StreamString expr;
1516 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1517 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001518 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001519 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 +00001520 if (result_valobj_sp->GetError().Success())
1521 {
1522 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001523 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001524 {
1525 if (scalar.UInt(1))
1526 {
1527 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1528 }
1529 else
1530 {
1531 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1532 }
1533 }
1534 }
1535 else
1536 {
1537 error = result_valobj_sp->GetError();
1538 }
1539 }
1540 }
1541 }
1542 }
1543 }
1544 else
1545 {
1546 error.SetErrorString("invalid image token");
1547 }
1548 return error;
1549}
1550
Greg Clayton75906e42011-05-11 18:39:18 +00001551const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001552Process::GetABI()
1553{
Greg Clayton75906e42011-05-11 18:39:18 +00001554 if (!m_abi_sp)
1555 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1556 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001557}
1558
Jim Ingham642036f2010-09-23 02:01:19 +00001559LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001560Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001561{
1562 LanguageRuntimeCollection::iterator pos;
1563 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001564 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001565 {
Jim Inghame3117662012-03-10 00:22:19 +00001566 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001567
Jim Inghame3117662012-03-10 00:22:19 +00001568 m_language_runtimes[language] = runtime_sp;
1569 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001570 }
1571 else
1572 return (*pos).second.get();
1573}
1574
1575CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001576Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001577{
Jim Inghame3117662012-03-10 00:22:19 +00001578 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001579 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1580 return static_cast<CPPLanguageRuntime *> (runtime);
1581 return NULL;
1582}
1583
1584ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001585Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001586{
Jim Inghame3117662012-03-10 00:22:19 +00001587 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001588 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1589 return static_cast<ObjCLanguageRuntime *> (runtime);
1590 return NULL;
1591}
1592
Enrico Granata6b1763b2012-05-21 16:51:35 +00001593bool
1594Process::IsPossibleDynamicValue (ValueObject& in_value)
1595{
1596 if (in_value.IsDynamic())
1597 return false;
1598 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1599
1600 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1601 {
1602 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1603 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1604 }
1605
1606 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1607 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1608 return true;
1609
1610 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1611 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1612}
1613
Chris Lattner24943d22010-06-08 16:52:24 +00001614BreakpointSiteList &
1615Process::GetBreakpointSiteList()
1616{
1617 return m_breakpoint_site_list;
1618}
1619
1620const BreakpointSiteList &
1621Process::GetBreakpointSiteList() const
1622{
1623 return m_breakpoint_site_list;
1624}
1625
1626
1627void
1628Process::DisableAllBreakpointSites ()
1629{
1630 m_breakpoint_site_list.SetEnabledForAll (false);
Jim Ingham06b84492012-07-04 00:35:43 +00001631 size_t num_sites = m_breakpoint_site_list.GetSize();
1632 for (size_t i = 0; i < num_sites; i++)
1633 {
1634 DisableBreakpoint (m_breakpoint_site_list.GetByIndex(i).get());
1635 }
Chris Lattner24943d22010-06-08 16:52:24 +00001636}
1637
1638Error
1639Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1640{
1641 Error error (DisableBreakpointSiteByID (break_id));
1642
1643 if (error.Success())
1644 m_breakpoint_site_list.Remove(break_id);
1645
1646 return error;
1647}
1648
1649Error
1650Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1651{
1652 Error error;
1653 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1654 if (bp_site_sp)
1655 {
1656 if (bp_site_sp->IsEnabled())
1657 error = DisableBreakpoint (bp_site_sp.get());
1658 }
1659 else
1660 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001661 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001662 }
1663
1664 return error;
1665}
1666
1667Error
1668Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1669{
1670 Error error;
1671 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1672 if (bp_site_sp)
1673 {
1674 if (!bp_site_sp->IsEnabled())
1675 error = EnableBreakpoint (bp_site_sp.get());
1676 }
1677 else
1678 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001679 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001680 }
1681 return error;
1682}
1683
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001684lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001685Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001686{
Greg Clayton265ab332011-05-19 18:17:41 +00001687 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001688 if (load_addr != LLDB_INVALID_ADDRESS)
1689 {
1690 BreakpointSiteSP bp_site_sp;
1691
1692 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1693 // create a new breakpoint site and add it.
1694
1695 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1696
1697 if (bp_site_sp)
1698 {
1699 bp_site_sp->AddOwner (owner);
1700 owner->SetBreakpointSite (bp_site_sp);
1701 return bp_site_sp->GetID();
1702 }
1703 else
1704 {
1705 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1706 if (bp_site_sp)
1707 {
1708 if (EnableBreakpoint (bp_site_sp.get()).Success())
1709 {
1710 owner->SetBreakpointSite (bp_site_sp);
1711 return m_breakpoint_site_list.Add (bp_site_sp);
1712 }
1713 }
1714 }
1715 }
1716 // We failed to enable the breakpoint
1717 return LLDB_INVALID_BREAK_ID;
1718
1719}
1720
1721void
1722Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1723{
1724 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1725 if (num_owners == 0)
1726 {
1727 DisableBreakpoint(bp_site_sp.get());
1728 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1729 }
1730}
1731
1732
1733size_t
1734Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1735{
1736 size_t bytes_removed = 0;
1737 addr_t intersect_addr;
1738 size_t intersect_size;
1739 size_t opcode_offset;
1740 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001741 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001742 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001743
Jim Ingham82820f92011-06-29 19:42:28 +00001744 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001745 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001746 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001747 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001748 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001749 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001750 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001751 {
1752 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1753 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001754 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001755 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001756 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001757 }
Chris Lattner24943d22010-06-08 16:52:24 +00001758 }
1759 }
1760 }
1761 return bytes_removed;
1762}
1763
1764
Greg Claytonb1888f22011-03-19 01:12:21 +00001765
1766size_t
1767Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1768{
1769 PlatformSP platform_sp (m_target.GetPlatform());
1770 if (platform_sp)
1771 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1772 return 0;
1773}
1774
Chris Lattner24943d22010-06-08 16:52:24 +00001775Error
1776Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1777{
1778 Error error;
1779 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001780 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001781 const addr_t bp_addr = bp_site->GetLoadAddress();
1782 if (log)
1783 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1784 if (bp_site->IsEnabled())
1785 {
1786 if (log)
1787 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1788 return error;
1789 }
1790
1791 if (bp_addr == LLDB_INVALID_ADDRESS)
1792 {
1793 error.SetErrorString("BreakpointSite contains an invalid load address.");
1794 return error;
1795 }
1796 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1797 // trap for the breakpoint site
1798 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1799
1800 if (bp_opcode_size == 0)
1801 {
Greg Clayton9c236732011-10-26 00:56:27 +00001802 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001803 }
1804 else
1805 {
1806 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1807
1808 if (bp_opcode_bytes == NULL)
1809 {
1810 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1811 return error;
1812 }
1813
1814 // Save the original opcode by reading it
1815 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1816 {
1817 // Write a software breakpoint in place of the original opcode
1818 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1819 {
1820 uint8_t verify_bp_opcode_bytes[64];
1821 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1822 {
1823 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1824 {
1825 bp_site->SetEnabled(true);
1826 bp_site->SetType (BreakpointSite::eSoftware);
1827 if (log)
1828 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1829 bp_site->GetID(),
1830 (uint64_t)bp_addr);
1831 }
1832 else
Greg Clayton9c236732011-10-26 00:56:27 +00001833 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00001834 }
1835 else
1836 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1837 }
1838 else
1839 error.SetErrorString("Unable to write breakpoint trap to memory.");
1840 }
1841 else
1842 error.SetErrorString("Unable to read memory at breakpoint address.");
1843 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001844 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001845 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1846 bp_site->GetID(),
1847 (uint64_t)bp_addr,
1848 error.AsCString());
1849 return error;
1850}
1851
1852Error
1853Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1854{
1855 Error error;
1856 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001857 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001858 addr_t bp_addr = bp_site->GetLoadAddress();
1859 lldb::user_id_t breakID = bp_site->GetID();
1860 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001861 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001862
1863 if (bp_site->IsHardware())
1864 {
1865 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1866 }
1867 else if (bp_site->IsEnabled())
1868 {
1869 const size_t break_op_size = bp_site->GetByteSize();
1870 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1871 if (break_op_size > 0)
1872 {
1873 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001874 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001875 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001876 bool break_op_found = false;
1877
1878 // Read the breakpoint opcode
1879 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1880 {
1881 bool verify = false;
1882 // Make sure we have the a breakpoint opcode exists at this address
1883 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1884 {
1885 break_op_found = true;
1886 // We found a valid breakpoint opcode at this address, now restore
1887 // the saved opcode.
1888 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1889 {
1890 verify = true;
1891 }
1892 else
1893 error.SetErrorString("Memory write failed when restoring original opcode.");
1894 }
1895 else
1896 {
1897 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1898 // Set verify to true and so we can check if the original opcode has already been restored
1899 verify = true;
1900 }
1901
1902 if (verify)
1903 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001904 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001905 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001906 // Verify that our original opcode made it back to the inferior
1907 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1908 {
1909 // compare the memory we just read with the original opcode
1910 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1911 {
1912 // SUCCESS
1913 bp_site->SetEnabled(false);
1914 if (log)
1915 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1916 return error;
1917 }
1918 else
1919 {
1920 if (break_op_found)
1921 error.SetErrorString("Failed to restore original opcode.");
1922 }
1923 }
1924 else
1925 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1926 }
1927 }
1928 else
1929 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1930 }
1931 }
1932 else
1933 {
1934 if (log)
1935 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1936 return error;
1937 }
1938
1939 if (log)
1940 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1941 bp_site->GetID(),
1942 (uint64_t)bp_addr,
1943 error.AsCString());
1944 return error;
1945
1946}
1947
Sean Callananf90b5f32012-06-07 22:26:42 +00001948// Comment out line below to disable memory caching, overriding the process setting
1949// target.process.disable-memory-cache
Greg Claytonfd119992011-01-07 06:08:19 +00001950#define ENABLE_MEMORY_CACHING
1951// Uncomment to verify memory caching works after making changes to caching code
1952//#define VERIFY_MEMORY_READS
1953
Sean Callananf90b5f32012-06-07 22:26:42 +00001954size_t
1955Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1956{
1957 if (!GetDisableMemoryCache())
1958 {
Greg Claytonfd119992011-01-07 06:08:19 +00001959#if defined (VERIFY_MEMORY_READS)
Sean Callananf90b5f32012-06-07 22:26:42 +00001960 // Memory caching is enabled, with debug verification
1961
1962 if (buf && size)
1963 {
1964 // Uncomment the line below to make sure memory caching is working.
1965 // I ran this through the test suite and got no assertions, so I am
1966 // pretty confident this is working well. If any changes are made to
1967 // memory caching, uncomment the line below and test your changes!
1968
1969 // Verify all memory reads by using the cache first, then redundantly
1970 // reading the same memory from the inferior and comparing to make sure
1971 // everything is exactly the same.
1972 std::string verify_buf (size, '\0');
1973 assert (verify_buf.size() == size);
1974 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1975 Error verify_error;
1976 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1977 assert (cache_bytes_read == verify_bytes_read);
1978 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1979 assert (verify_error.Success() == error.Success());
1980 return cache_bytes_read;
1981 }
1982 return 0;
1983#else // !defined(VERIFY_MEMORY_READS)
1984 // Memory caching is enabled, without debug verification
1985
1986 return m_memory_cache.Read (addr, buf, size, error);
1987#endif // defined (VERIFY_MEMORY_READS)
Greg Claytonfd119992011-01-07 06:08:19 +00001988 }
Sean Callananf90b5f32012-06-07 22:26:42 +00001989 else
1990 {
1991 // Memory caching is disabled
1992
1993 return ReadMemoryFromInferior (addr, buf, size, error);
1994 }
Greg Claytonfd119992011-01-07 06:08:19 +00001995}
Greg Claytonfd119992011-01-07 06:08:19 +00001996
Greg Claytondd29b972012-05-18 23:20:01 +00001997size_t
1998Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
1999{
Greg Claytoneeeb2af2012-05-19 00:18:00 +00002000 char buf[256];
Greg Claytondd29b972012-05-18 23:20:01 +00002001 out_str.clear();
2002 addr_t curr_addr = addr;
2003 while (1)
2004 {
2005 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2006 if (length == 0)
2007 break;
2008 out_str.append(buf, length);
2009 // If we got "length - 1" bytes, we didn't get the whole C string, we
2010 // need to read some more characters
2011 if (length == sizeof(buf) - 1)
2012 curr_addr += length;
2013 else
2014 break;
2015 }
2016 return out_str.size();
2017}
2018
Greg Claytonfd119992011-01-07 06:08:19 +00002019
2020size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00002021Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002022{
2023 size_t total_cstr_len = 0;
2024 if (dst && dst_max_len)
2025 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002026 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002027 // NULL out everything just to be safe
2028 memset (dst, 0, dst_max_len);
2029 Error error;
2030 addr_t curr_addr = addr;
2031 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2032 size_t bytes_left = dst_max_len - 1;
2033 char *curr_dst = dst;
2034
2035 while (bytes_left > 0)
2036 {
2037 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2038 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2039 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2040
2041 if (bytes_read == 0)
2042 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00002043 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002044 dst[total_cstr_len] = '\0';
2045 break;
2046 }
2047 const size_t len = strlen(curr_dst);
2048
2049 total_cstr_len += len;
2050
2051 if (len < bytes_to_read)
2052 break;
2053
2054 curr_dst += bytes_read;
2055 curr_addr += bytes_read;
2056 bytes_left -= bytes_read;
2057 }
2058 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00002059 else
2060 {
2061 if (dst == NULL)
2062 result_error.SetErrorString("invalid arguments");
2063 else
2064 result_error.Clear();
2065 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002066 return total_cstr_len;
2067}
2068
2069size_t
Greg Claytonfd119992011-01-07 06:08:19 +00002070Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2071{
Chris Lattner24943d22010-06-08 16:52:24 +00002072 if (buf == NULL || size == 0)
2073 return 0;
2074
2075 size_t bytes_read = 0;
2076 uint8_t *bytes = (uint8_t *)buf;
2077
2078 while (bytes_read < size)
2079 {
2080 const size_t curr_size = size - bytes_read;
2081 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2082 bytes + bytes_read,
2083 curr_size,
2084 error);
2085 bytes_read += curr_bytes_read;
2086 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2087 break;
2088 }
2089
2090 // Replace any software breakpoint opcodes that fall into this range back
2091 // into "buf" before we return
2092 if (bytes_read > 0)
2093 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2094 return bytes_read;
2095}
2096
Greg Claytonf72fdee2010-12-16 20:01:20 +00002097uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002098Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002099{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002100 Scalar scalar;
2101 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2102 return scalar.ULongLong(fail_value);
2103 return fail_value;
2104}
2105
2106addr_t
2107Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2108{
2109 Scalar scalar;
2110 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2111 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2112 return LLDB_INVALID_ADDRESS;
2113}
2114
2115
2116bool
2117Process::WritePointerToMemory (lldb::addr_t vm_addr,
2118 lldb::addr_t ptr_value,
2119 Error &error)
2120{
2121 Scalar scalar;
2122 const uint32_t addr_byte_size = GetAddressByteSize();
2123 if (addr_byte_size <= 4)
2124 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002125 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002126 scalar = ptr_value;
2127 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002128}
2129
Chris Lattner24943d22010-06-08 16:52:24 +00002130size_t
2131Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2132{
2133 size_t bytes_written = 0;
2134 const uint8_t *bytes = (const uint8_t *)buf;
2135
2136 while (bytes_written < size)
2137 {
2138 const size_t curr_size = size - bytes_written;
2139 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2140 bytes + bytes_written,
2141 curr_size,
2142 error);
2143 bytes_written += curr_bytes_written;
2144 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2145 break;
2146 }
2147 return bytes_written;
2148}
2149
2150size_t
2151Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2152{
Greg Claytonfd119992011-01-07 06:08:19 +00002153#if defined (ENABLE_MEMORY_CACHING)
2154 m_memory_cache.Flush (addr, size);
2155#endif
2156
Chris Lattner24943d22010-06-08 16:52:24 +00002157 if (buf == NULL || size == 0)
2158 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002159
Jim Ingham21f37ad2011-08-09 02:12:22 +00002160 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002161
Chris Lattner24943d22010-06-08 16:52:24 +00002162 // We need to write any data that would go where any current software traps
2163 // (enabled software breakpoints) any software traps (breakpoints) that we
2164 // may have placed in our tasks memory.
2165
2166 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2167 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2168
2169 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002170 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002171
2172 BreakpointSiteList::collection::const_iterator pos;
2173 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002174 addr_t intersect_addr = 0;
2175 size_t intersect_size = 0;
2176 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002177 const uint8_t *ubuf = (const uint8_t *)buf;
2178
2179 for (pos = iter; pos != end; ++pos)
2180 {
2181 BreakpointSiteSP bp;
2182 bp = pos->second;
2183
2184 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2185 assert(addr <= intersect_addr && intersect_addr < addr + size);
2186 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2187 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2188
2189 // Check for bytes before this breakpoint
2190 const addr_t curr_addr = addr + bytes_written;
2191 if (intersect_addr > curr_addr)
2192 {
2193 // There are some bytes before this breakpoint that we need to
2194 // just write to memory
2195 size_t curr_size = intersect_addr - curr_addr;
2196 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2197 ubuf + bytes_written,
2198 curr_size,
2199 error);
2200 bytes_written += curr_bytes_written;
2201 if (curr_bytes_written != curr_size)
2202 {
2203 // We weren't able to write all of the requested bytes, we
2204 // are done looping and will return the number of bytes that
2205 // we have written so far.
2206 break;
2207 }
2208 }
2209
2210 // Now write any bytes that would cover up any software breakpoints
2211 // directly into the breakpoint opcode buffer
2212 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2213 bytes_written += intersect_size;
2214 }
2215
2216 // Write any remaining bytes after the last breakpoint if we have any left
2217 if (bytes_written < size)
2218 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2219 ubuf + bytes_written,
2220 size - bytes_written,
2221 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002222
Chris Lattner24943d22010-06-08 16:52:24 +00002223 return bytes_written;
2224}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002225
2226size_t
2227Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2228{
2229 if (byte_size == UINT32_MAX)
2230 byte_size = scalar.GetByteSize();
2231 if (byte_size > 0)
2232 {
2233 uint8_t buf[32];
2234 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2235 if (mem_size > 0)
2236 return WriteMemory(addr, buf, mem_size, error);
2237 else
2238 error.SetErrorString ("failed to get scalar as memory data");
2239 }
2240 else
2241 {
2242 error.SetErrorString ("invalid scalar value");
2243 }
2244 return 0;
2245}
2246
2247size_t
2248Process::ReadScalarIntegerFromMemory (addr_t addr,
2249 uint32_t byte_size,
2250 bool is_signed,
2251 Scalar &scalar,
2252 Error &error)
2253{
2254 uint64_t uval;
2255
2256 if (byte_size <= sizeof(uval))
2257 {
2258 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2259 if (bytes_read == byte_size)
2260 {
2261 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2262 uint32_t offset = 0;
2263 if (byte_size <= 4)
2264 scalar = data.GetMaxU32 (&offset, byte_size);
2265 else
2266 scalar = data.GetMaxU64 (&offset, byte_size);
2267
2268 if (is_signed)
2269 scalar.SignExtend(byte_size * 8);
2270 return bytes_read;
2271 }
2272 }
2273 else
2274 {
2275 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2276 }
2277 return 0;
2278}
2279
Greg Clayton613b8732011-05-17 03:37:42 +00002280#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002281addr_t
2282Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2283{
Jim Inghame6bd1422011-06-20 17:32:44 +00002284 if (GetPrivateState() != eStateStopped)
2285 return LLDB_INVALID_ADDRESS;
2286
Greg Clayton613b8732011-05-17 03:37:42 +00002287#if defined (USE_ALLOCATE_MEMORY_CACHE)
2288 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2289#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002290 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2291 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2292 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002293 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 +00002294 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002295 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002296 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002297 m_mod_id.GetStopID(),
2298 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002299 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002300#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002301}
2302
Sean Callanan6cf6c472011-09-20 23:01:51 +00002303bool
2304Process::CanJIT ()
2305{
Sean Callanan04200f62012-02-14 22:50:38 +00002306 if (m_can_jit == eCanJITDontKnow)
2307 {
2308 Error err;
2309
2310 uint64_t allocated_memory = AllocateMemory(8,
2311 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2312 err);
2313
2314 if (err.Success())
2315 m_can_jit = eCanJITYes;
2316 else
2317 m_can_jit = eCanJITNo;
2318
2319 DeallocateMemory (allocated_memory);
2320 }
2321
Sean Callanan6cf6c472011-09-20 23:01:51 +00002322 return m_can_jit == eCanJITYes;
2323}
2324
2325void
2326Process::SetCanJIT (bool can_jit)
2327{
2328 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2329}
2330
Chris Lattner24943d22010-06-08 16:52:24 +00002331Error
2332Process::DeallocateMemory (addr_t ptr)
2333{
Greg Clayton613b8732011-05-17 03:37:42 +00002334 Error error;
2335#if defined (USE_ALLOCATE_MEMORY_CACHE)
2336 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2337 {
2338 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2339 }
2340#else
2341 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002342
2343 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2344 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002345 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 +00002346 ptr,
2347 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002348 m_mod_id.GetStopID(),
2349 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002350#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002351 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002352}
2353
Greg Claytonb5a8f142012-02-05 02:38:54 +00002354ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002355Process::ReadModuleFromMemory (const FileSpec& file_spec,
2356 lldb::addr_t header_addr,
2357 bool add_image_to_target,
2358 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002359{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002360 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002361 if (module_sp)
2362 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002363 Error error;
2364 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2365 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002366 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002367 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002368 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002369 m_target.GetImages().Append(module_sp);
2370 if (load_sections_in_target)
2371 {
2372 bool changed = false;
2373 module_sp->SetLoadAddress (m_target, 0, changed);
2374 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002375 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002376 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002377 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002378 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002379 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002380}
Chris Lattner24943d22010-06-08 16:52:24 +00002381
2382Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002383Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002384{
2385 Error error;
2386 error.SetErrorString("watchpoints are not supported");
2387 return error;
2388}
2389
2390Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002391Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002392{
2393 Error error;
2394 error.SetErrorString("watchpoints are not supported");
2395 return error;
2396}
2397
2398StateType
2399Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2400{
2401 StateType state;
2402 // Now wait for the process to launch and return control to us, and then
2403 // call DidLaunch:
2404 while (1)
2405 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002406 event_sp.reset();
2407 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2408
Greg Clayton20206082011-11-17 01:23:07 +00002409 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002410 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002411
2412 // If state is invalid, then we timed out
2413 if (state == eStateInvalid)
2414 break;
2415
2416 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002417 HandlePrivateEvent (event_sp);
2418 }
2419 return state;
2420}
2421
2422Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002423Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002424{
2425 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002426 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002427 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002428 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002429 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002430
Greg Clayton5beb99d2011-08-11 02:48:45 +00002431 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002432 if (exe_module)
2433 {
Greg Clayton180546b2011-04-30 01:09:13 +00002434 char local_exec_file_path[PATH_MAX];
2435 char platform_exec_file_path[PATH_MAX];
2436 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2437 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002438 if (exe_module->GetFileSpec().Exists())
2439 {
Greg Claytona2f74232011-02-24 22:24:29 +00002440 if (PrivateStateThreadIsValid ())
2441 PausePrivateStateThread ();
2442
Chris Lattner24943d22010-06-08 16:52:24 +00002443 error = WillLaunch (exe_module);
2444 if (error.Success())
2445 {
Greg Claytond8c62532010-10-07 04:19:01 +00002446 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002447 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002448
2449 // Now launch using these arguments.
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002450 error = DoLaunch (exe_module, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +00002451
2452 if (error.Fail())
2453 {
2454 if (GetID() != LLDB_INVALID_PROCESS_ID)
2455 {
2456 SetID (LLDB_INVALID_PROCESS_ID);
2457 const char *error_string = error.AsCString();
2458 if (error_string == NULL)
2459 error_string = "launch failed";
2460 SetExitStatus (-1, error_string);
2461 }
2462 }
2463 else
2464 {
2465 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002466 TimeValue timeout_time;
2467 timeout_time = TimeValue::Now();
2468 timeout_time.OffsetWithSeconds(10);
2469 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002470
Greg Clayton49859592011-06-22 01:42:17 +00002471 if (state == eStateInvalid || event_sp.get() == NULL)
2472 {
2473 // We were able to launch the process, but we failed to
2474 // catch the initial stop.
2475 SetExitStatus (0, "failed to catch stop after launch");
2476 Destroy();
2477 }
2478 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002479 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002480
Chris Lattner24943d22010-06-08 16:52:24 +00002481 DidLaunch ();
2482
Greg Clayton9ce95382012-02-13 23:10:39 +00002483 DynamicLoader *dyld = GetDynamicLoader ();
2484 if (dyld)
2485 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002486
Greg Clayton37f962e2011-08-22 02:49:39 +00002487 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002488 // This delays passing the stopped event to listeners till DidLaunch gets
2489 // a chance to complete...
2490 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002491
2492 if (PrivateStateThreadIsValid ())
2493 ResumePrivateStateThread ();
2494 else
2495 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002496 }
2497 else if (state == eStateExited)
2498 {
2499 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2500 // not likely to work, and return an invalid pid.
2501 HandlePrivateEvent (event_sp);
2502 }
2503 }
2504 }
2505 }
2506 else
2507 {
Greg Clayton9c236732011-10-26 00:56:27 +00002508 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002509 }
2510 }
2511 return error;
2512}
2513
Greg Clayton46c9a352012-02-09 06:16:32 +00002514
2515Error
2516Process::LoadCore ()
2517{
2518 Error error = DoLoadCore();
2519 if (error.Success())
2520 {
2521 if (PrivateStateThreadIsValid ())
2522 ResumePrivateStateThread ();
2523 else
2524 StartPrivateStateThread ();
2525
Greg Clayton9ce95382012-02-13 23:10:39 +00002526 DynamicLoader *dyld = GetDynamicLoader ();
2527 if (dyld)
2528 dyld->DidAttach();
2529
2530 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002531 // We successfully loaded a core file, now pretend we stopped so we can
2532 // show all of the threads in the core file and explore the crashed
2533 // state.
2534 SetPrivateState (eStateStopped);
2535
2536 }
2537 return error;
2538}
2539
Greg Clayton9ce95382012-02-13 23:10:39 +00002540DynamicLoader *
2541Process::GetDynamicLoader ()
2542{
2543 if (m_dyld_ap.get() == NULL)
2544 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2545 return m_dyld_ap.get();
2546}
Greg Clayton46c9a352012-02-09 06:16:32 +00002547
2548
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002549Process::NextEventAction::EventActionResult
2550Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002551{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002552 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2553 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002554 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002555 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002556 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002557 return eEventActionRetry;
2558
2559 case eStateStopped:
2560 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002561 {
2562 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002563 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002564 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2565 if (m_exec_count > 0)
2566 {
2567 --m_exec_count;
Jim Ingham027aaa72012-04-19 01:40:33 +00002568 m_process->PrivateResume ();
Jim Inghamf4928de2012-05-23 15:46:31 +00002569 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Clayton2d9adb72011-11-12 02:10:56 +00002570 return eEventActionRetry;
2571 }
2572 else
2573 {
2574 m_process->CompleteAttach ();
2575 return eEventActionSuccess;
2576 }
2577 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002578 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002579
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002580 default:
2581 case eStateExited:
2582 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002583 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002584 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002585
2586 m_exit_string.assign ("No valid Process");
2587 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002588}
Chris Lattner24943d22010-06-08 16:52:24 +00002589
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002590Process::NextEventAction::EventActionResult
2591Process::AttachCompletionHandler::HandleBeingInterrupted()
2592{
2593 return eEventActionSuccess;
2594}
2595
2596const char *
2597Process::AttachCompletionHandler::GetExitString ()
2598{
2599 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002600}
2601
2602Error
Greg Clayton527154d2011-11-15 03:53:30 +00002603Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002604{
Chris Lattner24943d22010-06-08 16:52:24 +00002605 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002606 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002607 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002608 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002609
Greg Clayton527154d2011-11-15 03:53:30 +00002610 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002611 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002612 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002613 {
Greg Clayton527154d2011-11-15 03:53:30 +00002614 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002615
Greg Clayton527154d2011-11-15 03:53:30 +00002616 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002617 {
Greg Clayton527154d2011-11-15 03:53:30 +00002618 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2619
2620 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002621 {
Greg Clayton527154d2011-11-15 03:53:30 +00002622 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2623 if (error.Success())
2624 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002625 m_should_detach = true;
2626
Greg Clayton527154d2011-11-15 03:53:30 +00002627 SetPublicState (eStateAttaching);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002628 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
Greg Clayton527154d2011-11-15 03:53:30 +00002629 if (error.Fail())
2630 {
2631 if (GetID() != LLDB_INVALID_PROCESS_ID)
2632 {
2633 SetID (LLDB_INVALID_PROCESS_ID);
2634 if (error.AsCString() == NULL)
2635 error.SetErrorString("attach failed");
2636
2637 SetExitStatus(-1, error.AsCString());
2638 }
2639 }
2640 else
2641 {
2642 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2643 StartPrivateStateThread();
2644 }
2645 return error;
2646 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002647 }
Greg Clayton527154d2011-11-15 03:53:30 +00002648 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002649 {
Greg Clayton527154d2011-11-15 03:53:30 +00002650 ProcessInstanceInfoList process_infos;
2651 PlatformSP platform_sp (m_target.GetPlatform ());
2652
2653 if (platform_sp)
2654 {
2655 ProcessInstanceInfoMatch match_info;
2656 match_info.GetProcessInfo() = attach_info;
2657 match_info.SetNameMatchType (eNameMatchEquals);
2658 platform_sp->FindProcesses (match_info, process_infos);
2659 const uint32_t num_matches = process_infos.GetSize();
2660 if (num_matches == 1)
2661 {
2662 attach_pid = process_infos.GetProcessIDAtIndex(0);
2663 // Fall through and attach using the above process ID
2664 }
2665 else
2666 {
2667 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2668 if (num_matches > 1)
2669 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2670 else
2671 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2672 }
2673 }
2674 else
2675 {
2676 error.SetErrorString ("invalid platform, can't find processes by name");
2677 return error;
2678 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002679 }
Chris Lattner24943d22010-06-08 16:52:24 +00002680 }
2681 else
Greg Clayton527154d2011-11-15 03:53:30 +00002682 {
2683 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002684 }
2685 }
Greg Clayton527154d2011-11-15 03:53:30 +00002686
2687 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002688 {
Greg Clayton527154d2011-11-15 03:53:30 +00002689 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002690 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002691 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002692 m_should_detach = true;
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002693 SetPublicState (eStateAttaching);
Greg Clayton527154d2011-11-15 03:53:30 +00002694
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002695 error = DoAttachToProcessWithID (attach_pid, attach_info);
Greg Clayton527154d2011-11-15 03:53:30 +00002696 if (error.Success())
2697 {
2698
2699 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2700 StartPrivateStateThread();
2701 }
2702 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002703 {
2704 if (GetID() != LLDB_INVALID_PROCESS_ID)
2705 {
2706 SetID (LLDB_INVALID_PROCESS_ID);
2707 const char *error_string = error.AsCString();
2708 if (error_string == NULL)
2709 error_string = "attach failed";
2710
2711 SetExitStatus(-1, error_string);
2712 }
2713 }
Chris Lattner24943d22010-06-08 16:52:24 +00002714 }
2715 }
2716 return error;
2717}
2718
Greg Clayton75c703d2011-02-16 04:46:07 +00002719void
2720Process::CompleteAttach ()
2721{
2722 // Let the process subclass figure out at much as it can about the process
2723 // before we go looking for a dynamic loader plug-in.
2724 DidAttach();
2725
Jim Ingham0d7f7772011-09-15 01:10:17 +00002726 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2727 // the same as the one we've already set, switch architectures.
2728 PlatformSP platform_sp (m_target.GetPlatform ());
2729 assert (platform_sp.get());
2730 if (platform_sp)
2731 {
Greg Claytonb170aee2012-05-08 01:45:38 +00002732 const ArchSpec &target_arch = m_target.GetArchitecture();
2733 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2734 {
2735 ArchSpec platform_arch;
2736 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2737 if (platform_sp)
2738 {
2739 m_target.SetPlatform (platform_sp);
2740 m_target.SetArchitecture(platform_arch);
2741 }
2742 }
2743 else
2744 {
2745 ProcessInstanceInfo process_info;
2746 platform_sp->GetProcessInfo (GetID(), process_info);
2747 const ArchSpec &process_arch = process_info.GetArchitecture();
2748 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2749 m_target.SetArchitecture (process_arch);
2750 }
Jim Ingham0d7f7772011-09-15 01:10:17 +00002751 }
2752
2753 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002754 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00002755 DynamicLoader *dyld = GetDynamicLoader ();
2756 if (dyld)
2757 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00002758
Greg Clayton37f962e2011-08-22 02:49:39 +00002759 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002760 // Figure out which one is the executable, and set that in our target:
Jim Ingham93367902012-05-30 02:19:25 +00002761 ModuleList &target_modules = m_target.GetImages();
2762 Mutex::Locker modules_locker(target_modules.GetMutex());
2763 size_t num_modules = target_modules.GetSize();
2764 ModuleSP new_executable_module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00002765
Greg Clayton75c703d2011-02-16 04:46:07 +00002766 for (int i = 0; i < num_modules; i++)
2767 {
Jim Ingham93367902012-05-30 02:19:25 +00002768 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002769 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002770 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002771 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham93367902012-05-30 02:19:25 +00002772 new_executable_module_sp = module_sp;
Greg Clayton75c703d2011-02-16 04:46:07 +00002773 break;
2774 }
2775 }
Jim Ingham93367902012-05-30 02:19:25 +00002776 if (new_executable_module_sp)
2777 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton75c703d2011-02-16 04:46:07 +00002778}
2779
Chris Lattner24943d22010-06-08 16:52:24 +00002780Error
Greg Claytone71e2582011-02-04 01:58:07 +00002781Process::ConnectRemote (const char *remote_url)
2782{
Greg Claytone71e2582011-02-04 01:58:07 +00002783 m_abi_sp.reset();
2784 m_process_input_reader.reset();
2785
2786 // Find the process and its architecture. Make sure it matches the architecture
2787 // of the current Target, and if not adjust it.
2788
2789 Error error (DoConnectRemote (remote_url));
2790 if (error.Success())
2791 {
Greg Claytona2f74232011-02-24 22:24:29 +00002792 if (GetID() != LLDB_INVALID_PROCESS_ID)
2793 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002794 EventSP event_sp;
2795 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2796
2797 if (state == eStateStopped || state == eStateCrashed)
2798 {
2799 // If we attached and actually have a process on the other end, then
2800 // this ended up being the equivalent of an attach.
2801 CompleteAttach ();
2802
2803 // This delays passing the stopped event to listeners till
2804 // CompleteAttach gets a chance to complete...
2805 HandlePrivateEvent (event_sp);
2806
2807 }
Greg Claytona2f74232011-02-24 22:24:29 +00002808 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002809
2810 if (PrivateStateThreadIsValid ())
2811 ResumePrivateStateThread ();
2812 else
2813 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002814 }
2815 return error;
2816}
2817
2818
2819Error
Jim Ingham027aaa72012-04-19 01:40:33 +00002820Process::PrivateResume ()
Chris Lattner24943d22010-06-08 16:52:24 +00002821{
Greg Claytone005f2c2010-11-06 01:53:30 +00002822 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002823 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002824 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002825 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002826 StateAsCString(m_public_state.GetValue()),
2827 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002828
2829 Error error (WillResume());
2830 // Tell the process it is about to resume before the thread list
2831 if (error.Success())
2832 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002833 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002834 // can let all of our threads know that they are about to be
2835 // resumed. Threads will each be called with
2836 // Thread::WillResume(StateType) where StateType contains the state
2837 // that they are supposed to have when the process is resumed
2838 // (suspended/running/stepping). Threads should also check
2839 // their resume signal in lldb::Thread::GetResumeSignal()
2840 // to see if they are suppoed to start back up with a signal.
2841 if (m_thread_list.WillResume())
2842 {
Jim Ingham1831e782012-04-07 00:00:41 +00002843 // Last thing, do the PreResumeActions.
2844 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00002845 {
Jim Ingham1831e782012-04-07 00:00:41 +00002846 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
2847 }
2848 else
2849 {
2850 m_mod_id.BumpResumeID();
2851 error = DoResume();
2852 if (error.Success())
2853 {
2854 DidResume();
2855 m_thread_list.DidResume();
2856 if (log)
2857 log->Printf ("Process thinks the process has resumed.");
2858 }
Chris Lattner24943d22010-06-08 16:52:24 +00002859 }
2860 }
2861 else
2862 {
Jim Inghamac959662011-01-24 06:34:17 +00002863 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002864 }
2865 }
Jim Inghamac959662011-01-24 06:34:17 +00002866 else if (log)
2867 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002868 return error;
2869}
2870
2871Error
2872Process::Halt ()
2873{
Jim Ingham43892562012-06-06 00:29:30 +00002874 // First make sure we aren't in the middle of handling an event, or we might restart. This is pretty weak, since
2875 // we could just straightaway get another event. It just narrows the window...
2876 m_currently_handling_event.WaitForValueEqualTo(false);
2877
2878
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002879 // Pause our private state thread so we can ensure no one else eats
2880 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002881 Listener halt_listener ("lldb.process.halt_listener");
2882 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002883
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002884 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002885 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002886
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002887 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002888 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002889
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002890 bool caused_stop = false;
2891
2892 // Ask the process subclass to actually halt our process
2893 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002894 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002895 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002896 if (m_public_state.GetValue() == eStateAttaching)
2897 {
2898 SetExitStatus(SIGKILL, "Cancelled async attach.");
2899 Destroy ();
2900 }
2901 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002902 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002903 // If "caused_stop" is true, then DoHalt stopped the process. If
2904 // "caused_stop" is false, the process was already stopped.
2905 // If the DoHalt caused the process to stop, then we want to catch
2906 // this event and set the interrupted bool to true before we pass
2907 // this along so clients know that the process was interrupted by
2908 // a halt command.
2909 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002910 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002911 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002912 TimeValue timeout_time;
2913 timeout_time = TimeValue::Now();
2914 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002915 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2916 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002917
Jim Inghamf9f40c22011-02-08 05:20:59 +00002918 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002919 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002920 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002921 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002922 }
2923 else
2924 {
Greg Clayton20206082011-11-17 01:23:07 +00002925 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002926 {
2927 // We caused the process to interrupt itself, so mark this
2928 // as such in the stop event so clients can tell an interrupted
2929 // process from a natural stop
2930 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2931 }
2932 else
2933 {
2934 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2935 if (log)
2936 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2937 error.SetErrorString ("Did not get stopped event after halt.");
2938 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002939 }
2940 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002941 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002942 }
2943 }
Chris Lattner24943d22010-06-08 16:52:24 +00002944 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002945 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002946 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002947
2948 // Post any event we might have consumed. If all goes well, we will have
2949 // stopped the process, intercepted the event and set the interrupted
2950 // bool in the event. Post it to the private event queue and that will end up
2951 // correctly setting the state.
2952 if (event_sp)
2953 m_private_state_broadcaster.BroadcastEvent(event_sp);
2954
Chris Lattner24943d22010-06-08 16:52:24 +00002955 return error;
2956}
2957
2958Error
2959Process::Detach ()
2960{
2961 Error error (WillDetach());
2962
2963 if (error.Success())
2964 {
2965 DisableAllBreakpointSites();
2966 error = DoDetach();
2967 if (error.Success())
2968 {
2969 DidDetach();
2970 StopPrivateStateThread();
2971 }
2972 }
2973 return error;
2974}
2975
2976Error
2977Process::Destroy ()
2978{
2979 Error error (WillDestroy());
2980 if (error.Success())
2981 {
Jim Inghamf4928de2012-05-23 15:46:31 +00002982 if (m_public_state.GetValue() == eStateRunning)
2983 {
Jim Ingham43892562012-06-06 00:29:30 +00002984 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TEMPORARY));
2985 if (log)
2986 log->Printf("Process::Destroy() About to halt.");
Jim Inghamf4928de2012-05-23 15:46:31 +00002987 error = Halt();
2988 if (error.Success())
2989 {
2990 // Consume the halt event.
2991 EventSP stop_event;
2992 TimeValue timeout (TimeValue::Now());
Jim Ingham43892562012-06-06 00:29:30 +00002993 timeout.OffsetWithSeconds(1);
Jim Inghamf4928de2012-05-23 15:46:31 +00002994 StateType state = WaitForProcessToStop (&timeout);
2995 if (state != eStateStopped)
2996 {
Jim Ingham43892562012-06-06 00:29:30 +00002997 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TEMPORARY));
Jim Inghamf4928de2012-05-23 15:46:31 +00002998 if (log)
2999 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
Jim Ingham43892562012-06-06 00:29:30 +00003000 // If we really couldn't stop the process then we should just error out here, but if the
3001 // lower levels just bobbled sending the event and we really are stopped, then continue on.
3002 StateType private_state = m_private_state.GetValue();
3003 if (private_state != eStateStopped && private_state != eStateExited)
3004 {
3005 return error;
3006 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003007 }
3008 }
3009 else
3010 {
Jim Ingham43892562012-06-06 00:29:30 +00003011 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TEMPORARY));
Jim Inghamf4928de2012-05-23 15:46:31 +00003012 if (log)
3013 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
Jim Ingham43892562012-06-06 00:29:30 +00003014 return error;
Jim Inghamf4928de2012-05-23 15:46:31 +00003015 }
3016 }
Jim Ingham43892562012-06-06 00:29:30 +00003017
3018 if (m_public_state.GetValue() != eStateRunning)
3019 {
3020 // Ditch all thread plans, and remove all our breakpoints: in case we have to restart the target to
3021 // kill it, we don't want it hitting a breakpoint...
3022 // Only do this if we've stopped, however, since if we didn't manage to halt it above, then
3023 // we're not going to have much luck doing this now.
3024 m_thread_list.DiscardThreadPlans();
3025 DisableAllBreakpointSites();
3026 }
Jim Inghamf4928de2012-05-23 15:46:31 +00003027
Chris Lattner24943d22010-06-08 16:52:24 +00003028 error = DoDestroy();
3029 if (error.Success())
3030 {
3031 DidDestroy();
3032 StopPrivateStateThread();
3033 }
Caroline Tice861efb32010-11-16 05:07:41 +00003034 m_stdio_communication.StopReadThread();
3035 m_stdio_communication.Disconnect();
3036 if (m_process_input_reader && m_process_input_reader->IsActive())
3037 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3038 if (m_process_input_reader)
3039 m_process_input_reader.reset();
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003040
3041 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3042 // the last events through the event system, in which case we might strand the write lock. Unlock
3043 // it here so when we do to tear down the process we don't get an error destroying the lock.
3044 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00003045 }
3046 return error;
3047}
3048
3049Error
3050Process::Signal (int signal)
3051{
3052 Error error (WillSignal());
3053 if (error.Success())
3054 {
3055 error = DoSignal(signal);
3056 if (error.Success())
3057 DidSignal();
3058 }
3059 return error;
3060}
3061
Greg Clayton395fc332011-02-15 21:59:32 +00003062lldb::ByteOrder
3063Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00003064{
Greg Clayton395fc332011-02-15 21:59:32 +00003065 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00003066}
3067
3068uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00003069Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00003070{
Greg Clayton395fc332011-02-15 21:59:32 +00003071 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00003072}
3073
Greg Clayton395fc332011-02-15 21:59:32 +00003074
Chris Lattner24943d22010-06-08 16:52:24 +00003075bool
3076Process::ShouldBroadcastEvent (Event *event_ptr)
3077{
3078 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3079 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00003080 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003081
3082 switch (state)
3083 {
Greg Claytone71e2582011-02-04 01:58:07 +00003084 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00003085 case eStateAttaching:
3086 case eStateLaunching:
3087 case eStateDetached:
3088 case eStateExited:
3089 case eStateUnloaded:
3090 // These events indicate changes in the state of the debugging session, always report them.
3091 return_value = true;
3092 break;
3093 case eStateInvalid:
3094 // We stopped for no apparent reason, don't report it.
3095 return_value = false;
3096 break;
3097 case eStateRunning:
3098 case eStateStepping:
3099 // If we've started the target running, we handle the cases where we
3100 // are already running and where there is a transition from stopped to
3101 // running differently.
3102 // running -> running: Automatically suppress extra running events
3103 // stopped -> running: Report except when there is one or more no votes
3104 // and no yes votes.
3105 SynchronouslyNotifyStateChanged (state);
3106 switch (m_public_state.GetValue())
3107 {
3108 case eStateRunning:
3109 case eStateStepping:
3110 // We always suppress multiple runnings with no PUBLIC stop in between.
3111 return_value = false;
3112 break;
3113 default:
3114 // TODO: make this work correctly. For now always report
3115 // run if we aren't running so we don't miss any runnning
3116 // events. If I run the lldb/test/thread/a.out file and
3117 // break at main.cpp:58, run and hit the breakpoints on
3118 // multiple threads, then somehow during the stepping over
3119 // of all breakpoints no run gets reported.
Chris Lattner24943d22010-06-08 16:52:24 +00003120
3121 // This is a transition from stop to run.
3122 switch (m_thread_list.ShouldReportRun (event_ptr))
3123 {
Greg Clayton4a379b12012-07-17 03:23:13 +00003124 default:
Chris Lattner24943d22010-06-08 16:52:24 +00003125 case eVoteYes:
3126 case eVoteNoOpinion:
3127 return_value = true;
3128 break;
3129 case eVoteNo:
3130 return_value = false;
3131 break;
3132 }
3133 break;
3134 }
3135 break;
3136 case eStateStopped:
3137 case eStateCrashed:
3138 case eStateSuspended:
3139 {
3140 // We've stopped. First see if we're going to restart the target.
3141 // If we are going to stop, then we always broadcast the event.
3142 // 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 +00003143 // If no thread has an opinion, we don't report it.
Jim Inghamf63f2ba2012-05-16 01:32:14 +00003144
3145 RefreshStateAfterStop ();
Jim Ingham3ae449a2010-11-17 02:32:00 +00003146 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003147 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003148 if (log)
3149 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003150 return true;
3151 }
3152 else
3153 {
Chris Lattner24943d22010-06-08 16:52:24 +00003154
3155 if (m_thread_list.ShouldStop (event_ptr) == false)
3156 {
3157 switch (m_thread_list.ShouldReportStop (event_ptr))
3158 {
3159 case eVoteYes:
3160 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003161 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003162 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003163 case eVoteNo:
3164 return_value = false;
3165 break;
3166 }
3167
3168 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003169 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham027aaa72012-04-19 01:40:33 +00003170 PrivateResume ();
Chris Lattner24943d22010-06-08 16:52:24 +00003171 }
3172 else
3173 {
3174 return_value = true;
3175 SynchronouslyNotifyStateChanged (state);
3176 }
3177 }
3178 }
3179 }
3180
3181 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003182 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003183 return return_value;
3184}
3185
Chris Lattner24943d22010-06-08 16:52:24 +00003186
3187bool
Jim Ingham1831e782012-04-07 00:00:41 +00003188Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003189{
Greg Claytone005f2c2010-11-06 01:53:30 +00003190 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003191
Greg Claytonb72d0f02011-04-12 05:54:46 +00003192 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003193 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003194 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3195
Jim Ingham1831e782012-04-07 00:00:41 +00003196 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003197 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003198
3199 // Create a thread that watches our internal state and controls which
3200 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003201 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003202 if (already_running)
3203 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3204 else
3205 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003206
3207 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003208 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003209 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3210 if (success)
3211 {
3212 ResumePrivateStateThread();
3213 return true;
3214 }
3215 else
3216 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003217}
3218
3219void
3220Process::PausePrivateStateThread ()
3221{
3222 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3223}
3224
3225void
3226Process::ResumePrivateStateThread ()
3227{
3228 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3229}
3230
3231void
3232Process::StopPrivateStateThread ()
3233{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003234 if (PrivateStateThreadIsValid ())
3235 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003236 else
3237 {
3238 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3239 if (log)
3240 printf ("Went to stop the private state thread, but it was already invalid.");
3241 }
Chris Lattner24943d22010-06-08 16:52:24 +00003242}
3243
3244void
3245Process::ControlPrivateStateThread (uint32_t signal)
3246{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003247 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003248
3249 assert (signal == eBroadcastInternalStateControlStop ||
3250 signal == eBroadcastInternalStateControlPause ||
3251 signal == eBroadcastInternalStateControlResume);
3252
3253 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003254 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003255
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003256 // Signal the private state thread. First we should copy this is case the
3257 // thread starts exiting since the private state thread will NULL this out
3258 // when it exits
3259 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003260 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003261 {
3262 TimeValue timeout_time;
3263 bool timed_out;
3264
3265 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3266
3267 timeout_time = TimeValue::Now();
3268 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003269 if (log)
3270 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003271 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3272 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3273
3274 if (signal == eBroadcastInternalStateControlStop)
3275 {
3276 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003277 {
3278 Error error;
3279 Host::ThreadCancel (private_state_thread, &error);
3280 if (log)
3281 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3282 }
3283 else
3284 {
3285 if (log)
3286 log->Printf ("The control event killed the private state thread without having to cancel.");
3287 }
Chris Lattner24943d22010-06-08 16:52:24 +00003288
3289 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003290 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003291 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003292 }
3293 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003294 else
3295 {
3296 if (log)
3297 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3298 }
Chris Lattner24943d22010-06-08 16:52:24 +00003299}
3300
3301void
Jim Ingham5d90ade2012-07-27 23:57:19 +00003302Process::SendAsyncInterrupt ()
3303{
3304 if (PrivateStateThreadIsValid())
3305 m_private_state_broadcaster.BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3306 else
3307 BroadcastEvent (Process::eBroadcastBitInterrupt, NULL);
3308}
3309
3310void
Chris Lattner24943d22010-06-08 16:52:24 +00003311Process::HandlePrivateEvent (EventSP &event_sp)
3312{
Greg Claytone005f2c2010-11-06 01:53:30 +00003313 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Ingham43892562012-06-06 00:29:30 +00003314 m_currently_handling_event.SetValue(true, eBroadcastNever);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003315
Greg Clayton68ca8232011-01-25 02:58:48 +00003316 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003317
3318 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003319 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003320 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003321 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003322 switch (action_result)
3323 {
3324 case NextEventAction::eEventActionSuccess:
3325 SetNextEventAction(NULL);
3326 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003327
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003328 case NextEventAction::eEventActionRetry:
3329 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003330
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003331 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003332 // Handle Exiting Here. If we already got an exited event,
3333 // we should just propagate it. Otherwise, swallow this event,
3334 // and set our state to exit so the next event will kill us.
3335 if (new_state != eStateExited)
3336 {
3337 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003338 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003339 SetNextEventAction(NULL);
3340 return;
3341 }
3342 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003343 break;
3344 }
3345 }
3346
Chris Lattner24943d22010-06-08 16:52:24 +00003347 // See if we should broadcast this state to external clients?
3348 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003349
3350 if (should_broadcast)
3351 {
3352 if (log)
3353 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003354 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003355 __FUNCTION__,
3356 GetID(),
3357 StateAsCString(new_state),
3358 StateAsCString (GetState ()),
3359 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003360 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003361 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003362 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003363 PushProcessInputReader ();
3364 else
3365 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003366
Chris Lattner24943d22010-06-08 16:52:24 +00003367 BroadcastEvent (event_sp);
3368 }
3369 else
3370 {
3371 if (log)
3372 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003373 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003374 __FUNCTION__,
3375 GetID(),
3376 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003377 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003378 }
3379 }
Jim Ingham43892562012-06-06 00:29:30 +00003380 m_currently_handling_event.SetValue(false, eBroadcastAlways);
Chris Lattner24943d22010-06-08 16:52:24 +00003381}
3382
3383void *
3384Process::PrivateStateThread (void *arg)
3385{
3386 Process *proc = static_cast<Process*> (arg);
3387 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003388 return result;
3389}
3390
3391void *
3392Process::RunPrivateStateThread ()
3393{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003394 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003395 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003396
Greg Claytone005f2c2010-11-06 01:53:30 +00003397 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003398 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003399 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003400
3401 bool exit_now = false;
3402 while (!exit_now)
3403 {
3404 EventSP event_sp;
3405 WaitForEventsPrivate (NULL, event_sp, control_only);
3406 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3407 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003408 if (log)
3409 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3410
Chris Lattner24943d22010-06-08 16:52:24 +00003411 switch (event_sp->GetType())
3412 {
3413 case eBroadcastInternalStateControlStop:
3414 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003415 break; // doing any internal state managment below
3416
3417 case eBroadcastInternalStateControlPause:
3418 control_only = true;
3419 break;
3420
3421 case eBroadcastInternalStateControlResume:
3422 control_only = false;
3423 break;
3424 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003425
Chris Lattner24943d22010-06-08 16:52:24 +00003426 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003427 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003428 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00003429 else if (event_sp->GetType() == eBroadcastBitInterrupt)
3430 {
3431 if (m_public_state.GetValue() == eStateAttaching)
3432 {
3433 if (log)
3434 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt while attaching - forwarding interrupt.", __FUNCTION__, this, GetID());
3435 BroadcastEvent (eBroadcastBitInterrupt, NULL);
3436 }
3437 else
3438 {
3439 if (log)
3440 log->Printf ("Process::%s (arg = %p, pid = %llu) woke up with an interrupt - Halting.", __FUNCTION__, this, GetID());
3441 Halt();
3442 }
3443 continue;
3444 }
Chris Lattner24943d22010-06-08 16:52:24 +00003445
3446 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3447
3448 if (internal_state != eStateInvalid)
3449 {
3450 HandlePrivateEvent (event_sp);
3451 }
3452
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003453 if (internal_state == eStateInvalid ||
3454 internal_state == eStateExited ||
3455 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003456 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003457 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003458 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 +00003459
Chris Lattner24943d22010-06-08 16:52:24 +00003460 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003461 }
Chris Lattner24943d22010-06-08 16:52:24 +00003462 }
3463
Caroline Tice926060e2010-10-29 21:48:37 +00003464 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003465 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003466 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003467
Greg Claytona4881d02011-01-22 07:12:45 +00003468 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3469 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003470 return NULL;
3471}
3472
Chris Lattner24943d22010-06-08 16:52:24 +00003473//------------------------------------------------------------------
3474// Process Event Data
3475//------------------------------------------------------------------
3476
3477Process::ProcessEventData::ProcessEventData () :
3478 EventData (),
3479 m_process_sp (),
3480 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003481 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003482 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003483 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003484{
3485}
3486
3487Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3488 EventData (),
3489 m_process_sp (process_sp),
3490 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003491 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003492 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003493 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003494{
3495}
3496
3497Process::ProcessEventData::~ProcessEventData()
3498{
3499}
3500
3501const ConstString &
3502Process::ProcessEventData::GetFlavorString ()
3503{
3504 static ConstString g_flavor ("Process::ProcessEventData");
3505 return g_flavor;
3506}
3507
3508const ConstString &
3509Process::ProcessEventData::GetFlavor () const
3510{
3511 return ProcessEventData::GetFlavorString ();
3512}
3513
Chris Lattner24943d22010-06-08 16:52:24 +00003514void
3515Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3516{
3517 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003518 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3519 // the public event queue, then other times when we're pretending that this is where we stopped at the
3520 // end of expression evaluation. m_update_state is used to distinguish these
3521 // three cases; it is 0 when we're just pulling it off for private handling,
3522 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003523
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003524 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003525 return;
3526
3527 m_process_sp->SetPublicState (m_state);
3528
3529 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3530 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003531 {
3532 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003533 uint32_t num_threads = curr_thread_list.GetSize();
3534 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003535
Jim Ingham21f37ad2011-08-09 02:12:22 +00003536 // The actions might change one of the thread's stop_info's opinions about whether we should
3537 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003538
3539 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3540 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3541 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3542 // 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
3543 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003544 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003545 for (idx = 0; idx < num_threads; ++idx)
3546 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3547
Jim Ingham21f37ad2011-08-09 02:12:22 +00003548 bool still_should_stop = true;
3549
Chris Lattner24943d22010-06-08 16:52:24 +00003550 for (idx = 0; idx < num_threads; ++idx)
3551 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003552 curr_thread_list = m_process_sp->GetThreadList();
3553 if (curr_thread_list.GetSize() != num_threads)
3554 {
3555 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003556 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003557 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 +00003558 break;
3559 }
3560
3561 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3562
3563 if (thread_sp->GetIndexID() != thread_index_array[idx])
3564 {
3565 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003566 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003567 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003568 idx,
3569 thread_index_array[idx],
3570 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003571 break;
3572 }
3573
Jim Ingham6297a3a2010-10-20 00:39:53 +00003574 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3575 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00003576 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003577 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003578 // The stop action might restart the target. If it does, then we want to mark that in the
3579 // event so that whoever is receiving it will know to wait for the running event and reflect
3580 // that state appropriately.
3581 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003582
3583 // FIXME: we might have run.
3584 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003585 {
3586 SetRestarted (true);
3587 break;
3588 }
3589 else if (!stop_info_sp->ShouldStop(event_ptr))
3590 {
3591 still_should_stop = false;
3592 }
Chris Lattner24943d22010-06-08 16:52:24 +00003593 }
3594 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003595
Jim Ingham21f37ad2011-08-09 02:12:22 +00003596
3597 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003598 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003599 if (!still_should_stop)
3600 {
3601 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003602 SetRestarted(true);
Jim Ingham027aaa72012-04-19 01:40:33 +00003603 // Use the public resume method here, since this is just
3604 // extending a public resume.
Jim Ingham21f37ad2011-08-09 02:12:22 +00003605 m_process_sp->Resume();
3606 }
3607 else
3608 {
3609 // If we didn't restart, run the Stop Hooks here:
3610 // They might also restart the target, so watch for that.
3611 m_process_sp->GetTarget().RunStopHooks();
3612 if (m_process_sp->GetPrivateState() == eStateRunning)
3613 SetRestarted(true);
3614 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003615 }
3616
Chris Lattner24943d22010-06-08 16:52:24 +00003617 }
3618}
3619
3620void
3621Process::ProcessEventData::Dump (Stream *s) const
3622{
3623 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003624 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003625
Greg Claytonb72d0f02011-04-12 05:54:46 +00003626 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003627}
3628
3629const Process::ProcessEventData *
3630Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3631{
3632 if (event_ptr)
3633 {
3634 const EventData *event_data = event_ptr->GetData();
3635 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3636 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3637 }
3638 return NULL;
3639}
3640
3641ProcessSP
3642Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3643{
3644 ProcessSP process_sp;
3645 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3646 if (data)
3647 process_sp = data->GetProcessSP();
3648 return process_sp;
3649}
3650
3651StateType
3652Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3653{
3654 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3655 if (data == NULL)
3656 return eStateInvalid;
3657 else
3658 return data->GetState();
3659}
3660
3661bool
3662Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3663{
3664 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3665 if (data == NULL)
3666 return false;
3667 else
3668 return data->GetRestarted();
3669}
3670
3671void
3672Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3673{
3674 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3675 if (data != NULL)
3676 data->SetRestarted(new_value);
3677}
3678
3679bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003680Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3681{
3682 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3683 if (data == NULL)
3684 return false;
3685 else
3686 return data->GetInterrupted ();
3687}
3688
3689void
3690Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3691{
3692 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3693 if (data != NULL)
3694 data->SetInterrupted(new_value);
3695}
3696
3697bool
Chris Lattner24943d22010-06-08 16:52:24 +00003698Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3699{
3700 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3701 if (data)
3702 {
3703 data->SetUpdateStateOnRemoval();
3704 return true;
3705 }
3706 return false;
3707}
3708
Greg Clayton289afcb2012-02-18 05:35:26 +00003709lldb::TargetSP
3710Process::CalculateTarget ()
3711{
3712 return m_target.shared_from_this();
3713}
3714
Chris Lattner24943d22010-06-08 16:52:24 +00003715void
Greg Claytona830adb2010-10-04 01:05:56 +00003716Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003717{
Greg Clayton567e7f32011-09-22 04:58:26 +00003718 exe_ctx.SetTargetPtr (&m_target);
3719 exe_ctx.SetProcessPtr (this);
3720 exe_ctx.SetThreadPtr(NULL);
3721 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003722}
3723
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003724//uint32_t
3725//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3726//{
3727// return 0;
3728//}
3729//
3730//ArchSpec
3731//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3732//{
3733// return Host::GetArchSpecForExistingProcess (pid);
3734//}
3735//
3736//ArchSpec
3737//Process::GetArchSpecForExistingProcess (const char *process_name)
3738//{
3739// return Host::GetArchSpecForExistingProcess (process_name);
3740//}
3741//
Caroline Tice861efb32010-11-16 05:07:41 +00003742void
3743Process::AppendSTDOUT (const char * s, size_t len)
3744{
Greg Clayton20d338f2010-11-18 05:57:03 +00003745 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003746 m_stdout_data.append (s, len);
Greg Claytonb3781332010-12-05 19:16:56 +00003747 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003748}
3749
3750void
Greg Claytonbd06ff42011-11-13 04:45:22 +00003751Process::AppendSTDERR (const char * s, size_t len)
3752{
3753 Mutex::Locker locker (m_stdio_communication_mutex);
3754 m_stderr_data.append (s, len);
3755 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3756}
3757
3758//------------------------------------------------------------------
3759// Process STDIO
3760//------------------------------------------------------------------
3761
3762size_t
3763Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3764{
3765 Mutex::Locker locker(m_stdio_communication_mutex);
3766 size_t bytes_available = m_stdout_data.size();
3767 if (bytes_available > 0)
3768 {
3769 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3770 if (log)
3771 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3772 if (bytes_available > buf_size)
3773 {
3774 memcpy(buf, m_stdout_data.c_str(), buf_size);
3775 m_stdout_data.erase(0, buf_size);
3776 bytes_available = buf_size;
3777 }
3778 else
3779 {
3780 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3781 m_stdout_data.clear();
3782 }
3783 }
3784 return bytes_available;
3785}
3786
3787
3788size_t
3789Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3790{
3791 Mutex::Locker locker(m_stdio_communication_mutex);
3792 size_t bytes_available = m_stderr_data.size();
3793 if (bytes_available > 0)
3794 {
3795 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3796 if (log)
3797 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3798 if (bytes_available > buf_size)
3799 {
3800 memcpy(buf, m_stderr_data.c_str(), buf_size);
3801 m_stderr_data.erase(0, buf_size);
3802 bytes_available = buf_size;
3803 }
3804 else
3805 {
3806 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3807 m_stderr_data.clear();
3808 }
3809 }
3810 return bytes_available;
3811}
3812
3813void
Caroline Tice861efb32010-11-16 05:07:41 +00003814Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3815{
3816 Process *process = (Process *) baton;
3817 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3818}
3819
3820size_t
3821Process::ProcessInputReaderCallback (void *baton,
3822 InputReader &reader,
3823 lldb::InputReaderAction notification,
3824 const char *bytes,
3825 size_t bytes_len)
3826{
3827 Process *process = (Process *) baton;
3828
3829 switch (notification)
3830 {
3831 case eInputReaderActivate:
3832 break;
3833
3834 case eInputReaderDeactivate:
3835 break;
3836
3837 case eInputReaderReactivate:
3838 break;
3839
Caroline Tice4a348082011-05-02 20:41:46 +00003840 case eInputReaderAsynchronousOutputWritten:
3841 break;
3842
Caroline Tice861efb32010-11-16 05:07:41 +00003843 case eInputReaderGotToken:
3844 {
3845 Error error;
3846 process->PutSTDIN (bytes, bytes_len, error);
3847 }
3848 break;
3849
Caroline Ticec4f55fe2010-11-19 20:47:54 +00003850 case eInputReaderInterrupt:
3851 process->Halt ();
3852 break;
3853
3854 case eInputReaderEndOfFile:
3855 process->AppendSTDOUT ("^D", 2);
3856 break;
3857
Caroline Tice861efb32010-11-16 05:07:41 +00003858 case eInputReaderDone:
3859 break;
3860
3861 }
3862
3863 return bytes_len;
3864}
3865
3866void
3867Process::ResetProcessInputReader ()
3868{
3869 m_process_input_reader.reset();
3870}
3871
3872void
Greg Clayton464c6162011-11-17 22:14:31 +00003873Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00003874{
3875 // First set up the Read Thread for reading/handling process I/O
3876
3877 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3878
3879 if (conn_ap.get())
3880 {
3881 m_stdio_communication.SetConnection (conn_ap.release());
3882 if (m_stdio_communication.IsConnected())
3883 {
3884 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3885 m_stdio_communication.StartReadThread();
3886
3887 // Now read thread is set up, set up input reader.
3888
3889 if (!m_process_input_reader.get())
3890 {
3891 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3892 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3893 this,
3894 eInputReaderGranularityByte,
3895 NULL,
3896 NULL,
3897 false));
3898
3899 if (err.Fail())
3900 m_process_input_reader.reset();
3901 }
3902 }
3903 }
3904}
3905
3906void
3907Process::PushProcessInputReader ()
3908{
3909 if (m_process_input_reader && !m_process_input_reader->IsActive())
3910 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3911}
3912
3913void
3914Process::PopProcessInputReader ()
3915{
3916 if (m_process_input_reader && m_process_input_reader->IsActive())
3917 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3918}
3919
Greg Claytond284b662011-02-18 01:44:25 +00003920// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00003921void
Caroline Tice2a456812011-03-10 22:14:10 +00003922Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003923{
Greg Claytonb3448432011-03-24 21:19:54 +00003924 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00003925
3926 int i=0;
3927 const char *name;
3928 OptionEnumValueElement option_enum;
3929 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3930 {
3931 if (name)
3932 {
3933 option_enum.value = i;
3934 option_enum.string_value = name;
3935 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3936 g_plugins.push_back (option_enum);
3937 }
3938 ++i;
3939 }
3940 option_enum.value = 0;
3941 option_enum.string_value = NULL;
3942 option_enum.usage = NULL;
3943 g_plugins.push_back (option_enum);
3944
3945 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3946 {
3947 if (::strcmp (name, "plugin") == 0)
3948 {
3949 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3950 break;
3951 }
3952 }
Greg Clayton990de7b2010-11-18 23:32:35 +00003953 UserSettingsControllerSP &usc = GetSettingsController();
Greg Clayton990de7b2010-11-18 23:32:35 +00003954 UserSettingsController::InitializeSettingsController (usc,
3955 SettingsController::global_settings_table,
3956 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00003957
3958 // Now call SettingsInitialize() for each 'child' of Process settings
3959 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00003960}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003961
Greg Clayton990de7b2010-11-18 23:32:35 +00003962void
Caroline Tice2a456812011-03-10 22:14:10 +00003963Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00003964{
Caroline Tice2a456812011-03-10 22:14:10 +00003965 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3966
3967 Thread::SettingsTerminate ();
3968
3969 // Now terminate Process Settings.
3970
Greg Clayton990de7b2010-11-18 23:32:35 +00003971 UserSettingsControllerSP &usc = GetSettingsController();
3972 UserSettingsController::FinalizeSettingsController (usc);
3973 usc.reset();
3974}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003975
Greg Clayton990de7b2010-11-18 23:32:35 +00003976UserSettingsControllerSP &
3977Process::GetSettingsController ()
3978{
Greg Clayton334d33a2012-01-30 07:41:31 +00003979 static UserSettingsControllerSP g_settings_controller_sp;
3980 if (!g_settings_controller_sp)
3981 {
3982 g_settings_controller_sp.reset (new Process::SettingsController);
3983 // The first shared pointer to Process::SettingsController in
3984 // g_settings_controller_sp must be fully created above so that
3985 // the TargetInstanceSettings can use a weak_ptr to refer back
3986 // to the master setttings controller
3987 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp,
3988 false,
3989 InstanceSettings::GetDefaultName().AsCString()));
3990 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
3991 }
3992 return g_settings_controller_sp;
3993
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003994}
3995
Caroline Tice1ebef442010-09-27 00:30:10 +00003996void
3997Process::UpdateInstanceName ()
3998{
Greg Clayton5beb99d2011-08-11 02:48:45 +00003999 Module *module = GetTarget().GetExecutableModulePointer();
Greg Clayton13d24fb2012-01-29 20:56:30 +00004000 if (module && module->GetFileSpec().GetFilename())
Caroline Tice1ebef442010-09-27 00:30:10 +00004001 {
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00004002 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Clayton13d24fb2012-01-29 20:56:30 +00004003 module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1ebef442010-09-27 00:30:10 +00004004 }
4005}
4006
Greg Clayton427f2902010-12-14 02:59:59 +00004007ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00004008Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00004009 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00004010 bool stop_others,
4011 bool try_all_threads,
4012 bool discard_on_error,
4013 uint32_t single_thread_timeout_usec,
4014 Stream &errors)
4015{
4016 ExecutionResults return_value = eExecutionSetupError;
4017
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004018 if (thread_plan_sp.get() == NULL)
4019 {
4020 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00004021 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004022 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004023
4024 if (exe_ctx.GetProcessPtr() != this)
4025 {
4026 errors.Printf("RunThreadPlan called on wrong process.");
4027 return eExecutionSetupError;
4028 }
4029
4030 Thread *thread = exe_ctx.GetThreadPtr();
4031 if (thread == NULL)
4032 {
4033 errors.Printf("RunThreadPlan called with invalid thread.");
4034 return eExecutionSetupError;
4035 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004036
Jim Ingham5ab7fba2011-05-17 22:24:54 +00004037 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4038 // For that to be true the plan can't be private - since private plans suppress themselves in the
4039 // GetCompletedPlan call.
4040
4041 bool orig_plan_private = thread_plan_sp->GetPrivate();
4042 thread_plan_sp->SetPrivate(false);
4043
Jim Inghamac959662011-01-24 06:34:17 +00004044 if (m_private_state.GetValue() != eStateStopped)
4045 {
4046 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00004047 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00004048 }
4049
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004050 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00004051 const uint32_t thread_idx_id = thread->GetIndexID();
4052 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004053
4054 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4055 // so we should arrange to reset them as well.
4056
Greg Clayton567e7f32011-09-22 04:58:26 +00004057 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00004058
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004059 uint32_t selected_tid;
4060 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00004061 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004062 {
4063 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004064 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00004065 }
4066 else
4067 {
4068 selected_tid = LLDB_INVALID_THREAD_ID;
4069 }
4070
Jim Ingham1831e782012-04-07 00:00:41 +00004071 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004072 lldb::StateType old_state;
4073 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00004074
Jim Inghamd21d98b2012-04-10 01:21:57 +00004075 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00004076 if (Host::GetCurrentThread() == m_private_state_thread)
4077 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00004078 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4079 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00004080 // 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 +00004081 // we are fielding public events here.
4082 if (log)
4083 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4084
4085
Jim Ingham1831e782012-04-07 00:00:41 +00004086 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004087
4088 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4089 // returning control here.
4090 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4091 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4092 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4093 // do just what we want.
4094 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4095 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4096 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4097 old_state = m_public_state.GetValue();
4098 m_public_state.SetValueNoLock(eStateStopped);
4099
4100 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00004101 StartPrivateStateThread(true);
4102 }
4103
4104 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00004105
Jim Ingham6ae318c2011-01-23 21:14:08 +00004106 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004107
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004108 lldb::EventSP event_to_broadcast_sp;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004109
Jim Ingham15dcb7c2011-01-20 02:03:18 +00004110 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004111 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4112 // restored on exit to the function.
4113 //
4114 // If the event needs to propagate beyond the hijacker (e.g., the process exits during execution), then the event
4115 // is put into event_to_broadcast_sp for rebroadcasting.
Jim Ingham360f53f2010-11-30 02:22:11 +00004116
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004117 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004118
Jim Ingham360f53f2010-11-30 02:22:11 +00004119 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004120 {
4121 StreamString s;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004122 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4123 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
4124 thread->GetIndexID(),
4125 thread->GetID(),
4126 s.GetData());
4127 }
4128
4129 bool got_event;
4130 lldb::EventSP event_sp;
4131 lldb::StateType stop_state = lldb::eStateInvalid;
4132
4133 TimeValue* timeout_ptr = NULL;
4134 TimeValue real_timeout;
4135
4136 bool first_timeout = true;
4137 bool do_resume = true;
4138
4139 while (1)
4140 {
4141 // We usually want to resume the process if we get to the top of the loop.
4142 // The only exception is if we get two running events with no intervening
4143 // stop, which can happen, we will just wait for then next stop event.
4144
4145 if (do_resume)
4146 {
4147 // Do the initial resume and wait for the running event before going further.
4148
4149 Error resume_error = PrivateResume ();
4150 if (!resume_error.Success())
4151 {
4152 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
4153 return_value = eExecutionSetupError;
4154 break;
4155 }
4156
4157 real_timeout = TimeValue::Now();
4158 real_timeout.OffsetWithMicroSeconds(500000);
4159 timeout_ptr = &real_timeout;
4160
4161 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
4162 if (!got_event)
4163 {
4164 if (log)
4165 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
4166
4167 errors.Printf("Didn't get any event after initial resume, exiting.");
4168 return_value = eExecutionSetupError;
4169 break;
4170 }
4171
4172 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4173 if (stop_state != eStateRunning)
4174 {
4175 if (log)
4176 log->Printf("Process::RunThreadPlan(): didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
4177
4178 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
4179 return_value = eExecutionSetupError;
4180 break;
4181 }
4182
4183 if (log)
4184 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
4185 // We need to call the function synchronously, so spin waiting for it to return.
4186 // If we get interrupted while executing, we're going to lose our context, and
4187 // won't be able to gather the result at this point.
4188 // We set the timeout AFTER the resume, since the resume takes some time and we
4189 // don't want to charge that to the timeout.
4190
4191 if (single_thread_timeout_usec != 0)
4192 {
Enrico Granata6cca9692012-07-16 23:10:35 +00004193 // we have a > 0 timeout, let us set it so that we stop after the deadline
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004194 real_timeout = TimeValue::Now();
4195 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
4196
4197 timeout_ptr = &real_timeout;
4198 }
Enrico Granata6cca9692012-07-16 23:10:35 +00004199 else if (first_timeout)
4200 {
4201 // if we are willing to wait "forever" we still need to have an initial timeout
4202 // this timeout is going to induce all threads to run when hit. we do this so that
4203 // we can avoid ending locked up because of multithreaded contention issues
4204 real_timeout = TimeValue::Now();
4205 real_timeout.OffsetWithNanoSeconds(500000000UL);
4206 timeout_ptr = &real_timeout;
4207 }
4208 else
4209 {
4210 timeout_ptr = NULL; // if we are in a no-timeout scenario, then we only need a fake timeout the first time through
4211 // at this point in the code, all threads will be running so we are willing to wait forever, and do not
4212 // need a timeout
4213 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004214 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004215 else
4216 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004217 if (log)
4218 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
4219 do_resume = true;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004220 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004221
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004222 // Now wait for the process to stop again:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004223 event_sp.reset();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004224
Jim Inghamf9f40c22011-02-08 05:20:59 +00004225 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004226 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004227 if (timeout_ptr)
4228 {
4229 StreamString s;
4230 s.Printf ("about to wait - timeout is:\n ");
4231 timeout_ptr->Dump (&s, 120);
4232 s.Printf ("\nNow is:\n ");
4233 TimeValue::Now().Dump (&s, 120);
4234 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4235 }
Jim Inghamf6d3d792011-08-09 22:24:33 +00004236 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004237 {
4238 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4239 }
4240 }
4241
4242 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4243
4244 if (got_event)
4245 {
4246 if (event_sp.get())
4247 {
4248 bool keep_going = false;
Jim Ingham5d90ade2012-07-27 23:57:19 +00004249 if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004250 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004251 Halt();
4252 keep_going = false;
4253 return_value = eExecutionInterrupted;
4254 errors.Printf ("Execution halted by user interrupt.");
4255 if (log)
4256 log->Printf ("Process::RunThreadPlan(): Got interrupted by eBroadcastBitInterrupted, exiting.");
4257 }
4258 else
4259 {
4260 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4261 if (log)
4262 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
4263
4264 switch (stop_state)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004265 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004266 case lldb::eStateStopped:
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004267 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004268 // Yay, we're done. Now make sure that our thread plan actually completed.
4269 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
4270 if (!thread_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004271 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004272 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004273 if (log)
Jim Ingham5d90ade2012-07-27 23:57:19 +00004274 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4275 return_value = eExecutionInterrupted;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004276 }
4277 else
4278 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004279 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4280 StopReason stop_reason = eStopReasonInvalid;
4281 if (stop_info_sp)
4282 stop_reason = stop_info_sp->GetStopReason();
4283 if (stop_reason == eStopReasonPlanComplete)
4284 {
4285 if (log)
4286 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
4287 // Now mark this plan as private so it doesn't get reported as the stop reason
4288 // after this point.
4289 if (thread_plan_sp)
4290 thread_plan_sp->SetPrivate (orig_plan_private);
4291 return_value = eExecutionCompleted;
4292 }
4293 else
4294 {
4295 if (log)
4296 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004297
Jim Ingham5d90ade2012-07-27 23:57:19 +00004298 return_value = eExecutionInterrupted;
4299 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004300 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004301 }
4302 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004303
Jim Ingham5d90ade2012-07-27 23:57:19 +00004304 case lldb::eStateCrashed:
4305 if (log)
4306 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
4307 return_value = eExecutionInterrupted;
4308 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004309
Jim Ingham5d90ade2012-07-27 23:57:19 +00004310 case lldb::eStateRunning:
4311 do_resume = false;
4312 keep_going = true;
4313 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004314
Jim Ingham5d90ade2012-07-27 23:57:19 +00004315 default:
4316 if (log)
4317 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
4318
4319 if (stop_state == eStateExited)
4320 event_to_broadcast_sp = event_sp;
4321
4322 errors.Printf ("Execution stopped with unexpected state.");
4323 return_value = eExecutionInterrupted;
4324 break;
4325 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004326 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004327
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004328 if (keep_going)
4329 continue;
4330 else
4331 break;
4332 }
4333 else
4334 {
4335 if (log)
4336 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
4337 return_value = eExecutionInterrupted;
4338 break;
4339 }
4340 }
4341 else
4342 {
4343 // If we didn't get an event that means we've timed out...
4344 // We will interrupt the process here. Depending on what we were asked to do we will
4345 // either exit, or try with all threads running for the same timeout.
4346 // Not really sure what to do if Halt fails here...
4347
4348 if (log) {
4349 if (try_all_threads)
4350 {
4351 if (first_timeout)
4352 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4353 "trying with all threads enabled.",
4354 single_thread_timeout_usec);
4355 else
4356 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4357 "and timeout: %d timed out.",
4358 single_thread_timeout_usec);
4359 }
4360 else
4361 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4362 "halt and abandoning execution.",
4363 single_thread_timeout_usec);
4364 }
4365
4366 Error halt_error = Halt();
4367 if (halt_error.Success())
4368 {
4369 if (log)
4370 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
4371
4372 // If halt succeeds, it always produces a stopped event. Wait for that:
4373
4374 real_timeout = TimeValue::Now();
4375 real_timeout.OffsetWithMicroSeconds(500000);
4376
4377 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4378
4379 if (got_event)
4380 {
4381 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4382 if (log)
4383 {
4384 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
4385 if (stop_state == lldb::eStateStopped
4386 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4387 log->PutCString (" Event was the Halt interruption event.");
4388 }
4389
4390 if (stop_state == lldb::eStateStopped)
4391 {
4392 // Between the time we initiated the Halt and the time we delivered it, the process could have
4393 // already finished its job. Check that here:
4394
4395 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4396 {
4397 if (log)
4398 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4399 "Exiting wait loop.");
4400 return_value = eExecutionCompleted;
4401 break;
4402 }
4403
4404 if (!try_all_threads)
4405 {
4406 if (log)
4407 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
4408 return_value = eExecutionInterrupted;
4409 break;
4410 }
4411
4412 if (first_timeout)
4413 {
4414 // Set all the other threads to run, and return to the top of the loop, which will continue;
4415 first_timeout = false;
4416 thread_plan_sp->SetStopOthers (false);
4417 if (log)
4418 log->PutCString ("Process::RunThreadPlan(): about to resume.");
4419
4420 continue;
4421 }
4422 else
4423 {
4424 // Running all threads failed, so return Interrupted.
4425 if (log)
4426 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
4427 return_value = eExecutionInterrupted;
4428 break;
4429 }
4430 }
4431 }
4432 else
4433 { if (log)
4434 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
4435 "I'm getting out of here passing Interrupted.");
4436 return_value = eExecutionInterrupted;
4437 break;
4438 }
4439 }
4440 else
4441 {
4442 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4443 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
4444 if (log)
4445 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.",
4446 halt_error.AsCString());
4447 real_timeout = TimeValue::Now();
4448 real_timeout.OffsetWithMicroSeconds(500000);
4449 timeout_ptr = &real_timeout;
4450 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4451 if (!got_event || event_sp.get() == NULL)
4452 {
4453 // This is not going anywhere, bag out.
4454 if (log)
4455 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
4456 return_value = eExecutionInterrupted;
4457 break;
4458 }
4459 else
4460 {
4461 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4462 if (log)
4463 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
4464 if (stop_state == lldb::eStateStopped)
4465 {
4466 // Between the time we initiated the Halt and the time we delivered it, the process could have
4467 // already finished its job. Check that here:
4468
4469 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
4470 {
4471 if (log)
4472 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
4473 "Exiting wait loop.");
4474 return_value = eExecutionCompleted;
4475 break;
4476 }
4477
4478 if (first_timeout)
4479 {
4480 // Set all the other threads to run, and return to the top of the loop, which will continue;
4481 first_timeout = false;
4482 thread_plan_sp->SetStopOthers (false);
4483 if (log)
4484 log->PutCString ("Process::RunThreadPlan(): About to resume.");
4485
4486 continue;
4487 }
4488 else
4489 {
4490 // Running all threads failed, so return Interrupted.
4491 if (log)
4492 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
4493 return_value = eExecutionInterrupted;
4494 break;
4495 }
4496 }
4497 else
4498 {
4499 if (log)
4500 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4501 " a stopped event, instead got %s.", StateAsCString(stop_state));
4502 return_value = eExecutionInterrupted;
4503 break;
4504 }
4505 }
4506 }
4507
4508 }
4509
4510 } // END WAIT LOOP
4511
4512 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4513 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4514 {
4515 StopPrivateStateThread();
4516 Error error;
4517 m_private_state_thread = backup_private_state_thread;
4518 if (stopper_base_plan_sp != NULL)
4519 {
4520 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4521 }
4522 m_public_state.SetValueNoLock(old_state);
4523
4524 }
4525
4526
4527 // Now do some processing on the results of the run:
4528 if (return_value == eExecutionInterrupted)
4529 {
4530 if (log)
4531 {
4532 StreamString s;
4533 if (event_sp)
4534 event_sp->Dump (&s);
4535 else
4536 {
4537 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
4538 }
4539
4540 StreamString ts;
4541
4542 const char *event_explanation = NULL;
4543
4544 do
4545 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004546 if (!event_sp)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004547 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004548 event_explanation = "<no event>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004549 break;
4550 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004551 else if (event_sp->GetType() == eBroadcastBitInterrupt)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004552 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004553 event_explanation = "<user interrupt>";
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004554 break;
4555 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004556 else
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004557 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004558 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4559
4560 if (!event_data)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004561 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004562 event_explanation = "<no event data>";
4563 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004564 }
4565
Jim Ingham5d90ade2012-07-27 23:57:19 +00004566 Process *process = event_data->GetProcessSP().get();
4567
4568 if (!process)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004569 {
Jim Ingham5d90ade2012-07-27 23:57:19 +00004570 event_explanation = "<no process>";
4571 break;
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004572 }
Jim Ingham5d90ade2012-07-27 23:57:19 +00004573
4574 ThreadList &thread_list = process->GetThreadList();
4575
4576 uint32_t num_threads = thread_list.GetSize();
4577 uint32_t thread_index;
4578
4579 ts.Printf("<%u threads> ", num_threads);
4580
4581 for (thread_index = 0;
4582 thread_index < num_threads;
4583 ++thread_index)
4584 {
4585 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4586
4587 if (!thread)
4588 {
4589 ts.Printf("<?> ");
4590 continue;
4591 }
4592
4593 ts.Printf("<0x%4.4llx ", thread->GetID());
4594 RegisterContext *register_context = thread->GetRegisterContext().get();
4595
4596 if (register_context)
4597 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4598 else
4599 ts.Printf("[ip unknown] ");
4600
4601 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4602 if (stop_info_sp)
4603 {
4604 const char *stop_desc = stop_info_sp->GetDescription();
4605 if (stop_desc)
4606 ts.PutCString (stop_desc);
4607 }
4608 ts.Printf(">");
4609 }
4610
4611 event_explanation = ts.GetData();
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004612 }
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004613 } while (0);
4614
Jim Ingham5d90ade2012-07-27 23:57:19 +00004615 if (event_explanation)
4616 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004617 else
Jim Ingham5d90ade2012-07-27 23:57:19 +00004618 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4619 }
4620
4621 if (discard_on_error && thread_plan_sp)
4622 {
4623 if (log)
4624 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
4625 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4626 thread_plan_sp->SetPrivate (orig_plan_private);
4627 }
4628 else
4629 {
4630 if (log)
4631 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004632 }
4633 }
4634 else if (return_value == eExecutionSetupError)
4635 {
4636 if (log)
4637 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004638
4639 if (discard_on_error && thread_plan_sp)
4640 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004641 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004642 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004643 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004644 }
4645 else
4646 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004647 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004648 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004649 if (log)
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004650 log->PutCString("Process::RunThreadPlan(): thread plan is done");
4651 return_value = eExecutionCompleted;
4652 }
4653 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
4654 {
4655 if (log)
4656 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
4657 return_value = eExecutionDiscarded;
4658 }
4659 else
4660 {
4661 if (log)
4662 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
4663 if (discard_on_error && thread_plan_sp)
4664 {
4665 if (log)
4666 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
4667 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
4668 thread_plan_sp->SetPrivate (orig_plan_private);
4669 }
4670 }
4671 }
4672
4673 // Thread we ran the function in may have gone away because we ran the target
4674 // Check that it's still there, and if it is put it back in the context. Also restore the
4675 // frame in the context if it is still present.
4676 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4677 if (thread)
4678 {
4679 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
4680 }
4681
4682 // Also restore the current process'es selected frame & thread, since this function calling may
4683 // be done behind the user's back.
4684
4685 if (selected_tid != LLDB_INVALID_THREAD_ID)
4686 {
4687 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
4688 {
4689 // We were able to restore the selected thread, now restore the frame:
4690 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
4691 if (old_frame_sp)
4692 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00004693 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004694 }
4695 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004696
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004697 // If the process exited during the run of the thread plan, notify everyone.
Jim Ingham360f53f2010-11-30 02:22:11 +00004698
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004699 if (event_to_broadcast_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00004700 {
Sean Callanan5b0a5ac2012-07-11 21:31:24 +00004701 if (log)
4702 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
4703 BroadcastEvent(event_to_broadcast_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00004704 }
4705
4706 return return_value;
4707}
4708
4709const char *
4710Process::ExecutionResultAsCString (ExecutionResults result)
4711{
4712 const char *result_name;
4713
4714 switch (result)
4715 {
Greg Claytonb3448432011-03-24 21:19:54 +00004716 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004717 result_name = "eExecutionCompleted";
4718 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004719 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00004720 result_name = "eExecutionDiscarded";
4721 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004722 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004723 result_name = "eExecutionInterrupted";
4724 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004725 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00004726 result_name = "eExecutionSetupError";
4727 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004728 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00004729 result_name = "eExecutionTimedOut";
4730 break;
4731 }
4732 return result_name;
4733}
4734
Greg Claytonabe0fed2011-04-18 08:33:37 +00004735void
4736Process::GetStatus (Stream &strm)
4737{
4738 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00004739 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00004740 {
4741 if (state == eStateExited)
4742 {
4743 int exit_status = GetExitStatus();
4744 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00004745 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00004746 GetID(),
4747 exit_status,
4748 exit_status,
4749 exit_description ? exit_description : "");
4750 }
4751 else
4752 {
4753 if (state == eStateConnected)
4754 strm.Printf ("Connected to remote target.\n");
4755 else
Greg Clayton444e35b2011-10-19 18:09:39 +00004756 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00004757 }
4758 }
4759 else
4760 {
Greg Clayton444e35b2011-10-19 18:09:39 +00004761 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004762 }
4763}
4764
4765size_t
4766Process::GetThreadStatus (Stream &strm,
4767 bool only_threads_with_stop_reason,
4768 uint32_t start_frame,
4769 uint32_t num_frames,
4770 uint32_t num_frames_with_source)
4771{
4772 size_t num_thread_infos_dumped = 0;
4773
4774 const size_t num_threads = GetThreadList().GetSize();
4775 for (uint32_t i = 0; i < num_threads; i++)
4776 {
4777 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4778 if (thread)
4779 {
4780 if (only_threads_with_stop_reason)
4781 {
4782 if (thread->GetStopInfo().get() == NULL)
4783 continue;
4784 }
4785 thread->GetStatus (strm,
4786 start_frame,
4787 num_frames,
4788 num_frames_with_source);
4789 ++num_thread_infos_dumped;
4790 }
4791 }
4792 return num_thread_infos_dumped;
4793}
4794
Greg Clayton76113302012-02-22 04:37:26 +00004795void
4796Process::AddInvalidMemoryRegion (const LoadRange &region)
4797{
4798 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4799}
4800
4801bool
4802Process::RemoveInvalidMemoryRange (const LoadRange &region)
4803{
4804 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4805}
4806
Jim Ingham1831e782012-04-07 00:00:41 +00004807void
4808Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4809{
4810 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4811}
4812
4813bool
4814Process::RunPreResumeActions ()
4815{
4816 bool result = true;
4817 while (!m_pre_resume_actions.empty())
4818 {
4819 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
4820 m_pre_resume_actions.pop_back();
4821 bool this_result = action.callback (action.baton);
4822 if (result == true) result = this_result;
4823 }
4824 return result;
4825}
4826
4827void
4828Process::ClearPreResumeActions ()
4829{
4830 m_pre_resume_actions.clear();
4831}
Greg Clayton76113302012-02-22 04:37:26 +00004832
Greg Claytoncf5927e2012-05-18 02:38:05 +00004833void
4834Process::Flush ()
4835{
4836 m_thread_list.Flush();
4837}
4838
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004839//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004840// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004841//--------------------------------------------------------------
4842
Greg Claytond0a5a232010-09-19 02:33:57 +00004843Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00004844 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004845{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004846}
4847
Greg Claytond0a5a232010-09-19 02:33:57 +00004848Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004849{
4850}
4851
4852lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00004853Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004854{
Greg Clayton334d33a2012-01-30 07:41:31 +00004855 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4856 false,
4857 instance_name));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004858 return new_settings_sp;
4859}
4860
4861//--------------------------------------------------------------
4862// class ProcessInstanceSettings
4863//--------------------------------------------------------------
4864
Greg Clayton638351a2010-12-04 00:10:17 +00004865ProcessInstanceSettings::ProcessInstanceSettings
4866(
Greg Clayton334d33a2012-01-30 07:41:31 +00004867 const UserSettingsControllerSP &owner_sp,
Greg Clayton638351a2010-12-04 00:10:17 +00004868 bool live_instance,
4869 const char *name
4870) :
Greg Clayton334d33a2012-01-30 07:41:31 +00004871 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004872{
Caroline Tice396704b2010-09-09 18:26:37 +00004873 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4874 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4875 // 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 +00004876 // This is true for CreateInstanceName() too.
Greg Claytonabb33022011-11-08 02:43:13 +00004877
Caroline Tice75b11a32010-09-16 19:05:55 +00004878 if (GetInstanceName () == InstanceSettings::InvalidName())
4879 {
4880 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
Greg Clayton334d33a2012-01-30 07:41:31 +00004881 owner_sp->RegisterInstanceSettings (this);
Caroline Tice75b11a32010-09-16 19:05:55 +00004882 }
Greg Claytonabb33022011-11-08 02:43:13 +00004883
Caroline Tice396704b2010-09-09 18:26:37 +00004884 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004885 {
Greg Clayton334d33a2012-01-30 07:41:31 +00004886 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004887 CopyInstanceSettings (pending_settings,false);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004888 }
4889}
4890
4891ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Jim Ingham86827fb2012-07-02 05:40:07 +00004892 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString()),
4893 m_disable_memory_cache(rhs.m_disable_memory_cache),
4894 m_extra_startup_commands (rhs.m_extra_startup_commands)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004895{
4896 if (m_instance_name != InstanceSettings::GetDefaultName())
4897 {
Greg Clayton334d33a2012-01-30 07:41:31 +00004898 UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4899 if (owner_sp)
4900 {
4901 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4902 owner_sp->RemovePendingSettings (m_instance_name);
4903 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004904 }
4905}
4906
4907ProcessInstanceSettings::~ProcessInstanceSettings ()
4908{
4909}
4910
4911ProcessInstanceSettings&
4912ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4913{
4914 if (this != &rhs)
4915 {
Jim Ingham86827fb2012-07-02 05:40:07 +00004916 m_disable_memory_cache = rhs.m_disable_memory_cache;
4917 m_extra_startup_commands = rhs.m_extra_startup_commands;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004918 }
4919
4920 return *this;
4921}
4922
4923
4924void
4925ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4926 const char *index_value,
4927 const char *value,
4928 const ConstString &instance_name,
4929 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00004930 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004931 Error &err,
4932 bool pending)
4933{
Sean Callananf90b5f32012-06-07 22:26:42 +00004934 if (var_name == GetDisableMemoryCacheVarName())
4935 {
4936 bool success;
4937 bool result = Args::StringToBoolean(value, false, &success);
4938
4939 if (success)
4940 {
4941 m_disable_memory_cache = result;
4942 }
4943 else
4944 {
4945 err.SetErrorStringWithFormat ("Bad value \"%s\" for %s, should be Boolean.", value, GetDisableMemoryCacheVarName().AsCString());
4946 }
4947
4948 }
Jim Ingham86827fb2012-07-02 05:40:07 +00004949 else if (var_name == GetExtraStartupCommandVarName())
4950 {
4951 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_extra_startup_commands, value, err);
4952 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004953}
4954
4955void
4956ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4957 bool pending)
4958{
Sean Callananf90b5f32012-06-07 22:26:42 +00004959 if (new_settings.get() == NULL)
4960 return;
4961
4962 ProcessInstanceSettings *new_settings_ptr = static_cast <ProcessInstanceSettings *> (new_settings.get());
4963
4964 if (!new_settings_ptr)
4965 return;
4966
4967 *this = *new_settings_ptr;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004968}
4969
Caroline Ticebcb5b452010-09-20 21:37:42 +00004970bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004971ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4972 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00004973 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00004974 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004975{
Sean Callananf90b5f32012-06-07 22:26:42 +00004976 if (var_name == GetDisableMemoryCacheVarName())
4977 {
4978 value.AppendString(m_disable_memory_cache ? "true" : "false");
4979 return true;
4980 }
Jim Ingham86827fb2012-07-02 05:40:07 +00004981 else if (var_name == GetExtraStartupCommandVarName())
4982 {
4983 if (m_extra_startup_commands.GetArgumentCount() > 0)
4984 {
4985 for (int i = 0; i < m_extra_startup_commands.GetArgumentCount(); ++i)
4986 value.AppendString (m_extra_startup_commands.GetArgumentAtIndex (i));
4987 }
4988 return true;
4989 }
Sean Callananf90b5f32012-06-07 22:26:42 +00004990 else
4991 {
4992 if (err)
4993 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4994 return false;
4995 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004996}
4997
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004998const ConstString
4999ProcessInstanceSettings::CreateInstanceName ()
5000{
5001 static int instance_count = 1;
5002 StreamString sstr;
5003
5004 sstr.Printf ("process_%d", instance_count);
5005 ++instance_count;
5006
5007 const ConstString ret_val (sstr.GetData());
5008 return ret_val;
5009}
5010
Sean Callananf90b5f32012-06-07 22:26:42 +00005011const ConstString &
5012ProcessInstanceSettings::GetDisableMemoryCacheVarName () const
5013{
5014 static ConstString disable_memory_cache_var_name ("disable-memory-cache");
5015
5016 return disable_memory_cache_var_name;
5017}
5018
Jim Ingham86827fb2012-07-02 05:40:07 +00005019const ConstString &
5020ProcessInstanceSettings::GetExtraStartupCommandVarName () const
5021{
5022 static ConstString extra_startup_command_var_name ("extra-startup-command");
5023
5024 return extra_startup_command_var_name;
5025}
5026
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00005027//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00005028// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00005029//--------------------------------------------------
5030
5031SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00005032Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00005033{
5034 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
5035 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
5036};
5037
5038
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00005039SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00005040Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00005041{
Greg Clayton638351a2010-12-04 00:10:17 +00005042 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Sean Callananf90b5f32012-06-07 22:26:42 +00005043 { "disable-memory-cache", eSetVarTypeBoolean,
5044#ifdef ENABLE_MEMORY_CACHING
5045 "false",
5046#else
5047 "true",
5048#endif
5049 NULL, false, false, "Disable reading and caching of memory in fixed-size units." },
Jim Ingham86827fb2012-07-02 05:40:07 +00005050 { "extra-startup-command", eSetVarTypeArray, NULL, NULL, false, false, "A list containing extra commands understood by the particular process plugin used." },
Greg Clayton638351a2010-12-04 00:10:17 +00005051 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00005052};
5053
5054
Jim Ingham7508e732010-08-09 23:31:02 +00005055
Greg Claytonabb33022011-11-08 02:43:13 +00005056