blob: 7004cd243a7bacaca0b6d8c4739e32bc55f51d4e [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
Jim Ingham076b3042012-04-10 01:21:57 +000039#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000040
41using namespace lldb;
42using namespace lldb_private;
43
Greg Clayton32e0a752011-03-30 18:16:51 +000044void
Greg Clayton8b82f082011-04-12 05:54:46 +000045ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +000046{
47 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +000048 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +000049 s.Printf (" pid = %llu\n", m_pid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000050
51 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Clayton61e7a582011-12-01 23:28:38 +000052 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +000061 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +000062 if (argc > 0)
63 {
64 for (uint32_t i=0; i<argc; i++)
65 {
Greg Clayton8b82f082011-04-12 05:54:46 +000066 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000067 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +000068 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000069 else
Greg Clayton8b82f082011-04-12 05:54:46 +000070 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000071 }
72 }
Greg Clayton8b82f082011-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 Clayton95bf0fd2011-04-01 00:29:43 +000087 if (m_arch.IsValid())
88 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
89
Greg Clayton8b82f082011-04-12 05:54:46 +000090 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000091 {
Greg Clayton8b82f082011-04-12 05:54:46 +000092 cstr = platform->GetUserName (m_uid);
93 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000094 }
Greg Clayton8b82f082011-04-12 05:54:46 +000095 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000096 {
Greg Clayton8b82f082011-04-12 05:54:46 +000097 cstr = platform->GetGroupName (m_gid);
98 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000099 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000100 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000101 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000102 cstr = platform->GetUserName (m_euid);
103 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000104 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000105 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000106 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000107 cstr = platform->GetGroupName (m_egid);
108 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000109 }
110}
111
112void
Greg Clayton8b82f082011-04-12 05:54:46 +0000113ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000114{
Greg Clayton8b82f082011-04-12 05:54:46 +0000115 const char *label;
116 if (show_args || verbose)
117 label = "ARGUMENTS";
118 else
119 label = "NAME";
120
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000121 if (verbose)
122 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000123 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000124 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
125 }
126 else
127 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000128 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000129 s.PutCString ("====== ====== ========== ======= ============================\n");
130 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000131}
132
133void
Greg Clayton8b82f082011-04-12 05:54:46 +0000134ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000135{
136 if (m_pid != LLDB_INVALID_PROCESS_ID)
137 {
138 const char *cstr;
Greg Clayton61e7a582011-12-01 23:28:38 +0000139 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000140
Greg Clayton32e0a752011-03-30 18:16:51 +0000141
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000142 if (verbose)
143 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000144 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000148 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000149
Greg Clayton8b82f082011-04-12 05:54:46 +0000150 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000154 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000155
Greg Clayton8b82f082011-04-12 05:54:46 +0000156 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000160 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000161
Greg Clayton8b82f082011-04-12 05:54:46 +0000162 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000166 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000167 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
168 }
169 else
170 {
Jason Molendafd54b362011-09-20 21:44:10 +0000171 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000172 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000173 (int)m_arch.GetTriple().getArchName().size(),
174 m_arch.GetTriple().getArchName().data());
175 }
176
Greg Clayton8b82f082011-04-12 05:54:46 +0000177 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000178 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000179 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-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 Clayton8b82f082011-04-12 05:54:46 +0000186 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000187 }
188 }
189 }
190 else
191 {
192 s.PutCString (GetName());
193 }
194
195 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000196 }
197}
198
Greg Clayton8b82f082011-04-12 05:54:46 +0000199
200void
Greg Clayton982c9762011-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 Clayton8b82f082011-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 Clayton982c9762011-11-03 21:22:33 +0000237 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Clayton8b82f082011-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 Clayton1d885962011-11-08 02:43:13 +0000254void
Greg Claytonee95ed52011-11-17 22:14:31 +0000255ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Clayton1d885962011-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 Clayton1d885962011-11-08 02:43:13 +0000261 if (m_flags.Test(eLaunchFlagDisableSTDIO))
262 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000263 AppendSuppressFileAction (STDIN_FILENO , true, false);
264 AppendSuppressFileAction (STDOUT_FILENO, false, true);
265 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Clayton1d885962011-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 Claytonee95ed52011-11-17 22:14:31 +0000273 const char *in_path = NULL;
274 const char *out_path = NULL;
275 const char *err_path = NULL;
Greg Clayton1d885962011-11-08 02:43:13 +0000276 if (target)
277 {
Greg Clayton9845a8d2012-03-06 04:01:04 +0000278 in_path = target->GetStandardInputPath();
279 out_path = target->GetStandardOutputPath();
280 err_path = target->GetStandardErrorPath();
Greg Claytonee95ed52011-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 Clayton1d885962011-11-08 02:43:13 +0000286 {
Greg Claytonee95ed52011-11-17 22:14:31 +0000287 in_path = out_path = err_path = m_pty.GetSlaveName (NULL, 0);
Greg Clayton1d885962011-11-08 02:43:13 +0000288 }
289 }
290
Greg Claytonee95ed52011-11-17 22:14:31 +0000291 if (in_path)
Greg Clayton9845a8d2012-03-06 04:01:04 +0000292 AppendOpenFileAction(STDIN_FILENO, in_path, true, false);
293
Greg Claytonee95ed52011-11-17 22:14:31 +0000294 if (out_path)
Greg Clayton9845a8d2012-03-06 04:01:04 +0000295 AppendOpenFileAction(STDOUT_FILENO, out_path, false, true);
Greg Claytonee95ed52011-11-17 22:14:31 +0000296
297 if (err_path)
Greg Clayton9845a8d2012-03-06 04:01:04 +0000298 AppendOpenFileAction(STDERR_FILENO, err_path, false, true);
299
Greg Clayton1d885962011-11-08 02:43:13 +0000300 }
301 }
302}
303
Greg Clayton144f3a92011-11-15 03:53:30 +0000304
305bool
Greg Claytond1cf11a2012-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 Clayton144f3a92011-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 Clayton144f3a92011-11-15 03:53:30 +0000340 shell_arguments.AppendArgument ("-c");
Greg Claytond1cf11a2012-04-14 01:42:46 +0000341
342 StreamString shell_command;
343 if (will_debug)
Greg Clayton144f3a92011-11-15 03:53:30 +0000344 {
Greg Claytond1cf11a2012-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 Clayton144f3a92011-11-15 03:53:30 +0000362 }
363
364 const char **argv = GetArguments().GetConstArgumentVector ();
365 if (argv)
366 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000367 if (first_arg_is_full_shell_command)
Greg Clayton144f3a92011-11-15 03:53:30 +0000368 {
Greg Claytond1cf11a2012-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 Clayton144f3a92011-11-15 03:53:30 +0000374 }
Greg Claytond1cf11a2012-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 Clayton144f3a92011-11-15 03:53:30 +0000384 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000385 else
386 {
387 return false;
388 }
389
Greg Clayton144f3a92011-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 Clayton32e0a752011-03-30 18:16:51 +0000407bool
Greg Clayton8b82f082011-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 Clayton144f3a92011-11-15 03:53:30 +0000415 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Clayton8b82f082011-04-12 05:54:46 +0000416 else if (read)
Greg Clayton144f3a92011-11-15 03:53:30 +0000417 m_arg = O_NOCTTY | O_RDONLY;
Greg Clayton8b82f082011-04-12 05:54:46 +0000418 else
Greg Clayton144f3a92011-11-15 03:53:30 +0000419 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Clayton8b82f082011-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 Clayton144f3a92011-11-15 03:53:30 +0000507
Greg Clayton8b82f082011-04-12 05:54:46 +0000508 mode_t mode = 0;
509
Greg Clayton144f3a92011-11-15 03:53:30 +0000510 if (oflag & O_CREAT)
511 mode = 0640;
512
Greg Clayton8b82f082011-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 Claytonf6b8b582011-04-13 00:18:08 +0000534ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-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 Clayton8b82f082011-04-12 05:54:46 +0000545 case 'i': // STDIN for read only
546 {
547 ProcessLaunchInfo::FileAction action;
Greg Clayton9845a8d2012-03-06 04:01:04 +0000548 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Clayton8b82f082011-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 Clayton9845a8d2012-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 Clayton8b82f082011-04-12 05:54:46 +0000565 launch_info.AppendFileAction (action);
566 }
567 break;
568
Greg Clayton9845a8d2012-03-06 04:01:04 +0000569
Greg Clayton8b82f082011-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 Clayton9845a8d2012-03-06 04:01:04 +0000577 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Clayton8b82f082011-04-12 05:54:46 +0000578 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000579 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-04-12 05:54:46 +0000580 launch_info.AppendFileAction (action);
Greg Clayton9845a8d2012-03-06 04:01:04 +0000581 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Clayton8b82f082011-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 Clayton70512312012-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 Clayton8b82f082011-04-12 05:54:46 +0000597 break;
598
599 case 'A':
600 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
601 break;
602
Greg Clayton982c9762011-11-03 21:22:33 +0000603 case 'c':
Greg Clayton144f3a92011-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 Clayton982c9762011-11-03 21:22:33 +0000608 break;
609
Greg Clayton8b82f082011-04-12 05:54:46 +0000610 case 'v':
611 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
612 break;
613
614 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000615 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-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 Clayton144f3a92011-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 Clayton8b82f082011-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 Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000659ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000672 if (m_match_info.UserIDIsValid () &&
673 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000674 return false;
675
Greg Clayton8b82f082011-04-12 05:54:46 +0000676 if (m_match_info.GroupIDIsValid () &&
677 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000695ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000706 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000707 return false;
708
Greg Clayton8b82f082011-04-12 05:54:46 +0000709 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-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 Clayton8b82f082011-04-12 05:54:46 +0000729ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-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 Clayton58be07b2011-01-07 06:08:19 +0000735
Greg Claytonc3776bf2012-02-09 06:16:32 +0000736ProcessSP
737Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738{
Greg Claytonc3776bf2012-02-09 06:16:32 +0000739 ProcessSP process_sp;
Chris Lattner30fdc8d2010-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 Claytonc3776bf2012-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 Lattner30fdc8d2010-06-08 16:52:24 +0000752 }
753 }
754 else
755 {
Greg Claytonc982c762010-07-09 20:39:50 +0000756 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000757 {
Greg Claytonc3776bf2012-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 Lattner30fdc8d2010-06-08 16:52:24 +0000766 }
767 }
Greg Claytonc3776bf2012-02-09 06:16:32 +0000768 return process_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000769}
770
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000771ConstString &
772Process::GetStaticBroadcasterClass ()
773{
774 static ConstString class_name ("lldb.process");
775 return class_name;
776}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000777
778//----------------------------------------------------------------------
779// Process constructor
780//----------------------------------------------------------------------
781Process::Process(Target &target, Listener &listener) :
782 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000783 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Greg Claytonb9556ac2012-01-30 07:41:31 +0000784 ProcessInstanceSettings (GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000786 m_public_state (eStateUnloaded),
787 m_private_state (eStateUnloaded),
Jim Ingham4bddaeb2012-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 Lattner30fdc8d2010-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 Ingham4b536182011-08-09 02:12:22 +0000793 m_mod_id (),
Chris Lattner30fdc8d2010-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 Clayton3af9ea52010-11-18 05:57:03 +0000799 m_image_tokens (),
800 m_listener (listener),
801 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000802 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000803 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000804 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000805 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000806 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000807 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000808 m_stdout_data (),
Greg Clayton93e86192011-11-13 04:45:22 +0000809 m_stderr_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000810 m_memory_cache (*this),
811 m_allocated_memory_cache (*this),
Greg Claytone24c4ac2011-11-17 04:46:02 +0000812 m_should_detach (false),
Sean Callanan90539452011-09-20 23:01:51 +0000813 m_next_event_action_ap(),
Bill Wendling7a4b0072012-04-06 00:10:21 +0000814 m_run_lock (),
815 m_can_jit(eCanJITDontKnow)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816{
Caroline Tice1559a462010-09-27 00:30:10 +0000817 UpdateInstanceName();
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000818
819 CheckInWithManager ();
Caroline Tice1559a462010-09-27 00:30:10 +0000820
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000821 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822 if (log)
823 log->Printf ("%p Process::Process()", this);
824
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000825 SetEventName (eBroadcastBitStateChanged, "state-changed");
826 SetEventName (eBroadcastBitInterrupt, "interrupt");
827 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
828 SetEventName (eBroadcastBitSTDERR, "stderr-available");
829
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830 listener.StartListeningForEvents (this,
831 eBroadcastBitStateChanged |
832 eBroadcastBitInterrupt |
833 eBroadcastBitSTDOUT |
834 eBroadcastBitSTDERR);
835
836 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
837 eBroadcastBitStateChanged);
838
839 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
840 eBroadcastInternalStateControlStop |
841 eBroadcastInternalStateControlPause |
842 eBroadcastInternalStateControlResume);
843}
844
845//----------------------------------------------------------------------
846// Destructor
847//----------------------------------------------------------------------
848Process::~Process()
849{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000850 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000851 if (log)
852 log->Printf ("%p Process::~Process()", this);
853 StopPrivateStateThread();
854}
855
856void
857Process::Finalize()
858{
Greg Claytone24c4ac2011-11-17 04:46:02 +0000859 switch (GetPrivateState())
860 {
861 case eStateConnected:
862 case eStateAttaching:
863 case eStateLaunching:
864 case eStateStopped:
865 case eStateRunning:
866 case eStateStepping:
867 case eStateCrashed:
868 case eStateSuspended:
869 if (GetShouldDetach())
870 Detach();
871 else
872 Destroy();
873 break;
874
875 case eStateInvalid:
876 case eStateUnloaded:
877 case eStateDetached:
878 case eStateExited:
879 break;
880 }
881
Greg Clayton1ed54f52011-10-01 00:45:15 +0000882 // Clear our broadcaster before we proceed with destroying
883 Broadcaster::Clear();
884
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000885 // Do any cleanup needed prior to being destructed... Subclasses
886 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000887
888 // We need to destroy the loader before the derived Process class gets destroyed
889 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton894f82f2012-01-20 23:08:34 +0000890 m_dynamic_checkers_ap.reset();
891 m_abi_sp.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000892 m_os_ap.reset();
Greg Clayton894f82f2012-01-20 23:08:34 +0000893 m_dyld_ap.reset();
Greg Claytone1cd1be2012-01-29 20:56:30 +0000894 m_thread_list.Destroy();
Greg Clayton894f82f2012-01-20 23:08:34 +0000895 std::vector<Notifications> empty_notifications;
896 m_notifications.swap(empty_notifications);
897 m_image_tokens.clear();
898 m_memory_cache.Clear();
899 m_allocated_memory_cache.Clear();
900 m_language_runtimes.clear();
901 m_next_event_action_ap.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000902}
903
904void
905Process::RegisterNotificationCallbacks (const Notifications& callbacks)
906{
907 m_notifications.push_back(callbacks);
908 if (callbacks.initialize != NULL)
909 callbacks.initialize (callbacks.baton, this);
910}
911
912bool
913Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
914{
915 std::vector<Notifications>::iterator pos, end = m_notifications.end();
916 for (pos = m_notifications.begin(); pos != end; ++pos)
917 {
918 if (pos->baton == callbacks.baton &&
919 pos->initialize == callbacks.initialize &&
920 pos->process_state_changed == callbacks.process_state_changed)
921 {
922 m_notifications.erase(pos);
923 return true;
924 }
925 }
926 return false;
927}
928
929void
930Process::SynchronouslyNotifyStateChanged (StateType state)
931{
932 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
933 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
934 {
935 if (notification_pos->process_state_changed)
936 notification_pos->process_state_changed (notification_pos->baton, this, state);
937 }
938}
939
940// FIXME: We need to do some work on events before the general Listener sees them.
941// For instance if we are continuing from a breakpoint, we need to ensure that we do
942// the little "insert real insn, step & stop" trick. But we can't do that when the
943// event is delivered by the broadcaster - since that is done on the thread that is
944// waiting for new events, so if we needed more than one event for our handling, we would
945// stall. So instead we do it when we fetch the event off of the queue.
946//
947
948StateType
949Process::GetNextEvent (EventSP &event_sp)
950{
951 StateType state = eStateInvalid;
952
953 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
954 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
955
956 return state;
957}
958
959
960StateType
961Process::WaitForProcessToStop (const TimeValue *timeout)
962{
Jim Ingham4b536182011-08-09 02:12:22 +0000963 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
964 // We have to actually check each event, and in the case of a stopped event check the restarted flag
965 // on the event.
966 EventSP event_sp;
967 StateType state = GetState();
968 // If we are exited or detached, we won't ever get back to any
969 // other valid state...
970 if (state == eStateDetached || state == eStateExited)
971 return state;
972
973 while (state != eStateInvalid)
974 {
975 state = WaitForStateChangedEvents (timeout, event_sp);
976 switch (state)
977 {
978 case eStateCrashed:
979 case eStateDetached:
980 case eStateExited:
981 case eStateUnloaded:
982 return state;
983 case eStateStopped:
984 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
985 continue;
986 else
987 return state;
988 default:
989 continue;
990 }
991 }
992 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993}
994
995
996StateType
997Process::WaitForState
998(
999 const TimeValue *timeout,
1000 const StateType *match_states, const uint32_t num_match_states
1001)
1002{
1003 EventSP event_sp;
1004 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +00001005 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006 while (state != eStateInvalid)
1007 {
Greg Clayton05faeb72010-10-07 04:19:01 +00001008 // If we are exited or detached, we won't ever get back to any
1009 // other valid state...
1010 if (state == eStateDetached || state == eStateExited)
1011 return state;
1012
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001013 state = WaitForStateChangedEvents (timeout, event_sp);
1014
1015 for (i=0; i<num_match_states; ++i)
1016 {
1017 if (match_states[i] == state)
1018 return state;
1019 }
1020 }
1021 return state;
1022}
1023
Jim Ingham30f9b212010-10-11 23:53:14 +00001024bool
1025Process::HijackProcessEvents (Listener *listener)
1026{
1027 if (listener != NULL)
1028 {
1029 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
1030 }
1031 else
1032 return false;
1033}
1034
1035void
1036Process::RestoreProcessEvents ()
1037{
1038 RestoreBroadcaster();
1039}
1040
Jim Ingham0f16e732011-02-08 05:20:59 +00001041bool
1042Process::HijackPrivateProcessEvents (Listener *listener)
1043{
1044 if (listener != NULL)
1045 {
1046 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
1047 }
1048 else
1049 return false;
1050}
1051
1052void
1053Process::RestorePrivateProcessEvents ()
1054{
1055 m_private_state_broadcaster.RestoreBroadcaster();
1056}
1057
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058StateType
1059Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1060{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001061 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062
1063 if (log)
1064 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1065
1066 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001067 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1068 this,
1069 eBroadcastBitStateChanged,
1070 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1072
1073 if (log)
1074 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1075 __FUNCTION__,
1076 timeout,
1077 StateAsCString(state));
1078 return state;
1079}
1080
1081Event *
1082Process::PeekAtStateChangedEvents ()
1083{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001084 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085
1086 if (log)
1087 log->Printf ("Process::%s...", __FUNCTION__);
1088
1089 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +00001090 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1091 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001092 if (log)
1093 {
1094 if (event_ptr)
1095 {
1096 log->Printf ("Process::%s (event_ptr) => %s",
1097 __FUNCTION__,
1098 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1099 }
1100 else
1101 {
1102 log->Printf ("Process::%s no events found",
1103 __FUNCTION__);
1104 }
1105 }
1106 return event_ptr;
1107}
1108
1109StateType
1110Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1111{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001112 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113
1114 if (log)
1115 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1116
1117 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001118 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1119 &m_private_state_broadcaster,
1120 eBroadcastBitStateChanged,
1121 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1123
1124 // This is a bit of a hack, but when we wait here we could very well return
1125 // to the command-line, and that could disable the log, which would render the
1126 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001127 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +00001128 {
1129 if (state == eStateInvalid)
1130 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1131 else
1132 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1133 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134 return state;
1135}
1136
1137bool
1138Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1139{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001140 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141
1142 if (log)
1143 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1144
1145 if (control_only)
1146 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1147 else
1148 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1149}
1150
1151bool
1152Process::IsRunning () const
1153{
1154 return StateIsRunningState (m_public_state.GetValue());
1155}
1156
1157int
1158Process::GetExitStatus ()
1159{
1160 if (m_public_state.GetValue() == eStateExited)
1161 return m_exit_status;
1162 return -1;
1163}
1164
Greg Clayton85851dd2010-12-04 00:10:17 +00001165
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166const char *
1167Process::GetExitDescription ()
1168{
1169 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1170 return m_exit_string.c_str();
1171 return NULL;
1172}
1173
Greg Clayton6779606a2011-01-22 23:43:18 +00001174bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175Process::SetExitStatus (int status, const char *cstr)
1176{
Greg Clayton414f5d32011-01-25 02:58:48 +00001177 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1178 if (log)
1179 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1180 status, status,
1181 cstr ? "\"" : "",
1182 cstr ? cstr : "NULL",
1183 cstr ? "\"" : "");
1184
Greg Clayton6779606a2011-01-22 23:43:18 +00001185 // We were already in the exited state
1186 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +00001187 {
Greg Clayton385d6032011-01-26 23:47:29 +00001188 if (log)
1189 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +00001190 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +00001191 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001192
1193 m_exit_status = status;
1194 if (cstr)
1195 m_exit_string = cstr;
1196 else
1197 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001198
Greg Clayton6779606a2011-01-22 23:43:18 +00001199 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +00001200
Greg Clayton6779606a2011-01-22 23:43:18 +00001201 SetPrivateState (eStateExited);
1202 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001203}
1204
1205// This static callback can be used to watch for local child processes on
1206// the current host. The the child process exits, the process will be
1207// found in the global target list (we want to be completely sure that the
1208// lldb_private::Process doesn't go away before we can deliver the signal.
1209bool
Greg Claytone4e45922011-11-16 05:37:56 +00001210Process::SetProcessExitStatus (void *callback_baton,
1211 lldb::pid_t pid,
1212 bool exited,
1213 int signo, // Zero for no signal
1214 int exit_status // Exit value of process if signal is zero
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001215)
1216{
Greg Claytone4e45922011-11-16 05:37:56 +00001217 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1218 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00001219 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Claytone4e45922011-11-16 05:37:56 +00001220 callback_baton,
1221 pid,
1222 exited,
1223 signo,
1224 exit_status);
1225
1226 if (exited)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001227 {
Greg Clayton66111032010-06-23 01:19:29 +00001228 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001229 if (target_sp)
1230 {
1231 ProcessSP process_sp (target_sp->GetProcessSP());
1232 if (process_sp)
1233 {
1234 const char *signal_cstr = NULL;
1235 if (signo)
1236 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1237
1238 process_sp->SetExitStatus (exit_status, signal_cstr);
1239 }
1240 }
1241 return true;
1242 }
1243 return false;
1244}
1245
1246
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001247void
1248Process::UpdateThreadListIfNeeded ()
1249{
1250 const uint32_t stop_id = GetStopID();
1251 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1252 {
Greg Clayton2637f822011-11-17 01:23:07 +00001253 const StateType state = GetPrivateState();
1254 if (StateIsStoppedState (state, true))
1255 {
1256 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytone24c4ac2011-11-17 04:46:02 +00001257 // m_thread_list does have its own mutex, but we need to
1258 // hold onto the mutex between the call to UpdateThreadList(...)
1259 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton2637f822011-11-17 01:23:07 +00001260 ThreadList new_thread_list(this);
1261 // Always update the thread list with the protocol specific
Greg Clayton9fc13552012-04-10 00:18:59 +00001262 // thread list, but only update if "true" is returned
1263 if (UpdateThreadList (m_thread_list, new_thread_list))
1264 {
1265 OperatingSystem *os = GetOperatingSystem ();
1266 if (os)
1267 os->UpdateThreadList (m_thread_list, new_thread_list);
1268 m_thread_list.Update (new_thread_list);
1269 m_thread_list.SetStopID (stop_id);
1270 }
Greg Clayton2637f822011-11-17 01:23:07 +00001271 }
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001272 }
1273}
1274
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001275uint32_t
1276Process::GetNextThreadIndexID ()
1277{
1278 return ++m_thread_index_id;
1279}
1280
1281StateType
1282Process::GetState()
1283{
1284 // If any other threads access this we will need a mutex for it
1285 return m_public_state.GetValue ();
1286}
1287
1288void
1289Process::SetPublicState (StateType new_state)
1290{
Greg Clayton414f5d32011-01-25 02:58:48 +00001291 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001292 if (log)
1293 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001294 const StateType old_state = m_public_state.GetValue();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001295 m_public_state.SetValue (new_state);
Jim Ingham3b8285d2012-04-19 01:40:33 +00001296
1297 // On the transition from Run to Stopped, we unlock the writer end of the
1298 // run lock. The lock gets locked in Resume, which is the public API
1299 // to tell the program to run.
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001300 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1301 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001302 if (new_state == eStateDetached)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001303 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001304 if (log)
1305 log->Printf("Process::SetPublicState (%s) -- unlocking run lock for detach", StateAsCString(new_state));
1306 m_run_lock.WriteUnlock();
1307 }
1308 else
1309 {
1310 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1311 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1312 if (old_state_is_stopped != new_state_is_stopped)
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001313 {
Sean Callanan8b0737f2012-06-02 01:16:20 +00001314 if (new_state_is_stopped)
1315 {
1316 if (log)
1317 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1318 m_run_lock.WriteUnlock();
1319 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001320 }
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001321 }
1322 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001323}
1324
Jim Ingham3b8285d2012-04-19 01:40:33 +00001325Error
1326Process::Resume ()
1327{
1328 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1329 if (log)
1330 log->Printf("Process::Resume -- locking run lock");
1331 if (!m_run_lock.WriteTryLock())
1332 {
1333 Error error("Resume request failed - process still running.");
1334 if (log)
1335 log->Printf ("Process::Resume: -- WriteTryLock failed, not resuming.");
1336 return error;
1337 }
1338 return PrivateResume();
1339}
1340
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001341StateType
1342Process::GetPrivateState ()
1343{
1344 return m_private_state.GetValue();
1345}
1346
1347void
1348Process::SetPrivateState (StateType new_state)
1349{
Greg Clayton414f5d32011-01-25 02:58:48 +00001350 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001351 bool state_changed = false;
1352
1353 if (log)
1354 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1355
1356 Mutex::Locker locker(m_private_state.GetMutex());
1357
1358 const StateType old_state = m_private_state.GetValueNoLock ();
1359 state_changed = old_state != new_state;
Greg Clayton7fdf9ef2012-04-05 16:12:35 +00001360 // This code is left commented out in case we ever need to control
1361 // the private process state with another run lock. Right now it doesn't
1362 // seem like we need to do this, but if we ever do, we can uncomment and
1363 // use this code.
1364// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1365// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1366// if (old_state_is_stopped != new_state_is_stopped)
1367// {
1368// if (new_state_is_stopped)
1369// m_private_run_lock.WriteUnlock();
1370// else
1371// m_private_run_lock.WriteLock();
1372// }
1373
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001374 if (state_changed)
1375 {
1376 m_private_state.SetValueNoLock (new_state);
Greg Clayton2637f822011-11-17 01:23:07 +00001377 if (StateIsStoppedState(new_state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001378 {
Jim Ingham4b536182011-08-09 02:12:22 +00001379 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001380 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001381 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001382 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001383 }
1384 // Use our target to get a shared pointer to ourselves...
1385 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1386 }
1387 else
1388 {
1389 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001390 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001391 }
1392}
1393
Jim Ingham0faa43f2011-11-08 03:00:11 +00001394void
1395Process::SetRunningUserExpression (bool on)
1396{
1397 m_mod_id.SetRunningUserExpression (on);
1398}
1399
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400addr_t
1401Process::GetImageInfoAddress()
1402{
1403 return LLDB_INVALID_ADDRESS;
1404}
1405
Greg Clayton8f343b02010-11-04 01:54:29 +00001406//----------------------------------------------------------------------
1407// LoadImage
1408//
1409// This function provides a default implementation that works for most
1410// unix variants. Any Process subclasses that need to do shared library
1411// loading differently should override LoadImage and UnloadImage and
1412// do what is needed.
1413//----------------------------------------------------------------------
1414uint32_t
1415Process::LoadImage (const FileSpec &image_spec, Error &error)
1416{
Greg Claytonac7a3db2012-04-18 00:05:19 +00001417 char path[PATH_MAX];
1418 image_spec.GetPath(path, sizeof(path));
1419
Greg Clayton8f343b02010-11-04 01:54:29 +00001420 DynamicLoader *loader = GetDynamicLoader();
1421 if (loader)
1422 {
1423 error = loader->CanLoadImage();
1424 if (error.Fail())
1425 return LLDB_INVALID_IMAGE_TOKEN;
1426 }
1427
1428 if (error.Success())
1429 {
1430 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001431
1432 if (thread_sp)
1433 {
1434 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1435
1436 if (frame_sp)
1437 {
1438 ExecutionContext exe_ctx;
1439 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001440 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001441 StreamString expr;
Greg Clayton8f343b02010-11-04 01:54:29 +00001442 expr.Printf("dlopen (\"%s\", 2)", path);
1443 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001444 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001445 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chene92aa432011-09-09 00:01:43 +00001446 error = result_valobj_sp->GetError();
1447 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001448 {
1449 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001450 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001451 {
1452 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1453 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1454 {
1455 uint32_t image_token = m_image_tokens.size();
1456 m_image_tokens.push_back (image_ptr);
1457 return image_token;
1458 }
1459 }
1460 }
1461 }
1462 }
1463 }
Greg Claytonac7a3db2012-04-18 00:05:19 +00001464 if (!error.AsCString())
1465 error.SetErrorStringWithFormat("unable to load '%s'", path);
Greg Clayton8f343b02010-11-04 01:54:29 +00001466 return LLDB_INVALID_IMAGE_TOKEN;
1467}
1468
1469//----------------------------------------------------------------------
1470// UnloadImage
1471//
1472// This function provides a default implementation that works for most
1473// unix variants. Any Process subclasses that need to do shared library
1474// loading differently should override LoadImage and UnloadImage and
1475// do what is needed.
1476//----------------------------------------------------------------------
1477Error
1478Process::UnloadImage (uint32_t image_token)
1479{
1480 Error error;
1481 if (image_token < m_image_tokens.size())
1482 {
1483 const addr_t image_addr = m_image_tokens[image_token];
1484 if (image_addr == LLDB_INVALID_ADDRESS)
1485 {
1486 error.SetErrorString("image already unloaded");
1487 }
1488 else
1489 {
1490 DynamicLoader *loader = GetDynamicLoader();
1491 if (loader)
1492 error = loader->CanLoadImage();
1493
1494 if (error.Success())
1495 {
1496 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001497
1498 if (thread_sp)
1499 {
1500 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1501
1502 if (frame_sp)
1503 {
1504 ExecutionContext exe_ctx;
1505 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001506 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001507 StreamString expr;
1508 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1509 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001510 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan20bb3aa2011-12-21 22:22:58 +00001511 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +00001512 if (result_valobj_sp->GetError().Success())
1513 {
1514 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001515 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001516 {
1517 if (scalar.UInt(1))
1518 {
1519 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1520 }
1521 else
1522 {
1523 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1524 }
1525 }
1526 }
1527 else
1528 {
1529 error = result_valobj_sp->GetError();
1530 }
1531 }
1532 }
1533 }
1534 }
1535 }
1536 else
1537 {
1538 error.SetErrorString("invalid image token");
1539 }
1540 return error;
1541}
1542
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001543const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001544Process::GetABI()
1545{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001546 if (!m_abi_sp)
1547 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1548 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001549}
1550
Jim Ingham22777012010-09-23 02:01:19 +00001551LanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001552Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001553{
1554 LanguageRuntimeCollection::iterator pos;
1555 pos = m_language_runtimes.find (language);
Jim Inghamab175242012-03-10 00:22:19 +00001556 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham22777012010-09-23 02:01:19 +00001557 {
Jim Inghamab175242012-03-10 00:22:19 +00001558 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham22777012010-09-23 02:01:19 +00001559
Jim Inghamab175242012-03-10 00:22:19 +00001560 m_language_runtimes[language] = runtime_sp;
1561 return runtime_sp.get();
Jim Ingham22777012010-09-23 02:01:19 +00001562 }
1563 else
1564 return (*pos).second.get();
1565}
1566
1567CPPLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001568Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001569{
Jim Inghamab175242012-03-10 00:22:19 +00001570 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001571 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1572 return static_cast<CPPLanguageRuntime *> (runtime);
1573 return NULL;
1574}
1575
1576ObjCLanguageRuntime *
Jim Inghamab175242012-03-10 00:22:19 +00001577Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham22777012010-09-23 02:01:19 +00001578{
Jim Inghamab175242012-03-10 00:22:19 +00001579 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham22777012010-09-23 02:01:19 +00001580 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1581 return static_cast<ObjCLanguageRuntime *> (runtime);
1582 return NULL;
1583}
1584
Enrico Granatafd4c84e2012-05-21 16:51:35 +00001585bool
1586Process::IsPossibleDynamicValue (ValueObject& in_value)
1587{
1588 if (in_value.IsDynamic())
1589 return false;
1590 LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1591
1592 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC)
1593 {
1594 LanguageRuntime *runtime = GetLanguageRuntime (known_type);
1595 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1596 }
1597
1598 LanguageRuntime *cpp_runtime = GetLanguageRuntime (eLanguageTypeC_plus_plus);
1599 if (cpp_runtime && cpp_runtime->CouldHaveDynamicValue(in_value))
1600 return true;
1601
1602 LanguageRuntime *objc_runtime = GetLanguageRuntime (eLanguageTypeObjC);
1603 return objc_runtime ? objc_runtime->CouldHaveDynamicValue(in_value) : false;
1604}
1605
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001606BreakpointSiteList &
1607Process::GetBreakpointSiteList()
1608{
1609 return m_breakpoint_site_list;
1610}
1611
1612const BreakpointSiteList &
1613Process::GetBreakpointSiteList() const
1614{
1615 return m_breakpoint_site_list;
1616}
1617
1618
1619void
1620Process::DisableAllBreakpointSites ()
1621{
1622 m_breakpoint_site_list.SetEnabledForAll (false);
1623}
1624
1625Error
1626Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1627{
1628 Error error (DisableBreakpointSiteByID (break_id));
1629
1630 if (error.Success())
1631 m_breakpoint_site_list.Remove(break_id);
1632
1633 return error;
1634}
1635
1636Error
1637Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1638{
1639 Error error;
1640 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1641 if (bp_site_sp)
1642 {
1643 if (bp_site_sp->IsEnabled())
1644 error = DisableBreakpoint (bp_site_sp.get());
1645 }
1646 else
1647 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001648 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001649 }
1650
1651 return error;
1652}
1653
1654Error
1655Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1656{
1657 Error error;
1658 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1659 if (bp_site_sp)
1660 {
1661 if (!bp_site_sp->IsEnabled())
1662 error = EnableBreakpoint (bp_site_sp.get());
1663 }
1664 else
1665 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001666 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001667 }
1668 return error;
1669}
1670
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001671lldb::break_id_t
Greg Claytone1cd1be2012-01-29 20:56:30 +00001672Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001673{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001674 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001675 if (load_addr != LLDB_INVALID_ADDRESS)
1676 {
1677 BreakpointSiteSP bp_site_sp;
1678
1679 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1680 // create a new breakpoint site and add it.
1681
1682 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1683
1684 if (bp_site_sp)
1685 {
1686 bp_site_sp->AddOwner (owner);
1687 owner->SetBreakpointSite (bp_site_sp);
1688 return bp_site_sp->GetID();
1689 }
1690 else
1691 {
1692 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1693 if (bp_site_sp)
1694 {
1695 if (EnableBreakpoint (bp_site_sp.get()).Success())
1696 {
1697 owner->SetBreakpointSite (bp_site_sp);
1698 return m_breakpoint_site_list.Add (bp_site_sp);
1699 }
1700 }
1701 }
1702 }
1703 // We failed to enable the breakpoint
1704 return LLDB_INVALID_BREAK_ID;
1705
1706}
1707
1708void
1709Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1710{
1711 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1712 if (num_owners == 0)
1713 {
1714 DisableBreakpoint(bp_site_sp.get());
1715 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1716 }
1717}
1718
1719
1720size_t
1721Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1722{
1723 size_t bytes_removed = 0;
1724 addr_t intersect_addr;
1725 size_t intersect_size;
1726 size_t opcode_offset;
1727 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001728 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001729 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001730
Jim Ingham20c77192011-06-29 19:42:28 +00001731 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001732 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001733 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001734 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001735 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001736 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001737 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001738 {
1739 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1740 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001741 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001742 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001743 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001744 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001745 }
1746 }
1747 }
1748 return bytes_removed;
1749}
1750
1751
Greg Claytonded470d2011-03-19 01:12:21 +00001752
1753size_t
1754Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1755{
1756 PlatformSP platform_sp (m_target.GetPlatform());
1757 if (platform_sp)
1758 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1759 return 0;
1760}
1761
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001762Error
1763Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1764{
1765 Error error;
1766 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001767 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001768 const addr_t bp_addr = bp_site->GetLoadAddress();
1769 if (log)
1770 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1771 if (bp_site->IsEnabled())
1772 {
1773 if (log)
1774 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1775 return error;
1776 }
1777
1778 if (bp_addr == LLDB_INVALID_ADDRESS)
1779 {
1780 error.SetErrorString("BreakpointSite contains an invalid load address.");
1781 return error;
1782 }
1783 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1784 // trap for the breakpoint site
1785 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1786
1787 if (bp_opcode_size == 0)
1788 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001789 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001790 }
1791 else
1792 {
1793 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1794
1795 if (bp_opcode_bytes == NULL)
1796 {
1797 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1798 return error;
1799 }
1800
1801 // Save the original opcode by reading it
1802 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1803 {
1804 // Write a software breakpoint in place of the original opcode
1805 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1806 {
1807 uint8_t verify_bp_opcode_bytes[64];
1808 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1809 {
1810 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1811 {
1812 bp_site->SetEnabled(true);
1813 bp_site->SetType (BreakpointSite::eSoftware);
1814 if (log)
1815 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1816 bp_site->GetID(),
1817 (uint64_t)bp_addr);
1818 }
1819 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001820 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001821 }
1822 else
1823 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1824 }
1825 else
1826 error.SetErrorString("Unable to write breakpoint trap to memory.");
1827 }
1828 else
1829 error.SetErrorString("Unable to read memory at breakpoint address.");
1830 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001831 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001832 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1833 bp_site->GetID(),
1834 (uint64_t)bp_addr,
1835 error.AsCString());
1836 return error;
1837}
1838
1839Error
1840Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1841{
1842 Error error;
1843 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001844 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001845 addr_t bp_addr = bp_site->GetLoadAddress();
1846 lldb::user_id_t breakID = bp_site->GetID();
1847 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001848 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001849
1850 if (bp_site->IsHardware())
1851 {
1852 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1853 }
1854 else if (bp_site->IsEnabled())
1855 {
1856 const size_t break_op_size = bp_site->GetByteSize();
1857 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1858 if (break_op_size > 0)
1859 {
1860 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001861 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001862 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001863 bool break_op_found = false;
1864
1865 // Read the breakpoint opcode
1866 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1867 {
1868 bool verify = false;
1869 // Make sure we have the a breakpoint opcode exists at this address
1870 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1871 {
1872 break_op_found = true;
1873 // We found a valid breakpoint opcode at this address, now restore
1874 // the saved opcode.
1875 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1876 {
1877 verify = true;
1878 }
1879 else
1880 error.SetErrorString("Memory write failed when restoring original opcode.");
1881 }
1882 else
1883 {
1884 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1885 // Set verify to true and so we can check if the original opcode has already been restored
1886 verify = true;
1887 }
1888
1889 if (verify)
1890 {
Greg Claytonc982c762010-07-09 20:39:50 +00001891 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001892 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001893 // Verify that our original opcode made it back to the inferior
1894 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1895 {
1896 // compare the memory we just read with the original opcode
1897 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1898 {
1899 // SUCCESS
1900 bp_site->SetEnabled(false);
1901 if (log)
1902 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1903 return error;
1904 }
1905 else
1906 {
1907 if (break_op_found)
1908 error.SetErrorString("Failed to restore original opcode.");
1909 }
1910 }
1911 else
1912 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1913 }
1914 }
1915 else
1916 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1917 }
1918 }
1919 else
1920 {
1921 if (log)
1922 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1923 return error;
1924 }
1925
1926 if (log)
1927 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1928 bp_site->GetID(),
1929 (uint64_t)bp_addr,
1930 error.AsCString());
1931 return error;
1932
1933}
1934
Greg Clayton58be07b2011-01-07 06:08:19 +00001935// Comment out line below to disable memory caching
1936#define ENABLE_MEMORY_CACHING
1937// Uncomment to verify memory caching works after making changes to caching code
1938//#define VERIFY_MEMORY_READS
1939
1940#if defined (ENABLE_MEMORY_CACHING)
1941
1942#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001943
1944size_t
1945Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1946{
Greg Clayton58be07b2011-01-07 06:08:19 +00001947 // Memory caching is enabled, with debug verification
1948 if (buf && size)
1949 {
1950 // Uncomment the line below to make sure memory caching is working.
1951 // I ran this through the test suite and got no assertions, so I am
1952 // pretty confident this is working well. If any changes are made to
1953 // memory caching, uncomment the line below and test your changes!
1954
1955 // Verify all memory reads by using the cache first, then redundantly
1956 // reading the same memory from the inferior and comparing to make sure
1957 // everything is exactly the same.
1958 std::string verify_buf (size, '\0');
1959 assert (verify_buf.size() == size);
1960 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1961 Error verify_error;
1962 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1963 assert (cache_bytes_read == verify_bytes_read);
1964 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1965 assert (verify_error.Success() == error.Success());
1966 return cache_bytes_read;
1967 }
1968 return 0;
1969}
1970
1971#else // #if defined (VERIFY_MEMORY_READS)
1972
1973size_t
1974Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1975{
1976 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001977 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001978}
1979
1980#endif // #else for #if defined (VERIFY_MEMORY_READS)
1981
1982#else // #if defined (ENABLE_MEMORY_CACHING)
1983
1984size_t
1985Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1986{
1987 // Memory caching is disabled
1988 return ReadMemoryFromInferior (addr, buf, size, error);
1989}
1990
1991#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1992
Greg Clayton4c82d422012-05-18 23:20:01 +00001993size_t
1994Process::ReadCStringFromMemory (addr_t addr, std::string &out_str, Error &error)
1995{
Greg Claytonde87c0f2012-05-19 00:18:00 +00001996 char buf[256];
Greg Clayton4c82d422012-05-18 23:20:01 +00001997 out_str.clear();
1998 addr_t curr_addr = addr;
1999 while (1)
2000 {
2001 size_t length = ReadCStringFromMemory (curr_addr, buf, sizeof(buf), error);
2002 if (length == 0)
2003 break;
2004 out_str.append(buf, length);
2005 // If we got "length - 1" bytes, we didn't get the whole C string, we
2006 // need to read some more characters
2007 if (length == sizeof(buf) - 1)
2008 curr_addr += length;
2009 else
2010 break;
2011 }
2012 return out_str.size();
2013}
2014
Greg Clayton58be07b2011-01-07 06:08:19 +00002015
2016size_t
Greg Claytone91b7952011-12-15 03:14:23 +00002017Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Clayton8b82f082011-04-12 05:54:46 +00002018{
2019 size_t total_cstr_len = 0;
2020 if (dst && dst_max_len)
2021 {
Greg Claytone91b7952011-12-15 03:14:23 +00002022 result_error.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00002023 // NULL out everything just to be safe
2024 memset (dst, 0, dst_max_len);
2025 Error error;
2026 addr_t curr_addr = addr;
2027 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2028 size_t bytes_left = dst_max_len - 1;
2029 char *curr_dst = dst;
2030
2031 while (bytes_left > 0)
2032 {
2033 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
2034 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
2035 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
2036
2037 if (bytes_read == 0)
2038 {
Greg Claytone91b7952011-12-15 03:14:23 +00002039 result_error = error;
Greg Clayton8b82f082011-04-12 05:54:46 +00002040 dst[total_cstr_len] = '\0';
2041 break;
2042 }
2043 const size_t len = strlen(curr_dst);
2044
2045 total_cstr_len += len;
2046
2047 if (len < bytes_to_read)
2048 break;
2049
2050 curr_dst += bytes_read;
2051 curr_addr += bytes_read;
2052 bytes_left -= bytes_read;
2053 }
2054 }
Greg Claytone91b7952011-12-15 03:14:23 +00002055 else
2056 {
2057 if (dst == NULL)
2058 result_error.SetErrorString("invalid arguments");
2059 else
2060 result_error.Clear();
2061 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002062 return total_cstr_len;
2063}
2064
2065size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00002066Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
2067{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002068 if (buf == NULL || size == 0)
2069 return 0;
2070
2071 size_t bytes_read = 0;
2072 uint8_t *bytes = (uint8_t *)buf;
2073
2074 while (bytes_read < size)
2075 {
2076 const size_t curr_size = size - bytes_read;
2077 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
2078 bytes + bytes_read,
2079 curr_size,
2080 error);
2081 bytes_read += curr_bytes_read;
2082 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2083 break;
2084 }
2085
2086 // Replace any software breakpoint opcodes that fall into this range back
2087 // into "buf" before we return
2088 if (bytes_read > 0)
2089 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
2090 return bytes_read;
2091}
2092
Greg Clayton58a4c462010-12-16 20:01:20 +00002093uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002094Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00002095{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002096 Scalar scalar;
2097 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2098 return scalar.ULongLong(fail_value);
2099 return fail_value;
2100}
2101
2102addr_t
2103Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2104{
2105 Scalar scalar;
2106 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2107 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2108 return LLDB_INVALID_ADDRESS;
2109}
2110
2111
2112bool
2113Process::WritePointerToMemory (lldb::addr_t vm_addr,
2114 lldb::addr_t ptr_value,
2115 Error &error)
2116{
2117 Scalar scalar;
2118 const uint32_t addr_byte_size = GetAddressByteSize();
2119 if (addr_byte_size <= 4)
2120 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00002121 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002122 scalar = ptr_value;
2123 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00002124}
2125
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126size_t
2127Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2128{
2129 size_t bytes_written = 0;
2130 const uint8_t *bytes = (const uint8_t *)buf;
2131
2132 while (bytes_written < size)
2133 {
2134 const size_t curr_size = size - bytes_written;
2135 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2136 bytes + bytes_written,
2137 curr_size,
2138 error);
2139 bytes_written += curr_bytes_written;
2140 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2141 break;
2142 }
2143 return bytes_written;
2144}
2145
2146size_t
2147Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2148{
Greg Clayton58be07b2011-01-07 06:08:19 +00002149#if defined (ENABLE_MEMORY_CACHING)
2150 m_memory_cache.Flush (addr, size);
2151#endif
2152
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002153 if (buf == NULL || size == 0)
2154 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00002155
Jim Ingham4b536182011-08-09 02:12:22 +00002156 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00002157
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002158 // We need to write any data that would go where any current software traps
2159 // (enabled software breakpoints) any software traps (breakpoints) that we
2160 // may have placed in our tasks memory.
2161
2162 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2163 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2164
2165 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00002166 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002167
2168 BreakpointSiteList::collection::const_iterator pos;
2169 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00002170 addr_t intersect_addr = 0;
2171 size_t intersect_size = 0;
2172 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002173 const uint8_t *ubuf = (const uint8_t *)buf;
2174
2175 for (pos = iter; pos != end; ++pos)
2176 {
2177 BreakpointSiteSP bp;
2178 bp = pos->second;
2179
2180 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2181 assert(addr <= intersect_addr && intersect_addr < addr + size);
2182 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2183 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2184
2185 // Check for bytes before this breakpoint
2186 const addr_t curr_addr = addr + bytes_written;
2187 if (intersect_addr > curr_addr)
2188 {
2189 // There are some bytes before this breakpoint that we need to
2190 // just write to memory
2191 size_t curr_size = intersect_addr - curr_addr;
2192 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2193 ubuf + bytes_written,
2194 curr_size,
2195 error);
2196 bytes_written += curr_bytes_written;
2197 if (curr_bytes_written != curr_size)
2198 {
2199 // We weren't able to write all of the requested bytes, we
2200 // are done looping and will return the number of bytes that
2201 // we have written so far.
2202 break;
2203 }
2204 }
2205
2206 // Now write any bytes that would cover up any software breakpoints
2207 // directly into the breakpoint opcode buffer
2208 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2209 bytes_written += intersect_size;
2210 }
2211
2212 // Write any remaining bytes after the last breakpoint if we have any left
2213 if (bytes_written < size)
2214 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2215 ubuf + bytes_written,
2216 size - bytes_written,
2217 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00002218
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002219 return bytes_written;
2220}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00002221
2222size_t
2223Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2224{
2225 if (byte_size == UINT32_MAX)
2226 byte_size = scalar.GetByteSize();
2227 if (byte_size > 0)
2228 {
2229 uint8_t buf[32];
2230 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2231 if (mem_size > 0)
2232 return WriteMemory(addr, buf, mem_size, error);
2233 else
2234 error.SetErrorString ("failed to get scalar as memory data");
2235 }
2236 else
2237 {
2238 error.SetErrorString ("invalid scalar value");
2239 }
2240 return 0;
2241}
2242
2243size_t
2244Process::ReadScalarIntegerFromMemory (addr_t addr,
2245 uint32_t byte_size,
2246 bool is_signed,
2247 Scalar &scalar,
2248 Error &error)
2249{
2250 uint64_t uval;
2251
2252 if (byte_size <= sizeof(uval))
2253 {
2254 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2255 if (bytes_read == byte_size)
2256 {
2257 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2258 uint32_t offset = 0;
2259 if (byte_size <= 4)
2260 scalar = data.GetMaxU32 (&offset, byte_size);
2261 else
2262 scalar = data.GetMaxU64 (&offset, byte_size);
2263
2264 if (is_signed)
2265 scalar.SignExtend(byte_size * 8);
2266 return bytes_read;
2267 }
2268 }
2269 else
2270 {
2271 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2272 }
2273 return 0;
2274}
2275
Greg Claytond495c532011-05-17 03:37:42 +00002276#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002277addr_t
2278Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2279{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00002280 if (GetPrivateState() != eStateStopped)
2281 return LLDB_INVALID_ADDRESS;
2282
Greg Claytond495c532011-05-17 03:37:42 +00002283#if defined (USE_ALLOCATE_MEMORY_CACHE)
2284 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2285#else
Greg Claytonb2daec92011-01-23 19:58:49 +00002286 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2287 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2288 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002289 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002290 size,
Greg Claytond495c532011-05-17 03:37:42 +00002291 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00002292 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00002293 m_mod_id.GetStopID(),
2294 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00002295 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00002296#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002297}
2298
Sean Callanan90539452011-09-20 23:01:51 +00002299bool
2300Process::CanJIT ()
2301{
Sean Callanana7b443a2012-02-14 22:50:38 +00002302 if (m_can_jit == eCanJITDontKnow)
2303 {
2304 Error err;
2305
2306 uint64_t allocated_memory = AllocateMemory(8,
2307 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2308 err);
2309
2310 if (err.Success())
2311 m_can_jit = eCanJITYes;
2312 else
2313 m_can_jit = eCanJITNo;
2314
2315 DeallocateMemory (allocated_memory);
2316 }
2317
Sean Callanan90539452011-09-20 23:01:51 +00002318 return m_can_jit == eCanJITYes;
2319}
2320
2321void
2322Process::SetCanJIT (bool can_jit)
2323{
2324 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2325}
2326
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002327Error
2328Process::DeallocateMemory (addr_t ptr)
2329{
Greg Claytond495c532011-05-17 03:37:42 +00002330 Error error;
2331#if defined (USE_ALLOCATE_MEMORY_CACHE)
2332 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2333 {
2334 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2335 }
2336#else
2337 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00002338
2339 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2340 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00002341 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00002342 ptr,
2343 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00002344 m_mod_id.GetStopID(),
2345 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00002346#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00002347 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002348}
2349
Greg Claytonc9660542012-02-05 02:38:54 +00002350ModuleSP
Greg Claytonc859e2d2012-02-13 23:10:39 +00002351Process::ReadModuleFromMemory (const FileSpec& file_spec,
2352 lldb::addr_t header_addr,
2353 bool add_image_to_target,
2354 bool load_sections_in_target)
Greg Claytonc9660542012-02-05 02:38:54 +00002355{
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002356 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonc9660542012-02-05 02:38:54 +00002357 if (module_sp)
2358 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002359 Error error;
2360 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2361 if (objfile)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002362 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002363 if (add_image_to_target)
Greg Claytonc859e2d2012-02-13 23:10:39 +00002364 {
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002365 m_target.GetImages().Append(module_sp);
2366 if (load_sections_in_target)
2367 {
2368 bool changed = false;
2369 module_sp->SetLoadAddress (m_target, 0, changed);
2370 }
Greg Claytonc859e2d2012-02-13 23:10:39 +00002371 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002372 return module_sp;
Greg Claytonc859e2d2012-02-13 23:10:39 +00002373 }
Greg Claytonc9660542012-02-05 02:38:54 +00002374 }
Greg Claytonc7f09cc2012-02-24 21:55:59 +00002375 return ModuleSP();
Greg Claytonc9660542012-02-05 02:38:54 +00002376}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002377
2378Error
Johnny Chen01a67862011-10-14 00:42:25 +00002379Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002380{
2381 Error error;
2382 error.SetErrorString("watchpoints are not supported");
2383 return error;
2384}
2385
2386Error
Johnny Chen01a67862011-10-14 00:42:25 +00002387Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002388{
2389 Error error;
2390 error.SetErrorString("watchpoints are not supported");
2391 return error;
2392}
2393
2394StateType
2395Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2396{
2397 StateType state;
2398 // Now wait for the process to launch and return control to us, and then
2399 // call DidLaunch:
2400 while (1)
2401 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002402 event_sp.reset();
2403 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2404
Greg Clayton2637f822011-11-17 01:23:07 +00002405 if (StateIsStoppedState(state, false))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002407
2408 // If state is invalid, then we timed out
2409 if (state == eStateInvalid)
2410 break;
2411
2412 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002413 HandlePrivateEvent (event_sp);
2414 }
2415 return state;
2416}
2417
2418Error
Greg Clayton982c9762011-11-03 21:22:33 +00002419Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002420{
2421 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002422 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002423 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002424 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002425 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002426
Greg Claytonaa149cb2011-08-11 02:48:45 +00002427 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 if (exe_module)
2429 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002430 char local_exec_file_path[PATH_MAX];
2431 char platform_exec_file_path[PATH_MAX];
2432 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2433 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434 if (exe_module->GetFileSpec().Exists())
2435 {
Greg Clayton71337622011-02-24 22:24:29 +00002436 if (PrivateStateThreadIsValid ())
2437 PausePrivateStateThread ();
2438
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002439 error = WillLaunch (exe_module);
2440 if (error.Success())
2441 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002442 SetPublicState (eStateLaunching);
Greg Claytone24c4ac2011-11-17 04:46:02 +00002443 m_should_detach = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002444
2445 // Now launch using these arguments.
Greg Clayton982c9762011-11-03 21:22:33 +00002446 error = DoLaunch (exe_module, launch_info);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002447
2448 if (error.Fail())
2449 {
2450 if (GetID() != LLDB_INVALID_PROCESS_ID)
2451 {
2452 SetID (LLDB_INVALID_PROCESS_ID);
2453 const char *error_string = error.AsCString();
2454 if (error_string == NULL)
2455 error_string = "launch failed";
2456 SetExitStatus (-1, error_string);
2457 }
2458 }
2459 else
2460 {
2461 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002462 TimeValue timeout_time;
2463 timeout_time = TimeValue::Now();
2464 timeout_time.OffsetWithSeconds(10);
2465 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002466
Greg Clayton1a38ea72011-06-22 01:42:17 +00002467 if (state == eStateInvalid || event_sp.get() == NULL)
2468 {
2469 // We were able to launch the process, but we failed to
2470 // catch the initial stop.
2471 SetExitStatus (0, "failed to catch stop after launch");
2472 Destroy();
2473 }
2474 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002475 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002476
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002477 DidLaunch ();
2478
Greg Claytonc859e2d2012-02-13 23:10:39 +00002479 DynamicLoader *dyld = GetDynamicLoader ();
2480 if (dyld)
2481 dyld->DidLaunch();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002482
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002483 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002484 // This delays passing the stopped event to listeners till DidLaunch gets
2485 // a chance to complete...
2486 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002487
2488 if (PrivateStateThreadIsValid ())
2489 ResumePrivateStateThread ();
2490 else
2491 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002492 }
2493 else if (state == eStateExited)
2494 {
2495 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2496 // not likely to work, and return an invalid pid.
2497 HandlePrivateEvent (event_sp);
2498 }
2499 }
2500 }
2501 }
2502 else
2503 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002504 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002505 }
2506 }
2507 return error;
2508}
2509
Greg Claytonc3776bf2012-02-09 06:16:32 +00002510
2511Error
2512Process::LoadCore ()
2513{
2514 Error error = DoLoadCore();
2515 if (error.Success())
2516 {
2517 if (PrivateStateThreadIsValid ())
2518 ResumePrivateStateThread ();
2519 else
2520 StartPrivateStateThread ();
2521
Greg Claytonc859e2d2012-02-13 23:10:39 +00002522 DynamicLoader *dyld = GetDynamicLoader ();
2523 if (dyld)
2524 dyld->DidAttach();
2525
2526 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Claytonc3776bf2012-02-09 06:16:32 +00002527 // We successfully loaded a core file, now pretend we stopped so we can
2528 // show all of the threads in the core file and explore the crashed
2529 // state.
2530 SetPrivateState (eStateStopped);
2531
2532 }
2533 return error;
2534}
2535
Greg Claytonc859e2d2012-02-13 23:10:39 +00002536DynamicLoader *
2537Process::GetDynamicLoader ()
2538{
2539 if (m_dyld_ap.get() == NULL)
2540 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2541 return m_dyld_ap.get();
2542}
Greg Claytonc3776bf2012-02-09 06:16:32 +00002543
2544
Jim Inghambb3a2832011-01-29 01:49:25 +00002545Process::NextEventAction::EventActionResult
2546Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002547{
Jim Inghambb3a2832011-01-29 01:49:25 +00002548 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2549 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002550 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002551 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002552 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002553 return eEventActionRetry;
2554
2555 case eStateStopped:
2556 case eStateCrashed:
Greg Claytonc9ed4782011-11-12 02:10:56 +00002557 {
2558 // During attach, prior to sending the eStateStopped event,
Jim Inghamb1e2e842012-04-12 18:49:31 +00002559 // lldb_private::Process subclasses must set the new process ID.
Greg Claytonc9ed4782011-11-12 02:10:56 +00002560 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2561 if (m_exec_count > 0)
2562 {
2563 --m_exec_count;
Jim Ingham3b8285d2012-04-19 01:40:33 +00002564 m_process->PrivateResume ();
Jim Ingham04e0a222012-05-23 15:46:31 +00002565 Process::ProcessEventData::SetRestartedInEvent (event_sp.get(), true);
Greg Claytonc9ed4782011-11-12 02:10:56 +00002566 return eEventActionRetry;
2567 }
2568 else
2569 {
2570 m_process->CompleteAttach ();
2571 return eEventActionSuccess;
2572 }
2573 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002574 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00002575
Greg Clayton513c26c2011-01-29 07:10:55 +00002576 default:
2577 case eStateExited:
2578 case eStateInvalid:
Greg Clayton513c26c2011-01-29 07:10:55 +00002579 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002580 }
Greg Claytonc9ed4782011-11-12 02:10:56 +00002581
2582 m_exit_string.assign ("No valid Process");
2583 return eEventActionExit;
Jim Inghambb3a2832011-01-29 01:49:25 +00002584}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002585
Jim Inghambb3a2832011-01-29 01:49:25 +00002586Process::NextEventAction::EventActionResult
2587Process::AttachCompletionHandler::HandleBeingInterrupted()
2588{
2589 return eEventActionSuccess;
2590}
2591
2592const char *
2593Process::AttachCompletionHandler::GetExitString ()
2594{
2595 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002596}
2597
2598Error
Greg Clayton144f3a92011-11-15 03:53:30 +00002599Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002600{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002601 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002602 m_process_input_reader.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002603 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002604 m_os_ap.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002605
Greg Clayton144f3a92011-11-15 03:53:30 +00002606 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone996fd32011-03-08 22:40:15 +00002607 Error error;
Greg Clayton144f3a92011-11-15 03:53:30 +00002608 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham5aee1622010-08-09 23:31:02 +00002609 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002610 char process_name[PATH_MAX];
Jim Ingham4299fdb2011-09-15 01:10:17 +00002611
Greg Clayton144f3a92011-11-15 03:53:30 +00002612 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Ingham2ecb7422010-08-17 21:54:19 +00002613 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002614 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2615
2616 if (wait_for_launch)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002617 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002618 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2619 if (error.Success())
2620 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002621 m_should_detach = true;
2622
Greg Clayton144f3a92011-11-15 03:53:30 +00002623 SetPublicState (eStateAttaching);
Han Ming Ong84647042012-02-25 01:07:38 +00002624 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002625 if (error.Fail())
2626 {
2627 if (GetID() != LLDB_INVALID_PROCESS_ID)
2628 {
2629 SetID (LLDB_INVALID_PROCESS_ID);
2630 if (error.AsCString() == NULL)
2631 error.SetErrorString("attach failed");
2632
2633 SetExitStatus(-1, error.AsCString());
2634 }
2635 }
2636 else
2637 {
2638 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2639 StartPrivateStateThread();
2640 }
2641 return error;
2642 }
Greg Claytone996fd32011-03-08 22:40:15 +00002643 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002644 else
Greg Claytone996fd32011-03-08 22:40:15 +00002645 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002646 ProcessInstanceInfoList process_infos;
2647 PlatformSP platform_sp (m_target.GetPlatform ());
2648
2649 if (platform_sp)
2650 {
2651 ProcessInstanceInfoMatch match_info;
2652 match_info.GetProcessInfo() = attach_info;
2653 match_info.SetNameMatchType (eNameMatchEquals);
2654 platform_sp->FindProcesses (match_info, process_infos);
2655 const uint32_t num_matches = process_infos.GetSize();
2656 if (num_matches == 1)
2657 {
2658 attach_pid = process_infos.GetProcessIDAtIndex(0);
2659 // Fall through and attach using the above process ID
2660 }
2661 else
2662 {
2663 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2664 if (num_matches > 1)
2665 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2666 else
2667 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2668 }
2669 }
2670 else
2671 {
2672 error.SetErrorString ("invalid platform, can't find processes by name");
2673 return error;
2674 }
Greg Claytone996fd32011-03-08 22:40:15 +00002675 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002676 }
2677 else
Greg Clayton144f3a92011-11-15 03:53:30 +00002678 {
2679 error.SetErrorString ("invalid process name");
Greg Claytone996fd32011-03-08 22:40:15 +00002680 }
2681 }
Greg Clayton144f3a92011-11-15 03:53:30 +00002682
2683 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone996fd32011-03-08 22:40:15 +00002684 {
Greg Clayton144f3a92011-11-15 03:53:30 +00002685 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone996fd32011-03-08 22:40:15 +00002686 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002687 {
Greg Claytone24c4ac2011-11-17 04:46:02 +00002688 m_should_detach = true;
Greg Claytone996fd32011-03-08 22:40:15 +00002689 SetPublicState (eStateAttaching);
Greg Clayton144f3a92011-11-15 03:53:30 +00002690
Han Ming Ong84647042012-02-25 01:07:38 +00002691 error = DoAttachToProcessWithID (attach_pid, attach_info);
Greg Clayton144f3a92011-11-15 03:53:30 +00002692 if (error.Success())
2693 {
2694
2695 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2696 StartPrivateStateThread();
2697 }
2698 else
Greg Claytone996fd32011-03-08 22:40:15 +00002699 {
2700 if (GetID() != LLDB_INVALID_PROCESS_ID)
2701 {
2702 SetID (LLDB_INVALID_PROCESS_ID);
2703 const char *error_string = error.AsCString();
2704 if (error_string == NULL)
2705 error_string = "attach failed";
2706
2707 SetExitStatus(-1, error_string);
2708 }
2709 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710 }
2711 }
2712 return error;
2713}
2714
Greg Clayton144f3a92011-11-15 03:53:30 +00002715//Error
2716//Process::Attach (const char *process_name, bool wait_for_launch)
2717//{
2718// m_abi_sp.reset();
2719// m_process_input_reader.reset();
2720//
2721// // Find the process and its architecture. Make sure it matches the architecture
2722// // of the current Target, and if not adjust it.
2723// Error error;
2724//
2725// if (!wait_for_launch)
2726// {
2727// ProcessInstanceInfoList process_infos;
2728// PlatformSP platform_sp (m_target.GetPlatform ());
2729// assert (platform_sp.get());
2730//
2731// if (platform_sp)
2732// {
2733// ProcessInstanceInfoMatch match_info;
2734// match_info.GetProcessInfo().SetName(process_name);
2735// match_info.SetNameMatchType (eNameMatchEquals);
2736// platform_sp->FindProcesses (match_info, process_infos);
2737// if (process_infos.GetSize() > 1)
2738// {
2739// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2740// }
2741// else if (process_infos.GetSize() == 0)
2742// {
2743// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2744// }
2745// }
2746// else
2747// {
2748// error.SetErrorString ("invalid platform");
2749// }
2750// }
2751//
2752// if (error.Success())
2753// {
2754// m_dyld_ap.reset();
2755// m_os_ap.reset();
2756//
2757// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2758// if (error.Success())
2759// {
2760// SetPublicState (eStateAttaching);
2761// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2762// if (error.Fail())
2763// {
2764// if (GetID() != LLDB_INVALID_PROCESS_ID)
2765// {
2766// SetID (LLDB_INVALID_PROCESS_ID);
2767// const char *error_string = error.AsCString();
2768// if (error_string == NULL)
2769// error_string = "attach failed";
2770//
2771// SetExitStatus(-1, error_string);
2772// }
2773// }
2774// else
2775// {
2776// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2777// StartPrivateStateThread();
2778// }
2779// }
2780// }
2781// return error;
2782//}
2783
Greg Clayton93d3c8332011-02-16 04:46:07 +00002784void
2785Process::CompleteAttach ()
2786{
2787 // Let the process subclass figure out at much as it can about the process
2788 // before we go looking for a dynamic loader plug-in.
2789 DidAttach();
2790
Jim Ingham4299fdb2011-09-15 01:10:17 +00002791 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2792 // the same as the one we've already set, switch architectures.
2793 PlatformSP platform_sp (m_target.GetPlatform ());
2794 assert (platform_sp.get());
2795 if (platform_sp)
2796 {
Greg Clayton70512312012-05-08 01:45:38 +00002797 const ArchSpec &target_arch = m_target.GetArchitecture();
2798 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture (target_arch))
2799 {
2800 ArchSpec platform_arch;
2801 platform_sp = platform_sp->GetPlatformForArchitecture (target_arch, &platform_arch);
2802 if (platform_sp)
2803 {
2804 m_target.SetPlatform (platform_sp);
2805 m_target.SetArchitecture(platform_arch);
2806 }
2807 }
2808 else
2809 {
2810 ProcessInstanceInfo process_info;
2811 platform_sp->GetProcessInfo (GetID(), process_info);
2812 const ArchSpec &process_arch = process_info.GetArchitecture();
2813 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2814 m_target.SetArchitecture (process_arch);
2815 }
Jim Ingham4299fdb2011-09-15 01:10:17 +00002816 }
2817
2818 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002819 // plug-in
Greg Claytonc859e2d2012-02-13 23:10:39 +00002820 DynamicLoader *dyld = GetDynamicLoader ();
2821 if (dyld)
2822 dyld->DidAttach();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002823
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002824 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002825 // Figure out which one is the executable, and set that in our target:
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002826 ModuleList &target_modules = m_target.GetImages();
2827 Mutex::Locker modules_locker(target_modules.GetMutex());
2828 size_t num_modules = target_modules.GetSize();
2829 ModuleSP new_executable_module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002830
Greg Clayton93d3c8332011-02-16 04:46:07 +00002831 for (int i = 0; i < num_modules; i++)
2832 {
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002833 ModuleSP module_sp (target_modules.GetModuleAtIndexUnlocked (i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002834 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002835 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002836 if (m_target.GetExecutableModulePointer() != module_sp.get())
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002837 new_executable_module_sp = module_sp;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002838 break;
2839 }
2840 }
Jim Ingham3ee12ef2012-05-30 02:19:25 +00002841 if (new_executable_module_sp)
2842 m_target.SetExecutableModule (new_executable_module_sp, false);
Greg Clayton93d3c8332011-02-16 04:46:07 +00002843}
2844
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002845Error
Greg Claytonb766a732011-02-04 01:58:07 +00002846Process::ConnectRemote (const char *remote_url)
2847{
Greg Claytonb766a732011-02-04 01:58:07 +00002848 m_abi_sp.reset();
2849 m_process_input_reader.reset();
2850
2851 // Find the process and its architecture. Make sure it matches the architecture
2852 // of the current Target, and if not adjust it.
2853
2854 Error error (DoConnectRemote (remote_url));
2855 if (error.Success())
2856 {
Greg Clayton71337622011-02-24 22:24:29 +00002857 if (GetID() != LLDB_INVALID_PROCESS_ID)
2858 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002859 EventSP event_sp;
2860 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2861
2862 if (state == eStateStopped || state == eStateCrashed)
2863 {
2864 // If we attached and actually have a process on the other end, then
2865 // this ended up being the equivalent of an attach.
2866 CompleteAttach ();
2867
2868 // This delays passing the stopped event to listeners till
2869 // CompleteAttach gets a chance to complete...
2870 HandlePrivateEvent (event_sp);
2871
2872 }
Greg Clayton71337622011-02-24 22:24:29 +00002873 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002874
2875 if (PrivateStateThreadIsValid ())
2876 ResumePrivateStateThread ();
2877 else
2878 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002879 }
2880 return error;
2881}
2882
2883
2884Error
Jim Ingham3b8285d2012-04-19 01:40:33 +00002885Process::PrivateResume ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002886{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002887 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002888 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002889 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002890 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002891 StateAsCString(m_public_state.GetValue()),
2892 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002893
2894 Error error (WillResume());
2895 // Tell the process it is about to resume before the thread list
2896 if (error.Success())
2897 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002898 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002899 // can let all of our threads know that they are about to be
2900 // resumed. Threads will each be called with
2901 // Thread::WillResume(StateType) where StateType contains the state
2902 // that they are supposed to have when the process is resumed
2903 // (suspended/running/stepping). Threads should also check
2904 // their resume signal in lldb::Thread::GetResumeSignal()
2905 // to see if they are suppoed to start back up with a signal.
2906 if (m_thread_list.WillResume())
2907 {
Jim Ingham372787f2012-04-07 00:00:41 +00002908 // Last thing, do the PreResumeActions.
2909 if (!RunPreResumeActions())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002910 {
Jim Ingham372787f2012-04-07 00:00:41 +00002911 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
2912 }
2913 else
2914 {
2915 m_mod_id.BumpResumeID();
2916 error = DoResume();
2917 if (error.Success())
2918 {
2919 DidResume();
2920 m_thread_list.DidResume();
2921 if (log)
2922 log->Printf ("Process thinks the process has resumed.");
2923 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002924 }
2925 }
2926 else
2927 {
Jim Ingham444586b2011-01-24 06:34:17 +00002928 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002929 }
2930 }
Jim Ingham444586b2011-01-24 06:34:17 +00002931 else if (log)
2932 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002933 return error;
2934}
2935
2936Error
2937Process::Halt ()
2938{
Jim Inghambb3a2832011-01-29 01:49:25 +00002939 // Pause our private state thread so we can ensure no one else eats
2940 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002941 Listener halt_listener ("lldb.process.halt_listener");
2942 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002943
Jim Inghambb3a2832011-01-29 01:49:25 +00002944 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002945 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002946
Greg Clayton513c26c2011-01-29 07:10:55 +00002947 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002948 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002949
Greg Clayton513c26c2011-01-29 07:10:55 +00002950 bool caused_stop = false;
2951
2952 // Ask the process subclass to actually halt our process
2953 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002954 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002955 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002956 if (m_public_state.GetValue() == eStateAttaching)
2957 {
2958 SetExitStatus(SIGKILL, "Cancelled async attach.");
2959 Destroy ();
2960 }
2961 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002962 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002963 // If "caused_stop" is true, then DoHalt stopped the process. If
2964 // "caused_stop" is false, the process was already stopped.
2965 // If the DoHalt caused the process to stop, then we want to catch
2966 // this event and set the interrupted bool to true before we pass
2967 // this along so clients know that the process was interrupted by
2968 // a halt command.
2969 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002970 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002971 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002972 TimeValue timeout_time;
2973 timeout_time = TimeValue::Now();
2974 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002975 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2976 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002977
Jim Ingham0f16e732011-02-08 05:20:59 +00002978 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002979 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002980 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002981 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002982 }
2983 else
2984 {
Greg Clayton2637f822011-11-17 01:23:07 +00002985 if (StateIsStoppedState (state, false))
Jim Inghambb3a2832011-01-29 01:49:25 +00002986 {
2987 // We caused the process to interrupt itself, so mark this
2988 // as such in the stop event so clients can tell an interrupted
2989 // process from a natural stop
2990 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2991 }
2992 else
2993 {
2994 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2995 if (log)
2996 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2997 error.SetErrorString ("Did not get stopped event after halt.");
2998 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002999 }
3000 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003001 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003002 }
3003 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003004 }
Jim Inghambb3a2832011-01-29 01:49:25 +00003005 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00003006 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00003007
3008 // Post any event we might have consumed. If all goes well, we will have
3009 // stopped the process, intercepted the event and set the interrupted
3010 // bool in the event. Post it to the private event queue and that will end up
3011 // correctly setting the state.
3012 if (event_sp)
3013 m_private_state_broadcaster.BroadcastEvent(event_sp);
3014
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003015 return error;
3016}
3017
3018Error
3019Process::Detach ()
3020{
3021 Error error (WillDetach());
3022
3023 if (error.Success())
3024 {
3025 DisableAllBreakpointSites();
3026 error = DoDetach();
3027 if (error.Success())
3028 {
3029 DidDetach();
3030 StopPrivateStateThread();
3031 }
3032 }
3033 return error;
3034}
3035
3036Error
3037Process::Destroy ()
3038{
3039 Error error (WillDestroy());
3040 if (error.Success())
3041 {
3042 DisableAllBreakpointSites();
Jim Ingham04e0a222012-05-23 15:46:31 +00003043 if (m_public_state.GetValue() == eStateRunning)
3044 {
3045 error = Halt();
3046 if (error.Success())
3047 {
3048 // Consume the halt event.
3049 EventSP stop_event;
3050 TimeValue timeout (TimeValue::Now());
3051 timeout.OffsetWithMicroSeconds(1000);
3052 StateType state = WaitForProcessToStop (&timeout);
3053 if (state != eStateStopped)
3054 {
3055 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3056 if (log)
3057 log->Printf("Process::Destroy() Halt failed to stop, state is: %s", StateAsCString(state));
3058 }
3059 }
3060 else
3061 {
3062 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3063 if (log)
3064 log->Printf("Process::Destroy() Halt got error: %s", error.AsCString());
3065 }
3066 }
3067
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003068 error = DoDestroy();
3069 if (error.Success())
3070 {
3071 DidDestroy();
3072 StopPrivateStateThread();
3073 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003074 m_stdio_communication.StopReadThread();
3075 m_stdio_communication.Disconnect();
3076 if (m_process_input_reader && m_process_input_reader->IsActive())
3077 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3078 if (m_process_input_reader)
3079 m_process_input_reader.reset();
Jim Inghamb1e2e842012-04-12 18:49:31 +00003080
3081 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
3082 // the last events through the event system, in which case we might strand the write lock. Unlock
3083 // it here so when we do to tear down the process we don't get an error destroying the lock.
3084 m_run_lock.WriteUnlock();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003085 }
3086 return error;
3087}
3088
3089Error
3090Process::Signal (int signal)
3091{
3092 Error error (WillSignal());
3093 if (error.Success())
3094 {
3095 error = DoSignal(signal);
3096 if (error.Success())
3097 DidSignal();
3098 }
3099 return error;
3100}
3101
Greg Clayton514487e2011-02-15 21:59:32 +00003102lldb::ByteOrder
3103Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003104{
Greg Clayton514487e2011-02-15 21:59:32 +00003105 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003106}
3107
3108uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00003109Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003110{
Greg Clayton514487e2011-02-15 21:59:32 +00003111 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003112}
3113
Greg Clayton514487e2011-02-15 21:59:32 +00003114
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115bool
3116Process::ShouldBroadcastEvent (Event *event_ptr)
3117{
3118 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
3119 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003120 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003121
3122 switch (state)
3123 {
Greg Claytonb766a732011-02-04 01:58:07 +00003124 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003125 case eStateAttaching:
3126 case eStateLaunching:
3127 case eStateDetached:
3128 case eStateExited:
3129 case eStateUnloaded:
3130 // These events indicate changes in the state of the debugging session, always report them.
3131 return_value = true;
3132 break;
3133 case eStateInvalid:
3134 // We stopped for no apparent reason, don't report it.
3135 return_value = false;
3136 break;
3137 case eStateRunning:
3138 case eStateStepping:
3139 // If we've started the target running, we handle the cases where we
3140 // are already running and where there is a transition from stopped to
3141 // running differently.
3142 // running -> running: Automatically suppress extra running events
3143 // stopped -> running: Report except when there is one or more no votes
3144 // and no yes votes.
3145 SynchronouslyNotifyStateChanged (state);
3146 switch (m_public_state.GetValue())
3147 {
3148 case eStateRunning:
3149 case eStateStepping:
3150 // We always suppress multiple runnings with no PUBLIC stop in between.
3151 return_value = false;
3152 break;
3153 default:
3154 // TODO: make this work correctly. For now always report
3155 // run if we aren't running so we don't miss any runnning
3156 // events. If I run the lldb/test/thread/a.out file and
3157 // break at main.cpp:58, run and hit the breakpoints on
3158 // multiple threads, then somehow during the stepping over
3159 // of all breakpoints no run gets reported.
3160 return_value = true;
3161
3162 // This is a transition from stop to run.
3163 switch (m_thread_list.ShouldReportRun (event_ptr))
3164 {
3165 case eVoteYes:
3166 case eVoteNoOpinion:
3167 return_value = true;
3168 break;
3169 case eVoteNo:
3170 return_value = false;
3171 break;
3172 }
3173 break;
3174 }
3175 break;
3176 case eStateStopped:
3177 case eStateCrashed:
3178 case eStateSuspended:
3179 {
3180 // We've stopped. First see if we're going to restart the target.
3181 // If we are going to stop, then we always broadcast the event.
3182 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00003183 // If no thread has an opinion, we don't report it.
Jim Inghamcb4ca112012-05-16 01:32:14 +00003184
3185 RefreshStateAfterStop ();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003186 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003187 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00003188 if (log)
3189 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003190 return true;
3191 }
3192 else
3193 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003194
3195 if (m_thread_list.ShouldStop (event_ptr) == false)
3196 {
3197 switch (m_thread_list.ShouldReportStop (event_ptr))
3198 {
3199 case eVoteYes:
3200 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00003201 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003202 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003203 case eVoteNo:
3204 return_value = false;
3205 break;
3206 }
3207
3208 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003209 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Jim Ingham3b8285d2012-04-19 01:40:33 +00003210 PrivateResume ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003211 }
3212 else
3213 {
3214 return_value = true;
3215 SynchronouslyNotifyStateChanged (state);
3216 }
3217 }
3218 }
3219 }
3220
3221 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00003222 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003223 return return_value;
3224}
3225
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003226
3227bool
Jim Ingham372787f2012-04-07 00:00:41 +00003228Process::StartPrivateStateThread (bool force)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003229{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003230 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003231
Greg Clayton8b82f082011-04-12 05:54:46 +00003232 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00003234 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3235
Jim Ingham372787f2012-04-07 00:00:41 +00003236 if (!force && already_running)
Greg Clayton8b82f082011-04-12 05:54:46 +00003237 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003238
3239 // Create a thread that watches our internal state and controls which
3240 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00003241 char thread_name[1024];
Jim Ingham372787f2012-04-07 00:00:41 +00003242 if (already_running)
3243 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3244 else
3245 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Ingham076b3042012-04-10 01:21:57 +00003246
3247 // Create the private state thread, and start it running.
Greg Clayton3e06bd92011-01-09 21:07:35 +00003248 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Ingham076b3042012-04-10 01:21:57 +00003249 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3250 if (success)
3251 {
3252 ResumePrivateStateThread();
3253 return true;
3254 }
3255 else
3256 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003257}
3258
3259void
3260Process::PausePrivateStateThread ()
3261{
3262 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3263}
3264
3265void
3266Process::ResumePrivateStateThread ()
3267{
3268 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3269}
3270
3271void
3272Process::StopPrivateStateThread ()
3273{
Greg Clayton8b82f082011-04-12 05:54:46 +00003274 if (PrivateStateThreadIsValid ())
3275 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003276 else
3277 {
3278 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3279 if (log)
3280 printf ("Went to stop the private state thread, but it was already invalid.");
3281 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003282}
3283
3284void
3285Process::ControlPrivateStateThread (uint32_t signal)
3286{
Jim Inghamb1e2e842012-04-12 18:49:31 +00003287 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003288
3289 assert (signal == eBroadcastInternalStateControlStop ||
3290 signal == eBroadcastInternalStateControlPause ||
3291 signal == eBroadcastInternalStateControlResume);
3292
3293 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003294 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003295
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003296 // Signal the private state thread. First we should copy this is case the
3297 // thread starts exiting since the private state thread will NULL this out
3298 // when it exits
3299 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00003300 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003301 {
3302 TimeValue timeout_time;
3303 bool timed_out;
3304
3305 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3306
3307 timeout_time = TimeValue::Now();
3308 timeout_time.OffsetWithSeconds(2);
Jim Inghamb1e2e842012-04-12 18:49:31 +00003309 if (log)
3310 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003311 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3312 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3313
3314 if (signal == eBroadcastInternalStateControlStop)
3315 {
3316 if (timed_out)
Jim Inghamb1e2e842012-04-12 18:49:31 +00003317 {
3318 Error error;
3319 Host::ThreadCancel (private_state_thread, &error);
3320 if (log)
3321 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3322 }
3323 else
3324 {
3325 if (log)
3326 log->Printf ("The control event killed the private state thread without having to cancel.");
3327 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003328
3329 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00003330 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00003331 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003332 }
3333 }
Jim Inghamb1e2e842012-04-12 18:49:31 +00003334 else
3335 {
3336 if (log)
3337 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3338 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003339}
3340
3341void
3342Process::HandlePrivateEvent (EventSP &event_sp)
3343{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003344 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00003345
Greg Clayton414f5d32011-01-25 02:58:48 +00003346 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00003347
3348 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00003349 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00003350 {
Jim Ingham754ab982011-01-29 04:05:41 +00003351 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00003352 switch (action_result)
3353 {
3354 case NextEventAction::eEventActionSuccess:
3355 SetNextEventAction(NULL);
3356 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003357
Jim Inghambb3a2832011-01-29 01:49:25 +00003358 case NextEventAction::eEventActionRetry:
3359 break;
Greg Claytonc9ed4782011-11-12 02:10:56 +00003360
Jim Inghambb3a2832011-01-29 01:49:25 +00003361 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003362 // Handle Exiting Here. If we already got an exited event,
3363 // we should just propagate it. Otherwise, swallow this event,
3364 // and set our state to exit so the next event will kill us.
3365 if (new_state != eStateExited)
3366 {
3367 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00003368 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00003369 SetNextEventAction(NULL);
3370 return;
3371 }
3372 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00003373 break;
3374 }
3375 }
3376
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003377 // See if we should broadcast this state to external clients?
3378 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003379
3380 if (should_broadcast)
3381 {
3382 if (log)
3383 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003384 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00003385 __FUNCTION__,
3386 GetID(),
3387 StateAsCString(new_state),
3388 StateAsCString (GetState ()),
3389 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003390 }
Jim Ingham9575d842011-03-11 03:53:59 +00003391 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00003392 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003393 PushProcessInputReader ();
3394 else
3395 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00003396
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003397 BroadcastEvent (event_sp);
3398 }
3399 else
3400 {
3401 if (log)
3402 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003403 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00003404 __FUNCTION__,
3405 GetID(),
3406 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00003407 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003408 }
3409 }
3410}
3411
3412void *
3413Process::PrivateStateThread (void *arg)
3414{
3415 Process *proc = static_cast<Process*> (arg);
3416 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003417 return result;
3418}
3419
3420void *
3421Process::RunPrivateStateThread ()
3422{
Jim Ingham076b3042012-04-10 01:21:57 +00003423 bool control_only = true;
Jim Inghamb1e2e842012-04-12 18:49:31 +00003424 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003425
Greg Clayton2d4edfb2010-11-06 01:53:30 +00003426 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003427 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003428 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003429
3430 bool exit_now = false;
3431 while (!exit_now)
3432 {
3433 EventSP event_sp;
3434 WaitForEventsPrivate (NULL, event_sp, control_only);
3435 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3436 {
Jim Inghamb1e2e842012-04-12 18:49:31 +00003437 if (log)
3438 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3439
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003440 switch (event_sp->GetType())
3441 {
3442 case eBroadcastInternalStateControlStop:
3443 exit_now = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003444 break; // doing any internal state managment below
3445
3446 case eBroadcastInternalStateControlPause:
3447 control_only = true;
3448 break;
3449
3450 case eBroadcastInternalStateControlResume:
3451 control_only = false;
3452 break;
3453 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003454
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003455 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003456 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003457 }
3458
3459
3460 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3461
3462 if (internal_state != eStateInvalid)
3463 {
3464 HandlePrivateEvent (event_sp);
3465 }
3466
Greg Clayton58d1c9a2010-10-18 04:14:23 +00003467 if (internal_state == eStateInvalid ||
3468 internal_state == eStateExited ||
3469 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003470 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003471 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003472 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003473
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003474 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003475 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003476 }
3477
Caroline Tice20ad3c42010-10-29 21:48:37 +00003478 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003479 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00003480 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003481
Greg Clayton6ed95942011-01-22 07:12:45 +00003482 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3483 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003484 return NULL;
3485}
3486
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003487//------------------------------------------------------------------
3488// Process Event Data
3489//------------------------------------------------------------------
3490
3491Process::ProcessEventData::ProcessEventData () :
3492 EventData (),
3493 m_process_sp (),
3494 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00003495 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003496 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003497 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003498{
3499}
3500
3501Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3502 EventData (),
3503 m_process_sp (process_sp),
3504 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00003505 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00003506 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003507 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003508{
3509}
3510
3511Process::ProcessEventData::~ProcessEventData()
3512{
3513}
3514
3515const ConstString &
3516Process::ProcessEventData::GetFlavorString ()
3517{
3518 static ConstString g_flavor ("Process::ProcessEventData");
3519 return g_flavor;
3520}
3521
3522const ConstString &
3523Process::ProcessEventData::GetFlavor () const
3524{
3525 return ProcessEventData::GetFlavorString ();
3526}
3527
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003528void
3529Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3530{
3531 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00003532 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3533 // the public event queue, then other times when we're pretending that this is where we stopped at the
3534 // end of expression evaluation. m_update_state is used to distinguish these
3535 // three cases; it is 0 when we're just pulling it off for private handling,
3536 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003537
Jim Inghama8604692011-05-22 21:45:01 +00003538 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003539 return;
3540
3541 m_process_sp->SetPublicState (m_state);
3542
3543 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3544 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0faa43f2011-11-08 03:00:11 +00003545 {
3546 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Clayton61e7a582011-12-01 23:28:38 +00003547 uint32_t num_threads = curr_thread_list.GetSize();
3548 uint32_t idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00003549
Jim Ingham4b536182011-08-09 02:12:22 +00003550 // The actions might change one of the thread's stop_info's opinions about whether we should
3551 // stop the process, so we need to query that as we go.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003552
3553 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3554 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3555 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3556 // 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
3557 // against this list & bag out if anything differs.
Greg Clayton61e7a582011-12-01 23:28:38 +00003558 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0faa43f2011-11-08 03:00:11 +00003559 for (idx = 0; idx < num_threads; ++idx)
3560 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3561
Jim Ingham4b536182011-08-09 02:12:22 +00003562 bool still_should_stop = true;
3563
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003564 for (idx = 0; idx < num_threads; ++idx)
3565 {
Jim Ingham0faa43f2011-11-08 03:00:11 +00003566 curr_thread_list = m_process_sp->GetThreadList();
3567 if (curr_thread_list.GetSize() != num_threads)
3568 {
3569 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003570 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003571 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003572 break;
3573 }
3574
3575 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3576
3577 if (thread_sp->GetIndexID() != thread_index_array[idx])
3578 {
3579 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham87c665f2011-12-01 20:26:15 +00003580 if (log)
Greg Clayton61e7a582011-12-01 23:28:38 +00003581 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham87c665f2011-12-01 20:26:15 +00003582 idx,
3583 thread_index_array[idx],
3584 thread_sp->GetIndexID());
Jim Ingham0faa43f2011-11-08 03:00:11 +00003585 break;
3586 }
3587
Jim Inghamb15bfc72010-10-20 00:39:53 +00003588 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3589 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003590 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003591 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003592 // The stop action might restart the target. If it does, then we want to mark that in the
3593 // event so that whoever is receiving it will know to wait for the running event and reflect
3594 // that state appropriately.
3595 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0faa43f2011-11-08 03:00:11 +00003596
3597 // FIXME: we might have run.
3598 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham4b536182011-08-09 02:12:22 +00003599 {
3600 SetRestarted (true);
3601 break;
3602 }
3603 else if (!stop_info_sp->ShouldStop(event_ptr))
3604 {
3605 still_should_stop = false;
3606 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003607 }
3608 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003609
Jim Ingham4b536182011-08-09 02:12:22 +00003610
3611 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003612 {
Jim Ingham4b536182011-08-09 02:12:22 +00003613 if (!still_should_stop)
3614 {
3615 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003616 SetRestarted(true);
Jim Ingham3b8285d2012-04-19 01:40:33 +00003617 // Use the public resume method here, since this is just
3618 // extending a public resume.
Jim Ingham4b536182011-08-09 02:12:22 +00003619 m_process_sp->Resume();
3620 }
3621 else
3622 {
3623 // If we didn't restart, run the Stop Hooks here:
3624 // They might also restart the target, so watch for that.
3625 m_process_sp->GetTarget().RunStopHooks();
3626 if (m_process_sp->GetPrivateState() == eStateRunning)
3627 SetRestarted(true);
3628 }
Jim Ingham9575d842011-03-11 03:53:59 +00003629 }
3630
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003631 }
3632}
3633
3634void
3635Process::ProcessEventData::Dump (Stream *s) const
3636{
3637 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003638 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003639
Greg Clayton8b82f082011-04-12 05:54:46 +00003640 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003641}
3642
3643const Process::ProcessEventData *
3644Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3645{
3646 if (event_ptr)
3647 {
3648 const EventData *event_data = event_ptr->GetData();
3649 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3650 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3651 }
3652 return NULL;
3653}
3654
3655ProcessSP
3656Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3657{
3658 ProcessSP process_sp;
3659 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3660 if (data)
3661 process_sp = data->GetProcessSP();
3662 return process_sp;
3663}
3664
3665StateType
3666Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3667{
3668 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3669 if (data == NULL)
3670 return eStateInvalid;
3671 else
3672 return data->GetState();
3673}
3674
3675bool
3676Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3677{
3678 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3679 if (data == NULL)
3680 return false;
3681 else
3682 return data->GetRestarted();
3683}
3684
3685void
3686Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3687{
3688 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3689 if (data != NULL)
3690 data->SetRestarted(new_value);
3691}
3692
3693bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003694Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3695{
3696 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3697 if (data == NULL)
3698 return false;
3699 else
3700 return data->GetInterrupted ();
3701}
3702
3703void
3704Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3705{
3706 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3707 if (data != NULL)
3708 data->SetInterrupted(new_value);
3709}
3710
3711bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003712Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3713{
3714 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3715 if (data)
3716 {
3717 data->SetUpdateStateOnRemoval();
3718 return true;
3719 }
3720 return false;
3721}
3722
Greg Claytond9e416c2012-02-18 05:35:26 +00003723lldb::TargetSP
3724Process::CalculateTarget ()
3725{
3726 return m_target.shared_from_this();
3727}
3728
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003729void
Greg Clayton0603aa92010-10-04 01:05:56 +00003730Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003731{
Greg Claytonc14ee322011-09-22 04:58:26 +00003732 exe_ctx.SetTargetPtr (&m_target);
3733 exe_ctx.SetProcessPtr (this);
3734 exe_ctx.SetThreadPtr(NULL);
3735 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003736}
3737
Greg Claytone996fd32011-03-08 22:40:15 +00003738//uint32_t
3739//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3740//{
3741// return 0;
3742//}
3743//
3744//ArchSpec
3745//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3746//{
3747// return Host::GetArchSpecForExistingProcess (pid);
3748//}
3749//
3750//ArchSpec
3751//Process::GetArchSpecForExistingProcess (const char *process_name)
3752//{
3753// return Host::GetArchSpecForExistingProcess (process_name);
3754//}
3755//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003756void
3757Process::AppendSTDOUT (const char * s, size_t len)
3758{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003759 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003760 m_stdout_data.append (s, len);
Greg Claytona9ff3062010-12-05 19:16:56 +00003761 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003762}
3763
3764void
Greg Clayton93e86192011-11-13 04:45:22 +00003765Process::AppendSTDERR (const char * s, size_t len)
3766{
3767 Mutex::Locker locker (m_stdio_communication_mutex);
3768 m_stderr_data.append (s, len);
3769 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3770}
3771
3772//------------------------------------------------------------------
3773// Process STDIO
3774//------------------------------------------------------------------
3775
3776size_t
3777Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3778{
3779 Mutex::Locker locker(m_stdio_communication_mutex);
3780 size_t bytes_available = m_stdout_data.size();
3781 if (bytes_available > 0)
3782 {
3783 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3784 if (log)
3785 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3786 if (bytes_available > buf_size)
3787 {
3788 memcpy(buf, m_stdout_data.c_str(), buf_size);
3789 m_stdout_data.erase(0, buf_size);
3790 bytes_available = buf_size;
3791 }
3792 else
3793 {
3794 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3795 m_stdout_data.clear();
3796 }
3797 }
3798 return bytes_available;
3799}
3800
3801
3802size_t
3803Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3804{
3805 Mutex::Locker locker(m_stdio_communication_mutex);
3806 size_t bytes_available = m_stderr_data.size();
3807 if (bytes_available > 0)
3808 {
3809 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3810 if (log)
3811 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3812 if (bytes_available > buf_size)
3813 {
3814 memcpy(buf, m_stderr_data.c_str(), buf_size);
3815 m_stderr_data.erase(0, buf_size);
3816 bytes_available = buf_size;
3817 }
3818 else
3819 {
3820 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3821 m_stderr_data.clear();
3822 }
3823 }
3824 return bytes_available;
3825}
3826
3827void
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003828Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3829{
3830 Process *process = (Process *) baton;
3831 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3832}
3833
3834size_t
3835Process::ProcessInputReaderCallback (void *baton,
3836 InputReader &reader,
3837 lldb::InputReaderAction notification,
3838 const char *bytes,
3839 size_t bytes_len)
3840{
3841 Process *process = (Process *) baton;
3842
3843 switch (notification)
3844 {
3845 case eInputReaderActivate:
3846 break;
3847
3848 case eInputReaderDeactivate:
3849 break;
3850
3851 case eInputReaderReactivate:
3852 break;
3853
Caroline Tice969ed3d2011-05-02 20:41:46 +00003854 case eInputReaderAsynchronousOutputWritten:
3855 break;
3856
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003857 case eInputReaderGotToken:
3858 {
3859 Error error;
3860 process->PutSTDIN (bytes, bytes_len, error);
3861 }
3862 break;
3863
Caroline Ticeefed6132010-11-19 20:47:54 +00003864 case eInputReaderInterrupt:
3865 process->Halt ();
3866 break;
3867
3868 case eInputReaderEndOfFile:
3869 process->AppendSTDOUT ("^D", 2);
3870 break;
3871
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003872 case eInputReaderDone:
3873 break;
3874
3875 }
3876
3877 return bytes_len;
3878}
3879
3880void
3881Process::ResetProcessInputReader ()
3882{
3883 m_process_input_reader.reset();
3884}
3885
3886void
Greg Claytonee95ed52011-11-17 22:14:31 +00003887Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003888{
3889 // First set up the Read Thread for reading/handling process I/O
3890
3891 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3892
3893 if (conn_ap.get())
3894 {
3895 m_stdio_communication.SetConnection (conn_ap.release());
3896 if (m_stdio_communication.IsConnected())
3897 {
3898 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3899 m_stdio_communication.StartReadThread();
3900
3901 // Now read thread is set up, set up input reader.
3902
3903 if (!m_process_input_reader.get())
3904 {
3905 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3906 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3907 this,
3908 eInputReaderGranularityByte,
3909 NULL,
3910 NULL,
3911 false));
3912
3913 if (err.Fail())
3914 m_process_input_reader.reset();
3915 }
3916 }
3917 }
3918}
3919
3920void
3921Process::PushProcessInputReader ()
3922{
3923 if (m_process_input_reader && !m_process_input_reader->IsActive())
3924 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3925}
3926
3927void
3928Process::PopProcessInputReader ()
3929{
3930 if (m_process_input_reader && m_process_input_reader->IsActive())
3931 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3932}
3933
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003934// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003935void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003936Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003937{
Greg Claytone0d378b2011-03-24 21:19:54 +00003938 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003939
3940 int i=0;
3941 const char *name;
3942 OptionEnumValueElement option_enum;
3943 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3944 {
3945 if (name)
3946 {
3947 option_enum.value = i;
3948 option_enum.string_value = name;
3949 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3950 g_plugins.push_back (option_enum);
3951 }
3952 ++i;
3953 }
3954 option_enum.value = 0;
3955 option_enum.string_value = NULL;
3956 option_enum.usage = NULL;
3957 g_plugins.push_back (option_enum);
3958
3959 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3960 {
3961 if (::strcmp (name, "plugin") == 0)
3962 {
3963 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3964 break;
3965 }
3966 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003967 UserSettingsControllerSP &usc = GetSettingsController();
3968 usc.reset (new SettingsController);
3969 UserSettingsController::InitializeSettingsController (usc,
3970 SettingsController::global_settings_table,
3971 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003972
3973 // Now call SettingsInitialize() for each 'child' of Process settings
3974 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003975}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003976
Greg Clayton99d0faf2010-11-18 23:32:35 +00003977void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003978Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003979{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003980 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3981
3982 Thread::SettingsTerminate ();
3983
3984 // Now terminate Process Settings.
3985
Greg Clayton99d0faf2010-11-18 23:32:35 +00003986 UserSettingsControllerSP &usc = GetSettingsController();
3987 UserSettingsController::FinalizeSettingsController (usc);
3988 usc.reset();
3989}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003990
Greg Clayton99d0faf2010-11-18 23:32:35 +00003991UserSettingsControllerSP &
3992Process::GetSettingsController ()
3993{
Greg Claytonb9556ac2012-01-30 07:41:31 +00003994 static UserSettingsControllerSP g_settings_controller_sp;
3995 if (!g_settings_controller_sp)
3996 {
3997 g_settings_controller_sp.reset (new Process::SettingsController);
3998 // The first shared pointer to Process::SettingsController in
3999 // g_settings_controller_sp must be fully created above so that
4000 // the TargetInstanceSettings can use a weak_ptr to refer back
4001 // to the master setttings controller
4002 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp,
4003 false,
4004 InstanceSettings::GetDefaultName().AsCString()));
4005 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
4006 }
4007 return g_settings_controller_sp;
4008
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004009}
4010
Caroline Tice1559a462010-09-27 00:30:10 +00004011void
4012Process::UpdateInstanceName ()
4013{
Greg Claytonaa149cb2011-08-11 02:48:45 +00004014 Module *module = GetTarget().GetExecutableModulePointer();
Greg Claytone1cd1be2012-01-29 20:56:30 +00004015 if (module && module->GetFileSpec().GetFilename())
Caroline Tice1559a462010-09-27 00:30:10 +00004016 {
Greg Claytondbe54502010-11-19 03:46:01 +00004017 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytone1cd1be2012-01-29 20:56:30 +00004018 module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00004019 }
4020}
4021
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00004022ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00004023Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham372787f2012-04-07 00:00:41 +00004024 lldb::ThreadPlanSP &thread_plan_sp,
Jim Inghamf48169b2010-11-30 02:22:11 +00004025 bool stop_others,
4026 bool try_all_threads,
4027 bool discard_on_error,
4028 uint32_t single_thread_timeout_usec,
4029 Stream &errors)
4030{
4031 ExecutionResults return_value = eExecutionSetupError;
4032
Jim Ingham77787032011-01-20 02:03:18 +00004033 if (thread_plan_sp.get() == NULL)
4034 {
4035 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004036 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00004037 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004038
4039 if (exe_ctx.GetProcessPtr() != this)
4040 {
4041 errors.Printf("RunThreadPlan called on wrong process.");
4042 return eExecutionSetupError;
4043 }
4044
4045 Thread *thread = exe_ctx.GetThreadPtr();
4046 if (thread == NULL)
4047 {
4048 errors.Printf("RunThreadPlan called with invalid thread.");
4049 return eExecutionSetupError;
4050 }
Jim Ingham77787032011-01-20 02:03:18 +00004051
Jim Ingham17e5c4e2011-05-17 22:24:54 +00004052 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
4053 // For that to be true the plan can't be private - since private plans suppress themselves in the
4054 // GetCompletedPlan call.
4055
4056 bool orig_plan_private = thread_plan_sp->GetPrivate();
4057 thread_plan_sp->SetPrivate(false);
4058
Jim Ingham444586b2011-01-24 06:34:17 +00004059 if (m_private_state.GetValue() != eStateStopped)
4060 {
4061 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004062 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00004063 }
4064
Jim Ingham66243842011-08-13 00:56:10 +00004065 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00004066 const uint32_t thread_idx_id = thread->GetIndexID();
4067 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004068
4069 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
4070 // so we should arrange to reset them as well.
4071
Greg Claytonc14ee322011-09-22 04:58:26 +00004072 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00004073
Jim Ingham66243842011-08-13 00:56:10 +00004074 uint32_t selected_tid;
4075 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00004076 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00004077 {
4078 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00004079 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00004080 }
4081 else
4082 {
4083 selected_tid = LLDB_INVALID_THREAD_ID;
4084 }
4085
Jim Ingham372787f2012-04-07 00:00:41 +00004086 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Ingham076b3042012-04-10 01:21:57 +00004087 lldb::StateType old_state;
4088 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham372787f2012-04-07 00:00:41 +00004089
Jim Ingham076b3042012-04-10 01:21:57 +00004090 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham372787f2012-04-07 00:00:41 +00004091 if (Host::GetCurrentThread() == m_private_state_thread)
4092 {
Jim Ingham076b3042012-04-10 01:21:57 +00004093 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
4094 // we are the thread that is generating public events.
Jim Ingham372787f2012-04-07 00:00:41 +00004095 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Ingham076b3042012-04-10 01:21:57 +00004096 // we are fielding public events here.
4097 if (log)
4098 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
4099
4100
Jim Ingham372787f2012-04-07 00:00:41 +00004101 backup_private_state_thread = m_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004102
4103 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
4104 // returning control here.
4105 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
4106 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
4107 // before the plan we want to run. Since base plans always stop and return control to the user, that will
4108 // do just what we want.
4109 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
4110 thread->QueueThreadPlan (stopper_base_plan_sp, false);
4111 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
4112 old_state = m_public_state.GetValue();
4113 m_public_state.SetValueNoLock(eStateStopped);
4114
4115 // Now spin up the private state thread:
Jim Ingham372787f2012-04-07 00:00:41 +00004116 StartPrivateStateThread(true);
4117 }
4118
4119 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Inghamf48169b2010-11-30 02:22:11 +00004120
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004121 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00004122
4123 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
4124 // restored on exit to the function.
4125
4126 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00004127
Jim Ingham77787032011-01-20 02:03:18 +00004128 if (log)
4129 {
4130 StreamString s;
4131 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton81c22f62011-10-19 18:09:39 +00004132 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00004133 thread->GetIndexID(),
4134 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00004135 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00004136 }
4137
Jim Ingham0f16e732011-02-08 05:20:59 +00004138 bool got_event;
4139 lldb::EventSP event_sp;
4140 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00004141
4142 TimeValue* timeout_ptr = NULL;
4143 TimeValue real_timeout;
4144
Jim Ingham0f16e732011-02-08 05:20:59 +00004145 bool first_timeout = true;
4146 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00004147
Jim Inghamf48169b2010-11-30 02:22:11 +00004148 while (1)
4149 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004150 // We usually want to resume the process if we get to the top of the loop.
4151 // The only exception is if we get two running events with no intervening
4152 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00004153
Jim Ingham0f16e732011-02-08 05:20:59 +00004154 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00004155 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004156 // Do the initial resume and wait for the running event before going further.
4157
Jim Ingham3b8285d2012-04-19 01:40:33 +00004158 Error resume_error = PrivateResume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00004159 if (!resume_error.Success())
4160 {
4161 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00004162 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00004163 break;
4164 }
4165
4166 real_timeout = TimeValue::Now();
4167 real_timeout.OffsetWithMicroSeconds(500000);
4168 timeout_ptr = &real_timeout;
4169
Sean Callananc1b312a2012-01-05 02:00:14 +00004170 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
Jim Ingham076b3042012-04-10 01:21:57 +00004171 if (!got_event)
Jim Ingham0f16e732011-02-08 05:20:59 +00004172 {
4173 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004174 log->PutCString("Process::RunThreadPlan(): didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004175
4176 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004177 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00004178 break;
4179 }
4180
4181 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4182 if (stop_state != eStateRunning)
4183 {
4184 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004185 log->Printf("Process::RunThreadPlan(): didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00004186
4187 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00004188 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00004189 break;
4190 }
4191
4192 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004193 log->PutCString ("Process::RunThreadPlan(): resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004194 // We need to call the function synchronously, so spin waiting for it to return.
4195 // If we get interrupted while executing, we're going to lose our context, and
4196 // won't be able to gather the result at this point.
4197 // We set the timeout AFTER the resume, since the resume takes some time and we
4198 // don't want to charge that to the timeout.
4199
4200 if (single_thread_timeout_usec != 0)
4201 {
4202 real_timeout = TimeValue::Now();
Jim Inghame39f85c2012-04-13 23:09:49 +00004203 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
Jim Ingham0f16e732011-02-08 05:20:59 +00004204
4205 timeout_ptr = &real_timeout;
4206 }
4207 }
4208 else
4209 {
4210 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004211 log->PutCString ("Process::RunThreadPlan(): handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004212 do_resume = true;
4213 }
4214
4215 // Now wait for the process to stop again:
4216 stop_state = lldb::eStateInvalid;
4217 event_sp.reset();
Jim Inghame39f85c2012-04-13 23:09:49 +00004218
4219 if (log)
4220 {
4221 if (timeout_ptr)
4222 {
4223 StreamString s;
4224 s.Printf ("about to wait - timeout is:\n ");
4225 timeout_ptr->Dump (&s, 120);
4226 s.Printf ("\nNow is:\n ");
4227 TimeValue::Now().Dump (&s, 120);
4228 log->Printf ("Process::RunThreadPlan(): %s", s.GetData());
4229 }
4230 else
4231 {
4232 log->Printf ("Process::RunThreadPlan(): about to wait forever.");
4233 }
4234 }
4235
Jim Ingham0f16e732011-02-08 05:20:59 +00004236 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4237
4238 if (got_event)
4239 {
4240 if (event_sp.get())
4241 {
4242 bool keep_going = false;
4243 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4244 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004245 log->Printf("Process::RunThreadPlan(): in while loop, got event: %s.", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00004246
4247 switch (stop_state)
4248 {
4249 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00004250 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004251 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00004252 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00004253 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00004254 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004255 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00004256 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004257 log->Printf ("Process::RunThreadPlan(): execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00004258 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00004259 }
4260 else
4261 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00004262 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4263 StopReason stop_reason = eStopReasonInvalid;
4264 if (stop_info_sp)
4265 stop_reason = stop_info_sp->GetStopReason();
4266 if (stop_reason == eStopReasonPlanComplete)
4267 {
4268 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004269 log->PutCString ("Process::RunThreadPlan(): execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004270 // Now mark this plan as private so it doesn't get reported as the stop reason
4271 // after this point.
4272 if (thread_plan_sp)
4273 thread_plan_sp->SetPrivate (orig_plan_private);
4274 return_value = eExecutionCompleted;
4275 }
4276 else
4277 {
4278 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004279 log->PutCString ("Process::RunThreadPlan(): thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00004280
4281 return_value = eExecutionInterrupted;
4282 }
Jim Ingham160f78c2011-05-17 01:10:11 +00004283 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00004284 }
4285 break;
4286
Jim Ingham0f16e732011-02-08 05:20:59 +00004287 case lldb::eStateCrashed:
4288 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004289 log->PutCString ("Process::RunThreadPlan(): execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004290 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004291 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004292
Jim Ingham0f16e732011-02-08 05:20:59 +00004293 case lldb::eStateRunning:
4294 do_resume = false;
4295 keep_going = true;
4296 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00004297
Jim Ingham0f16e732011-02-08 05:20:59 +00004298 default:
4299 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004300 log->Printf("Process::RunThreadPlan(): execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00004301
4302 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004303 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004304 break;
4305 }
4306 if (keep_going)
4307 continue;
4308 else
4309 break;
4310 }
4311 else
4312 {
4313 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004314 log->PutCString ("Process::RunThreadPlan(): got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00004315 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004316 break;
4317 }
4318 }
4319 else
4320 {
4321 // If we didn't get an event that means we've timed out...
4322 // We will interrupt the process here. Depending on what we were asked to do we will
4323 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00004324 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00004325
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004326 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00004327 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00004328 {
4329 if (first_timeout)
4330 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4331 "trying with all threads enabled.",
4332 single_thread_timeout_usec);
4333 else
4334 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4335 "and timeout: %d timed out.",
4336 single_thread_timeout_usec);
4337 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004338 else
Jim Ingham0f16e732011-02-08 05:20:59 +00004339 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4340 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00004341 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00004342 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004343
Greg Claytonc14ee322011-09-22 04:58:26 +00004344 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00004345 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00004346 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004347 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004348 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004349
Jim Ingham0f16e732011-02-08 05:20:59 +00004350 // If halt succeeds, it always produces a stopped event. Wait for that:
4351
4352 real_timeout = TimeValue::Now();
4353 real_timeout.OffsetWithMicroSeconds(500000);
4354
4355 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00004356
4357 if (got_event)
4358 {
4359 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4360 if (log)
4361 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004362 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00004363 if (stop_state == lldb::eStateStopped
4364 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00004365 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00004366 }
4367
Jim Ingham0f16e732011-02-08 05:20:59 +00004368 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00004369 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004370 // Between the time we initiated the Halt and the time we delivered it, the process could have
4371 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00004372
Greg Claytonc14ee322011-09-22 04:58:26 +00004373 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004374 {
4375 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004376 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004377 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004378 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004379 break;
4380 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004381
Jim Ingham0f16e732011-02-08 05:20:59 +00004382 if (!try_all_threads)
4383 {
4384 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004385 log->PutCString ("Process::RunThreadPlan(): try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004386 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004387 break;
4388 }
4389
4390 if (first_timeout)
4391 {
4392 // Set all the other threads to run, and return to the top of the loop, which will continue;
4393 first_timeout = false;
4394 thread_plan_sp->SetStopOthers (false);
4395 if (log)
Jim Inghame39f85c2012-04-13 23:09:49 +00004396 log->PutCString ("Process::RunThreadPlan(): about to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004397
4398 continue;
4399 }
4400 else
4401 {
4402 // Running all threads failed, so return Interrupted.
4403 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004404 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004405 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004406 break;
4407 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004408 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004409 }
4410 else
4411 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004412 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004413 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004414 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004415 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00004416 }
4417 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004418 else
4419 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004420 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4421 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00004422 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004423 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.",
4424 halt_error.AsCString());
4425 real_timeout = TimeValue::Now();
4426 real_timeout.OffsetWithMicroSeconds(500000);
4427 timeout_ptr = &real_timeout;
4428 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4429 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004430 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004431 // This is not going anywhere, bag out.
4432 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004433 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004434 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004435 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00004436 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004437 else
4438 {
4439 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4440 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004441 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00004442 if (stop_state == lldb::eStateStopped)
4443 {
4444 // Between the time we initiated the Halt and the time we delivered it, the process could have
4445 // already finished its job. Check that here:
4446
Greg Claytonc14ee322011-09-22 04:58:26 +00004447 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00004448 {
4449 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004450 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00004451 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004452 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004453 break;
4454 }
4455
4456 if (first_timeout)
4457 {
4458 // Set all the other threads to run, and return to the top of the loop, which will continue;
4459 first_timeout = false;
4460 thread_plan_sp->SetStopOthers (false);
4461 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004462 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004463
4464 continue;
4465 }
4466 else
4467 {
4468 // Running all threads failed, so return Interrupted.
4469 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004470 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00004471 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004472 break;
4473 }
4474 }
4475 else
4476 {
Sean Callanan39821ac2011-08-09 22:07:08 +00004477 if (log)
4478 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4479 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00004480 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00004481 break;
4482 }
4483 }
Jim Inghame22e88b2011-01-22 01:30:53 +00004484 }
4485
Jim Inghamf48169b2010-11-30 02:22:11 +00004486 }
4487
Jim Ingham0f16e732011-02-08 05:20:59 +00004488 } // END WAIT LOOP
4489
Jim Ingham372787f2012-04-07 00:00:41 +00004490 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4491 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4492 {
4493 StopPrivateStateThread();
Jim Ingham372787f2012-04-07 00:00:41 +00004494 Error error;
Jim Ingham372787f2012-04-07 00:00:41 +00004495 m_private_state_thread = backup_private_state_thread;
Jim Ingham076b3042012-04-10 01:21:57 +00004496 if (stopper_base_plan_sp != NULL)
4497 {
4498 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4499 }
4500 m_public_state.SetValueNoLock(old_state);
4501
Jim Ingham372787f2012-04-07 00:00:41 +00004502 }
4503
4504
Jim Ingham0f16e732011-02-08 05:20:59 +00004505 // Now do some processing on the results of the run:
4506 if (return_value == eExecutionInterrupted)
4507 {
Jim Inghamf48169b2010-11-30 02:22:11 +00004508 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00004509 {
4510 StreamString s;
4511 if (event_sp)
4512 event_sp->Dump (&s);
4513 else
4514 {
Jim Ingham20829ac2011-08-09 22:24:33 +00004515 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004516 }
4517
4518 StreamString ts;
4519
Jim Ingham20829ac2011-08-09 22:24:33 +00004520 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00004521
4522 do
4523 {
4524 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4525
4526 if (!event_data)
4527 {
4528 event_explanation = "<no event data>";
4529 break;
4530 }
4531
4532 Process *process = event_data->GetProcessSP().get();
4533
4534 if (!process)
4535 {
4536 event_explanation = "<no process>";
4537 break;
4538 }
4539
4540 ThreadList &thread_list = process->GetThreadList();
4541
4542 uint32_t num_threads = thread_list.GetSize();
4543 uint32_t thread_index;
4544
4545 ts.Printf("<%u threads> ", num_threads);
4546
4547 for (thread_index = 0;
4548 thread_index < num_threads;
4549 ++thread_index)
4550 {
4551 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4552
4553 if (!thread)
4554 {
4555 ts.Printf("<?> ");
4556 continue;
4557 }
4558
Greg Clayton81c22f62011-10-19 18:09:39 +00004559 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Ingham0f16e732011-02-08 05:20:59 +00004560 RegisterContext *register_context = thread->GetRegisterContext().get();
4561
4562 if (register_context)
4563 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4564 else
4565 ts.Printf("[ip unknown] ");
4566
4567 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4568 if (stop_info_sp)
4569 {
4570 const char *stop_desc = stop_info_sp->GetDescription();
4571 if (stop_desc)
4572 ts.PutCString (stop_desc);
4573 }
4574 ts.Printf(">");
4575 }
4576
4577 event_explanation = ts.GetData();
4578 } while (0);
4579
4580 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004581 {
4582 if (event_explanation)
4583 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4584 else
4585 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4586 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004587
4588 if (discard_on_error && thread_plan_sp)
4589 {
Jim Inghame39f85c2012-04-13 23:09:49 +00004590 if (log)
4591 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - discarding thread plans up to %p.", thread_plan_sp.get());
Greg Claytonc14ee322011-09-22 04:58:26 +00004592 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004593 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004594 }
Jim Inghame39f85c2012-04-13 23:09:49 +00004595 else
4596 {
4597 if (log)
4598 log->Printf ("Process::RunThreadPlan: ExecutionInterrupted - for plan: %p not discarding.", thread_plan_sp.get());
4599
4600 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004601 }
4602 }
4603 else if (return_value == eExecutionSetupError)
4604 {
4605 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004606 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00004607
4608 if (discard_on_error && thread_plan_sp)
4609 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004610 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004611 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00004612 }
4613 }
4614 else
4615 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004616 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004617 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004618 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004619 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00004620 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00004621 }
Greg Claytonc14ee322011-09-22 04:58:26 +00004622 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00004623 {
Greg Clayton414f5d32011-01-25 02:58:48 +00004624 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004625 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00004626 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00004627 }
4628 else
4629 {
4630 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004631 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00004632 if (discard_on_error && thread_plan_sp)
4633 {
Jim Ingham0f16e732011-02-08 05:20:59 +00004634 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00004635 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00004636 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00004637 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00004638 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004639 }
4640 }
Jim Ingham0f16e732011-02-08 05:20:59 +00004641
Jim Inghamf48169b2010-11-30 02:22:11 +00004642 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00004643 // Check that it's still there, and if it is put it back in the context. Also restore the
4644 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00004645 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4646 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00004647 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004648 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00004649 }
Jim Inghamf48169b2010-11-30 02:22:11 +00004650
4651 // Also restore the current process'es selected frame & thread, since this function calling may
4652 // be done behind the user's back.
4653
4654 if (selected_tid != LLDB_INVALID_THREAD_ID)
4655 {
Greg Claytonc14ee322011-09-22 04:58:26 +00004656 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00004657 {
4658 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00004659 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00004660 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00004661 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00004662 }
4663 }
4664
4665 return return_value;
4666}
4667
4668const char *
4669Process::ExecutionResultAsCString (ExecutionResults result)
4670{
4671 const char *result_name;
4672
4673 switch (result)
4674 {
Greg Claytone0d378b2011-03-24 21:19:54 +00004675 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004676 result_name = "eExecutionCompleted";
4677 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004678 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00004679 result_name = "eExecutionDiscarded";
4680 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004681 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00004682 result_name = "eExecutionInterrupted";
4683 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004684 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00004685 result_name = "eExecutionSetupError";
4686 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00004687 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00004688 result_name = "eExecutionTimedOut";
4689 break;
4690 }
4691 return result_name;
4692}
4693
Greg Clayton7260f622011-04-18 08:33:37 +00004694void
4695Process::GetStatus (Stream &strm)
4696{
4697 const StateType state = GetState();
Greg Clayton2637f822011-11-17 01:23:07 +00004698 if (StateIsStoppedState(state, false))
Greg Clayton7260f622011-04-18 08:33:37 +00004699 {
4700 if (state == eStateExited)
4701 {
4702 int exit_status = GetExitStatus();
4703 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00004704 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00004705 GetID(),
4706 exit_status,
4707 exit_status,
4708 exit_description ? exit_description : "");
4709 }
4710 else
4711 {
4712 if (state == eStateConnected)
4713 strm.Printf ("Connected to remote target.\n");
4714 else
Greg Clayton81c22f62011-10-19 18:09:39 +00004715 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00004716 }
4717 }
4718 else
4719 {
Greg Clayton81c22f62011-10-19 18:09:39 +00004720 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00004721 }
4722}
4723
4724size_t
4725Process::GetThreadStatus (Stream &strm,
4726 bool only_threads_with_stop_reason,
4727 uint32_t start_frame,
4728 uint32_t num_frames,
4729 uint32_t num_frames_with_source)
4730{
4731 size_t num_thread_infos_dumped = 0;
4732
4733 const size_t num_threads = GetThreadList().GetSize();
4734 for (uint32_t i = 0; i < num_threads; i++)
4735 {
4736 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4737 if (thread)
4738 {
4739 if (only_threads_with_stop_reason)
4740 {
4741 if (thread->GetStopInfo().get() == NULL)
4742 continue;
4743 }
4744 thread->GetStatus (strm,
4745 start_frame,
4746 num_frames,
4747 num_frames_with_source);
4748 ++num_thread_infos_dumped;
4749 }
4750 }
4751 return num_thread_infos_dumped;
4752}
4753
Greg Claytona9f40ad2012-02-22 04:37:26 +00004754void
4755Process::AddInvalidMemoryRegion (const LoadRange &region)
4756{
4757 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4758}
4759
4760bool
4761Process::RemoveInvalidMemoryRange (const LoadRange &region)
4762{
4763 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4764}
4765
Jim Ingham372787f2012-04-07 00:00:41 +00004766void
4767Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4768{
4769 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4770}
4771
4772bool
4773Process::RunPreResumeActions ()
4774{
4775 bool result = true;
4776 while (!m_pre_resume_actions.empty())
4777 {
4778 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
4779 m_pre_resume_actions.pop_back();
4780 bool this_result = action.callback (action.baton);
4781 if (result == true) result = this_result;
4782 }
4783 return result;
4784}
4785
4786void
4787Process::ClearPreResumeActions ()
4788{
4789 m_pre_resume_actions.clear();
4790}
Greg Claytona9f40ad2012-02-22 04:37:26 +00004791
Greg Claytonfa559e52012-05-18 02:38:05 +00004792void
4793Process::Flush ()
4794{
4795 m_thread_list.Flush();
4796}
4797
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004798//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004799// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004800//--------------------------------------------------------------
4801
Greg Clayton1b654882010-09-19 02:33:57 +00004802Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004803 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004804{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004805}
4806
Greg Clayton1b654882010-09-19 02:33:57 +00004807Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004808{
4809}
4810
4811lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004812Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004813{
Greg Claytonb9556ac2012-01-30 07:41:31 +00004814 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4815 false,
4816 instance_name));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004817 return new_settings_sp;
4818}
4819
4820//--------------------------------------------------------------
4821// class ProcessInstanceSettings
4822//--------------------------------------------------------------
4823
Greg Clayton85851dd2010-12-04 00:10:17 +00004824ProcessInstanceSettings::ProcessInstanceSettings
4825(
Greg Claytonb9556ac2012-01-30 07:41:31 +00004826 const UserSettingsControllerSP &owner_sp,
Greg Clayton85851dd2010-12-04 00:10:17 +00004827 bool live_instance,
4828 const char *name
4829) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004830 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004831{
Caroline Ticef20e8232010-09-09 18:26:37 +00004832 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4833 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4834 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice9e41c152010-09-16 19:05:55 +00004835 // This is true for CreateInstanceName() too.
Greg Clayton1d885962011-11-08 02:43:13 +00004836
Caroline Tice9e41c152010-09-16 19:05:55 +00004837 if (GetInstanceName () == InstanceSettings::InvalidName())
4838 {
4839 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
Greg Claytonb9556ac2012-01-30 07:41:31 +00004840 owner_sp->RegisterInstanceSettings (this);
Caroline Tice9e41c152010-09-16 19:05:55 +00004841 }
Greg Clayton1d885962011-11-08 02:43:13 +00004842
Caroline Ticef20e8232010-09-09 18:26:37 +00004843 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004844 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004845 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004846 CopyInstanceSettings (pending_settings,false);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004847 }
4848}
4849
4850ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonb9556ac2012-01-30 07:41:31 +00004851 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004852{
4853 if (m_instance_name != InstanceSettings::GetDefaultName())
4854 {
Greg Claytonb9556ac2012-01-30 07:41:31 +00004855 UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4856 if (owner_sp)
4857 {
4858 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4859 owner_sp->RemovePendingSettings (m_instance_name);
4860 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004861 }
4862}
4863
4864ProcessInstanceSettings::~ProcessInstanceSettings ()
4865{
4866}
4867
4868ProcessInstanceSettings&
4869ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4870{
4871 if (this != &rhs)
4872 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004873 }
4874
4875 return *this;
4876}
4877
4878
4879void
4880ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4881 const char *index_value,
4882 const char *value,
4883 const ConstString &instance_name,
4884 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004885 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004886 Error &err,
4887 bool pending)
4888{
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004889}
4890
4891void
4892ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4893 bool pending)
4894{
Greg Clayton1d885962011-11-08 02:43:13 +00004895// if (new_settings.get() == NULL)
4896// return;
4897//
4898// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004899}
4900
Caroline Tice12cecd72010-09-20 21:37:42 +00004901bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004902ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4903 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004904 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004905 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004906{
Greg Clayton1d885962011-11-08 02:43:13 +00004907 if (err)
4908 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4909 return false;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004910}
4911
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004912const ConstString
4913ProcessInstanceSettings::CreateInstanceName ()
4914{
4915 static int instance_count = 1;
4916 StreamString sstr;
4917
4918 sstr.Printf ("process_%d", instance_count);
4919 ++instance_count;
4920
4921 const ConstString ret_val (sstr.GetData());
4922 return ret_val;
4923}
4924
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004925//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004926// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004927//--------------------------------------------------
4928
4929SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004930Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004931{
4932 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4933 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4934};
4935
4936
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004937SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004938Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004939{
Greg Clayton85851dd2010-12-04 00:10:17 +00004940 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton85851dd2010-12-04 00:10:17 +00004941 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004942};
4943
4944
Jim Ingham5aee1622010-08-09 23:31:02 +00004945
Greg Clayton1d885962011-11-08 02:43:13 +00004946