blob: 97f8c5400409f5abff55c6d66f0287d70d526959 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Tice861efb32010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Tice861efb32010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytonf15996e2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton0baa3942010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton37f962e2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham642036f2010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
Jim Inghamd21d98b2012-04-10 01:21:57 +000039#include "lldb/Target/ThreadPlanBase.h"
Chris Lattner24943d22010-06-08 16:52:24 +000040
41using namespace lldb;
42using namespace lldb_private;
43
Greg Clayton24bc5d92011-03-30 18:16:51 +000044void
Greg Claytonb72d0f02011-04-12 05:54:46 +000045ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +000046{
47 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +000048 if (m_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +000049 s.Printf (" pid = %llu\n", m_pid);
Greg Claytonff39f742011-04-01 00:29:43 +000050
51 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytond9919d32011-12-01 23:28:38 +000052 s.Printf (" parent = %llu\n", m_parent_pid);
Greg Claytonff39f742011-04-01 00:29:43 +000053
54 if (m_executable)
55 {
56 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
57 s.PutCString (" file = ");
58 m_executable.Dump(&s);
59 s.EOL();
60 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000061 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +000062 if (argc > 0)
63 {
64 for (uint32_t i=0; i<argc; i++)
65 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000066 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +000067 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +000068 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000069 else
Greg Claytonb72d0f02011-04-12 05:54:46 +000070 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000071 }
72 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000073
74 const uint32_t envc = m_environment.GetArgumentCount();
75 if (envc > 0)
76 {
77 for (uint32_t i=0; i<envc; i++)
78 {
79 const char *env = m_environment.GetArgumentAtIndex(i);
80 if (i < 10)
81 s.Printf (" env[%u] = %s\n", i, env);
82 else
83 s.Printf ("env[%u] = %s\n", i, env);
84 }
85 }
86
Greg Claytonff39f742011-04-01 00:29:43 +000087 if (m_arch.IsValid())
88 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
89
Greg Claytonb72d0f02011-04-12 05:54:46 +000090 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000091 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000092 cstr = platform->GetUserName (m_uid);
93 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000094 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000095 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000096 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000097 cstr = platform->GetGroupName (m_gid);
98 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000099 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000100 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000101 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000102 cstr = platform->GetUserName (m_euid);
103 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000104 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000105 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000106 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000107 cstr = platform->GetGroupName (m_egid);
108 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000109 }
110}
111
112void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000113ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000114{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000115 const char *label;
116 if (show_args || verbose)
117 label = "ARGUMENTS";
118 else
119 label = "NAME";
120
Greg Claytonff39f742011-04-01 00:29:43 +0000121 if (verbose)
122 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000123 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000124 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
125 }
126 else
127 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000128 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000129 s.PutCString ("====== ====== ========== ======= ============================\n");
130 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000131}
132
133void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000134ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000135{
136 if (m_pid != LLDB_INVALID_PROCESS_ID)
137 {
138 const char *cstr;
Greg Claytond9919d32011-12-01 23:28:38 +0000139 s.Printf ("%-6llu %-6llu ", m_pid, m_parent_pid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000140
Greg Clayton24bc5d92011-03-30 18:16:51 +0000141
Greg Claytonff39f742011-04-01 00:29:43 +0000142 if (verbose)
143 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000144 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000145 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
146 s.Printf ("%-10s ", cstr);
147 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000148 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000149
Greg Claytonb72d0f02011-04-12 05:54:46 +0000150 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000151 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
152 s.Printf ("%-10s ", cstr);
153 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000154 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000155
Greg Claytonb72d0f02011-04-12 05:54:46 +0000156 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000157 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
158 s.Printf ("%-10s ", cstr);
159 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000160 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000161
Greg Claytonb72d0f02011-04-12 05:54:46 +0000162 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000163 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
164 s.Printf ("%-10s ", cstr);
165 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000166 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000167 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
168 }
169 else
170 {
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000171 s.Printf ("%-10s %-7d %s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000172 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000173 (int)m_arch.GetTriple().getArchName().size(),
174 m_arch.GetTriple().getArchName().data());
175 }
176
Greg Claytonb72d0f02011-04-12 05:54:46 +0000177 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000178 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000179 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000180 if (argc > 0)
181 {
182 for (uint32_t i=0; i<argc; i++)
183 {
184 if (i > 0)
185 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000186 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000187 }
188 }
189 }
190 else
191 {
192 s.PutCString (GetName());
193 }
194
195 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000196 }
197}
198
Greg Claytonb72d0f02011-04-12 05:54:46 +0000199
200void
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000201ProcessInfo::SetArguments (char const **argv,
202 bool first_arg_is_executable,
203 bool first_arg_is_executable_and_argument)
204{
205 m_arguments.SetArguments (argv);
206
207 // Is the first argument the executable?
208 if (first_arg_is_executable)
209 {
210 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
211 if (first_arg)
212 {
213 // Yes the first argument is an executable, set it as the executable
214 // in the launch options. Don't resolve the file path as the path
215 // could be a remote platform path
216 const bool resolve = false;
217 m_executable.SetFile(first_arg, resolve);
218
219 // If argument zero is an executable and shouldn't be included
220 // in the arguments, remove it from the front of the arguments
221 if (first_arg_is_executable_and_argument == false)
222 m_arguments.DeleteArgumentAtIndex (0);
223 }
224 }
225}
226void
227ProcessInfo::SetArguments (const Args& args,
228 bool first_arg_is_executable,
229 bool first_arg_is_executable_and_argument)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000230{
231 // Copy all arguments
232 m_arguments = args;
233
234 // Is the first argument the executable?
235 if (first_arg_is_executable)
236 {
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000237 const char *first_arg = m_arguments.GetArgumentAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000238 if (first_arg)
239 {
240 // Yes the first argument is an executable, set it as the executable
241 // in the launch options. Don't resolve the file path as the path
242 // could be a remote platform path
243 const bool resolve = false;
244 m_executable.SetFile(first_arg, resolve);
245
246 // If argument zero is an executable and shouldn't be included
247 // in the arguments, remove it from the front of the arguments
248 if (first_arg_is_executable_and_argument == false)
249 m_arguments.DeleteArgumentAtIndex (0);
250 }
251 }
252}
253
Greg Claytonabb33022011-11-08 02:43:13 +0000254void
Greg Clayton464c6162011-11-17 22:14:31 +0000255ProcessLaunchInfo::FinalizeFileActions (Target *target, bool default_to_use_pty)
Greg Claytonabb33022011-11-08 02:43:13 +0000256{
257 // If notthing was specified, then check the process for any default
258 // settings that were set with "settings set"
259 if (m_file_actions.empty())
260 {
Greg Claytonabb33022011-11-08 02:43:13 +0000261 if (m_flags.Test(eLaunchFlagDisableSTDIO))
262 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000263 AppendSuppressFileAction (STDIN_FILENO , true, false);
264 AppendSuppressFileAction (STDOUT_FILENO, false, true);
265 AppendSuppressFileAction (STDERR_FILENO, false, true);
Greg Claytonabb33022011-11-08 02:43:13 +0000266 }
267 else
268 {
269 // Check for any values that might have gotten set with any of:
270 // (lldb) settings set target.input-path
271 // (lldb) settings set target.output-path
272 // (lldb) settings set target.error-path
Greg Clayton464c6162011-11-17 22:14:31 +0000273 const char *in_path = NULL;
274 const char *out_path = NULL;
275 const char *err_path = NULL;
Greg Claytonabb33022011-11-08 02:43:13 +0000276 if (target)
277 {
Greg Clayton95ec1682012-03-06 04:01:04 +0000278 in_path = target->GetStandardInputPath();
279 out_path = target->GetStandardOutputPath();
280 err_path = target->GetStandardErrorPath();
Greg Clayton464c6162011-11-17 22:14:31 +0000281 }
282
283 if (default_to_use_pty && (!in_path && !out_path && !err_path))
284 {
285 if (m_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, NULL, 0))
Greg Claytonabb33022011-11-08 02:43:13 +0000286 {
Greg Clayton464c6162011-11-17 22:14:31 +0000287 in_path = out_path = err_path = m_pty.GetSlaveName (NULL, 0);
Greg Claytonabb33022011-11-08 02:43:13 +0000288 }
289 }
290
Greg Clayton464c6162011-11-17 22:14:31 +0000291 if (in_path)
Greg Clayton95ec1682012-03-06 04:01:04 +0000292 AppendOpenFileAction(STDIN_FILENO, in_path, true, false);
293
Greg Clayton464c6162011-11-17 22:14:31 +0000294 if (out_path)
Greg Clayton95ec1682012-03-06 04:01:04 +0000295 AppendOpenFileAction(STDOUT_FILENO, out_path, false, true);
Greg Clayton464c6162011-11-17 22:14:31 +0000296
297 if (err_path)
Greg Clayton95ec1682012-03-06 04:01:04 +0000298 AppendOpenFileAction(STDERR_FILENO, err_path, false, true);
299
Greg Claytonabb33022011-11-08 02:43:13 +0000300 }
301 }
302}
303
Greg Clayton527154d2011-11-15 03:53:30 +0000304
305bool
306ProcessLaunchInfo::ConvertArgumentsForLaunchingInShell (Error &error, bool localhost)
307{
308 error.Clear();
309
310 if (GetFlags().Test (eLaunchFlagLaunchInShell))
311 {
312 const char *shell_executable = GetShell();
313 if (shell_executable)
314 {
315 char shell_resolved_path[PATH_MAX];
316
317 if (localhost)
318 {
319 FileSpec shell_filespec (shell_executable, true);
320
321 if (!shell_filespec.Exists())
322 {
323 // Resolve the path in case we just got "bash", "sh" or "tcsh"
324 if (!shell_filespec.ResolveExecutableLocation ())
325 {
326 error.SetErrorStringWithFormat("invalid shell path '%s'", shell_executable);
327 return false;
328 }
329 }
330 shell_filespec.GetPath (shell_resolved_path, sizeof(shell_resolved_path));
331 shell_executable = shell_resolved_path;
332 }
333
334 Args shell_arguments;
335 std::string safe_arg;
336 shell_arguments.AppendArgument (shell_executable);
337 StreamString shell_command;
338 shell_arguments.AppendArgument ("-c");
339 shell_command.PutCString ("exec");
340 if (GetArchitecture().IsValid())
341 {
342 shell_command.Printf(" /usr/bin/arch -arch %s", GetArchitecture().GetArchitectureName());
343 // Set the resume count to 2:
344 // 1 - stop in shell
345 // 2 - stop in /usr/bin/arch
346 // 3 - then we will stop in our program
347 SetResumeCount(2);
348 }
349 else
350 {
351 // Set the resume count to 1:
352 // 1 - stop in shell
353 // 2 - then we will stop in our program
354 SetResumeCount(1);
355 }
356
357 const char **argv = GetArguments().GetConstArgumentVector ();
358 if (argv)
359 {
360 for (size_t i=0; argv[i] != NULL; ++i)
361 {
362 const char *arg = Args::GetShellSafeArgument (argv[i], safe_arg);
363 shell_command.Printf(" %s", arg);
364 }
365 }
366 shell_arguments.AppendArgument (shell_command.GetString().c_str());
367
368 m_executable.SetFile(shell_executable, false);
369 m_arguments = shell_arguments;
370 return true;
371 }
372 else
373 {
374 error.SetErrorString ("invalid shell path");
375 }
376 }
377 else
378 {
379 error.SetErrorString ("not launching in shell");
380 }
381 return false;
382}
383
384
Greg Clayton24bc5d92011-03-30 18:16:51 +0000385bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000386ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
387{
388 if ((read || write) && fd >= 0 && path && path[0])
389 {
390 m_action = eFileActionOpen;
391 m_fd = fd;
392 if (read && write)
Greg Clayton527154d2011-11-15 03:53:30 +0000393 m_arg = O_NOCTTY | O_CREAT | O_RDWR;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000394 else if (read)
Greg Clayton527154d2011-11-15 03:53:30 +0000395 m_arg = O_NOCTTY | O_RDONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000396 else
Greg Clayton527154d2011-11-15 03:53:30 +0000397 m_arg = O_NOCTTY | O_CREAT | O_WRONLY;
Greg Claytonb72d0f02011-04-12 05:54:46 +0000398 m_path.assign (path);
399 return true;
400 }
401 else
402 {
403 Clear();
404 }
405 return false;
406}
407
408bool
409ProcessLaunchInfo::FileAction::Close (int fd)
410{
411 Clear();
412 if (fd >= 0)
413 {
414 m_action = eFileActionClose;
415 m_fd = fd;
416 }
417 return m_fd >= 0;
418}
419
420
421bool
422ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
423{
424 Clear();
425 if (fd >= 0 && dup_fd >= 0)
426 {
427 m_action = eFileActionDuplicate;
428 m_fd = fd;
429 m_arg = dup_fd;
430 }
431 return m_fd >= 0;
432}
433
434
435
436bool
437ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
438 const FileAction *info,
439 Log *log,
440 Error& error)
441{
442 if (info == NULL)
443 return false;
444
445 switch (info->m_action)
446 {
447 case eFileActionNone:
448 error.Clear();
449 break;
450
451 case eFileActionClose:
452 if (info->m_fd == -1)
453 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
454 else
455 {
456 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
457 eErrorTypePOSIX);
458 if (log && (error.Fail() || log))
459 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
460 file_actions, info->m_fd);
461 }
462 break;
463
464 case eFileActionDuplicate:
465 if (info->m_fd == -1)
466 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
467 else if (info->m_arg == -1)
468 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
469 else
470 {
471 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
472 eErrorTypePOSIX);
473 if (log && (error.Fail() || log))
474 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
475 file_actions, info->m_fd, info->m_arg);
476 }
477 break;
478
479 case eFileActionOpen:
480 if (info->m_fd == -1)
481 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
482 else
483 {
484 int oflag = info->m_arg;
Greg Clayton527154d2011-11-15 03:53:30 +0000485
Greg Claytonb72d0f02011-04-12 05:54:46 +0000486 mode_t mode = 0;
487
Greg Clayton527154d2011-11-15 03:53:30 +0000488 if (oflag & O_CREAT)
489 mode = 0640;
490
Greg Claytonb72d0f02011-04-12 05:54:46 +0000491 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
492 info->m_fd,
493 info->m_path.c_str(),
494 oflag,
495 mode),
496 eErrorTypePOSIX);
497 if (error.Fail() || log)
498 error.PutToLog(log,
499 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
500 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
501 }
502 break;
503
504 default:
505 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
506 break;
507 }
508 return error.Success();
509}
510
511Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000512ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000513{
514 Error error;
515 char short_option = (char) m_getopt_table[option_idx].val;
516
517 switch (short_option)
518 {
519 case 's': // Stop at program entry point
520 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
521 break;
522
Greg Claytonb72d0f02011-04-12 05:54:46 +0000523 case 'i': // STDIN for read only
524 {
525 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000526 if (action.Open (STDIN_FILENO, option_arg, true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000527 launch_info.AppendFileAction (action);
528 }
529 break;
530
531 case 'o': // Open STDOUT for write only
532 {
533 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000534 if (action.Open (STDOUT_FILENO, option_arg, false, true))
535 launch_info.AppendFileAction (action);
536 }
537 break;
538
539 case 'e': // STDERR for write only
540 {
541 ProcessLaunchInfo::FileAction action;
542 if (action.Open (STDERR_FILENO, option_arg, false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000543 launch_info.AppendFileAction (action);
544 }
545 break;
546
Greg Clayton95ec1682012-03-06 04:01:04 +0000547
Greg Claytonb72d0f02011-04-12 05:54:46 +0000548 case 'p': // Process plug-in name
549 launch_info.SetProcessPluginName (option_arg);
550 break;
551
552 case 'n': // Disable STDIO
553 {
554 ProcessLaunchInfo::FileAction action;
Greg Clayton95ec1682012-03-06 04:01:04 +0000555 if (action.Open (STDIN_FILENO, "/dev/null", true, false))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000556 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000557 if (action.Open (STDOUT_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000558 launch_info.AppendFileAction (action);
Greg Clayton95ec1682012-03-06 04:01:04 +0000559 if (action.Open (STDERR_FILENO, "/dev/null", false, true))
Greg Claytonb72d0f02011-04-12 05:54:46 +0000560 launch_info.AppendFileAction (action);
561 }
562 break;
563
564 case 'w':
565 launch_info.SetWorkingDirectory (option_arg);
566 break;
567
568 case 't': // Open process in new terminal window
569 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
570 break;
571
572 case 'a':
573 launch_info.GetArchitecture().SetTriple (option_arg,
574 m_interpreter.GetPlatform(true).get());
575 break;
576
577 case 'A':
578 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
579 break;
580
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000581 case 'c':
Greg Clayton527154d2011-11-15 03:53:30 +0000582 if (option_arg && option_arg[0])
583 launch_info.SetShell (option_arg);
584 else
585 launch_info.SetShell ("/bin/bash");
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000586 break;
587
Greg Claytonb72d0f02011-04-12 05:54:46 +0000588 case 'v':
589 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
590 break;
591
592 default:
Greg Clayton9c236732011-10-26 00:56:27 +0000593 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Claytonb72d0f02011-04-12 05:54:46 +0000594 break;
595
596 }
597 return error;
598}
599
600OptionDefinition
601ProcessLaunchCommandOptions::g_option_table[] =
602{
603{ 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."},
604{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
605{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
606{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
607{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
608{ LLDB_OPT_SET_ALL, false, "environment", 'v', required_argument, NULL, 0, eArgTypeNone, "Specify an environment variable name/value stirng (--environement NAME=VALUE). Can be specified multiple times for subsequent environment entries."},
Greg Clayton527154d2011-11-15 03:53:30 +0000609{ LLDB_OPT_SET_ALL, false, "shell", 'c', optional_argument, NULL, 0, eArgTypePath, "Run the process in a shell (not supported on all platforms)."},
Greg Claytonb72d0f02011-04-12 05:54:46 +0000610
611{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
612{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
613{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
614
615{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
616
617{ 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."},
618
619{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
620};
621
622
623
624bool
625ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000626{
627 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
628 return true;
629 const char *match_name = m_match_info.GetName();
630 if (!match_name)
631 return true;
632
633 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
634}
635
636bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000637ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000638{
639 if (!NameMatches (proc_info.GetName()))
640 return false;
641
642 if (m_match_info.ProcessIDIsValid() &&
643 m_match_info.GetProcessID() != proc_info.GetProcessID())
644 return false;
645
646 if (m_match_info.ParentProcessIDIsValid() &&
647 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
648 return false;
649
Greg Claytonb72d0f02011-04-12 05:54:46 +0000650 if (m_match_info.UserIDIsValid () &&
651 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000652 return false;
653
Greg Claytonb72d0f02011-04-12 05:54:46 +0000654 if (m_match_info.GroupIDIsValid () &&
655 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000656 return false;
657
658 if (m_match_info.EffectiveUserIDIsValid () &&
659 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
660 return false;
661
662 if (m_match_info.EffectiveGroupIDIsValid () &&
663 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
664 return false;
665
666 if (m_match_info.GetArchitecture().IsValid() &&
667 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
668 return false;
669 return true;
670}
671
672bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000673ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000674{
675 if (m_name_match_type != eNameMatchIgnore)
676 return false;
677
678 if (m_match_info.ProcessIDIsValid())
679 return false;
680
681 if (m_match_info.ParentProcessIDIsValid())
682 return false;
683
Greg Claytonb72d0f02011-04-12 05:54:46 +0000684 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000685 return false;
686
Greg Claytonb72d0f02011-04-12 05:54:46 +0000687 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000688 return false;
689
690 if (m_match_info.EffectiveUserIDIsValid ())
691 return false;
692
693 if (m_match_info.EffectiveGroupIDIsValid ())
694 return false;
695
696 if (m_match_info.GetArchitecture().IsValid())
697 return false;
698
699 if (m_match_all_users)
700 return false;
701
702 return true;
703
704}
705
706void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000707ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000708{
709 m_match_info.Clear();
710 m_name_match_type = eNameMatchIgnore;
711 m_match_all_users = false;
712}
Greg Claytonfd119992011-01-07 06:08:19 +0000713
Greg Clayton46c9a352012-02-09 06:16:32 +0000714ProcessSP
715Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener, const FileSpec *crash_file_path)
Chris Lattner24943d22010-06-08 16:52:24 +0000716{
Greg Clayton46c9a352012-02-09 06:16:32 +0000717 ProcessSP process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000718 ProcessCreateInstance create_callback = NULL;
719 if (plugin_name)
720 {
721 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
722 if (create_callback)
723 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000724 process_sp = create_callback(target, listener, crash_file_path);
725 if (process_sp)
726 {
727 if (!process_sp->CanDebug(target, true))
728 process_sp.reset();
729 }
Chris Lattner24943d22010-06-08 16:52:24 +0000730 }
731 }
732 else
733 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000734 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000735 {
Greg Clayton46c9a352012-02-09 06:16:32 +0000736 process_sp = create_callback(target, listener, crash_file_path);
737 if (process_sp)
738 {
739 if (!process_sp->CanDebug(target, false))
740 process_sp.reset();
741 else
742 break;
743 }
Chris Lattner24943d22010-06-08 16:52:24 +0000744 }
745 }
Greg Clayton46c9a352012-02-09 06:16:32 +0000746 return process_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000747}
748
Jim Ingham5a15e692012-02-16 06:50:00 +0000749ConstString &
750Process::GetStaticBroadcasterClass ()
751{
752 static ConstString class_name ("lldb.process");
753 return class_name;
754}
Chris Lattner24943d22010-06-08 16:52:24 +0000755
756//----------------------------------------------------------------------
757// Process constructor
758//----------------------------------------------------------------------
759Process::Process(Target &target, Listener &listener) :
760 UserID (LLDB_INVALID_PROCESS_ID),
Jim Ingham5a15e692012-02-16 06:50:00 +0000761 Broadcaster (&(target.GetDebugger()), "lldb.process"),
Greg Clayton334d33a2012-01-30 07:41:31 +0000762 ProcessInstanceSettings (GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000763 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000764 m_public_state (eStateUnloaded),
765 m_private_state (eStateUnloaded),
Jim Ingham5a15e692012-02-16 06:50:00 +0000766 m_private_state_broadcaster (NULL, "lldb.process.internal_state_broadcaster"),
767 m_private_state_control_broadcaster (NULL, "lldb.process.internal_state_control_broadcaster"),
Chris Lattner24943d22010-06-08 16:52:24 +0000768 m_private_state_listener ("lldb.process.internal_state_listener"),
769 m_private_state_control_wait(),
770 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham21f37ad2011-08-09 02:12:22 +0000771 m_mod_id (),
Chris Lattner24943d22010-06-08 16:52:24 +0000772 m_thread_index_id (0),
773 m_exit_status (-1),
774 m_exit_string (),
775 m_thread_list (this),
776 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000777 m_image_tokens (),
778 m_listener (listener),
779 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000780 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000781 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000782 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000783 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000784 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000785 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000786 m_stdout_data (),
Greg Claytonbd06ff42011-11-13 04:45:22 +0000787 m_stderr_data (),
Greg Clayton613b8732011-05-17 03:37:42 +0000788 m_memory_cache (*this),
789 m_allocated_memory_cache (*this),
Greg Claytonffa43a62011-11-17 04:46:02 +0000790 m_should_detach (false),
Sean Callanan6cf6c472011-09-20 23:01:51 +0000791 m_next_event_action_ap(),
Bill Wendlingce96dad2012-04-06 00:10:21 +0000792 m_run_lock (),
793 m_can_jit(eCanJITDontKnow)
Chris Lattner24943d22010-06-08 16:52:24 +0000794{
Caroline Tice1ebef442010-09-27 00:30:10 +0000795 UpdateInstanceName();
Jim Ingham5a15e692012-02-16 06:50:00 +0000796
797 CheckInWithManager ();
Caroline Tice1ebef442010-09-27 00:30:10 +0000798
Greg Claytone005f2c2010-11-06 01:53:30 +0000799 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000800 if (log)
801 log->Printf ("%p Process::Process()", this);
802
Greg Clayton49ce6822010-10-31 03:01:06 +0000803 SetEventName (eBroadcastBitStateChanged, "state-changed");
804 SetEventName (eBroadcastBitInterrupt, "interrupt");
805 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
806 SetEventName (eBroadcastBitSTDERR, "stderr-available");
807
Chris Lattner24943d22010-06-08 16:52:24 +0000808 listener.StartListeningForEvents (this,
809 eBroadcastBitStateChanged |
810 eBroadcastBitInterrupt |
811 eBroadcastBitSTDOUT |
812 eBroadcastBitSTDERR);
813
814 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
815 eBroadcastBitStateChanged);
816
817 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
818 eBroadcastInternalStateControlStop |
819 eBroadcastInternalStateControlPause |
820 eBroadcastInternalStateControlResume);
821}
822
823//----------------------------------------------------------------------
824// Destructor
825//----------------------------------------------------------------------
826Process::~Process()
827{
Greg Claytone005f2c2010-11-06 01:53:30 +0000828 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000829 if (log)
830 log->Printf ("%p Process::~Process()", this);
831 StopPrivateStateThread();
832}
833
834void
835Process::Finalize()
836{
Greg Claytonffa43a62011-11-17 04:46:02 +0000837 switch (GetPrivateState())
838 {
839 case eStateConnected:
840 case eStateAttaching:
841 case eStateLaunching:
842 case eStateStopped:
843 case eStateRunning:
844 case eStateStepping:
845 case eStateCrashed:
846 case eStateSuspended:
847 if (GetShouldDetach())
848 Detach();
849 else
850 Destroy();
851 break;
852
853 case eStateInvalid:
854 case eStateUnloaded:
855 case eStateDetached:
856 case eStateExited:
857 break;
858 }
859
Greg Clayton2f57db02011-10-01 00:45:15 +0000860 // Clear our broadcaster before we proceed with destroying
861 Broadcaster::Clear();
862
Chris Lattner24943d22010-06-08 16:52:24 +0000863 // Do any cleanup needed prior to being destructed... Subclasses
864 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000865
866 // We need to destroy the loader before the derived Process class gets destroyed
867 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton182be6a2012-01-20 23:08:34 +0000868 m_dynamic_checkers_ap.reset();
869 m_abi_sp.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +0000870 m_os_ap.reset();
Greg Clayton182be6a2012-01-20 23:08:34 +0000871 m_dyld_ap.reset();
Greg Clayton13d24fb2012-01-29 20:56:30 +0000872 m_thread_list.Destroy();
Greg Clayton182be6a2012-01-20 23:08:34 +0000873 std::vector<Notifications> empty_notifications;
874 m_notifications.swap(empty_notifications);
875 m_image_tokens.clear();
876 m_memory_cache.Clear();
877 m_allocated_memory_cache.Clear();
878 m_language_runtimes.clear();
879 m_next_event_action_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000880}
881
882void
883Process::RegisterNotificationCallbacks (const Notifications& callbacks)
884{
885 m_notifications.push_back(callbacks);
886 if (callbacks.initialize != NULL)
887 callbacks.initialize (callbacks.baton, this);
888}
889
890bool
891Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
892{
893 std::vector<Notifications>::iterator pos, end = m_notifications.end();
894 for (pos = m_notifications.begin(); pos != end; ++pos)
895 {
896 if (pos->baton == callbacks.baton &&
897 pos->initialize == callbacks.initialize &&
898 pos->process_state_changed == callbacks.process_state_changed)
899 {
900 m_notifications.erase(pos);
901 return true;
902 }
903 }
904 return false;
905}
906
907void
908Process::SynchronouslyNotifyStateChanged (StateType state)
909{
910 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
911 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
912 {
913 if (notification_pos->process_state_changed)
914 notification_pos->process_state_changed (notification_pos->baton, this, state);
915 }
916}
917
918// FIXME: We need to do some work on events before the general Listener sees them.
919// For instance if we are continuing from a breakpoint, we need to ensure that we do
920// the little "insert real insn, step & stop" trick. But we can't do that when the
921// event is delivered by the broadcaster - since that is done on the thread that is
922// waiting for new events, so if we needed more than one event for our handling, we would
923// stall. So instead we do it when we fetch the event off of the queue.
924//
925
926StateType
927Process::GetNextEvent (EventSP &event_sp)
928{
929 StateType state = eStateInvalid;
930
931 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
932 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
933
934 return state;
935}
936
937
938StateType
939Process::WaitForProcessToStop (const TimeValue *timeout)
940{
Jim Ingham21f37ad2011-08-09 02:12:22 +0000941 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
942 // We have to actually check each event, and in the case of a stopped event check the restarted flag
943 // on the event.
944 EventSP event_sp;
945 StateType state = GetState();
946 // If we are exited or detached, we won't ever get back to any
947 // other valid state...
948 if (state == eStateDetached || state == eStateExited)
949 return state;
950
951 while (state != eStateInvalid)
952 {
953 state = WaitForStateChangedEvents (timeout, event_sp);
954 switch (state)
955 {
956 case eStateCrashed:
957 case eStateDetached:
958 case eStateExited:
959 case eStateUnloaded:
960 return state;
961 case eStateStopped:
962 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
963 continue;
964 else
965 return state;
966 default:
967 continue;
968 }
969 }
970 return state;
Chris Lattner24943d22010-06-08 16:52:24 +0000971}
972
973
974StateType
975Process::WaitForState
976(
977 const TimeValue *timeout,
978 const StateType *match_states, const uint32_t num_match_states
979)
980{
981 EventSP event_sp;
982 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000983 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000984 while (state != eStateInvalid)
985 {
Greg Claytond8c62532010-10-07 04:19:01 +0000986 // If we are exited or detached, we won't ever get back to any
987 // other valid state...
988 if (state == eStateDetached || state == eStateExited)
989 return state;
990
Chris Lattner24943d22010-06-08 16:52:24 +0000991 state = WaitForStateChangedEvents (timeout, event_sp);
992
993 for (i=0; i<num_match_states; ++i)
994 {
995 if (match_states[i] == state)
996 return state;
997 }
998 }
999 return state;
1000}
1001
Jim Ingham63e24d72010-10-11 23:53:14 +00001002bool
1003Process::HijackProcessEvents (Listener *listener)
1004{
1005 if (listener != NULL)
1006 {
1007 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
1008 }
1009 else
1010 return false;
1011}
1012
1013void
1014Process::RestoreProcessEvents ()
1015{
1016 RestoreBroadcaster();
1017}
1018
Jim Inghamf9f40c22011-02-08 05:20:59 +00001019bool
1020Process::HijackPrivateProcessEvents (Listener *listener)
1021{
1022 if (listener != NULL)
1023 {
1024 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
1025 }
1026 else
1027 return false;
1028}
1029
1030void
1031Process::RestorePrivateProcessEvents ()
1032{
1033 m_private_state_broadcaster.RestoreBroadcaster();
1034}
1035
Chris Lattner24943d22010-06-08 16:52:24 +00001036StateType
1037Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
1038{
Greg Claytone005f2c2010-11-06 01:53:30 +00001039 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001040
1041 if (log)
1042 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1043
1044 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +00001045 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
1046 this,
1047 eBroadcastBitStateChanged,
1048 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +00001049 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1050
1051 if (log)
1052 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
1053 __FUNCTION__,
1054 timeout,
1055 StateAsCString(state));
1056 return state;
1057}
1058
1059Event *
1060Process::PeekAtStateChangedEvents ()
1061{
Greg Claytone005f2c2010-11-06 01:53:30 +00001062 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001063
1064 if (log)
1065 log->Printf ("Process::%s...", __FUNCTION__);
1066
1067 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +00001068 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
1069 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +00001070 if (log)
1071 {
1072 if (event_ptr)
1073 {
1074 log->Printf ("Process::%s (event_ptr) => %s",
1075 __FUNCTION__,
1076 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
1077 }
1078 else
1079 {
1080 log->Printf ("Process::%s no events found",
1081 __FUNCTION__);
1082 }
1083 }
1084 return event_ptr;
1085}
1086
1087StateType
1088Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
1089{
Greg Claytone005f2c2010-11-06 01:53:30 +00001090 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001091
1092 if (log)
1093 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1094
1095 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +00001096 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
1097 &m_private_state_broadcaster,
1098 eBroadcastBitStateChanged,
1099 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +00001100 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1101
1102 // This is a bit of a hack, but when we wait here we could very well return
1103 // to the command-line, and that could disable the log, which would render the
1104 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +00001105 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +00001106 {
1107 if (state == eStateInvalid)
1108 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
1109 else
1110 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
1111 }
Chris Lattner24943d22010-06-08 16:52:24 +00001112 return state;
1113}
1114
1115bool
1116Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
1117{
Greg Claytone005f2c2010-11-06 01:53:30 +00001118 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001119
1120 if (log)
1121 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1122
1123 if (control_only)
1124 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1125 else
1126 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1127}
1128
1129bool
1130Process::IsRunning () const
1131{
1132 return StateIsRunningState (m_public_state.GetValue());
1133}
1134
1135int
1136Process::GetExitStatus ()
1137{
1138 if (m_public_state.GetValue() == eStateExited)
1139 return m_exit_status;
1140 return -1;
1141}
1142
Greg Clayton638351a2010-12-04 00:10:17 +00001143
Chris Lattner24943d22010-06-08 16:52:24 +00001144const char *
1145Process::GetExitDescription ()
1146{
1147 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1148 return m_exit_string.c_str();
1149 return NULL;
1150}
1151
Greg Clayton72e1c782011-01-22 23:43:18 +00001152bool
Chris Lattner24943d22010-06-08 16:52:24 +00001153Process::SetExitStatus (int status, const char *cstr)
1154{
Greg Clayton68ca8232011-01-25 02:58:48 +00001155 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1156 if (log)
1157 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1158 status, status,
1159 cstr ? "\"" : "",
1160 cstr ? cstr : "NULL",
1161 cstr ? "\"" : "");
1162
Greg Clayton72e1c782011-01-22 23:43:18 +00001163 // We were already in the exited state
1164 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001165 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001166 if (log)
1167 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001168 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001169 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001170
1171 m_exit_status = status;
1172 if (cstr)
1173 m_exit_string = cstr;
1174 else
1175 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001176
Greg Clayton72e1c782011-01-22 23:43:18 +00001177 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001178
Greg Clayton72e1c782011-01-22 23:43:18 +00001179 SetPrivateState (eStateExited);
1180 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001181}
1182
1183// This static callback can be used to watch for local child processes on
1184// the current host. The the child process exits, the process will be
1185// found in the global target list (we want to be completely sure that the
1186// lldb_private::Process doesn't go away before we can deliver the signal.
1187bool
Greg Clayton1c4642c2011-11-16 05:37:56 +00001188Process::SetProcessExitStatus (void *callback_baton,
1189 lldb::pid_t pid,
1190 bool exited,
1191 int signo, // Zero for no signal
1192 int exit_status // Exit value of process if signal is zero
Chris Lattner24943d22010-06-08 16:52:24 +00001193)
1194{
Greg Clayton1c4642c2011-11-16 05:37:56 +00001195 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
1196 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00001197 log->Printf ("Process::SetProcessExitStatus (baton=%p, pid=%llu, exited=%i, signal=%i, exit_status=%i)\n",
Greg Clayton1c4642c2011-11-16 05:37:56 +00001198 callback_baton,
1199 pid,
1200 exited,
1201 signo,
1202 exit_status);
1203
1204 if (exited)
Chris Lattner24943d22010-06-08 16:52:24 +00001205 {
Greg Clayton63094e02010-06-23 01:19:29 +00001206 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001207 if (target_sp)
1208 {
1209 ProcessSP process_sp (target_sp->GetProcessSP());
1210 if (process_sp)
1211 {
1212 const char *signal_cstr = NULL;
1213 if (signo)
1214 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1215
1216 process_sp->SetExitStatus (exit_status, signal_cstr);
1217 }
1218 }
1219 return true;
1220 }
1221 return false;
1222}
1223
1224
Greg Clayton37f962e2011-08-22 02:49:39 +00001225void
1226Process::UpdateThreadListIfNeeded ()
1227{
1228 const uint32_t stop_id = GetStopID();
1229 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1230 {
Greg Clayton20206082011-11-17 01:23:07 +00001231 const StateType state = GetPrivateState();
1232 if (StateIsStoppedState (state, true))
1233 {
1234 Mutex::Locker locker (m_thread_list.GetMutex ());
Greg Claytonffa43a62011-11-17 04:46:02 +00001235 // m_thread_list does have its own mutex, but we need to
1236 // hold onto the mutex between the call to UpdateThreadList(...)
1237 // and the os->UpdateThreadList(...) so it doesn't change on us
Greg Clayton20206082011-11-17 01:23:07 +00001238 ThreadList new_thread_list(this);
1239 // Always update the thread list with the protocol specific
Greg Claytonae932352012-04-10 00:18:59 +00001240 // thread list, but only update if "true" is returned
1241 if (UpdateThreadList (m_thread_list, new_thread_list))
1242 {
1243 OperatingSystem *os = GetOperatingSystem ();
1244 if (os)
1245 os->UpdateThreadList (m_thread_list, new_thread_list);
1246 m_thread_list.Update (new_thread_list);
1247 m_thread_list.SetStopID (stop_id);
1248 }
Greg Clayton20206082011-11-17 01:23:07 +00001249 }
Greg Clayton37f962e2011-08-22 02:49:39 +00001250 }
1251}
1252
Chris Lattner24943d22010-06-08 16:52:24 +00001253uint32_t
1254Process::GetNextThreadIndexID ()
1255{
1256 return ++m_thread_index_id;
1257}
1258
1259StateType
1260Process::GetState()
1261{
1262 // If any other threads access this we will need a mutex for it
1263 return m_public_state.GetValue ();
1264}
1265
1266void
1267Process::SetPublicState (StateType new_state)
1268{
Greg Clayton68ca8232011-01-25 02:58:48 +00001269 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001270 if (log)
1271 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
Greg Claytona894fe72012-04-05 16:12:35 +00001272 const StateType old_state = m_public_state.GetValue();
Chris Lattner24943d22010-06-08 16:52:24 +00001273 m_public_state.SetValue (new_state);
Greg Claytona894fe72012-04-05 16:12:35 +00001274 if (!IsHijackedForEvent(eBroadcastBitStateChanged))
1275 {
1276 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1277 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1278 if (old_state_is_stopped != new_state_is_stopped)
1279 {
1280 if (new_state_is_stopped)
1281 {
1282 if (log)
1283 log->Printf("Process::SetPublicState (%s) -- unlocking run lock", StateAsCString(new_state));
1284 m_run_lock.WriteUnlock();
1285 }
1286 else
1287 {
1288 if (log)
1289 log->Printf("Process::SetPublicState (%s) -- locking run lock", StateAsCString(new_state));
1290 m_run_lock.WriteLock();
1291 }
1292 }
1293 }
Chris Lattner24943d22010-06-08 16:52:24 +00001294}
1295
1296StateType
1297Process::GetPrivateState ()
1298{
1299 return m_private_state.GetValue();
1300}
1301
1302void
1303Process::SetPrivateState (StateType new_state)
1304{
Greg Clayton68ca8232011-01-25 02:58:48 +00001305 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001306 bool state_changed = false;
1307
1308 if (log)
1309 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1310
1311 Mutex::Locker locker(m_private_state.GetMutex());
1312
1313 const StateType old_state = m_private_state.GetValueNoLock ();
1314 state_changed = old_state != new_state;
Greg Claytona894fe72012-04-05 16:12:35 +00001315 // This code is left commented out in case we ever need to control
1316 // the private process state with another run lock. Right now it doesn't
1317 // seem like we need to do this, but if we ever do, we can uncomment and
1318 // use this code.
1319// const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1320// const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1321// if (old_state_is_stopped != new_state_is_stopped)
1322// {
1323// if (new_state_is_stopped)
1324// m_private_run_lock.WriteUnlock();
1325// else
1326// m_private_run_lock.WriteLock();
1327// }
1328
Chris Lattner24943d22010-06-08 16:52:24 +00001329 if (state_changed)
1330 {
1331 m_private_state.SetValueNoLock (new_state);
Greg Clayton20206082011-11-17 01:23:07 +00001332 if (StateIsStoppedState(new_state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00001333 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00001334 m_mod_id.BumpStopID();
Greg Claytonfd119992011-01-07 06:08:19 +00001335 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001336 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00001337 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner24943d22010-06-08 16:52:24 +00001338 }
1339 // Use our target to get a shared pointer to ourselves...
1340 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1341 }
1342 else
1343 {
1344 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00001345 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner24943d22010-06-08 16:52:24 +00001346 }
1347}
1348
Jim Ingham0296fe72011-11-08 03:00:11 +00001349void
1350Process::SetRunningUserExpression (bool on)
1351{
1352 m_mod_id.SetRunningUserExpression (on);
1353}
1354
Chris Lattner24943d22010-06-08 16:52:24 +00001355addr_t
1356Process::GetImageInfoAddress()
1357{
1358 return LLDB_INVALID_ADDRESS;
1359}
1360
Greg Clayton0baa3942010-11-04 01:54:29 +00001361//----------------------------------------------------------------------
1362// LoadImage
1363//
1364// This function provides a default implementation that works for most
1365// unix variants. Any Process subclasses that need to do shared library
1366// loading differently should override LoadImage and UnloadImage and
1367// do what is needed.
1368//----------------------------------------------------------------------
1369uint32_t
1370Process::LoadImage (const FileSpec &image_spec, Error &error)
1371{
1372 DynamicLoader *loader = GetDynamicLoader();
1373 if (loader)
1374 {
1375 error = loader->CanLoadImage();
1376 if (error.Fail())
1377 return LLDB_INVALID_IMAGE_TOKEN;
1378 }
1379
1380 if (error.Success())
1381 {
1382 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001383
1384 if (thread_sp)
1385 {
1386 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1387
1388 if (frame_sp)
1389 {
1390 ExecutionContext exe_ctx;
1391 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001392 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001393 StreamString expr;
1394 char path[PATH_MAX];
1395 image_spec.GetPath(path, sizeof(path));
1396 expr.Printf("dlopen (\"%s\", 2)", path);
1397 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001398 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001399 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chenb14ec342011-09-09 00:01:43 +00001400 error = result_valobj_sp->GetError();
1401 if (error.Success())
Greg Clayton0baa3942010-11-04 01:54:29 +00001402 {
1403 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001404 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001405 {
1406 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1407 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1408 {
1409 uint32_t image_token = m_image_tokens.size();
1410 m_image_tokens.push_back (image_ptr);
1411 return image_token;
1412 }
1413 }
1414 }
1415 }
1416 }
1417 }
1418 return LLDB_INVALID_IMAGE_TOKEN;
1419}
1420
1421//----------------------------------------------------------------------
1422// UnloadImage
1423//
1424// This function provides a default implementation that works for most
1425// unix variants. Any Process subclasses that need to do shared library
1426// loading differently should override LoadImage and UnloadImage and
1427// do what is needed.
1428//----------------------------------------------------------------------
1429Error
1430Process::UnloadImage (uint32_t image_token)
1431{
1432 Error error;
1433 if (image_token < m_image_tokens.size())
1434 {
1435 const addr_t image_addr = m_image_tokens[image_token];
1436 if (image_addr == LLDB_INVALID_ADDRESS)
1437 {
1438 error.SetErrorString("image already unloaded");
1439 }
1440 else
1441 {
1442 DynamicLoader *loader = GetDynamicLoader();
1443 if (loader)
1444 error = loader->CanLoadImage();
1445
1446 if (error.Success())
1447 {
1448 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton0baa3942010-11-04 01:54:29 +00001449
1450 if (thread_sp)
1451 {
1452 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1453
1454 if (frame_sp)
1455 {
1456 ExecutionContext exe_ctx;
1457 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001458 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001459 StreamString expr;
1460 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1461 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001462 lldb::ValueObjectSP result_valobj_sp;
Sean Callanandaa6efe2011-12-21 22:22:58 +00001463 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, lldb::eLanguageTypeUnknown, ClangUserExpression::eResultTypeAny, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +00001464 if (result_valobj_sp->GetError().Success())
1465 {
1466 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001467 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001468 {
1469 if (scalar.UInt(1))
1470 {
1471 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1472 }
1473 else
1474 {
1475 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1476 }
1477 }
1478 }
1479 else
1480 {
1481 error = result_valobj_sp->GetError();
1482 }
1483 }
1484 }
1485 }
1486 }
1487 }
1488 else
1489 {
1490 error.SetErrorString("invalid image token");
1491 }
1492 return error;
1493}
1494
Greg Clayton75906e42011-05-11 18:39:18 +00001495const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001496Process::GetABI()
1497{
Greg Clayton75906e42011-05-11 18:39:18 +00001498 if (!m_abi_sp)
1499 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1500 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001501}
1502
Jim Ingham642036f2010-09-23 02:01:19 +00001503LanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001504Process::GetLanguageRuntime(lldb::LanguageType language, bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001505{
1506 LanguageRuntimeCollection::iterator pos;
1507 pos = m_language_runtimes.find (language);
Jim Inghame3117662012-03-10 00:22:19 +00001508 if (pos == m_language_runtimes.end() || (retry_if_null && !(*pos).second))
Jim Ingham642036f2010-09-23 02:01:19 +00001509 {
Jim Inghame3117662012-03-10 00:22:19 +00001510 lldb::LanguageRuntimeSP runtime_sp(LanguageRuntime::FindPlugin(this, language));
Jim Ingham642036f2010-09-23 02:01:19 +00001511
Jim Inghame3117662012-03-10 00:22:19 +00001512 m_language_runtimes[language] = runtime_sp;
1513 return runtime_sp.get();
Jim Ingham642036f2010-09-23 02:01:19 +00001514 }
1515 else
1516 return (*pos).second.get();
1517}
1518
1519CPPLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001520Process::GetCPPLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001521{
Jim Inghame3117662012-03-10 00:22:19 +00001522 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001523 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1524 return static_cast<CPPLanguageRuntime *> (runtime);
1525 return NULL;
1526}
1527
1528ObjCLanguageRuntime *
Jim Inghame3117662012-03-10 00:22:19 +00001529Process::GetObjCLanguageRuntime (bool retry_if_null)
Jim Ingham642036f2010-09-23 02:01:19 +00001530{
Jim Inghame3117662012-03-10 00:22:19 +00001531 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC, retry_if_null);
Jim Ingham642036f2010-09-23 02:01:19 +00001532 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1533 return static_cast<ObjCLanguageRuntime *> (runtime);
1534 return NULL;
1535}
1536
Chris Lattner24943d22010-06-08 16:52:24 +00001537BreakpointSiteList &
1538Process::GetBreakpointSiteList()
1539{
1540 return m_breakpoint_site_list;
1541}
1542
1543const BreakpointSiteList &
1544Process::GetBreakpointSiteList() const
1545{
1546 return m_breakpoint_site_list;
1547}
1548
1549
1550void
1551Process::DisableAllBreakpointSites ()
1552{
1553 m_breakpoint_site_list.SetEnabledForAll (false);
1554}
1555
1556Error
1557Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1558{
1559 Error error (DisableBreakpointSiteByID (break_id));
1560
1561 if (error.Success())
1562 m_breakpoint_site_list.Remove(break_id);
1563
1564 return error;
1565}
1566
1567Error
1568Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1569{
1570 Error error;
1571 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1572 if (bp_site_sp)
1573 {
1574 if (bp_site_sp->IsEnabled())
1575 error = DisableBreakpoint (bp_site_sp.get());
1576 }
1577 else
1578 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001579 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001580 }
1581
1582 return error;
1583}
1584
1585Error
1586Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1587{
1588 Error error;
1589 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1590 if (bp_site_sp)
1591 {
1592 if (!bp_site_sp->IsEnabled())
1593 error = EnableBreakpoint (bp_site_sp.get());
1594 }
1595 else
1596 {
Greg Clayton444e35b2011-10-19 18:09:39 +00001597 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner24943d22010-06-08 16:52:24 +00001598 }
1599 return error;
1600}
1601
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001602lldb::break_id_t
Greg Clayton13d24fb2012-01-29 20:56:30 +00001603Process::CreateBreakpointSite (const BreakpointLocationSP &owner, bool use_hardware)
Chris Lattner24943d22010-06-08 16:52:24 +00001604{
Greg Clayton265ab332011-05-19 18:17:41 +00001605 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001606 if (load_addr != LLDB_INVALID_ADDRESS)
1607 {
1608 BreakpointSiteSP bp_site_sp;
1609
1610 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1611 // create a new breakpoint site and add it.
1612
1613 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1614
1615 if (bp_site_sp)
1616 {
1617 bp_site_sp->AddOwner (owner);
1618 owner->SetBreakpointSite (bp_site_sp);
1619 return bp_site_sp->GetID();
1620 }
1621 else
1622 {
1623 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1624 if (bp_site_sp)
1625 {
1626 if (EnableBreakpoint (bp_site_sp.get()).Success())
1627 {
1628 owner->SetBreakpointSite (bp_site_sp);
1629 return m_breakpoint_site_list.Add (bp_site_sp);
1630 }
1631 }
1632 }
1633 }
1634 // We failed to enable the breakpoint
1635 return LLDB_INVALID_BREAK_ID;
1636
1637}
1638
1639void
1640Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1641{
1642 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1643 if (num_owners == 0)
1644 {
1645 DisableBreakpoint(bp_site_sp.get());
1646 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1647 }
1648}
1649
1650
1651size_t
1652Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1653{
1654 size_t bytes_removed = 0;
1655 addr_t intersect_addr;
1656 size_t intersect_size;
1657 size_t opcode_offset;
1658 size_t idx;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001659 BreakpointSiteSP bp_sp;
Jim Ingham82820f92011-06-29 19:42:28 +00001660 BreakpointSiteList bp_sites_in_range;
Chris Lattner24943d22010-06-08 16:52:24 +00001661
Jim Ingham82820f92011-06-29 19:42:28 +00001662 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner24943d22010-06-08 16:52:24 +00001663 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001664 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +00001665 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001666 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner24943d22010-06-08 16:52:24 +00001667 {
Greg Clayton987c7eb2011-09-17 08:33:22 +00001668 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham82820f92011-06-29 19:42:28 +00001669 {
1670 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1671 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton987c7eb2011-09-17 08:33:22 +00001672 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham82820f92011-06-29 19:42:28 +00001673 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton987c7eb2011-09-17 08:33:22 +00001674 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham82820f92011-06-29 19:42:28 +00001675 }
Chris Lattner24943d22010-06-08 16:52:24 +00001676 }
1677 }
1678 }
1679 return bytes_removed;
1680}
1681
1682
Greg Claytonb1888f22011-03-19 01:12:21 +00001683
1684size_t
1685Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1686{
1687 PlatformSP platform_sp (m_target.GetPlatform());
1688 if (platform_sp)
1689 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1690 return 0;
1691}
1692
Chris Lattner24943d22010-06-08 16:52:24 +00001693Error
1694Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1695{
1696 Error error;
1697 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001698 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001699 const addr_t bp_addr = bp_site->GetLoadAddress();
1700 if (log)
1701 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1702 if (bp_site->IsEnabled())
1703 {
1704 if (log)
1705 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1706 return error;
1707 }
1708
1709 if (bp_addr == LLDB_INVALID_ADDRESS)
1710 {
1711 error.SetErrorString("BreakpointSite contains an invalid load address.");
1712 return error;
1713 }
1714 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1715 // trap for the breakpoint site
1716 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1717
1718 if (bp_opcode_size == 0)
1719 {
Greg Clayton9c236732011-10-26 00:56:27 +00001720 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001721 }
1722 else
1723 {
1724 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1725
1726 if (bp_opcode_bytes == NULL)
1727 {
1728 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1729 return error;
1730 }
1731
1732 // Save the original opcode by reading it
1733 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1734 {
1735 // Write a software breakpoint in place of the original opcode
1736 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1737 {
1738 uint8_t verify_bp_opcode_bytes[64];
1739 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1740 {
1741 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1742 {
1743 bp_site->SetEnabled(true);
1744 bp_site->SetType (BreakpointSite::eSoftware);
1745 if (log)
1746 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1747 bp_site->GetID(),
1748 (uint64_t)bp_addr);
1749 }
1750 else
Greg Clayton9c236732011-10-26 00:56:27 +00001751 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner24943d22010-06-08 16:52:24 +00001752 }
1753 else
1754 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1755 }
1756 else
1757 error.SetErrorString("Unable to write breakpoint trap to memory.");
1758 }
1759 else
1760 error.SetErrorString("Unable to read memory at breakpoint address.");
1761 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001762 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001763 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1764 bp_site->GetID(),
1765 (uint64_t)bp_addr,
1766 error.AsCString());
1767 return error;
1768}
1769
1770Error
1771Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1772{
1773 Error error;
1774 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001775 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001776 addr_t bp_addr = bp_site->GetLoadAddress();
1777 lldb::user_id_t breakID = bp_site->GetID();
1778 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00001779 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001780
1781 if (bp_site->IsHardware())
1782 {
1783 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1784 }
1785 else if (bp_site->IsEnabled())
1786 {
1787 const size_t break_op_size = bp_site->GetByteSize();
1788 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1789 if (break_op_size > 0)
1790 {
1791 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001792 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001793 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001794 bool break_op_found = false;
1795
1796 // Read the breakpoint opcode
1797 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1798 {
1799 bool verify = false;
1800 // Make sure we have the a breakpoint opcode exists at this address
1801 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1802 {
1803 break_op_found = true;
1804 // We found a valid breakpoint opcode at this address, now restore
1805 // the saved opcode.
1806 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1807 {
1808 verify = true;
1809 }
1810 else
1811 error.SetErrorString("Memory write failed when restoring original opcode.");
1812 }
1813 else
1814 {
1815 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1816 // Set verify to true and so we can check if the original opcode has already been restored
1817 verify = true;
1818 }
1819
1820 if (verify)
1821 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001822 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001823 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001824 // Verify that our original opcode made it back to the inferior
1825 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1826 {
1827 // compare the memory we just read with the original opcode
1828 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1829 {
1830 // SUCCESS
1831 bp_site->SetEnabled(false);
1832 if (log)
1833 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1834 return error;
1835 }
1836 else
1837 {
1838 if (break_op_found)
1839 error.SetErrorString("Failed to restore original opcode.");
1840 }
1841 }
1842 else
1843 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1844 }
1845 }
1846 else
1847 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1848 }
1849 }
1850 else
1851 {
1852 if (log)
1853 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1854 return error;
1855 }
1856
1857 if (log)
1858 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1859 bp_site->GetID(),
1860 (uint64_t)bp_addr,
1861 error.AsCString());
1862 return error;
1863
1864}
1865
Greg Claytonfd119992011-01-07 06:08:19 +00001866// Comment out line below to disable memory caching
1867#define ENABLE_MEMORY_CACHING
1868// Uncomment to verify memory caching works after making changes to caching code
1869//#define VERIFY_MEMORY_READS
1870
1871#if defined (ENABLE_MEMORY_CACHING)
1872
1873#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001874
1875size_t
1876Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1877{
Greg Claytonfd119992011-01-07 06:08:19 +00001878 // Memory caching is enabled, with debug verification
1879 if (buf && size)
1880 {
1881 // Uncomment the line below to make sure memory caching is working.
1882 // I ran this through the test suite and got no assertions, so I am
1883 // pretty confident this is working well. If any changes are made to
1884 // memory caching, uncomment the line below and test your changes!
1885
1886 // Verify all memory reads by using the cache first, then redundantly
1887 // reading the same memory from the inferior and comparing to make sure
1888 // everything is exactly the same.
1889 std::string verify_buf (size, '\0');
1890 assert (verify_buf.size() == size);
1891 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1892 Error verify_error;
1893 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1894 assert (cache_bytes_read == verify_bytes_read);
1895 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1896 assert (verify_error.Success() == error.Success());
1897 return cache_bytes_read;
1898 }
1899 return 0;
1900}
1901
1902#else // #if defined (VERIFY_MEMORY_READS)
1903
1904size_t
1905Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1906{
1907 // Memory caching enabled, no verification
Greg Clayton613b8732011-05-17 03:37:42 +00001908 return m_memory_cache.Read (addr, buf, size, error);
Greg Claytonfd119992011-01-07 06:08:19 +00001909}
1910
1911#endif // #else for #if defined (VERIFY_MEMORY_READS)
1912
1913#else // #if defined (ENABLE_MEMORY_CACHING)
1914
1915size_t
1916Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1917{
1918 // Memory caching is disabled
1919 return ReadMemoryFromInferior (addr, buf, size, error);
1920}
1921
1922#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1923
1924
1925size_t
Greg Clayton4a2e3372011-12-15 03:14:23 +00001926Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len, Error &result_error)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001927{
1928 size_t total_cstr_len = 0;
1929 if (dst && dst_max_len)
1930 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00001931 result_error.Clear();
Greg Claytonb72d0f02011-04-12 05:54:46 +00001932 // NULL out everything just to be safe
1933 memset (dst, 0, dst_max_len);
1934 Error error;
1935 addr_t curr_addr = addr;
1936 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1937 size_t bytes_left = dst_max_len - 1;
1938 char *curr_dst = dst;
1939
1940 while (bytes_left > 0)
1941 {
1942 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1943 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1944 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1945
1946 if (bytes_read == 0)
1947 {
Greg Clayton4a2e3372011-12-15 03:14:23 +00001948 result_error = error;
Greg Claytonb72d0f02011-04-12 05:54:46 +00001949 dst[total_cstr_len] = '\0';
1950 break;
1951 }
1952 const size_t len = strlen(curr_dst);
1953
1954 total_cstr_len += len;
1955
1956 if (len < bytes_to_read)
1957 break;
1958
1959 curr_dst += bytes_read;
1960 curr_addr += bytes_read;
1961 bytes_left -= bytes_read;
1962 }
1963 }
Greg Clayton4a2e3372011-12-15 03:14:23 +00001964 else
1965 {
1966 if (dst == NULL)
1967 result_error.SetErrorString("invalid arguments");
1968 else
1969 result_error.Clear();
1970 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00001971 return total_cstr_len;
1972}
1973
1974size_t
Greg Claytonfd119992011-01-07 06:08:19 +00001975Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1976{
Chris Lattner24943d22010-06-08 16:52:24 +00001977 if (buf == NULL || size == 0)
1978 return 0;
1979
1980 size_t bytes_read = 0;
1981 uint8_t *bytes = (uint8_t *)buf;
1982
1983 while (bytes_read < size)
1984 {
1985 const size_t curr_size = size - bytes_read;
1986 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1987 bytes + bytes_read,
1988 curr_size,
1989 error);
1990 bytes_read += curr_bytes_read;
1991 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1992 break;
1993 }
1994
1995 // Replace any software breakpoint opcodes that fall into this range back
1996 // into "buf" before we return
1997 if (bytes_read > 0)
1998 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1999 return bytes_read;
2000}
2001
Greg Claytonf72fdee2010-12-16 20:01:20 +00002002uint64_t
Greg Claytonc0fa5332011-05-22 22:46:53 +00002003Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Claytonf72fdee2010-12-16 20:01:20 +00002004{
Greg Claytonc0fa5332011-05-22 22:46:53 +00002005 Scalar scalar;
2006 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
2007 return scalar.ULongLong(fail_value);
2008 return fail_value;
2009}
2010
2011addr_t
2012Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
2013{
2014 Scalar scalar;
2015 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
2016 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2017 return LLDB_INVALID_ADDRESS;
2018}
2019
2020
2021bool
2022Process::WritePointerToMemory (lldb::addr_t vm_addr,
2023 lldb::addr_t ptr_value,
2024 Error &error)
2025{
2026 Scalar scalar;
2027 const uint32_t addr_byte_size = GetAddressByteSize();
2028 if (addr_byte_size <= 4)
2029 scalar = (uint32_t)ptr_value;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002030 else
Greg Claytonc0fa5332011-05-22 22:46:53 +00002031 scalar = ptr_value;
2032 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Claytonf72fdee2010-12-16 20:01:20 +00002033}
2034
Chris Lattner24943d22010-06-08 16:52:24 +00002035size_t
2036Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
2037{
2038 size_t bytes_written = 0;
2039 const uint8_t *bytes = (const uint8_t *)buf;
2040
2041 while (bytes_written < size)
2042 {
2043 const size_t curr_size = size - bytes_written;
2044 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
2045 bytes + bytes_written,
2046 curr_size,
2047 error);
2048 bytes_written += curr_bytes_written;
2049 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2050 break;
2051 }
2052 return bytes_written;
2053}
2054
2055size_t
2056Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2057{
Greg Claytonfd119992011-01-07 06:08:19 +00002058#if defined (ENABLE_MEMORY_CACHING)
2059 m_memory_cache.Flush (addr, size);
2060#endif
2061
Chris Lattner24943d22010-06-08 16:52:24 +00002062 if (buf == NULL || size == 0)
2063 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00002064
Jim Ingham21f37ad2011-08-09 02:12:22 +00002065 m_mod_id.BumpMemoryID();
Jim Inghame41494a2011-04-16 00:01:13 +00002066
Chris Lattner24943d22010-06-08 16:52:24 +00002067 // We need to write any data that would go where any current software traps
2068 // (enabled software breakpoints) any software traps (breakpoints) that we
2069 // may have placed in our tasks memory.
2070
2071 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
2072 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
2073
2074 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonc8bc1c32011-05-16 02:35:02 +00002075 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner24943d22010-06-08 16:52:24 +00002076
2077 BreakpointSiteList::collection::const_iterator pos;
2078 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00002079 addr_t intersect_addr = 0;
2080 size_t intersect_size = 0;
2081 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00002082 const uint8_t *ubuf = (const uint8_t *)buf;
2083
2084 for (pos = iter; pos != end; ++pos)
2085 {
2086 BreakpointSiteSP bp;
2087 bp = pos->second;
2088
2089 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
2090 assert(addr <= intersect_addr && intersect_addr < addr + size);
2091 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
2092 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2093
2094 // Check for bytes before this breakpoint
2095 const addr_t curr_addr = addr + bytes_written;
2096 if (intersect_addr > curr_addr)
2097 {
2098 // There are some bytes before this breakpoint that we need to
2099 // just write to memory
2100 size_t curr_size = intersect_addr - curr_addr;
2101 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
2102 ubuf + bytes_written,
2103 curr_size,
2104 error);
2105 bytes_written += curr_bytes_written;
2106 if (curr_bytes_written != curr_size)
2107 {
2108 // We weren't able to write all of the requested bytes, we
2109 // are done looping and will return the number of bytes that
2110 // we have written so far.
2111 break;
2112 }
2113 }
2114
2115 // Now write any bytes that would cover up any software breakpoints
2116 // directly into the breakpoint opcode buffer
2117 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
2118 bytes_written += intersect_size;
2119 }
2120
2121 // Write any remaining bytes after the last breakpoint if we have any left
2122 if (bytes_written < size)
2123 bytes_written += WriteMemoryPrivate (addr + bytes_written,
2124 ubuf + bytes_written,
2125 size - bytes_written,
2126 error);
Jim Inghame41494a2011-04-16 00:01:13 +00002127
Chris Lattner24943d22010-06-08 16:52:24 +00002128 return bytes_written;
2129}
Greg Claytonc0fa5332011-05-22 22:46:53 +00002130
2131size_t
2132Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
2133{
2134 if (byte_size == UINT32_MAX)
2135 byte_size = scalar.GetByteSize();
2136 if (byte_size > 0)
2137 {
2138 uint8_t buf[32];
2139 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
2140 if (mem_size > 0)
2141 return WriteMemory(addr, buf, mem_size, error);
2142 else
2143 error.SetErrorString ("failed to get scalar as memory data");
2144 }
2145 else
2146 {
2147 error.SetErrorString ("invalid scalar value");
2148 }
2149 return 0;
2150}
2151
2152size_t
2153Process::ReadScalarIntegerFromMemory (addr_t addr,
2154 uint32_t byte_size,
2155 bool is_signed,
2156 Scalar &scalar,
2157 Error &error)
2158{
2159 uint64_t uval;
2160
2161 if (byte_size <= sizeof(uval))
2162 {
2163 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
2164 if (bytes_read == byte_size)
2165 {
2166 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
2167 uint32_t offset = 0;
2168 if (byte_size <= 4)
2169 scalar = data.GetMaxU32 (&offset, byte_size);
2170 else
2171 scalar = data.GetMaxU64 (&offset, byte_size);
2172
2173 if (is_signed)
2174 scalar.SignExtend(byte_size * 8);
2175 return bytes_read;
2176 }
2177 }
2178 else
2179 {
2180 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
2181 }
2182 return 0;
2183}
2184
Greg Clayton613b8732011-05-17 03:37:42 +00002185#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner24943d22010-06-08 16:52:24 +00002186addr_t
2187Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
2188{
Jim Inghame6bd1422011-06-20 17:32:44 +00002189 if (GetPrivateState() != eStateStopped)
2190 return LLDB_INVALID_ADDRESS;
2191
Greg Clayton613b8732011-05-17 03:37:42 +00002192#if defined (USE_ALLOCATE_MEMORY_CACHE)
2193 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2194#else
Greg Clayton2860ba92011-01-23 19:58:49 +00002195 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
2196 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2197 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002198 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002199 size,
Greg Clayton613b8732011-05-17 03:37:42 +00002200 GetPermissionsAsCString (permissions),
Greg Clayton2860ba92011-01-23 19:58:49 +00002201 (uint64_t)allocated_addr,
Jim Ingham21f37ad2011-08-09 02:12:22 +00002202 m_mod_id.GetStopID(),
2203 m_mod_id.GetMemoryID());
Greg Clayton2860ba92011-01-23 19:58:49 +00002204 return allocated_addr;
Greg Clayton613b8732011-05-17 03:37:42 +00002205#endif
Chris Lattner24943d22010-06-08 16:52:24 +00002206}
2207
Sean Callanan6cf6c472011-09-20 23:01:51 +00002208bool
2209Process::CanJIT ()
2210{
Sean Callanan04200f62012-02-14 22:50:38 +00002211 if (m_can_jit == eCanJITDontKnow)
2212 {
2213 Error err;
2214
2215 uint64_t allocated_memory = AllocateMemory(8,
2216 ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2217 err);
2218
2219 if (err.Success())
2220 m_can_jit = eCanJITYes;
2221 else
2222 m_can_jit = eCanJITNo;
2223
2224 DeallocateMemory (allocated_memory);
2225 }
2226
Sean Callanan6cf6c472011-09-20 23:01:51 +00002227 return m_can_jit == eCanJITYes;
2228}
2229
2230void
2231Process::SetCanJIT (bool can_jit)
2232{
2233 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2234}
2235
Chris Lattner24943d22010-06-08 16:52:24 +00002236Error
2237Process::DeallocateMemory (addr_t ptr)
2238{
Greg Clayton613b8732011-05-17 03:37:42 +00002239 Error error;
2240#if defined (USE_ALLOCATE_MEMORY_CACHE)
2241 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
2242 {
2243 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
2244 }
2245#else
2246 error = DoDeallocateMemory (ptr);
Greg Clayton2860ba92011-01-23 19:58:49 +00002247
2248 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2249 if (log)
Jim Ingham21f37ad2011-08-09 02:12:22 +00002250 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00002251 ptr,
2252 error.AsCString("SUCCESS"),
Jim Ingham21f37ad2011-08-09 02:12:22 +00002253 m_mod_id.GetStopID(),
2254 m_mod_id.GetMemoryID());
Greg Clayton613b8732011-05-17 03:37:42 +00002255#endif
Greg Clayton2860ba92011-01-23 19:58:49 +00002256 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002257}
2258
Greg Claytonb5a8f142012-02-05 02:38:54 +00002259ModuleSP
Greg Clayton9ce95382012-02-13 23:10:39 +00002260Process::ReadModuleFromMemory (const FileSpec& file_spec,
2261 lldb::addr_t header_addr,
2262 bool add_image_to_target,
2263 bool load_sections_in_target)
Greg Claytonb5a8f142012-02-05 02:38:54 +00002264{
Greg Clayton6c5438b2012-02-24 21:55:59 +00002265 ModuleSP module_sp (new Module (file_spec, ArchSpec()));
Greg Claytonb5a8f142012-02-05 02:38:54 +00002266 if (module_sp)
2267 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002268 Error error;
2269 ObjectFile *objfile = module_sp->GetMemoryObjectFile (shared_from_this(), header_addr, error);
2270 if (objfile)
Greg Clayton9ce95382012-02-13 23:10:39 +00002271 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002272 if (add_image_to_target)
Greg Clayton9ce95382012-02-13 23:10:39 +00002273 {
Greg Clayton6c5438b2012-02-24 21:55:59 +00002274 m_target.GetImages().Append(module_sp);
2275 if (load_sections_in_target)
2276 {
2277 bool changed = false;
2278 module_sp->SetLoadAddress (m_target, 0, changed);
2279 }
Greg Clayton9ce95382012-02-13 23:10:39 +00002280 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002281 return module_sp;
Greg Clayton9ce95382012-02-13 23:10:39 +00002282 }
Greg Claytonb5a8f142012-02-05 02:38:54 +00002283 }
Greg Clayton6c5438b2012-02-24 21:55:59 +00002284 return ModuleSP();
Greg Claytonb5a8f142012-02-05 02:38:54 +00002285}
Chris Lattner24943d22010-06-08 16:52:24 +00002286
2287Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002288Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002289{
2290 Error error;
2291 error.SetErrorString("watchpoints are not supported");
2292 return error;
2293}
2294
2295Error
Johnny Chenecd4feb2011-10-14 00:42:25 +00002296Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner24943d22010-06-08 16:52:24 +00002297{
2298 Error error;
2299 error.SetErrorString("watchpoints are not supported");
2300 return error;
2301}
2302
2303StateType
2304Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2305{
2306 StateType state;
2307 // Now wait for the process to launch and return control to us, and then
2308 // call DidLaunch:
2309 while (1)
2310 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002311 event_sp.reset();
2312 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2313
Greg Clayton20206082011-11-17 01:23:07 +00002314 if (StateIsStoppedState(state, false))
Chris Lattner24943d22010-06-08 16:52:24 +00002315 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002316
2317 // If state is invalid, then we timed out
2318 if (state == eStateInvalid)
2319 break;
2320
2321 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002322 HandlePrivateEvent (event_sp);
2323 }
2324 return state;
2325}
2326
2327Error
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002328Process::Launch (const ProcessLaunchInfo &launch_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002329{
2330 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002331 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002332 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002333 m_os_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002334 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002335
Greg Clayton5beb99d2011-08-11 02:48:45 +00002336 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner24943d22010-06-08 16:52:24 +00002337 if (exe_module)
2338 {
Greg Clayton180546b2011-04-30 01:09:13 +00002339 char local_exec_file_path[PATH_MAX];
2340 char platform_exec_file_path[PATH_MAX];
2341 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2342 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002343 if (exe_module->GetFileSpec().Exists())
2344 {
Greg Claytona2f74232011-02-24 22:24:29 +00002345 if (PrivateStateThreadIsValid ())
2346 PausePrivateStateThread ();
2347
Chris Lattner24943d22010-06-08 16:52:24 +00002348 error = WillLaunch (exe_module);
2349 if (error.Success())
2350 {
Greg Claytond8c62532010-10-07 04:19:01 +00002351 SetPublicState (eStateLaunching);
Greg Claytonffa43a62011-11-17 04:46:02 +00002352 m_should_detach = false;
Chris Lattner24943d22010-06-08 16:52:24 +00002353
2354 // Now launch using these arguments.
Greg Clayton36bc5ea2011-11-03 21:22:33 +00002355 error = DoLaunch (exe_module, launch_info);
Chris Lattner24943d22010-06-08 16:52:24 +00002356
2357 if (error.Fail())
2358 {
2359 if (GetID() != LLDB_INVALID_PROCESS_ID)
2360 {
2361 SetID (LLDB_INVALID_PROCESS_ID);
2362 const char *error_string = error.AsCString();
2363 if (error_string == NULL)
2364 error_string = "launch failed";
2365 SetExitStatus (-1, error_string);
2366 }
2367 }
2368 else
2369 {
2370 EventSP event_sp;
Greg Clayton49859592011-06-22 01:42:17 +00002371 TimeValue timeout_time;
2372 timeout_time = TimeValue::Now();
2373 timeout_time.OffsetWithSeconds(10);
2374 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00002375
Greg Clayton49859592011-06-22 01:42:17 +00002376 if (state == eStateInvalid || event_sp.get() == NULL)
2377 {
2378 // We were able to launch the process, but we failed to
2379 // catch the initial stop.
2380 SetExitStatus (0, "failed to catch stop after launch");
2381 Destroy();
2382 }
2383 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner24943d22010-06-08 16:52:24 +00002384 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002385
Chris Lattner24943d22010-06-08 16:52:24 +00002386 DidLaunch ();
2387
Greg Clayton9ce95382012-02-13 23:10:39 +00002388 DynamicLoader *dyld = GetDynamicLoader ();
2389 if (dyld)
2390 dyld->DidLaunch();
Greg Clayton75c703d2011-02-16 04:46:07 +00002391
Greg Clayton37f962e2011-08-22 02:49:39 +00002392 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner24943d22010-06-08 16:52:24 +00002393 // This delays passing the stopped event to listeners till DidLaunch gets
2394 // a chance to complete...
2395 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002396
2397 if (PrivateStateThreadIsValid ())
2398 ResumePrivateStateThread ();
2399 else
2400 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002401 }
2402 else if (state == eStateExited)
2403 {
2404 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2405 // not likely to work, and return an invalid pid.
2406 HandlePrivateEvent (event_sp);
2407 }
2408 }
2409 }
2410 }
2411 else
2412 {
Greg Clayton9c236732011-10-26 00:56:27 +00002413 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002414 }
2415 }
2416 return error;
2417}
2418
Greg Clayton46c9a352012-02-09 06:16:32 +00002419
2420Error
2421Process::LoadCore ()
2422{
2423 Error error = DoLoadCore();
2424 if (error.Success())
2425 {
2426 if (PrivateStateThreadIsValid ())
2427 ResumePrivateStateThread ();
2428 else
2429 StartPrivateStateThread ();
2430
Greg Clayton9ce95382012-02-13 23:10:39 +00002431 DynamicLoader *dyld = GetDynamicLoader ();
2432 if (dyld)
2433 dyld->DidAttach();
2434
2435 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton46c9a352012-02-09 06:16:32 +00002436 // We successfully loaded a core file, now pretend we stopped so we can
2437 // show all of the threads in the core file and explore the crashed
2438 // state.
2439 SetPrivateState (eStateStopped);
2440
2441 }
2442 return error;
2443}
2444
Greg Clayton9ce95382012-02-13 23:10:39 +00002445DynamicLoader *
2446Process::GetDynamicLoader ()
2447{
2448 if (m_dyld_ap.get() == NULL)
2449 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
2450 return m_dyld_ap.get();
2451}
Greg Clayton46c9a352012-02-09 06:16:32 +00002452
2453
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002454Process::NextEventAction::EventActionResult
2455Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002456{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002457 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2458 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002459 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002460 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002461 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002462 return eEventActionRetry;
2463
2464 case eStateStopped:
2465 case eStateCrashed:
Greg Clayton2d9adb72011-11-12 02:10:56 +00002466 {
2467 // During attach, prior to sending the eStateStopped event,
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002468 // lldb_private::Process subclasses must set the new process ID.
Greg Clayton2d9adb72011-11-12 02:10:56 +00002469 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2470 if (m_exec_count > 0)
2471 {
2472 --m_exec_count;
2473 m_process->Resume();
2474 return eEventActionRetry;
2475 }
2476 else
2477 {
2478 m_process->CompleteAttach ();
2479 return eEventActionSuccess;
2480 }
2481 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002482 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00002483
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002484 default:
2485 case eStateExited:
2486 case eStateInvalid:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002487 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002488 }
Greg Clayton2d9adb72011-11-12 02:10:56 +00002489
2490 m_exit_string.assign ("No valid Process");
2491 return eEventActionExit;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002492}
Chris Lattner24943d22010-06-08 16:52:24 +00002493
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002494Process::NextEventAction::EventActionResult
2495Process::AttachCompletionHandler::HandleBeingInterrupted()
2496{
2497 return eEventActionSuccess;
2498}
2499
2500const char *
2501Process::AttachCompletionHandler::GetExitString ()
2502{
2503 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002504}
2505
2506Error
Greg Clayton527154d2011-11-15 03:53:30 +00002507Process::Attach (ProcessAttachInfo &attach_info)
Chris Lattner24943d22010-06-08 16:52:24 +00002508{
Chris Lattner24943d22010-06-08 16:52:24 +00002509 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002510 m_process_input_reader.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002511 m_dyld_ap.reset();
Greg Clayton37f962e2011-08-22 02:49:39 +00002512 m_os_ap.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002513
Greg Clayton527154d2011-11-15 03:53:30 +00002514 lldb::pid_t attach_pid = attach_info.GetProcessID();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002515 Error error;
Greg Clayton527154d2011-11-15 03:53:30 +00002516 if (attach_pid == LLDB_INVALID_PROCESS_ID)
Jim Ingham7508e732010-08-09 23:31:02 +00002517 {
Greg Clayton527154d2011-11-15 03:53:30 +00002518 char process_name[PATH_MAX];
Jim Ingham0d7f7772011-09-15 01:10:17 +00002519
Greg Clayton527154d2011-11-15 03:53:30 +00002520 if (attach_info.GetExecutableFile().GetPath (process_name, sizeof(process_name)))
Jim Inghamea294182010-08-17 21:54:19 +00002521 {
Greg Clayton527154d2011-11-15 03:53:30 +00002522 const bool wait_for_launch = attach_info.GetWaitForLaunch();
2523
2524 if (wait_for_launch)
Chris Lattner24943d22010-06-08 16:52:24 +00002525 {
Greg Clayton527154d2011-11-15 03:53:30 +00002526 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2527 if (error.Success())
2528 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002529 m_should_detach = true;
2530
Greg Clayton527154d2011-11-15 03:53:30 +00002531 SetPublicState (eStateAttaching);
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002532 error = DoAttachToProcessWithName (process_name, wait_for_launch, attach_info);
Greg Clayton527154d2011-11-15 03:53:30 +00002533 if (error.Fail())
2534 {
2535 if (GetID() != LLDB_INVALID_PROCESS_ID)
2536 {
2537 SetID (LLDB_INVALID_PROCESS_ID);
2538 if (error.AsCString() == NULL)
2539 error.SetErrorString("attach failed");
2540
2541 SetExitStatus(-1, error.AsCString());
2542 }
2543 }
2544 else
2545 {
2546 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2547 StartPrivateStateThread();
2548 }
2549 return error;
2550 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002551 }
Greg Clayton527154d2011-11-15 03:53:30 +00002552 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002553 {
Greg Clayton527154d2011-11-15 03:53:30 +00002554 ProcessInstanceInfoList process_infos;
2555 PlatformSP platform_sp (m_target.GetPlatform ());
2556
2557 if (platform_sp)
2558 {
2559 ProcessInstanceInfoMatch match_info;
2560 match_info.GetProcessInfo() = attach_info;
2561 match_info.SetNameMatchType (eNameMatchEquals);
2562 platform_sp->FindProcesses (match_info, process_infos);
2563 const uint32_t num_matches = process_infos.GetSize();
2564 if (num_matches == 1)
2565 {
2566 attach_pid = process_infos.GetProcessIDAtIndex(0);
2567 // Fall through and attach using the above process ID
2568 }
2569 else
2570 {
2571 match_info.GetProcessInfo().GetExecutableFile().GetPath (process_name, sizeof(process_name));
2572 if (num_matches > 1)
2573 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2574 else
2575 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2576 }
2577 }
2578 else
2579 {
2580 error.SetErrorString ("invalid platform, can't find processes by name");
2581 return error;
2582 }
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002583 }
Chris Lattner24943d22010-06-08 16:52:24 +00002584 }
2585 else
Greg Clayton527154d2011-11-15 03:53:30 +00002586 {
2587 error.SetErrorString ("invalid process name");
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002588 }
2589 }
Greg Clayton527154d2011-11-15 03:53:30 +00002590
2591 if (attach_pid != LLDB_INVALID_PROCESS_ID)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002592 {
Greg Clayton527154d2011-11-15 03:53:30 +00002593 error = WillAttachToProcessWithID(attach_pid);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002594 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002595 {
Greg Claytonffa43a62011-11-17 04:46:02 +00002596 m_should_detach = true;
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002597 SetPublicState (eStateAttaching);
Greg Clayton527154d2011-11-15 03:53:30 +00002598
Han Ming Ongd1040dd2012-02-25 01:07:38 +00002599 error = DoAttachToProcessWithID (attach_pid, attach_info);
Greg Clayton527154d2011-11-15 03:53:30 +00002600 if (error.Success())
2601 {
2602
2603 SetNextEventAction(new Process::AttachCompletionHandler(this, attach_info.GetResumeCount()));
2604 StartPrivateStateThread();
2605 }
2606 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002607 {
2608 if (GetID() != LLDB_INVALID_PROCESS_ID)
2609 {
2610 SetID (LLDB_INVALID_PROCESS_ID);
2611 const char *error_string = error.AsCString();
2612 if (error_string == NULL)
2613 error_string = "attach failed";
2614
2615 SetExitStatus(-1, error_string);
2616 }
2617 }
Chris Lattner24943d22010-06-08 16:52:24 +00002618 }
2619 }
2620 return error;
2621}
2622
Greg Clayton527154d2011-11-15 03:53:30 +00002623//Error
2624//Process::Attach (const char *process_name, bool wait_for_launch)
2625//{
2626// m_abi_sp.reset();
2627// m_process_input_reader.reset();
2628//
2629// // Find the process and its architecture. Make sure it matches the architecture
2630// // of the current Target, and if not adjust it.
2631// Error error;
2632//
2633// if (!wait_for_launch)
2634// {
2635// ProcessInstanceInfoList process_infos;
2636// PlatformSP platform_sp (m_target.GetPlatform ());
2637// assert (platform_sp.get());
2638//
2639// if (platform_sp)
2640// {
2641// ProcessInstanceInfoMatch match_info;
2642// match_info.GetProcessInfo().SetName(process_name);
2643// match_info.SetNameMatchType (eNameMatchEquals);
2644// platform_sp->FindProcesses (match_info, process_infos);
2645// if (process_infos.GetSize() > 1)
2646// {
2647// error.SetErrorStringWithFormat ("more than one process named %s", process_name);
2648// }
2649// else if (process_infos.GetSize() == 0)
2650// {
2651// error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
2652// }
2653// }
2654// else
2655// {
2656// error.SetErrorString ("invalid platform");
2657// }
2658// }
2659//
2660// if (error.Success())
2661// {
2662// m_dyld_ap.reset();
2663// m_os_ap.reset();
2664//
2665// error = WillAttachToProcessWithName(process_name, wait_for_launch);
2666// if (error.Success())
2667// {
2668// SetPublicState (eStateAttaching);
2669// error = DoAttachToProcessWithName (process_name, wait_for_launch);
2670// if (error.Fail())
2671// {
2672// if (GetID() != LLDB_INVALID_PROCESS_ID)
2673// {
2674// SetID (LLDB_INVALID_PROCESS_ID);
2675// const char *error_string = error.AsCString();
2676// if (error_string == NULL)
2677// error_string = "attach failed";
2678//
2679// SetExitStatus(-1, error_string);
2680// }
2681// }
2682// else
2683// {
2684// SetNextEventAction(new Process::AttachCompletionHandler(this, 0));
2685// StartPrivateStateThread();
2686// }
2687// }
2688// }
2689// return error;
2690//}
2691
Greg Clayton75c703d2011-02-16 04:46:07 +00002692void
2693Process::CompleteAttach ()
2694{
2695 // Let the process subclass figure out at much as it can about the process
2696 // before we go looking for a dynamic loader plug-in.
2697 DidAttach();
2698
Jim Ingham0d7f7772011-09-15 01:10:17 +00002699 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2700 // the same as the one we've already set, switch architectures.
2701 PlatformSP platform_sp (m_target.GetPlatform ());
2702 assert (platform_sp.get());
2703 if (platform_sp)
2704 {
2705 ProcessInstanceInfo process_info;
2706 platform_sp->GetProcessInfo (GetID(), process_info);
2707 const ArchSpec &process_arch = process_info.GetArchitecture();
2708 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2709 m_target.SetArchitecture (process_arch);
2710 }
2711
2712 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton75c703d2011-02-16 04:46:07 +00002713 // plug-in
Greg Clayton9ce95382012-02-13 23:10:39 +00002714 DynamicLoader *dyld = GetDynamicLoader ();
2715 if (dyld)
2716 dyld->DidAttach();
Greg Clayton75c703d2011-02-16 04:46:07 +00002717
Greg Clayton37f962e2011-08-22 02:49:39 +00002718 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002719 // Figure out which one is the executable, and set that in our target:
2720 ModuleList &modules = m_target.GetImages();
2721
2722 size_t num_modules = modules.GetSize();
2723 for (int i = 0; i < num_modules; i++)
2724 {
2725 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002726 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002727 {
Greg Clayton5beb99d2011-08-11 02:48:45 +00002728 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton75c703d2011-02-16 04:46:07 +00002729 m_target.SetExecutableModule (module_sp, false);
2730 break;
2731 }
2732 }
2733}
2734
Chris Lattner24943d22010-06-08 16:52:24 +00002735Error
Greg Claytone71e2582011-02-04 01:58:07 +00002736Process::ConnectRemote (const char *remote_url)
2737{
Greg Claytone71e2582011-02-04 01:58:07 +00002738 m_abi_sp.reset();
2739 m_process_input_reader.reset();
2740
2741 // Find the process and its architecture. Make sure it matches the architecture
2742 // of the current Target, and if not adjust it.
2743
2744 Error error (DoConnectRemote (remote_url));
2745 if (error.Success())
2746 {
Greg Claytona2f74232011-02-24 22:24:29 +00002747 if (GetID() != LLDB_INVALID_PROCESS_ID)
2748 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002749 EventSP event_sp;
2750 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2751
2752 if (state == eStateStopped || state == eStateCrashed)
2753 {
2754 // If we attached and actually have a process on the other end, then
2755 // this ended up being the equivalent of an attach.
2756 CompleteAttach ();
2757
2758 // This delays passing the stopped event to listeners till
2759 // CompleteAttach gets a chance to complete...
2760 HandlePrivateEvent (event_sp);
2761
2762 }
Greg Claytona2f74232011-02-24 22:24:29 +00002763 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002764
2765 if (PrivateStateThreadIsValid ())
2766 ResumePrivateStateThread ();
2767 else
2768 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002769 }
2770 return error;
2771}
2772
2773
2774Error
Chris Lattner24943d22010-06-08 16:52:24 +00002775Process::Resume ()
2776{
Greg Claytone005f2c2010-11-06 01:53:30 +00002777 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002778 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002779 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham21f37ad2011-08-09 02:12:22 +00002780 m_mod_id.GetStopID(),
Jim Inghamac959662011-01-24 06:34:17 +00002781 StateAsCString(m_public_state.GetValue()),
2782 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002783
2784 Error error (WillResume());
2785 // Tell the process it is about to resume before the thread list
2786 if (error.Success())
2787 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002788 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002789 // can let all of our threads know that they are about to be
2790 // resumed. Threads will each be called with
2791 // Thread::WillResume(StateType) where StateType contains the state
2792 // that they are supposed to have when the process is resumed
2793 // (suspended/running/stepping). Threads should also check
2794 // their resume signal in lldb::Thread::GetResumeSignal()
2795 // to see if they are suppoed to start back up with a signal.
2796 if (m_thread_list.WillResume())
2797 {
Jim Ingham1831e782012-04-07 00:00:41 +00002798 // Last thing, do the PreResumeActions.
2799 if (!RunPreResumeActions())
Chris Lattner24943d22010-06-08 16:52:24 +00002800 {
Jim Ingham1831e782012-04-07 00:00:41 +00002801 error.SetErrorStringWithFormat ("Process::Resume PreResumeActions failed, not resuming.");
2802 }
2803 else
2804 {
2805 m_mod_id.BumpResumeID();
2806 error = DoResume();
2807 if (error.Success())
2808 {
2809 DidResume();
2810 m_thread_list.DidResume();
2811 if (log)
2812 log->Printf ("Process thinks the process has resumed.");
2813 }
Chris Lattner24943d22010-06-08 16:52:24 +00002814 }
2815 }
2816 else
2817 {
Jim Inghamac959662011-01-24 06:34:17 +00002818 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002819 }
2820 }
Jim Inghamac959662011-01-24 06:34:17 +00002821 else if (log)
2822 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002823 return error;
2824}
2825
2826Error
2827Process::Halt ()
2828{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002829 // Pause our private state thread so we can ensure no one else eats
2830 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002831 Listener halt_listener ("lldb.process.halt_listener");
2832 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002833
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002834 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002835 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002836
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002837 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002838 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002839
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002840 bool caused_stop = false;
2841
2842 // Ask the process subclass to actually halt our process
2843 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002844 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002845 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002846 if (m_public_state.GetValue() == eStateAttaching)
2847 {
2848 SetExitStatus(SIGKILL, "Cancelled async attach.");
2849 Destroy ();
2850 }
2851 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002852 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002853 // If "caused_stop" is true, then DoHalt stopped the process. If
2854 // "caused_stop" is false, the process was already stopped.
2855 // If the DoHalt caused the process to stop, then we want to catch
2856 // this event and set the interrupted bool to true before we pass
2857 // this along so clients know that the process was interrupted by
2858 // a halt command.
2859 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002860 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002861 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002862 TimeValue timeout_time;
2863 timeout_time = TimeValue::Now();
2864 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002865 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2866 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002867
Jim Inghamf9f40c22011-02-08 05:20:59 +00002868 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002869 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002870 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002871 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002872 }
2873 else
2874 {
Greg Clayton20206082011-11-17 01:23:07 +00002875 if (StateIsStoppedState (state, false))
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002876 {
2877 // We caused the process to interrupt itself, so mark this
2878 // as such in the stop event so clients can tell an interrupted
2879 // process from a natural stop
2880 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2881 }
2882 else
2883 {
2884 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2885 if (log)
2886 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2887 error.SetErrorString ("Did not get stopped event after halt.");
2888 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002889 }
2890 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002891 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002892 }
2893 }
Chris Lattner24943d22010-06-08 16:52:24 +00002894 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002895 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002896 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002897
2898 // Post any event we might have consumed. If all goes well, we will have
2899 // stopped the process, intercepted the event and set the interrupted
2900 // bool in the event. Post it to the private event queue and that will end up
2901 // correctly setting the state.
2902 if (event_sp)
2903 m_private_state_broadcaster.BroadcastEvent(event_sp);
2904
Chris Lattner24943d22010-06-08 16:52:24 +00002905 return error;
2906}
2907
2908Error
2909Process::Detach ()
2910{
2911 Error error (WillDetach());
2912
2913 if (error.Success())
2914 {
2915 DisableAllBreakpointSites();
2916 error = DoDetach();
2917 if (error.Success())
2918 {
2919 DidDetach();
2920 StopPrivateStateThread();
2921 }
2922 }
2923 return error;
2924}
2925
2926Error
2927Process::Destroy ()
2928{
2929 Error error (WillDestroy());
2930 if (error.Success())
2931 {
2932 DisableAllBreakpointSites();
2933 error = DoDestroy();
2934 if (error.Success())
2935 {
2936 DidDestroy();
2937 StopPrivateStateThread();
2938 }
Caroline Tice861efb32010-11-16 05:07:41 +00002939 m_stdio_communication.StopReadThread();
2940 m_stdio_communication.Disconnect();
2941 if (m_process_input_reader && m_process_input_reader->IsActive())
2942 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2943 if (m_process_input_reader)
2944 m_process_input_reader.reset();
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00002945
2946 // If we have been interrupted (to kill us) in the middle of running, we may not end up propagating
2947 // the last events through the event system, in which case we might strand the write lock. Unlock
2948 // it here so when we do to tear down the process we don't get an error destroying the lock.
2949 m_run_lock.WriteUnlock();
Chris Lattner24943d22010-06-08 16:52:24 +00002950 }
2951 return error;
2952}
2953
2954Error
2955Process::Signal (int signal)
2956{
2957 Error error (WillSignal());
2958 if (error.Success())
2959 {
2960 error = DoSignal(signal);
2961 if (error.Success())
2962 DidSignal();
2963 }
2964 return error;
2965}
2966
Greg Clayton395fc332011-02-15 21:59:32 +00002967lldb::ByteOrder
2968Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002969{
Greg Clayton395fc332011-02-15 21:59:32 +00002970 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002971}
2972
2973uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002974Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002975{
Greg Clayton395fc332011-02-15 21:59:32 +00002976 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002977}
2978
Greg Clayton395fc332011-02-15 21:59:32 +00002979
Chris Lattner24943d22010-06-08 16:52:24 +00002980bool
2981Process::ShouldBroadcastEvent (Event *event_ptr)
2982{
2983 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2984 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002985 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002986
2987 switch (state)
2988 {
Greg Claytone71e2582011-02-04 01:58:07 +00002989 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002990 case eStateAttaching:
2991 case eStateLaunching:
2992 case eStateDetached:
2993 case eStateExited:
2994 case eStateUnloaded:
2995 // These events indicate changes in the state of the debugging session, always report them.
2996 return_value = true;
2997 break;
2998 case eStateInvalid:
2999 // We stopped for no apparent reason, don't report it.
3000 return_value = false;
3001 break;
3002 case eStateRunning:
3003 case eStateStepping:
3004 // If we've started the target running, we handle the cases where we
3005 // are already running and where there is a transition from stopped to
3006 // running differently.
3007 // running -> running: Automatically suppress extra running events
3008 // stopped -> running: Report except when there is one or more no votes
3009 // and no yes votes.
3010 SynchronouslyNotifyStateChanged (state);
3011 switch (m_public_state.GetValue())
3012 {
3013 case eStateRunning:
3014 case eStateStepping:
3015 // We always suppress multiple runnings with no PUBLIC stop in between.
3016 return_value = false;
3017 break;
3018 default:
3019 // TODO: make this work correctly. For now always report
3020 // run if we aren't running so we don't miss any runnning
3021 // events. If I run the lldb/test/thread/a.out file and
3022 // break at main.cpp:58, run and hit the breakpoints on
3023 // multiple threads, then somehow during the stepping over
3024 // of all breakpoints no run gets reported.
3025 return_value = true;
3026
3027 // This is a transition from stop to run.
3028 switch (m_thread_list.ShouldReportRun (event_ptr))
3029 {
3030 case eVoteYes:
3031 case eVoteNoOpinion:
3032 return_value = true;
3033 break;
3034 case eVoteNo:
3035 return_value = false;
3036 break;
3037 }
3038 break;
3039 }
3040 break;
3041 case eStateStopped:
3042 case eStateCrashed:
3043 case eStateSuspended:
3044 {
3045 // We've stopped. First see if we're going to restart the target.
3046 // If we are going to stop, then we always broadcast the event.
3047 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Ingham5a47e8b2010-06-19 04:45:32 +00003048 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00003049 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00003050 {
Greg Clayton20d338f2010-11-18 05:57:03 +00003051 if (log)
3052 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003053 return true;
3054 }
3055 else
3056 {
Chris Lattner24943d22010-06-08 16:52:24 +00003057 RefreshStateAfterStop ();
3058
3059 if (m_thread_list.ShouldStop (event_ptr) == false)
3060 {
3061 switch (m_thread_list.ShouldReportStop (event_ptr))
3062 {
3063 case eVoteYes:
3064 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00003065 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00003066 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00003067 case eVoteNo:
3068 return_value = false;
3069 break;
3070 }
3071
3072 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00003073 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00003074 Resume ();
3075 }
3076 else
3077 {
3078 return_value = true;
3079 SynchronouslyNotifyStateChanged (state);
3080 }
3081 }
3082 }
3083 }
3084
3085 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003086 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner24943d22010-06-08 16:52:24 +00003087 return return_value;
3088}
3089
Chris Lattner24943d22010-06-08 16:52:24 +00003090
3091bool
Jim Ingham1831e782012-04-07 00:00:41 +00003092Process::StartPrivateStateThread (bool force)
Chris Lattner24943d22010-06-08 16:52:24 +00003093{
Greg Claytone005f2c2010-11-06 01:53:30 +00003094 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00003095
Greg Claytonb72d0f02011-04-12 05:54:46 +00003096 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00003097 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003098 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
3099
Jim Ingham1831e782012-04-07 00:00:41 +00003100 if (!force && already_running)
Greg Claytonb72d0f02011-04-12 05:54:46 +00003101 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00003102
3103 // Create a thread that watches our internal state and controls which
3104 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00003105 char thread_name[1024];
Jim Ingham1831e782012-04-07 00:00:41 +00003106 if (already_running)
3107 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state-override(pid=%llu)>", GetID());
3108 else
3109 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Jim Inghamd21d98b2012-04-10 01:21:57 +00003110
3111 // Create the private state thread, and start it running.
Greg Claytona875b642011-01-09 21:07:35 +00003112 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Jim Inghamd21d98b2012-04-10 01:21:57 +00003113 bool success = IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
3114 if (success)
3115 {
3116 ResumePrivateStateThread();
3117 return true;
3118 }
3119 else
3120 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00003121}
3122
3123void
3124Process::PausePrivateStateThread ()
3125{
3126 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
3127}
3128
3129void
3130Process::ResumePrivateStateThread ()
3131{
3132 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
3133}
3134
3135void
3136Process::StopPrivateStateThread ()
3137{
Greg Claytonb72d0f02011-04-12 05:54:46 +00003138 if (PrivateStateThreadIsValid ())
3139 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003140 else
3141 {
3142 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3143 if (log)
3144 printf ("Went to stop the private state thread, but it was already invalid.");
3145 }
Chris Lattner24943d22010-06-08 16:52:24 +00003146}
3147
3148void
3149Process::ControlPrivateStateThread (uint32_t signal)
3150{
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003151 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003152
3153 assert (signal == eBroadcastInternalStateControlStop ||
3154 signal == eBroadcastInternalStateControlPause ||
3155 signal == eBroadcastInternalStateControlResume);
3156
3157 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003158 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003159
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003160 // Signal the private state thread. First we should copy this is case the
3161 // thread starts exiting since the private state thread will NULL this out
3162 // when it exits
3163 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00003164 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00003165 {
3166 TimeValue timeout_time;
3167 bool timed_out;
3168
3169 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
3170
3171 timeout_time = TimeValue::Now();
3172 timeout_time.OffsetWithSeconds(2);
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003173 if (log)
3174 log->Printf ("Sending control event of type: %d.", signal);
Chris Lattner24943d22010-06-08 16:52:24 +00003175 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
3176 m_private_state_control_wait.SetValue (false, eBroadcastNever);
3177
3178 if (signal == eBroadcastInternalStateControlStop)
3179 {
3180 if (timed_out)
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003181 {
3182 Error error;
3183 Host::ThreadCancel (private_state_thread, &error);
3184 if (log)
3185 log->Printf ("Timed out responding to the control event, cancel got error: \"%s\".", error.AsCString());
3186 }
3187 else
3188 {
3189 if (log)
3190 log->Printf ("The control event killed the private state thread without having to cancel.");
3191 }
Chris Lattner24943d22010-06-08 16:52:24 +00003192
3193 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00003194 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00003195 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003196 }
3197 }
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003198 else
3199 {
3200 if (log)
3201 log->Printf ("Private state thread already dead, no need to signal it to stop.");
3202 }
Chris Lattner24943d22010-06-08 16:52:24 +00003203}
3204
3205void
3206Process::HandlePrivateEvent (EventSP &event_sp)
3207{
Greg Claytone005f2c2010-11-06 01:53:30 +00003208 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003209
Greg Clayton68ca8232011-01-25 02:58:48 +00003210 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003211
3212 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00003213 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003214 {
Jim Ingham68bffc52011-01-29 04:05:41 +00003215 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003216 switch (action_result)
3217 {
3218 case NextEventAction::eEventActionSuccess:
3219 SetNextEventAction(NULL);
3220 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003221
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003222 case NextEventAction::eEventActionRetry:
3223 break;
Greg Clayton2d9adb72011-11-12 02:10:56 +00003224
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003225 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00003226 // Handle Exiting Here. If we already got an exited event,
3227 // we should just propagate it. Otherwise, swallow this event,
3228 // and set our state to exit so the next event will kill us.
3229 if (new_state != eStateExited)
3230 {
3231 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00003232 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00003233 SetNextEventAction(NULL);
3234 return;
3235 }
3236 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00003237 break;
3238 }
3239 }
3240
Chris Lattner24943d22010-06-08 16:52:24 +00003241 // See if we should broadcast this state to external clients?
3242 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00003243
3244 if (should_broadcast)
3245 {
3246 if (log)
3247 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003248 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton68ca8232011-01-25 02:58:48 +00003249 __FUNCTION__,
3250 GetID(),
3251 StateAsCString(new_state),
3252 StateAsCString (GetState ()),
3253 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00003254 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003255 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00003256 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00003257 PushProcessInputReader ();
3258 else
3259 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00003260
Chris Lattner24943d22010-06-08 16:52:24 +00003261 BroadcastEvent (event_sp);
3262 }
3263 else
3264 {
3265 if (log)
3266 {
Greg Clayton444e35b2011-10-19 18:09:39 +00003267 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton68ca8232011-01-25 02:58:48 +00003268 __FUNCTION__,
3269 GetID(),
3270 StateAsCString(new_state),
Jason Molenda7e5fa7f2011-09-20 21:44:10 +00003271 StateAsCString (GetState ()));
Chris Lattner24943d22010-06-08 16:52:24 +00003272 }
3273 }
3274}
3275
3276void *
3277Process::PrivateStateThread (void *arg)
3278{
3279 Process *proc = static_cast<Process*> (arg);
3280 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00003281 return result;
3282}
3283
3284void *
3285Process::RunPrivateStateThread ()
3286{
Jim Inghamd21d98b2012-04-10 01:21:57 +00003287 bool control_only = true;
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003288 m_private_state_control_wait.SetValue (false, eBroadcastNever);
Chris Lattner24943d22010-06-08 16:52:24 +00003289
Greg Claytone005f2c2010-11-06 01:53:30 +00003290 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00003291 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003292 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003293
3294 bool exit_now = false;
3295 while (!exit_now)
3296 {
3297 EventSP event_sp;
3298 WaitForEventsPrivate (NULL, event_sp, control_only);
3299 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
3300 {
Jim Ingham7fa7b2f2012-04-12 18:49:31 +00003301 if (log)
3302 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
3303
Chris Lattner24943d22010-06-08 16:52:24 +00003304 switch (event_sp->GetType())
3305 {
3306 case eBroadcastInternalStateControlStop:
3307 exit_now = true;
Chris Lattner24943d22010-06-08 16:52:24 +00003308 break; // doing any internal state managment below
3309
3310 case eBroadcastInternalStateControlPause:
3311 control_only = true;
3312 break;
3313
3314 case eBroadcastInternalStateControlResume:
3315 control_only = false;
3316 break;
3317 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00003318
Chris Lattner24943d22010-06-08 16:52:24 +00003319 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00003320 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00003321 }
3322
3323
3324 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3325
3326 if (internal_state != eStateInvalid)
3327 {
3328 HandlePrivateEvent (event_sp);
3329 }
3330
Greg Clayton3b2c41c2010-10-18 04:14:23 +00003331 if (internal_state == eStateInvalid ||
3332 internal_state == eStateExited ||
3333 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00003334 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00003335 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003336 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00003337
Chris Lattner24943d22010-06-08 16:52:24 +00003338 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00003339 }
Chris Lattner24943d22010-06-08 16:52:24 +00003340 }
3341
Caroline Tice926060e2010-10-29 21:48:37 +00003342 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00003343 if (log)
Greg Clayton444e35b2011-10-19 18:09:39 +00003344 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003345
Greg Claytona4881d02011-01-22 07:12:45 +00003346 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
3347 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00003348 return NULL;
3349}
3350
Chris Lattner24943d22010-06-08 16:52:24 +00003351//------------------------------------------------------------------
3352// Process Event Data
3353//------------------------------------------------------------------
3354
3355Process::ProcessEventData::ProcessEventData () :
3356 EventData (),
3357 m_process_sp (),
3358 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003359 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003360 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003361 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003362{
3363}
3364
3365Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
3366 EventData (),
3367 m_process_sp (process_sp),
3368 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00003369 m_restarted (false),
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003370 m_update_state (0),
Jim Ingham3ae449a2010-11-17 02:32:00 +00003371 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00003372{
3373}
3374
3375Process::ProcessEventData::~ProcessEventData()
3376{
3377}
3378
3379const ConstString &
3380Process::ProcessEventData::GetFlavorString ()
3381{
3382 static ConstString g_flavor ("Process::ProcessEventData");
3383 return g_flavor;
3384}
3385
3386const ConstString &
3387Process::ProcessEventData::GetFlavor () const
3388{
3389 return ProcessEventData::GetFlavorString ();
3390}
3391
Chris Lattner24943d22010-06-08 16:52:24 +00003392void
3393Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
3394{
3395 // This function gets called twice for each event, once when the event gets pulled
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003396 // off of the private process event queue, and then any number of times, first when it gets pulled off of
3397 // the public event queue, then other times when we're pretending that this is where we stopped at the
3398 // end of expression evaluation. m_update_state is used to distinguish these
3399 // three cases; it is 0 when we're just pulling it off for private handling,
3400 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner24943d22010-06-08 16:52:24 +00003401
Jim Ingham6cf4d2b2011-05-22 21:45:01 +00003402 if (m_update_state != 1)
Chris Lattner24943d22010-06-08 16:52:24 +00003403 return;
3404
3405 m_process_sp->SetPublicState (m_state);
3406
3407 // If we're stopped and haven't restarted, then do the breakpoint commands here:
3408 if (m_state == eStateStopped && ! m_restarted)
Jim Ingham0296fe72011-11-08 03:00:11 +00003409 {
3410 ThreadList &curr_thread_list = m_process_sp->GetThreadList();
Greg Claytond9919d32011-12-01 23:28:38 +00003411 uint32_t num_threads = curr_thread_list.GetSize();
3412 uint32_t idx;
Greg Clayton643ee732010-08-04 01:40:35 +00003413
Jim Ingham21f37ad2011-08-09 02:12:22 +00003414 // The actions might change one of the thread's stop_info's opinions about whether we should
3415 // stop the process, so we need to query that as we go.
Jim Ingham0296fe72011-11-08 03:00:11 +00003416
3417 // One other complication here, is that we try to catch any case where the target has run (except for expressions)
3418 // and immediately exit, but if we get that wrong (which is possible) then the thread list might have changed, and
3419 // that would cause our iteration here to crash. We could make a copy of the thread list, but we'd really like
3420 // 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
3421 // against this list & bag out if anything differs.
Greg Claytond9919d32011-12-01 23:28:38 +00003422 std::vector<uint32_t> thread_index_array(num_threads);
Jim Ingham0296fe72011-11-08 03:00:11 +00003423 for (idx = 0; idx < num_threads; ++idx)
3424 thread_index_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3425
Jim Ingham21f37ad2011-08-09 02:12:22 +00003426 bool still_should_stop = true;
3427
Chris Lattner24943d22010-06-08 16:52:24 +00003428 for (idx = 0; idx < num_threads; ++idx)
3429 {
Jim Ingham0296fe72011-11-08 03:00:11 +00003430 curr_thread_list = m_process_sp->GetThreadList();
3431 if (curr_thread_list.GetSize() != num_threads)
3432 {
3433 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003434 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003435 log->Printf("Number of threads changed from %u to %u while processing event.", num_threads, curr_thread_list.GetSize());
Jim Ingham0296fe72011-11-08 03:00:11 +00003436 break;
3437 }
3438
3439 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
3440
3441 if (thread_sp->GetIndexID() != thread_index_array[idx])
3442 {
3443 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham60526c42011-12-01 20:26:15 +00003444 if (log)
Greg Claytond9919d32011-12-01 23:28:38 +00003445 log->Printf("The thread at position %u changed from %u to %u while processing event.",
Jim Ingham60526c42011-12-01 20:26:15 +00003446 idx,
3447 thread_index_array[idx],
3448 thread_sp->GetIndexID());
Jim Ingham0296fe72011-11-08 03:00:11 +00003449 break;
3450 }
3451
Jim Ingham6297a3a2010-10-20 00:39:53 +00003452 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3453 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00003454 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003455 stop_info_sp->PerformAction(event_ptr);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003456 // The stop action might restart the target. If it does, then we want to mark that in the
3457 // event so that whoever is receiving it will know to wait for the running event and reflect
3458 // that state appropriately.
3459 // We also need to stop processing actions, since they aren't expecting the target to be running.
Jim Ingham0296fe72011-11-08 03:00:11 +00003460
3461 // FIXME: we might have run.
3462 if (stop_info_sp->HasTargetRunSinceMe())
Jim Ingham21f37ad2011-08-09 02:12:22 +00003463 {
3464 SetRestarted (true);
3465 break;
3466 }
3467 else if (!stop_info_sp->ShouldStop(event_ptr))
3468 {
3469 still_should_stop = false;
3470 }
Chris Lattner24943d22010-06-08 16:52:24 +00003471 }
3472 }
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003473
Jim Ingham21f37ad2011-08-09 02:12:22 +00003474
3475 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Inghamd60d94a2011-03-11 03:53:59 +00003476 {
Jim Ingham21f37ad2011-08-09 02:12:22 +00003477 if (!still_should_stop)
3478 {
3479 // We've been asked to continue, so do that here.
Jim Inghamd60d94a2011-03-11 03:53:59 +00003480 SetRestarted(true);
Jim Ingham21f37ad2011-08-09 02:12:22 +00003481 m_process_sp->Resume();
3482 }
3483 else
3484 {
3485 // If we didn't restart, run the Stop Hooks here:
3486 // They might also restart the target, so watch for that.
3487 m_process_sp->GetTarget().RunStopHooks();
3488 if (m_process_sp->GetPrivateState() == eStateRunning)
3489 SetRestarted(true);
3490 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00003491 }
3492
Chris Lattner24943d22010-06-08 16:52:24 +00003493 }
3494}
3495
3496void
3497Process::ProcessEventData::Dump (Stream *s) const
3498{
3499 if (m_process_sp)
Greg Clayton444e35b2011-10-19 18:09:39 +00003500 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner24943d22010-06-08 16:52:24 +00003501
Greg Claytonb72d0f02011-04-12 05:54:46 +00003502 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003503}
3504
3505const Process::ProcessEventData *
3506Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3507{
3508 if (event_ptr)
3509 {
3510 const EventData *event_data = event_ptr->GetData();
3511 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3512 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3513 }
3514 return NULL;
3515}
3516
3517ProcessSP
3518Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3519{
3520 ProcessSP process_sp;
3521 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3522 if (data)
3523 process_sp = data->GetProcessSP();
3524 return process_sp;
3525}
3526
3527StateType
3528Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3529{
3530 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3531 if (data == NULL)
3532 return eStateInvalid;
3533 else
3534 return data->GetState();
3535}
3536
3537bool
3538Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3539{
3540 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3541 if (data == NULL)
3542 return false;
3543 else
3544 return data->GetRestarted();
3545}
3546
3547void
3548Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3549{
3550 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3551 if (data != NULL)
3552 data->SetRestarted(new_value);
3553}
3554
3555bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003556Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3557{
3558 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3559 if (data == NULL)
3560 return false;
3561 else
3562 return data->GetInterrupted ();
3563}
3564
3565void
3566Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3567{
3568 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3569 if (data != NULL)
3570 data->SetInterrupted(new_value);
3571}
3572
3573bool
Chris Lattner24943d22010-06-08 16:52:24 +00003574Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3575{
3576 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3577 if (data)
3578 {
3579 data->SetUpdateStateOnRemoval();
3580 return true;
3581 }
3582 return false;
3583}
3584
Greg Clayton289afcb2012-02-18 05:35:26 +00003585lldb::TargetSP
3586Process::CalculateTarget ()
3587{
3588 return m_target.shared_from_this();
3589}
3590
Chris Lattner24943d22010-06-08 16:52:24 +00003591void
Greg Claytona830adb2010-10-04 01:05:56 +00003592Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003593{
Greg Clayton567e7f32011-09-22 04:58:26 +00003594 exe_ctx.SetTargetPtr (&m_target);
3595 exe_ctx.SetProcessPtr (this);
3596 exe_ctx.SetThreadPtr(NULL);
3597 exe_ctx.SetFramePtr (NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00003598}
3599
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003600//uint32_t
3601//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3602//{
3603// return 0;
3604//}
3605//
3606//ArchSpec
3607//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3608//{
3609// return Host::GetArchSpecForExistingProcess (pid);
3610//}
3611//
3612//ArchSpec
3613//Process::GetArchSpecForExistingProcess (const char *process_name)
3614//{
3615// return Host::GetArchSpecForExistingProcess (process_name);
3616//}
3617//
Caroline Tice861efb32010-11-16 05:07:41 +00003618void
3619Process::AppendSTDOUT (const char * s, size_t len)
3620{
Greg Clayton20d338f2010-11-18 05:57:03 +00003621 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003622 m_stdout_data.append (s, len);
Greg Claytonb3781332010-12-05 19:16:56 +00003623 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003624}
3625
3626void
Greg Claytonbd06ff42011-11-13 04:45:22 +00003627Process::AppendSTDERR (const char * s, size_t len)
3628{
3629 Mutex::Locker locker (m_stdio_communication_mutex);
3630 m_stderr_data.append (s, len);
3631 BroadcastEventIfUnique (eBroadcastBitSTDERR, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
3632}
3633
3634//------------------------------------------------------------------
3635// Process STDIO
3636//------------------------------------------------------------------
3637
3638size_t
3639Process::GetSTDOUT (char *buf, size_t buf_size, Error &error)
3640{
3641 Mutex::Locker locker(m_stdio_communication_mutex);
3642 size_t bytes_available = m_stdout_data.size();
3643 if (bytes_available > 0)
3644 {
3645 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3646 if (log)
3647 log->Printf ("Process::GetSTDOUT (buf = %p, size = %zu)", buf, buf_size);
3648 if (bytes_available > buf_size)
3649 {
3650 memcpy(buf, m_stdout_data.c_str(), buf_size);
3651 m_stdout_data.erase(0, buf_size);
3652 bytes_available = buf_size;
3653 }
3654 else
3655 {
3656 memcpy(buf, m_stdout_data.c_str(), bytes_available);
3657 m_stdout_data.clear();
3658 }
3659 }
3660 return bytes_available;
3661}
3662
3663
3664size_t
3665Process::GetSTDERR (char *buf, size_t buf_size, Error &error)
3666{
3667 Mutex::Locker locker(m_stdio_communication_mutex);
3668 size_t bytes_available = m_stderr_data.size();
3669 if (bytes_available > 0)
3670 {
3671 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
3672 if (log)
3673 log->Printf ("Process::GetSTDERR (buf = %p, size = %zu)", buf, buf_size);
3674 if (bytes_available > buf_size)
3675 {
3676 memcpy(buf, m_stderr_data.c_str(), buf_size);
3677 m_stderr_data.erase(0, buf_size);
3678 bytes_available = buf_size;
3679 }
3680 else
3681 {
3682 memcpy(buf, m_stderr_data.c_str(), bytes_available);
3683 m_stderr_data.clear();
3684 }
3685 }
3686 return bytes_available;
3687}
3688
3689void
Caroline Tice861efb32010-11-16 05:07:41 +00003690Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3691{
3692 Process *process = (Process *) baton;
3693 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3694}
3695
3696size_t
3697Process::ProcessInputReaderCallback (void *baton,
3698 InputReader &reader,
3699 lldb::InputReaderAction notification,
3700 const char *bytes,
3701 size_t bytes_len)
3702{
3703 Process *process = (Process *) baton;
3704
3705 switch (notification)
3706 {
3707 case eInputReaderActivate:
3708 break;
3709
3710 case eInputReaderDeactivate:
3711 break;
3712
3713 case eInputReaderReactivate:
3714 break;
3715
Caroline Tice4a348082011-05-02 20:41:46 +00003716 case eInputReaderAsynchronousOutputWritten:
3717 break;
3718
Caroline Tice861efb32010-11-16 05:07:41 +00003719 case eInputReaderGotToken:
3720 {
3721 Error error;
3722 process->PutSTDIN (bytes, bytes_len, error);
3723 }
3724 break;
3725
Caroline Ticec4f55fe2010-11-19 20:47:54 +00003726 case eInputReaderInterrupt:
3727 process->Halt ();
3728 break;
3729
3730 case eInputReaderEndOfFile:
3731 process->AppendSTDOUT ("^D", 2);
3732 break;
3733
Caroline Tice861efb32010-11-16 05:07:41 +00003734 case eInputReaderDone:
3735 break;
3736
3737 }
3738
3739 return bytes_len;
3740}
3741
3742void
3743Process::ResetProcessInputReader ()
3744{
3745 m_process_input_reader.reset();
3746}
3747
3748void
Greg Clayton464c6162011-11-17 22:14:31 +00003749Process::SetSTDIOFileDescriptor (int file_descriptor)
Caroline Tice861efb32010-11-16 05:07:41 +00003750{
3751 // First set up the Read Thread for reading/handling process I/O
3752
3753 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3754
3755 if (conn_ap.get())
3756 {
3757 m_stdio_communication.SetConnection (conn_ap.release());
3758 if (m_stdio_communication.IsConnected())
3759 {
3760 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3761 m_stdio_communication.StartReadThread();
3762
3763 // Now read thread is set up, set up input reader.
3764
3765 if (!m_process_input_reader.get())
3766 {
3767 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3768 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3769 this,
3770 eInputReaderGranularityByte,
3771 NULL,
3772 NULL,
3773 false));
3774
3775 if (err.Fail())
3776 m_process_input_reader.reset();
3777 }
3778 }
3779 }
3780}
3781
3782void
3783Process::PushProcessInputReader ()
3784{
3785 if (m_process_input_reader && !m_process_input_reader->IsActive())
3786 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3787}
3788
3789void
3790Process::PopProcessInputReader ()
3791{
3792 if (m_process_input_reader && m_process_input_reader->IsActive())
3793 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3794}
3795
Greg Claytond284b662011-02-18 01:44:25 +00003796// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00003797void
Caroline Tice2a456812011-03-10 22:14:10 +00003798Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003799{
Greg Claytonb3448432011-03-24 21:19:54 +00003800 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00003801
3802 int i=0;
3803 const char *name;
3804 OptionEnumValueElement option_enum;
3805 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3806 {
3807 if (name)
3808 {
3809 option_enum.value = i;
3810 option_enum.string_value = name;
3811 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3812 g_plugins.push_back (option_enum);
3813 }
3814 ++i;
3815 }
3816 option_enum.value = 0;
3817 option_enum.string_value = NULL;
3818 option_enum.usage = NULL;
3819 g_plugins.push_back (option_enum);
3820
3821 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3822 {
3823 if (::strcmp (name, "plugin") == 0)
3824 {
3825 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3826 break;
3827 }
3828 }
Greg Clayton990de7b2010-11-18 23:32:35 +00003829 UserSettingsControllerSP &usc = GetSettingsController();
3830 usc.reset (new SettingsController);
3831 UserSettingsController::InitializeSettingsController (usc,
3832 SettingsController::global_settings_table,
3833 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00003834
3835 // Now call SettingsInitialize() for each 'child' of Process settings
3836 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00003837}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003838
Greg Clayton990de7b2010-11-18 23:32:35 +00003839void
Caroline Tice2a456812011-03-10 22:14:10 +00003840Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00003841{
Caroline Tice2a456812011-03-10 22:14:10 +00003842 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3843
3844 Thread::SettingsTerminate ();
3845
3846 // Now terminate Process Settings.
3847
Greg Clayton990de7b2010-11-18 23:32:35 +00003848 UserSettingsControllerSP &usc = GetSettingsController();
3849 UserSettingsController::FinalizeSettingsController (usc);
3850 usc.reset();
3851}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003852
Greg Clayton990de7b2010-11-18 23:32:35 +00003853UserSettingsControllerSP &
3854Process::GetSettingsController ()
3855{
Greg Clayton334d33a2012-01-30 07:41:31 +00003856 static UserSettingsControllerSP g_settings_controller_sp;
3857 if (!g_settings_controller_sp)
3858 {
3859 g_settings_controller_sp.reset (new Process::SettingsController);
3860 // The first shared pointer to Process::SettingsController in
3861 // g_settings_controller_sp must be fully created above so that
3862 // the TargetInstanceSettings can use a weak_ptr to refer back
3863 // to the master setttings controller
3864 InstanceSettingsSP default_instance_settings_sp (new ProcessInstanceSettings (g_settings_controller_sp,
3865 false,
3866 InstanceSettings::GetDefaultName().AsCString()));
3867 g_settings_controller_sp->SetDefaultInstanceSettings (default_instance_settings_sp);
3868 }
3869 return g_settings_controller_sp;
3870
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003871}
3872
Caroline Tice1ebef442010-09-27 00:30:10 +00003873void
3874Process::UpdateInstanceName ()
3875{
Greg Clayton5beb99d2011-08-11 02:48:45 +00003876 Module *module = GetTarget().GetExecutableModulePointer();
Greg Clayton13d24fb2012-01-29 20:56:30 +00003877 if (module && module->GetFileSpec().GetFilename())
Caroline Tice1ebef442010-09-27 00:30:10 +00003878 {
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003879 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Clayton13d24fb2012-01-29 20:56:30 +00003880 module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1ebef442010-09-27 00:30:10 +00003881 }
3882}
3883
Greg Clayton427f2902010-12-14 02:59:59 +00003884ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00003885Process::RunThreadPlan (ExecutionContext &exe_ctx,
Jim Ingham1831e782012-04-07 00:00:41 +00003886 lldb::ThreadPlanSP &thread_plan_sp,
Jim Ingham360f53f2010-11-30 02:22:11 +00003887 bool stop_others,
3888 bool try_all_threads,
3889 bool discard_on_error,
3890 uint32_t single_thread_timeout_usec,
3891 Stream &errors)
3892{
3893 ExecutionResults return_value = eExecutionSetupError;
3894
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003895 if (thread_plan_sp.get() == NULL)
3896 {
3897 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00003898 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003899 }
Greg Clayton567e7f32011-09-22 04:58:26 +00003900
3901 if (exe_ctx.GetProcessPtr() != this)
3902 {
3903 errors.Printf("RunThreadPlan called on wrong process.");
3904 return eExecutionSetupError;
3905 }
3906
3907 Thread *thread = exe_ctx.GetThreadPtr();
3908 if (thread == NULL)
3909 {
3910 errors.Printf("RunThreadPlan called with invalid thread.");
3911 return eExecutionSetupError;
3912 }
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003913
Jim Ingham5ab7fba2011-05-17 22:24:54 +00003914 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3915 // For that to be true the plan can't be private - since private plans suppress themselves in the
3916 // GetCompletedPlan call.
3917
3918 bool orig_plan_private = thread_plan_sp->GetPrivate();
3919 thread_plan_sp->SetPrivate(false);
3920
Jim Inghamac959662011-01-24 06:34:17 +00003921 if (m_private_state.GetValue() != eStateStopped)
3922 {
3923 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00003924 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00003925 }
3926
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003927 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton567e7f32011-09-22 04:58:26 +00003928 const uint32_t thread_idx_id = thread->GetIndexID();
3929 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003930
3931 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3932 // so we should arrange to reset them as well.
3933
Greg Clayton567e7f32011-09-22 04:58:26 +00003934 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Ingham360f53f2010-11-30 02:22:11 +00003935
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003936 uint32_t selected_tid;
3937 StackID selected_stack_id;
Greg Claytone40b6422011-09-18 18:59:15 +00003938 if (selected_thread_sp)
Jim Ingham360f53f2010-11-30 02:22:11 +00003939 {
3940 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham7bbebaf2011-08-13 00:56:10 +00003941 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Ingham360f53f2010-11-30 02:22:11 +00003942 }
3943 else
3944 {
3945 selected_tid = LLDB_INVALID_THREAD_ID;
3946 }
3947
Jim Ingham1831e782012-04-07 00:00:41 +00003948 lldb::thread_t backup_private_state_thread = LLDB_INVALID_HOST_THREAD;
Jim Inghamd21d98b2012-04-10 01:21:57 +00003949 lldb::StateType old_state;
3950 lldb::ThreadPlanSP stopper_base_plan_sp;
Jim Ingham1831e782012-04-07 00:00:41 +00003951
Jim Inghamd21d98b2012-04-10 01:21:57 +00003952 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham1831e782012-04-07 00:00:41 +00003953 if (Host::GetCurrentThread() == m_private_state_thread)
3954 {
Jim Inghamd21d98b2012-04-10 01:21:57 +00003955 // Yikes, we are running on the private state thread! So we can't wait for public events on this thread, since
3956 // we are the thread that is generating public events.
Jim Ingham1831e782012-04-07 00:00:41 +00003957 // The simplest thing to do is to spin up a temporary thread to handle private state thread events while
Jim Inghamd21d98b2012-04-10 01:21:57 +00003958 // we are fielding public events here.
3959 if (log)
3960 log->Printf ("Running thread plan on private state thread, spinning up another state thread to handle the events.");
3961
3962
Jim Ingham1831e782012-04-07 00:00:41 +00003963 backup_private_state_thread = m_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00003964
3965 // One other bit of business: we want to run just this thread plan and anything it pushes, and then stop,
3966 // returning control here.
3967 // But in the normal course of things, the plan above us on the stack would be given a shot at the stop
3968 // event before deciding to stop, and we don't want that. So we insert a "stopper" base plan on the stack
3969 // before the plan we want to run. Since base plans always stop and return control to the user, that will
3970 // do just what we want.
3971 stopper_base_plan_sp.reset(new ThreadPlanBase (*thread));
3972 thread->QueueThreadPlan (stopper_base_plan_sp, false);
3973 // Have to make sure our public state is stopped, since otherwise the reporting logic below doesn't work correctly.
3974 old_state = m_public_state.GetValue();
3975 m_public_state.SetValueNoLock(eStateStopped);
3976
3977 // Now spin up the private state thread:
Jim Ingham1831e782012-04-07 00:00:41 +00003978 StartPrivateStateThread(true);
3979 }
3980
3981 thread->QueueThreadPlan(thread_plan_sp, false); // This used to pass "true" does that make sense?
Jim Ingham360f53f2010-11-30 02:22:11 +00003982
Jim Ingham6ae318c2011-01-23 21:14:08 +00003983 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003984
3985 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3986 // restored on exit to the function.
3987
3988 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00003989
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003990 if (log)
3991 {
3992 StreamString s;
3993 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton444e35b2011-10-19 18:09:39 +00003994 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Clayton567e7f32011-09-22 04:58:26 +00003995 thread->GetIndexID(),
3996 thread->GetID(),
Jim Inghamf9f40c22011-02-08 05:20:59 +00003997 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003998 }
3999
Jim Inghamf9f40c22011-02-08 05:20:59 +00004000 bool got_event;
4001 lldb::EventSP event_sp;
4002 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00004003
4004 TimeValue* timeout_ptr = NULL;
4005 TimeValue real_timeout;
4006
Jim Inghamf9f40c22011-02-08 05:20:59 +00004007 bool first_timeout = true;
4008 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00004009
Jim Ingham360f53f2010-11-30 02:22:11 +00004010 while (1)
4011 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004012 // We usually want to resume the process if we get to the top of the loop.
4013 // The only exception is if we get two running events with no intervening
4014 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00004015
Jim Inghamf9f40c22011-02-08 05:20:59 +00004016 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00004017 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004018 // Do the initial resume and wait for the running event before going further.
4019
Greg Clayton567e7f32011-09-22 04:58:26 +00004020 Error resume_error = Resume ();
Jim Inghamf9f40c22011-02-08 05:20:59 +00004021 if (!resume_error.Success())
4022 {
4023 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00004024 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004025 break;
4026 }
4027
4028 real_timeout = TimeValue::Now();
4029 real_timeout.OffsetWithMicroSeconds(500000);
4030 timeout_ptr = &real_timeout;
4031
Sean Callananfaf04782012-01-05 02:00:14 +00004032 got_event = listener.WaitForEvent(timeout_ptr, event_sp);
Jim Inghamd21d98b2012-04-10 01:21:57 +00004033 if (!got_event)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004034 {
4035 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004036 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004037
4038 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00004039 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004040 break;
4041 }
4042
4043 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4044 if (stop_state != eStateRunning)
4045 {
4046 if (log)
4047 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
4048
4049 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00004050 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004051 break;
4052 }
4053
4054 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004055 log->PutCString ("Resuming succeeded.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004056 // We need to call the function synchronously, so spin waiting for it to return.
4057 // If we get interrupted while executing, we're going to lose our context, and
4058 // won't be able to gather the result at this point.
4059 // We set the timeout AFTER the resume, since the resume takes some time and we
4060 // don't want to charge that to the timeout.
4061
4062 if (single_thread_timeout_usec != 0)
4063 {
4064 real_timeout = TimeValue::Now();
4065 if (first_timeout)
4066 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
4067 else
4068 real_timeout.OffsetWithSeconds(10);
4069
4070 timeout_ptr = &real_timeout;
4071 }
4072 }
4073 else
4074 {
4075 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004076 log->PutCString ("Handled an extra running event.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004077 do_resume = true;
4078 }
4079
4080 // Now wait for the process to stop again:
4081 stop_state = lldb::eStateInvalid;
4082 event_sp.reset();
4083 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
4084
4085 if (got_event)
4086 {
4087 if (event_sp.get())
4088 {
4089 bool keep_going = false;
4090 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4091 if (log)
4092 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
4093
4094 switch (stop_state)
4095 {
4096 case lldb::eStateStopped:
Jim Ingham2370a972011-05-17 01:10:11 +00004097 {
Greg Clayton43994462011-06-03 22:12:42 +00004098 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Clayton567e7f32011-09-22 04:58:26 +00004099 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton43994462011-06-03 22:12:42 +00004100 if (!thread_sp)
Jim Ingham2370a972011-05-17 01:10:11 +00004101 {
Greg Clayton43994462011-06-03 22:12:42 +00004102 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham2370a972011-05-17 01:10:11 +00004103 if (log)
Greg Clayton43994462011-06-03 22:12:42 +00004104 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
4105 return_value = eExecutionInterrupted;
Jim Ingham2370a972011-05-17 01:10:11 +00004106 }
4107 else
4108 {
Greg Clayton43994462011-06-03 22:12:42 +00004109 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
4110 StopReason stop_reason = eStopReasonInvalid;
4111 if (stop_info_sp)
4112 stop_reason = stop_info_sp->GetStopReason();
4113 if (stop_reason == eStopReasonPlanComplete)
4114 {
4115 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004116 log->PutCString ("Execution completed successfully.");
Greg Clayton43994462011-06-03 22:12:42 +00004117 // Now mark this plan as private so it doesn't get reported as the stop reason
4118 // after this point.
4119 if (thread_plan_sp)
4120 thread_plan_sp->SetPrivate (orig_plan_private);
4121 return_value = eExecutionCompleted;
4122 }
4123 else
4124 {
4125 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004126 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton43994462011-06-03 22:12:42 +00004127
4128 return_value = eExecutionInterrupted;
4129 }
Jim Ingham2370a972011-05-17 01:10:11 +00004130 }
Greg Clayton43994462011-06-03 22:12:42 +00004131 }
4132 break;
4133
Jim Inghamf9f40c22011-02-08 05:20:59 +00004134 case lldb::eStateCrashed:
4135 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004136 log->PutCString ("Execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00004137 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004138 break;
Greg Clayton43994462011-06-03 22:12:42 +00004139
Jim Inghamf9f40c22011-02-08 05:20:59 +00004140 case lldb::eStateRunning:
4141 do_resume = false;
4142 keep_going = true;
4143 break;
Greg Clayton43994462011-06-03 22:12:42 +00004144
Jim Inghamf9f40c22011-02-08 05:20:59 +00004145 default:
4146 if (log)
4147 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham2370a972011-05-17 01:10:11 +00004148
4149 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytonb3448432011-03-24 21:19:54 +00004150 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004151 break;
4152 }
4153 if (keep_going)
4154 continue;
4155 else
4156 break;
4157 }
4158 else
4159 {
4160 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004161 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00004162 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004163 break;
4164 }
4165 }
4166 else
4167 {
4168 // If we didn't get an event that means we've timed out...
4169 // We will interrupt the process here. Depending on what we were asked to do we will
4170 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00004171 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00004172
Stephen Wilsonc2b98252011-01-12 04:20:03 +00004173 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00004174 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004175 {
4176 if (first_timeout)
4177 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4178 "trying with all threads enabled.",
4179 single_thread_timeout_usec);
4180 else
4181 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
4182 "and timeout: %d timed out.",
4183 single_thread_timeout_usec);
4184 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004185 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00004186 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
4187 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00004188 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00004189 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004190
Greg Clayton567e7f32011-09-22 04:58:26 +00004191 Error halt_error = Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00004192 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00004193 {
Jim Ingham360f53f2010-11-30 02:22:11 +00004194 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004195 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00004196
Jim Inghamf9f40c22011-02-08 05:20:59 +00004197 // If halt succeeds, it always produces a stopped event. Wait for that:
4198
4199 real_timeout = TimeValue::Now();
4200 real_timeout.OffsetWithMicroSeconds(500000);
4201
4202 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00004203
4204 if (got_event)
4205 {
4206 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4207 if (log)
4208 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004209 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00004210 if (stop_state == lldb::eStateStopped
4211 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Inghamf6d3d792011-08-09 22:24:33 +00004212 log->PutCString (" Event was the Halt interruption event.");
Jim Ingham360f53f2010-11-30 02:22:11 +00004213 }
4214
Jim Inghamf9f40c22011-02-08 05:20:59 +00004215 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00004216 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004217 // Between the time we initiated the Halt and the time we delivered it, the process could have
4218 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00004219
Greg Clayton567e7f32011-09-22 04:58:26 +00004220 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00004221 {
4222 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004223 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004224 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00004225 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004226 break;
4227 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004228
Jim Inghamf9f40c22011-02-08 05:20:59 +00004229 if (!try_all_threads)
4230 {
4231 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004232 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00004233 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004234 break;
4235 }
4236
4237 if (first_timeout)
4238 {
4239 // Set all the other threads to run, and return to the top of the loop, which will continue;
4240 first_timeout = false;
4241 thread_plan_sp->SetStopOthers (false);
4242 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004243 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004244
4245 continue;
4246 }
4247 else
4248 {
4249 // Running all threads failed, so return Interrupted.
4250 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004251 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00004252 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004253 break;
4254 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004255 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004256 }
4257 else
4258 { if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004259 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004260 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00004261 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004262 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00004263 }
4264 }
Jim Inghamc556b462011-01-22 01:30:53 +00004265 else
4266 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004267 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
4268 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00004269 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004270 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.",
4271 halt_error.AsCString());
4272 real_timeout = TimeValue::Now();
4273 real_timeout.OffsetWithMicroSeconds(500000);
4274 timeout_ptr = &real_timeout;
4275 got_event = listener.WaitForEvent(&real_timeout, event_sp);
4276 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00004277 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004278 // This is not going anywhere, bag out.
4279 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004280 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00004281 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004282 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00004283 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004284 else
4285 {
4286 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4287 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004288 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004289 if (stop_state == lldb::eStateStopped)
4290 {
4291 // Between the time we initiated the Halt and the time we delivered it, the process could have
4292 // already finished its job. Check that here:
4293
Greg Clayton567e7f32011-09-22 04:58:26 +00004294 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf9f40c22011-02-08 05:20:59 +00004295 {
4296 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004297 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Inghamf9f40c22011-02-08 05:20:59 +00004298 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00004299 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004300 break;
4301 }
4302
4303 if (first_timeout)
4304 {
4305 // Set all the other threads to run, and return to the top of the loop, which will continue;
4306 first_timeout = false;
4307 thread_plan_sp->SetStopOthers (false);
4308 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004309 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004310
4311 continue;
4312 }
4313 else
4314 {
4315 // Running all threads failed, so return Interrupted.
4316 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004317 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00004318 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004319 break;
4320 }
4321 }
4322 else
4323 {
Sean Callananed3f86b2011-08-09 22:07:08 +00004324 if (log)
4325 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
4326 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00004327 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004328 break;
4329 }
4330 }
Jim Inghamc556b462011-01-22 01:30:53 +00004331 }
4332
Jim Ingham360f53f2010-11-30 02:22:11 +00004333 }
4334
Jim Inghamf9f40c22011-02-08 05:20:59 +00004335 } // END WAIT LOOP
4336
Jim Ingham1831e782012-04-07 00:00:41 +00004337 // If we had to start up a temporary private state thread to run this thread plan, shut it down now.
4338 if (IS_VALID_LLDB_HOST_THREAD(backup_private_state_thread))
4339 {
4340 StopPrivateStateThread();
Jim Ingham1831e782012-04-07 00:00:41 +00004341 Error error;
Jim Ingham1831e782012-04-07 00:00:41 +00004342 m_private_state_thread = backup_private_state_thread;
Jim Inghamd21d98b2012-04-10 01:21:57 +00004343 if (stopper_base_plan_sp != NULL)
4344 {
4345 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
4346 }
4347 m_public_state.SetValueNoLock(old_state);
4348
Jim Ingham1831e782012-04-07 00:00:41 +00004349 }
4350
4351
Jim Inghamf9f40c22011-02-08 05:20:59 +00004352 // Now do some processing on the results of the run:
4353 if (return_value == eExecutionInterrupted)
4354 {
Jim Ingham360f53f2010-11-30 02:22:11 +00004355 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00004356 {
4357 StreamString s;
4358 if (event_sp)
4359 event_sp->Dump (&s);
4360 else
4361 {
Jim Inghamf6d3d792011-08-09 22:24:33 +00004362 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004363 }
4364
4365 StreamString ts;
4366
Jim Inghamf6d3d792011-08-09 22:24:33 +00004367 const char *event_explanation = NULL;
Jim Inghamf9f40c22011-02-08 05:20:59 +00004368
4369 do
4370 {
4371 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
4372
4373 if (!event_data)
4374 {
4375 event_explanation = "<no event data>";
4376 break;
4377 }
4378
4379 Process *process = event_data->GetProcessSP().get();
4380
4381 if (!process)
4382 {
4383 event_explanation = "<no process>";
4384 break;
4385 }
4386
4387 ThreadList &thread_list = process->GetThreadList();
4388
4389 uint32_t num_threads = thread_list.GetSize();
4390 uint32_t thread_index;
4391
4392 ts.Printf("<%u threads> ", num_threads);
4393
4394 for (thread_index = 0;
4395 thread_index < num_threads;
4396 ++thread_index)
4397 {
4398 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
4399
4400 if (!thread)
4401 {
4402 ts.Printf("<?> ");
4403 continue;
4404 }
4405
Greg Clayton444e35b2011-10-19 18:09:39 +00004406 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Inghamf9f40c22011-02-08 05:20:59 +00004407 RegisterContext *register_context = thread->GetRegisterContext().get();
4408
4409 if (register_context)
4410 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
4411 else
4412 ts.Printf("[ip unknown] ");
4413
4414 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
4415 if (stop_info_sp)
4416 {
4417 const char *stop_desc = stop_info_sp->GetDescription();
4418 if (stop_desc)
4419 ts.PutCString (stop_desc);
4420 }
4421 ts.Printf(">");
4422 }
4423
4424 event_explanation = ts.GetData();
4425 } while (0);
4426
4427 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004428 {
4429 if (event_explanation)
4430 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
4431 else
4432 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
4433 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004434
4435 if (discard_on_error && thread_plan_sp)
4436 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004437 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004438 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004439 }
4440 }
4441 }
4442 else if (return_value == eExecutionSetupError)
4443 {
4444 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004445 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Inghamf9f40c22011-02-08 05:20:59 +00004446
4447 if (discard_on_error && thread_plan_sp)
4448 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004449 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004450 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf9f40c22011-02-08 05:20:59 +00004451 }
4452 }
4453 else
4454 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004455 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004456 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004457 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004458 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00004459 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00004460 }
Greg Clayton567e7f32011-09-22 04:58:26 +00004461 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00004462 {
Greg Clayton68ca8232011-01-25 02:58:48 +00004463 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004464 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00004465 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00004466 }
4467 else
4468 {
4469 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004470 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00004471 if (discard_on_error && thread_plan_sp)
4472 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00004473 if (log)
Jim Inghamf6d3d792011-08-09 22:24:33 +00004474 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Clayton567e7f32011-09-22 04:58:26 +00004475 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham21f37ad2011-08-09 02:12:22 +00004476 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham360f53f2010-11-30 02:22:11 +00004477 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004478 }
4479 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00004480
Jim Ingham360f53f2010-11-30 02:22:11 +00004481 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004482 // Check that it's still there, and if it is put it back in the context. Also restore the
4483 // frame in the context if it is still present.
Greg Clayton567e7f32011-09-22 04:58:26 +00004484 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
4485 if (thread)
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004486 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004487 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004488 }
Jim Ingham360f53f2010-11-30 02:22:11 +00004489
4490 // Also restore the current process'es selected frame & thread, since this function calling may
4491 // be done behind the user's back.
4492
4493 if (selected_tid != LLDB_INVALID_THREAD_ID)
4494 {
Greg Clayton567e7f32011-09-22 04:58:26 +00004495 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Ingham360f53f2010-11-30 02:22:11 +00004496 {
4497 // We were able to restore the selected thread, now restore the frame:
Greg Clayton567e7f32011-09-22 04:58:26 +00004498 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham7bbebaf2011-08-13 00:56:10 +00004499 if (old_frame_sp)
Greg Clayton567e7f32011-09-22 04:58:26 +00004500 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Ingham360f53f2010-11-30 02:22:11 +00004501 }
4502 }
4503
4504 return return_value;
4505}
4506
4507const char *
4508Process::ExecutionResultAsCString (ExecutionResults result)
4509{
4510 const char *result_name;
4511
4512 switch (result)
4513 {
Greg Claytonb3448432011-03-24 21:19:54 +00004514 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004515 result_name = "eExecutionCompleted";
4516 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004517 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00004518 result_name = "eExecutionDiscarded";
4519 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004520 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00004521 result_name = "eExecutionInterrupted";
4522 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004523 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00004524 result_name = "eExecutionSetupError";
4525 break;
Greg Claytonb3448432011-03-24 21:19:54 +00004526 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00004527 result_name = "eExecutionTimedOut";
4528 break;
4529 }
4530 return result_name;
4531}
4532
Greg Claytonabe0fed2011-04-18 08:33:37 +00004533void
4534Process::GetStatus (Stream &strm)
4535{
4536 const StateType state = GetState();
Greg Clayton20206082011-11-17 01:23:07 +00004537 if (StateIsStoppedState(state, false))
Greg Claytonabe0fed2011-04-18 08:33:37 +00004538 {
4539 if (state == eStateExited)
4540 {
4541 int exit_status = GetExitStatus();
4542 const char *exit_description = GetExitDescription();
Greg Clayton444e35b2011-10-19 18:09:39 +00004543 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Claytonabe0fed2011-04-18 08:33:37 +00004544 GetID(),
4545 exit_status,
4546 exit_status,
4547 exit_description ? exit_description : "");
4548 }
4549 else
4550 {
4551 if (state == eStateConnected)
4552 strm.Printf ("Connected to remote target.\n");
4553 else
Greg Clayton444e35b2011-10-19 18:09:39 +00004554 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Claytonabe0fed2011-04-18 08:33:37 +00004555 }
4556 }
4557 else
4558 {
Greg Clayton444e35b2011-10-19 18:09:39 +00004559 strm.Printf ("Process %llu is running.\n", GetID());
Greg Claytonabe0fed2011-04-18 08:33:37 +00004560 }
4561}
4562
4563size_t
4564Process::GetThreadStatus (Stream &strm,
4565 bool only_threads_with_stop_reason,
4566 uint32_t start_frame,
4567 uint32_t num_frames,
4568 uint32_t num_frames_with_source)
4569{
4570 size_t num_thread_infos_dumped = 0;
4571
4572 const size_t num_threads = GetThreadList().GetSize();
4573 for (uint32_t i = 0; i < num_threads; i++)
4574 {
4575 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4576 if (thread)
4577 {
4578 if (only_threads_with_stop_reason)
4579 {
4580 if (thread->GetStopInfo().get() == NULL)
4581 continue;
4582 }
4583 thread->GetStatus (strm,
4584 start_frame,
4585 num_frames,
4586 num_frames_with_source);
4587 ++num_thread_infos_dumped;
4588 }
4589 }
4590 return num_thread_infos_dumped;
4591}
4592
Greg Clayton76113302012-02-22 04:37:26 +00004593void
4594Process::AddInvalidMemoryRegion (const LoadRange &region)
4595{
4596 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
4597}
4598
4599bool
4600Process::RemoveInvalidMemoryRange (const LoadRange &region)
4601{
4602 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(), region.GetByteSize());
4603}
4604
Jim Ingham1831e782012-04-07 00:00:41 +00004605void
4606Process::AddPreResumeAction (PreResumeActionCallback callback, void *baton)
4607{
4608 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton (callback, baton));
4609}
4610
4611bool
4612Process::RunPreResumeActions ()
4613{
4614 bool result = true;
4615 while (!m_pre_resume_actions.empty())
4616 {
4617 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
4618 m_pre_resume_actions.pop_back();
4619 bool this_result = action.callback (action.baton);
4620 if (result == true) result = this_result;
4621 }
4622 return result;
4623}
4624
4625void
4626Process::ClearPreResumeActions ()
4627{
4628 m_pre_resume_actions.clear();
4629}
Greg Clayton76113302012-02-22 04:37:26 +00004630
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004631//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004632// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004633//--------------------------------------------------------------
4634
Greg Claytond0a5a232010-09-19 02:33:57 +00004635Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00004636 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004637{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004638}
4639
Greg Claytond0a5a232010-09-19 02:33:57 +00004640Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004641{
4642}
4643
4644lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00004645Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004646{
Greg Clayton334d33a2012-01-30 07:41:31 +00004647 lldb::InstanceSettingsSP new_settings_sp (new ProcessInstanceSettings (GetSettingsController(),
4648 false,
4649 instance_name));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004650 return new_settings_sp;
4651}
4652
4653//--------------------------------------------------------------
4654// class ProcessInstanceSettings
4655//--------------------------------------------------------------
4656
Greg Clayton638351a2010-12-04 00:10:17 +00004657ProcessInstanceSettings::ProcessInstanceSettings
4658(
Greg Clayton334d33a2012-01-30 07:41:31 +00004659 const UserSettingsControllerSP &owner_sp,
Greg Clayton638351a2010-12-04 00:10:17 +00004660 bool live_instance,
4661 const char *name
4662) :
Greg Clayton334d33a2012-01-30 07:41:31 +00004663 InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004664{
Caroline Tice396704b2010-09-09 18:26:37 +00004665 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4666 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4667 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice75b11a32010-09-16 19:05:55 +00004668 // This is true for CreateInstanceName() too.
Greg Claytonabb33022011-11-08 02:43:13 +00004669
Caroline Tice75b11a32010-09-16 19:05:55 +00004670 if (GetInstanceName () == InstanceSettings::InvalidName())
4671 {
4672 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
Greg Clayton334d33a2012-01-30 07:41:31 +00004673 owner_sp->RegisterInstanceSettings (this);
Caroline Tice75b11a32010-09-16 19:05:55 +00004674 }
Greg Claytonabb33022011-11-08 02:43:13 +00004675
Caroline Tice396704b2010-09-09 18:26:37 +00004676 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004677 {
Greg Clayton334d33a2012-01-30 07:41:31 +00004678 const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004679 CopyInstanceSettings (pending_settings,false);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004680 }
4681}
4682
4683ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Clayton334d33a2012-01-30 07:41:31 +00004684 InstanceSettings (Process::GetSettingsController(), CreateInstanceName().AsCString())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004685{
4686 if (m_instance_name != InstanceSettings::GetDefaultName())
4687 {
Greg Clayton334d33a2012-01-30 07:41:31 +00004688 UserSettingsControllerSP owner_sp (m_owner_wp.lock());
4689 if (owner_sp)
4690 {
4691 CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name), false);
4692 owner_sp->RemovePendingSettings (m_instance_name);
4693 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004694 }
4695}
4696
4697ProcessInstanceSettings::~ProcessInstanceSettings ()
4698{
4699}
4700
4701ProcessInstanceSettings&
4702ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4703{
4704 if (this != &rhs)
4705 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004706 }
4707
4708 return *this;
4709}
4710
4711
4712void
4713ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4714 const char *index_value,
4715 const char *value,
4716 const ConstString &instance_name,
4717 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00004718 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004719 Error &err,
4720 bool pending)
4721{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004722}
4723
4724void
4725ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4726 bool pending)
4727{
Greg Claytonabb33022011-11-08 02:43:13 +00004728// if (new_settings.get() == NULL)
4729// return;
4730//
4731// ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004732}
4733
Caroline Ticebcb5b452010-09-20 21:37:42 +00004734bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004735ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4736 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00004737 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00004738 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004739{
Greg Claytonabb33022011-11-08 02:43:13 +00004740 if (err)
4741 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4742 return false;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004743}
4744
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004745const ConstString
4746ProcessInstanceSettings::CreateInstanceName ()
4747{
4748 static int instance_count = 1;
4749 StreamString sstr;
4750
4751 sstr.Printf ("process_%d", instance_count);
4752 ++instance_count;
4753
4754 const ConstString ret_val (sstr.GetData());
4755 return ret_val;
4756}
4757
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004758//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004759// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004760//--------------------------------------------------
4761
4762SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004763Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004764{
4765 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4766 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4767};
4768
4769
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004770SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004771Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004772{
Greg Clayton638351a2010-12-04 00:10:17 +00004773 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
Greg Clayton638351a2010-12-04 00:10:17 +00004774 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004775};
4776
4777
Jim Ingham7508e732010-08-09 23:31:02 +00004778
Greg Claytonabb33022011-11-08 02:43:13 +00004779