blob: 47a4c1c5b98eb0ef56a182a7e5718c96e2d2243e [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"
Jim Ingham642036f2010-09-23 02:01:19 +000028#include "lldb/Target/LanguageRuntime.h"
29#include "lldb/Target/CPPLanguageRuntime.h"
30#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000031#include "lldb/Target/Platform.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "lldb/Target/RegisterContext.h"
Greg Clayton643ee732010-08-04 01:40:35 +000033#include "lldb/Target/StopInfo.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Target/Target.h"
35#include "lldb/Target/TargetList.h"
36#include "lldb/Target/Thread.h"
37#include "lldb/Target/ThreadPlan.h"
38
39using namespace lldb;
40using namespace lldb_private;
41
Greg Clayton24bc5d92011-03-30 18:16:51 +000042void
Greg Claytonb72d0f02011-04-12 05:54:46 +000043ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton24bc5d92011-03-30 18:16:51 +000044{
45 const char *cstr;
Greg Claytonff39f742011-04-01 00:29:43 +000046 if (m_pid != LLDB_INVALID_PROCESS_ID)
47 s.Printf (" pid = %i\n", m_pid);
48
49 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
50 s.Printf (" parent = %i\n", m_parent_pid);
51
52 if (m_executable)
53 {
54 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
55 s.PutCString (" file = ");
56 m_executable.Dump(&s);
57 s.EOL();
58 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000059 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +000060 if (argc > 0)
61 {
62 for (uint32_t i=0; i<argc; i++)
63 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000064 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Claytonff39f742011-04-01 00:29:43 +000065 if (i < 10)
Greg Claytonb72d0f02011-04-12 05:54:46 +000066 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000067 else
Greg Claytonb72d0f02011-04-12 05:54:46 +000068 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Claytonff39f742011-04-01 00:29:43 +000069 }
70 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000071
72 const uint32_t envc = m_environment.GetArgumentCount();
73 if (envc > 0)
74 {
75 for (uint32_t i=0; i<envc; i++)
76 {
77 const char *env = m_environment.GetArgumentAtIndex(i);
78 if (i < 10)
79 s.Printf (" env[%u] = %s\n", i, env);
80 else
81 s.Printf ("env[%u] = %s\n", i, env);
82 }
83 }
84
Greg Claytonff39f742011-04-01 00:29:43 +000085 if (m_arch.IsValid())
86 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
87
Greg Claytonb72d0f02011-04-12 05:54:46 +000088 if (m_uid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000089 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000090 cstr = platform->GetUserName (m_uid);
91 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000092 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000093 if (m_gid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000094 {
Greg Claytonb72d0f02011-04-12 05:54:46 +000095 cstr = platform->GetGroupName (m_gid);
96 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +000097 }
Greg Claytonb72d0f02011-04-12 05:54:46 +000098 if (m_euid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +000099 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000100 cstr = platform->GetUserName (m_euid);
101 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000102 }
Greg Claytonb72d0f02011-04-12 05:54:46 +0000103 if (m_egid != UINT32_MAX)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000104 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000105 cstr = platform->GetGroupName (m_egid);
106 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton24bc5d92011-03-30 18:16:51 +0000107 }
108}
109
110void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000111ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton24bc5d92011-03-30 18:16:51 +0000112{
Greg Claytonb72d0f02011-04-12 05:54:46 +0000113 const char *label;
114 if (show_args || verbose)
115 label = "ARGUMENTS";
116 else
117 label = "NAME";
118
Greg Claytonff39f742011-04-01 00:29:43 +0000119 if (verbose)
120 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000121 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000122 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
123 }
124 else
125 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000126 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Claytonff39f742011-04-01 00:29:43 +0000127 s.PutCString ("====== ====== ========== ======= ============================\n");
128 }
Greg Clayton24bc5d92011-03-30 18:16:51 +0000129}
130
131void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000132ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000133{
134 if (m_pid != LLDB_INVALID_PROCESS_ID)
135 {
136 const char *cstr;
137 s.Printf ("%-6u %-6u ", m_pid, m_parent_pid);
138
Greg Clayton24bc5d92011-03-30 18:16:51 +0000139
Greg Claytonff39f742011-04-01 00:29:43 +0000140 if (verbose)
141 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000142 cstr = platform->GetUserName (m_uid);
Greg Claytonff39f742011-04-01 00:29:43 +0000143 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
144 s.Printf ("%-10s ", cstr);
145 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000146 s.Printf ("%-10u ", m_uid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000147
Greg Claytonb72d0f02011-04-12 05:54:46 +0000148 cstr = platform->GetGroupName (m_gid);
Greg Claytonff39f742011-04-01 00:29:43 +0000149 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
150 s.Printf ("%-10s ", cstr);
151 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000152 s.Printf ("%-10u ", m_gid);
Greg Clayton24bc5d92011-03-30 18:16:51 +0000153
Greg Claytonb72d0f02011-04-12 05:54:46 +0000154 cstr = platform->GetUserName (m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000155 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
156 s.Printf ("%-10s ", cstr);
157 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000158 s.Printf ("%-10u ", m_euid);
Greg Claytonff39f742011-04-01 00:29:43 +0000159
Greg Claytonb72d0f02011-04-12 05:54:46 +0000160 cstr = platform->GetGroupName (m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000161 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
162 s.Printf ("%-10s ", cstr);
163 else
Greg Claytonb72d0f02011-04-12 05:54:46 +0000164 s.Printf ("%-10u ", m_egid);
Greg Claytonff39f742011-04-01 00:29:43 +0000165 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
166 }
167 else
168 {
169 s.Printf ("%-10s %.*-7s ",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000170 platform->GetUserName (m_euid),
Greg Claytonff39f742011-04-01 00:29:43 +0000171 (int)m_arch.GetTriple().getArchName().size(),
172 m_arch.GetTriple().getArchName().data());
173 }
174
Greg Claytonb72d0f02011-04-12 05:54:46 +0000175 if (verbose || show_args)
Greg Claytonff39f742011-04-01 00:29:43 +0000176 {
Greg Claytonb72d0f02011-04-12 05:54:46 +0000177 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Claytonff39f742011-04-01 00:29:43 +0000178 if (argc > 0)
179 {
180 for (uint32_t i=0; i<argc; i++)
181 {
182 if (i > 0)
183 s.PutChar (' ');
Greg Claytonb72d0f02011-04-12 05:54:46 +0000184 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Claytonff39f742011-04-01 00:29:43 +0000185 }
186 }
187 }
188 else
189 {
190 s.PutCString (GetName());
191 }
192
193 s.EOL();
Greg Clayton24bc5d92011-03-30 18:16:51 +0000194 }
195}
196
Greg Claytonb72d0f02011-04-12 05:54:46 +0000197
198void
199ProcessInfo::SetArgumentsFromArgs (const Args& args,
200 bool first_arg_is_executable,
201 bool first_arg_is_executable_and_argument)
202{
203 // Copy all arguments
204 m_arguments = args;
205
206 // Is the first argument the executable?
207 if (first_arg_is_executable)
208 {
209 const char *first_arg = args.GetArgumentAtIndex (0);
210 if (first_arg)
211 {
212 // Yes the first argument is an executable, set it as the executable
213 // in the launch options. Don't resolve the file path as the path
214 // could be a remote platform path
215 const bool resolve = false;
216 m_executable.SetFile(first_arg, resolve);
217
218 // If argument zero is an executable and shouldn't be included
219 // in the arguments, remove it from the front of the arguments
220 if (first_arg_is_executable_and_argument == false)
221 m_arguments.DeleteArgumentAtIndex (0);
222 }
223 }
224}
225
Greg Clayton24bc5d92011-03-30 18:16:51 +0000226bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000227ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
228{
229 if ((read || write) && fd >= 0 && path && path[0])
230 {
231 m_action = eFileActionOpen;
232 m_fd = fd;
233 if (read && write)
234 m_arg = O_RDWR;
235 else if (read)
236 m_arg = O_RDONLY;
237 else
238 m_arg = O_WRONLY;
239 m_path.assign (path);
240 return true;
241 }
242 else
243 {
244 Clear();
245 }
246 return false;
247}
248
249bool
250ProcessLaunchInfo::FileAction::Close (int fd)
251{
252 Clear();
253 if (fd >= 0)
254 {
255 m_action = eFileActionClose;
256 m_fd = fd;
257 }
258 return m_fd >= 0;
259}
260
261
262bool
263ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
264{
265 Clear();
266 if (fd >= 0 && dup_fd >= 0)
267 {
268 m_action = eFileActionDuplicate;
269 m_fd = fd;
270 m_arg = dup_fd;
271 }
272 return m_fd >= 0;
273}
274
275
276
277bool
278ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
279 const FileAction *info,
280 Log *log,
281 Error& error)
282{
283 if (info == NULL)
284 return false;
285
286 switch (info->m_action)
287 {
288 case eFileActionNone:
289 error.Clear();
290 break;
291
292 case eFileActionClose:
293 if (info->m_fd == -1)
294 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
295 else
296 {
297 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
298 eErrorTypePOSIX);
299 if (log && (error.Fail() || log))
300 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
301 file_actions, info->m_fd);
302 }
303 break;
304
305 case eFileActionDuplicate:
306 if (info->m_fd == -1)
307 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
308 else if (info->m_arg == -1)
309 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
310 else
311 {
312 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
313 eErrorTypePOSIX);
314 if (log && (error.Fail() || log))
315 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
316 file_actions, info->m_fd, info->m_arg);
317 }
318 break;
319
320 case eFileActionOpen:
321 if (info->m_fd == -1)
322 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
323 else
324 {
325 int oflag = info->m_arg;
326 mode_t mode = 0;
327
328 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
329 info->m_fd,
330 info->m_path.c_str(),
331 oflag,
332 mode),
333 eErrorTypePOSIX);
334 if (error.Fail() || log)
335 error.PutToLog(log,
336 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
337 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
338 }
339 break;
340
341 default:
342 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
343 break;
344 }
345 return error.Success();
346}
347
348Error
Greg Clayton143fcc32011-04-13 00:18:08 +0000349ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Claytonb72d0f02011-04-12 05:54:46 +0000350{
351 Error error;
352 char short_option = (char) m_getopt_table[option_idx].val;
353
354 switch (short_option)
355 {
356 case 's': // Stop at program entry point
357 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
358 break;
359
360 case 'e': // STDERR for read + write
361 {
362 ProcessLaunchInfo::FileAction action;
363 if (action.Open(STDERR_FILENO, option_arg, true, true))
364 launch_info.AppendFileAction (action);
365 }
366 break;
367
368 case 'i': // STDIN for read only
369 {
370 ProcessLaunchInfo::FileAction action;
371 if (action.Open(STDIN_FILENO, option_arg, true, false))
372 launch_info.AppendFileAction (action);
373 }
374 break;
375
376 case 'o': // Open STDOUT for write only
377 {
378 ProcessLaunchInfo::FileAction action;
379 if (action.Open(STDOUT_FILENO, option_arg, false, true))
380 launch_info.AppendFileAction (action);
381 }
382 break;
383
384 case 'p': // Process plug-in name
385 launch_info.SetProcessPluginName (option_arg);
386 break;
387
388 case 'n': // Disable STDIO
389 {
390 ProcessLaunchInfo::FileAction action;
391 if (action.Open(STDERR_FILENO, "/dev/null", true, true))
392 launch_info.AppendFileAction (action);
393 if (action.Open(STDOUT_FILENO, "/dev/null", false, true))
394 launch_info.AppendFileAction (action);
395 if (action.Open(STDIN_FILENO, "/dev/null", true, false))
396 launch_info.AppendFileAction (action);
397 }
398 break;
399
400 case 'w':
401 launch_info.SetWorkingDirectory (option_arg);
402 break;
403
404 case 't': // Open process in new terminal window
405 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
406 break;
407
408 case 'a':
409 launch_info.GetArchitecture().SetTriple (option_arg,
410 m_interpreter.GetPlatform(true).get());
411 break;
412
413 case 'A':
414 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
415 break;
416
417 case 'v':
418 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
419 break;
420
421 default:
422 error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
423 break;
424
425 }
426 return error;
427}
428
429OptionDefinition
430ProcessLaunchCommandOptions::g_option_table[] =
431{
432{ 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."},
433{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
434{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
435{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
436{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
437{ 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."},
438
439{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
440{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
441{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
442
443{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
444
445{ 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."},
446
447{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
448};
449
450
451
452bool
453ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000454{
455 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
456 return true;
457 const char *match_name = m_match_info.GetName();
458 if (!match_name)
459 return true;
460
461 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
462}
463
464bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000465ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000466{
467 if (!NameMatches (proc_info.GetName()))
468 return false;
469
470 if (m_match_info.ProcessIDIsValid() &&
471 m_match_info.GetProcessID() != proc_info.GetProcessID())
472 return false;
473
474 if (m_match_info.ParentProcessIDIsValid() &&
475 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
476 return false;
477
Greg Claytonb72d0f02011-04-12 05:54:46 +0000478 if (m_match_info.UserIDIsValid () &&
479 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000480 return false;
481
Greg Claytonb72d0f02011-04-12 05:54:46 +0000482 if (m_match_info.GroupIDIsValid () &&
483 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000484 return false;
485
486 if (m_match_info.EffectiveUserIDIsValid () &&
487 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
488 return false;
489
490 if (m_match_info.EffectiveGroupIDIsValid () &&
491 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
492 return false;
493
494 if (m_match_info.GetArchitecture().IsValid() &&
495 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
496 return false;
497 return true;
498}
499
500bool
Greg Claytonb72d0f02011-04-12 05:54:46 +0000501ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton24bc5d92011-03-30 18:16:51 +0000502{
503 if (m_name_match_type != eNameMatchIgnore)
504 return false;
505
506 if (m_match_info.ProcessIDIsValid())
507 return false;
508
509 if (m_match_info.ParentProcessIDIsValid())
510 return false;
511
Greg Claytonb72d0f02011-04-12 05:54:46 +0000512 if (m_match_info.UserIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000513 return false;
514
Greg Claytonb72d0f02011-04-12 05:54:46 +0000515 if (m_match_info.GroupIDIsValid ())
Greg Clayton24bc5d92011-03-30 18:16:51 +0000516 return false;
517
518 if (m_match_info.EffectiveUserIDIsValid ())
519 return false;
520
521 if (m_match_info.EffectiveGroupIDIsValid ())
522 return false;
523
524 if (m_match_info.GetArchitecture().IsValid())
525 return false;
526
527 if (m_match_all_users)
528 return false;
529
530 return true;
531
532}
533
534void
Greg Claytonb72d0f02011-04-12 05:54:46 +0000535ProcessInstanceInfoMatch::Clear()
Greg Clayton24bc5d92011-03-30 18:16:51 +0000536{
537 m_match_info.Clear();
538 m_name_match_type = eNameMatchIgnore;
539 m_match_all_users = false;
540}
Greg Claytonfd119992011-01-07 06:08:19 +0000541
542//----------------------------------------------------------------------
543// MemoryCache constructor
544//----------------------------------------------------------------------
545Process::MemoryCache::MemoryCache() :
546 m_cache_line_byte_size (512),
547 m_cache_mutex (Mutex::eMutexTypeRecursive),
548 m_cache ()
549{
550}
551
552//----------------------------------------------------------------------
553// Destructor
554//----------------------------------------------------------------------
555Process::MemoryCache::~MemoryCache()
556{
557}
558
559void
560Process::MemoryCache::Clear()
561{
562 Mutex::Locker locker (m_cache_mutex);
563 m_cache.clear();
564}
565
566void
567Process::MemoryCache::Flush (addr_t addr, size_t size)
568{
569 if (size == 0)
570 return;
571
572 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
573 const addr_t end_addr = (addr + size - 1);
574 const addr_t flush_start_addr = addr - (addr % cache_line_byte_size);
575 const addr_t flush_end_addr = end_addr - (end_addr % cache_line_byte_size);
576
577 Mutex::Locker locker (m_cache_mutex);
578 if (m_cache.empty())
579 return;
580
581 assert ((flush_start_addr % cache_line_byte_size) == 0);
582
583 for (addr_t curr_addr = flush_start_addr; curr_addr <= flush_end_addr; curr_addr += cache_line_byte_size)
584 {
585 collection::iterator pos = m_cache.find (curr_addr);
586 if (pos != m_cache.end())
587 m_cache.erase(pos);
588 }
589}
590
591size_t
592Process::MemoryCache::Read
593(
594 Process *process,
595 addr_t addr,
596 void *dst,
597 size_t dst_len,
598 Error &error
599)
600{
601 size_t bytes_left = dst_len;
602 if (dst && bytes_left > 0)
603 {
604 const uint32_t cache_line_byte_size = m_cache_line_byte_size;
605 uint8_t *dst_buf = (uint8_t *)dst;
606 addr_t curr_addr = addr - (addr % cache_line_byte_size);
607 addr_t cache_offset = addr - curr_addr;
608 Mutex::Locker locker (m_cache_mutex);
609
610 while (bytes_left > 0)
611 {
612 collection::const_iterator pos = m_cache.find (curr_addr);
613 collection::const_iterator end = m_cache.end ();
614
615 if (pos != end)
616 {
617 size_t curr_read_size = cache_line_byte_size - cache_offset;
618 if (curr_read_size > bytes_left)
619 curr_read_size = bytes_left;
620
621 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes() + cache_offset, curr_read_size);
622
623 bytes_left -= curr_read_size;
624 curr_addr += curr_read_size + cache_offset;
625 cache_offset = 0;
626
627 if (bytes_left > 0)
628 {
629 // Get sequential cache page hits
630 for (++pos; (pos != end) && (bytes_left > 0); ++pos)
631 {
632 assert ((curr_addr % cache_line_byte_size) == 0);
633
634 if (pos->first != curr_addr)
635 break;
636
637 curr_read_size = pos->second->GetByteSize();
638 if (curr_read_size > bytes_left)
639 curr_read_size = bytes_left;
640
641 memcpy (dst_buf + dst_len - bytes_left, pos->second->GetBytes(), curr_read_size);
642
643 bytes_left -= curr_read_size;
644 curr_addr += curr_read_size;
645
646 // We have a cache page that succeeded to read some bytes
647 // but not an entire page. If this happens, we must cap
648 // off how much data we are able to read...
649 if (pos->second->GetByteSize() != cache_line_byte_size)
650 return dst_len - bytes_left;
651 }
652 }
653 }
654
655 // We need to read from the process
656
657 if (bytes_left > 0)
658 {
659 assert ((curr_addr % cache_line_byte_size) == 0);
660 std::auto_ptr<DataBufferHeap> data_buffer_heap_ap(new DataBufferHeap (cache_line_byte_size, 0));
661 size_t process_bytes_read = process->ReadMemoryFromInferior (curr_addr,
662 data_buffer_heap_ap->GetBytes(),
663 data_buffer_heap_ap->GetByteSize(),
664 error);
665 if (process_bytes_read == 0)
666 return dst_len - bytes_left;
667
668 if (process_bytes_read != cache_line_byte_size)
669 data_buffer_heap_ap->SetByteSize (process_bytes_read);
670 m_cache[curr_addr] = DataBufferSP (data_buffer_heap_ap.release());
671 // We have read data and put it into the cache, continue through the
672 // loop again to get the data out of the cache...
673 }
674 }
675 }
676
677 return dst_len - bytes_left;
678}
679
Chris Lattner24943d22010-06-08 16:52:24 +0000680Process*
681Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
682{
683 ProcessCreateInstance create_callback = NULL;
684 if (plugin_name)
685 {
686 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
687 if (create_callback)
688 {
689 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
690 if (debugger_ap->CanDebug(target))
691 return debugger_ap.release();
692 }
693 }
694 else
695 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000696 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner24943d22010-06-08 16:52:24 +0000697 {
Greg Clayton54e7afa2010-07-09 20:39:50 +0000698 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
699 if (debugger_ap->CanDebug(target))
700 return debugger_ap.release();
Chris Lattner24943d22010-06-08 16:52:24 +0000701 }
702 }
703 return NULL;
704}
705
706
707//----------------------------------------------------------------------
708// Process constructor
709//----------------------------------------------------------------------
710Process::Process(Target &target, Listener &listener) :
711 UserID (LLDB_INVALID_PROCESS_ID),
Greg Clayton49ce6822010-10-31 03:01:06 +0000712 Broadcaster ("lldb.process"),
Greg Claytonc0c1b0c2010-11-19 03:46:01 +0000713 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner24943d22010-06-08 16:52:24 +0000714 m_target (target),
Chris Lattner24943d22010-06-08 16:52:24 +0000715 m_public_state (eStateUnloaded),
716 m_private_state (eStateUnloaded),
717 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
718 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
719 m_private_state_listener ("lldb.process.internal_state_listener"),
720 m_private_state_control_wait(),
721 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
722 m_stop_id (0),
723 m_thread_index_id (0),
724 m_exit_status (-1),
725 m_exit_string (),
726 m_thread_list (this),
727 m_notifications (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000728 m_image_tokens (),
729 m_listener (listener),
730 m_breakpoint_site_list (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000731 m_dynamic_checkers_ap (),
Caroline Tice861efb32010-11-16 05:07:41 +0000732 m_unix_signals (),
Greg Clayton20d338f2010-11-18 05:57:03 +0000733 m_abi_sp (),
Caroline Tice861efb32010-11-16 05:07:41 +0000734 m_process_input_reader (),
Greg Claytona875b642011-01-09 21:07:35 +0000735 m_stdio_communication ("process.stdio"),
Greg Clayton20d338f2010-11-18 05:57:03 +0000736 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Claytonfd119992011-01-07 06:08:19 +0000737 m_stdout_data (),
Jim Inghamc2dc7c82011-01-29 01:49:25 +0000738 m_memory_cache (),
Greg Clayton7e2f91c2011-01-29 07:10:55 +0000739 m_next_event_action_ap()
Chris Lattner24943d22010-06-08 16:52:24 +0000740{
Caroline Tice1ebef442010-09-27 00:30:10 +0000741 UpdateInstanceName();
742
Greg Claytone005f2c2010-11-06 01:53:30 +0000743 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000744 if (log)
745 log->Printf ("%p Process::Process()", this);
746
Greg Clayton49ce6822010-10-31 03:01:06 +0000747 SetEventName (eBroadcastBitStateChanged, "state-changed");
748 SetEventName (eBroadcastBitInterrupt, "interrupt");
749 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
750 SetEventName (eBroadcastBitSTDERR, "stderr-available");
751
Chris Lattner24943d22010-06-08 16:52:24 +0000752 listener.StartListeningForEvents (this,
753 eBroadcastBitStateChanged |
754 eBroadcastBitInterrupt |
755 eBroadcastBitSTDOUT |
756 eBroadcastBitSTDERR);
757
758 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
759 eBroadcastBitStateChanged);
760
761 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
762 eBroadcastInternalStateControlStop |
763 eBroadcastInternalStateControlPause |
764 eBroadcastInternalStateControlResume);
765}
766
767//----------------------------------------------------------------------
768// Destructor
769//----------------------------------------------------------------------
770Process::~Process()
771{
Greg Claytone005f2c2010-11-06 01:53:30 +0000772 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner24943d22010-06-08 16:52:24 +0000773 if (log)
774 log->Printf ("%p Process::~Process()", this);
775 StopPrivateStateThread();
776}
777
778void
779Process::Finalize()
780{
781 // Do any cleanup needed prior to being destructed... Subclasses
782 // that override this method should call this superclass method as well.
Jim Ingham88fa7bd2011-02-16 17:54:55 +0000783
784 // We need to destroy the loader before the derived Process class gets destroyed
785 // since it is very likely that undoing the loader will require access to the real process.
786 if (m_dyld_ap.get() != NULL)
787 m_dyld_ap.reset();
Chris Lattner24943d22010-06-08 16:52:24 +0000788}
789
790void
791Process::RegisterNotificationCallbacks (const Notifications& callbacks)
792{
793 m_notifications.push_back(callbacks);
794 if (callbacks.initialize != NULL)
795 callbacks.initialize (callbacks.baton, this);
796}
797
798bool
799Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
800{
801 std::vector<Notifications>::iterator pos, end = m_notifications.end();
802 for (pos = m_notifications.begin(); pos != end; ++pos)
803 {
804 if (pos->baton == callbacks.baton &&
805 pos->initialize == callbacks.initialize &&
806 pos->process_state_changed == callbacks.process_state_changed)
807 {
808 m_notifications.erase(pos);
809 return true;
810 }
811 }
812 return false;
813}
814
815void
816Process::SynchronouslyNotifyStateChanged (StateType state)
817{
818 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
819 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
820 {
821 if (notification_pos->process_state_changed)
822 notification_pos->process_state_changed (notification_pos->baton, this, state);
823 }
824}
825
826// FIXME: We need to do some work on events before the general Listener sees them.
827// For instance if we are continuing from a breakpoint, we need to ensure that we do
828// the little "insert real insn, step & stop" trick. But we can't do that when the
829// event is delivered by the broadcaster - since that is done on the thread that is
830// waiting for new events, so if we needed more than one event for our handling, we would
831// stall. So instead we do it when we fetch the event off of the queue.
832//
833
834StateType
835Process::GetNextEvent (EventSP &event_sp)
836{
837 StateType state = eStateInvalid;
838
839 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
840 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
841
842 return state;
843}
844
845
846StateType
847Process::WaitForProcessToStop (const TimeValue *timeout)
848{
849 StateType match_states[] = { eStateStopped, eStateCrashed, eStateDetached, eStateExited, eStateUnloaded };
850 return WaitForState (timeout, match_states, sizeof(match_states) / sizeof(StateType));
851}
852
853
854StateType
855Process::WaitForState
856(
857 const TimeValue *timeout,
858 const StateType *match_states, const uint32_t num_match_states
859)
860{
861 EventSP event_sp;
862 uint32_t i;
Greg Claytond8c62532010-10-07 04:19:01 +0000863 StateType state = GetState();
Chris Lattner24943d22010-06-08 16:52:24 +0000864 while (state != eStateInvalid)
865 {
Greg Claytond8c62532010-10-07 04:19:01 +0000866 // If we are exited or detached, we won't ever get back to any
867 // other valid state...
868 if (state == eStateDetached || state == eStateExited)
869 return state;
870
Chris Lattner24943d22010-06-08 16:52:24 +0000871 state = WaitForStateChangedEvents (timeout, event_sp);
872
873 for (i=0; i<num_match_states; ++i)
874 {
875 if (match_states[i] == state)
876 return state;
877 }
878 }
879 return state;
880}
881
Jim Ingham63e24d72010-10-11 23:53:14 +0000882bool
883Process::HijackProcessEvents (Listener *listener)
884{
885 if (listener != NULL)
886 {
887 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
888 }
889 else
890 return false;
891}
892
893void
894Process::RestoreProcessEvents ()
895{
896 RestoreBroadcaster();
897}
898
Jim Inghamf9f40c22011-02-08 05:20:59 +0000899bool
900Process::HijackPrivateProcessEvents (Listener *listener)
901{
902 if (listener != NULL)
903 {
904 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
905 }
906 else
907 return false;
908}
909
910void
911Process::RestorePrivateProcessEvents ()
912{
913 m_private_state_broadcaster.RestoreBroadcaster();
914}
915
Chris Lattner24943d22010-06-08 16:52:24 +0000916StateType
917Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
918{
Greg Claytone005f2c2010-11-06 01:53:30 +0000919 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000920
921 if (log)
922 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
923
924 StateType state = eStateInvalid;
Greg Clayton36f63a92010-10-19 03:25:40 +0000925 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
926 this,
927 eBroadcastBitStateChanged,
928 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000929 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
930
931 if (log)
932 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
933 __FUNCTION__,
934 timeout,
935 StateAsCString(state));
936 return state;
937}
938
939Event *
940Process::PeekAtStateChangedEvents ()
941{
Greg Claytone005f2c2010-11-06 01:53:30 +0000942 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000943
944 if (log)
945 log->Printf ("Process::%s...", __FUNCTION__);
946
947 Event *event_ptr;
Greg Clayton36f63a92010-10-19 03:25:40 +0000948 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
949 eBroadcastBitStateChanged);
Chris Lattner24943d22010-06-08 16:52:24 +0000950 if (log)
951 {
952 if (event_ptr)
953 {
954 log->Printf ("Process::%s (event_ptr) => %s",
955 __FUNCTION__,
956 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
957 }
958 else
959 {
960 log->Printf ("Process::%s no events found",
961 __FUNCTION__);
962 }
963 }
964 return event_ptr;
965}
966
967StateType
968Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
969{
Greg Claytone005f2c2010-11-06 01:53:30 +0000970 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000971
972 if (log)
973 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
974
975 StateType state = eStateInvalid;
Greg Clayton72e1c782011-01-22 23:43:18 +0000976 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
977 &m_private_state_broadcaster,
978 eBroadcastBitStateChanged,
979 event_sp))
Chris Lattner24943d22010-06-08 16:52:24 +0000980 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
981
982 // This is a bit of a hack, but when we wait here we could very well return
983 // to the command-line, and that could disable the log, which would render the
984 // log we got above invalid.
Chris Lattner24943d22010-06-08 16:52:24 +0000985 if (log)
Greg Clayton72e1c782011-01-22 23:43:18 +0000986 {
987 if (state == eStateInvalid)
988 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
989 else
990 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
991 }
Chris Lattner24943d22010-06-08 16:52:24 +0000992 return state;
993}
994
995bool
996Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
997{
Greg Claytone005f2c2010-11-06 01:53:30 +0000998 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +0000999
1000 if (log)
1001 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
1002
1003 if (control_only)
1004 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
1005 else
1006 return m_private_state_listener.WaitForEvent(timeout, event_sp);
1007}
1008
1009bool
1010Process::IsRunning () const
1011{
1012 return StateIsRunningState (m_public_state.GetValue());
1013}
1014
1015int
1016Process::GetExitStatus ()
1017{
1018 if (m_public_state.GetValue() == eStateExited)
1019 return m_exit_status;
1020 return -1;
1021}
1022
Greg Clayton638351a2010-12-04 00:10:17 +00001023
1024void
1025Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
1026{
1027 if (m_inherit_host_env && !m_got_host_env)
1028 {
1029 m_got_host_env = true;
1030 StringList host_env;
1031 const size_t host_env_count = Host::GetEnvironment (host_env);
1032 for (size_t idx=0; idx<host_env_count; idx++)
1033 {
1034 const char *env_entry = host_env.GetStringAtIndex (idx);
1035 if (env_entry)
1036 {
Greg Clayton1f3dd642010-12-15 20:52:40 +00001037 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton638351a2010-12-04 00:10:17 +00001038 if (equal_pos)
1039 {
1040 std::string key (env_entry, equal_pos - env_entry);
1041 std::string value (equal_pos + 1);
1042 if (m_env_vars.find (key) == m_env_vars.end())
1043 m_env_vars[key] = value;
1044 }
1045 }
1046 }
1047 }
1048}
1049
1050
1051size_t
1052Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
1053{
1054 GetHostEnvironmentIfNeeded ();
1055
1056 dictionary::const_iterator pos, end = m_env_vars.end();
1057 for (pos = m_env_vars.begin(); pos != end; ++pos)
1058 {
1059 std::string env_var_equal_value (pos->first);
1060 env_var_equal_value.append(1, '=');
1061 env_var_equal_value.append (pos->second);
1062 env.AppendArgument (env_var_equal_value.c_str());
1063 }
1064 return env.GetArgumentCount();
1065}
1066
1067
Chris Lattner24943d22010-06-08 16:52:24 +00001068const char *
1069Process::GetExitDescription ()
1070{
1071 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1072 return m_exit_string.c_str();
1073 return NULL;
1074}
1075
Greg Clayton72e1c782011-01-22 23:43:18 +00001076bool
Chris Lattner24943d22010-06-08 16:52:24 +00001077Process::SetExitStatus (int status, const char *cstr)
1078{
Greg Clayton68ca8232011-01-25 02:58:48 +00001079 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
1080 if (log)
1081 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1082 status, status,
1083 cstr ? "\"" : "",
1084 cstr ? cstr : "NULL",
1085 cstr ? "\"" : "");
1086
Greg Clayton72e1c782011-01-22 23:43:18 +00001087 // We were already in the exited state
1088 if (m_private_state.GetValue() == eStateExited)
Greg Clayton68ca8232011-01-25 02:58:48 +00001089 {
Greg Clayton644ddfb2011-01-26 23:47:29 +00001090 if (log)
1091 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton72e1c782011-01-22 23:43:18 +00001092 return false;
Greg Clayton68ca8232011-01-25 02:58:48 +00001093 }
Greg Clayton72e1c782011-01-22 23:43:18 +00001094
1095 m_exit_status = status;
1096 if (cstr)
1097 m_exit_string = cstr;
1098 else
1099 m_exit_string.clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001100
Greg Clayton72e1c782011-01-22 23:43:18 +00001101 DidExit ();
Greg Clayton58e844b2010-12-08 05:08:21 +00001102
Greg Clayton72e1c782011-01-22 23:43:18 +00001103 SetPrivateState (eStateExited);
1104 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001105}
1106
1107// This static callback can be used to watch for local child processes on
1108// the current host. The the child process exits, the process will be
1109// found in the global target list (we want to be completely sure that the
1110// lldb_private::Process doesn't go away before we can deliver the signal.
1111bool
1112Process::SetProcessExitStatus
1113(
1114 void *callback_baton,
1115 lldb::pid_t pid,
1116 int signo, // Zero for no signal
1117 int exit_status // Exit value of process if signal is zero
1118)
1119{
1120 if (signo == 0 || exit_status)
1121 {
Greg Clayton63094e02010-06-23 01:19:29 +00001122 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner24943d22010-06-08 16:52:24 +00001123 if (target_sp)
1124 {
1125 ProcessSP process_sp (target_sp->GetProcessSP());
1126 if (process_sp)
1127 {
1128 const char *signal_cstr = NULL;
1129 if (signo)
1130 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1131
1132 process_sp->SetExitStatus (exit_status, signal_cstr);
1133 }
1134 }
1135 return true;
1136 }
1137 return false;
1138}
1139
1140
1141uint32_t
1142Process::GetNextThreadIndexID ()
1143{
1144 return ++m_thread_index_id;
1145}
1146
1147StateType
1148Process::GetState()
1149{
1150 // If any other threads access this we will need a mutex for it
1151 return m_public_state.GetValue ();
1152}
1153
1154void
1155Process::SetPublicState (StateType new_state)
1156{
Greg Clayton68ca8232011-01-25 02:58:48 +00001157 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001158 if (log)
1159 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1160 m_public_state.SetValue (new_state);
1161}
1162
1163StateType
1164Process::GetPrivateState ()
1165{
1166 return m_private_state.GetValue();
1167}
1168
1169void
1170Process::SetPrivateState (StateType new_state)
1171{
Greg Clayton68ca8232011-01-25 02:58:48 +00001172 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00001173 bool state_changed = false;
1174
1175 if (log)
1176 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1177
1178 Mutex::Locker locker(m_private_state.GetMutex());
1179
1180 const StateType old_state = m_private_state.GetValueNoLock ();
1181 state_changed = old_state != new_state;
1182 if (state_changed)
1183 {
1184 m_private_state.SetValueNoLock (new_state);
1185 if (StateIsStoppedState(new_state))
1186 {
1187 m_stop_id++;
Greg Claytonfd119992011-01-07 06:08:19 +00001188 m_memory_cache.Clear();
Chris Lattner24943d22010-06-08 16:52:24 +00001189 if (log)
1190 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_stop_id);
1191 }
1192 // Use our target to get a shared pointer to ourselves...
1193 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1194 }
1195 else
1196 {
1197 if (log)
1198 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
1199 }
1200}
1201
1202
1203uint32_t
1204Process::GetStopID() const
1205{
1206 return m_stop_id;
1207}
1208
1209addr_t
1210Process::GetImageInfoAddress()
1211{
1212 return LLDB_INVALID_ADDRESS;
1213}
1214
Greg Clayton0baa3942010-11-04 01:54:29 +00001215//----------------------------------------------------------------------
1216// LoadImage
1217//
1218// This function provides a default implementation that works for most
1219// unix variants. Any Process subclasses that need to do shared library
1220// loading differently should override LoadImage and UnloadImage and
1221// do what is needed.
1222//----------------------------------------------------------------------
1223uint32_t
1224Process::LoadImage (const FileSpec &image_spec, Error &error)
1225{
1226 DynamicLoader *loader = GetDynamicLoader();
1227 if (loader)
1228 {
1229 error = loader->CanLoadImage();
1230 if (error.Fail())
1231 return LLDB_INVALID_IMAGE_TOKEN;
1232 }
1233
1234 if (error.Success())
1235 {
1236 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1237 if (thread_sp == NULL)
1238 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
1239
1240 if (thread_sp)
1241 {
1242 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1243
1244 if (frame_sp)
1245 {
1246 ExecutionContext exe_ctx;
1247 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001248 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001249 StreamString expr;
1250 char path[PATH_MAX];
1251 image_spec.GetPath(path, sizeof(path));
1252 expr.Printf("dlopen (\"%s\", 2)", path);
1253 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001254 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan696cf5f2011-05-07 01:06:41 +00001255 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +00001256 if (result_valobj_sp->GetError().Success())
1257 {
1258 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001259 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001260 {
1261 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1262 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1263 {
1264 uint32_t image_token = m_image_tokens.size();
1265 m_image_tokens.push_back (image_ptr);
1266 return image_token;
1267 }
1268 }
1269 }
1270 }
1271 }
1272 }
1273 return LLDB_INVALID_IMAGE_TOKEN;
1274}
1275
1276//----------------------------------------------------------------------
1277// UnloadImage
1278//
1279// This function provides a default implementation that works for most
1280// unix variants. Any Process subclasses that need to do shared library
1281// loading differently should override LoadImage and UnloadImage and
1282// do what is needed.
1283//----------------------------------------------------------------------
1284Error
1285Process::UnloadImage (uint32_t image_token)
1286{
1287 Error error;
1288 if (image_token < m_image_tokens.size())
1289 {
1290 const addr_t image_addr = m_image_tokens[image_token];
1291 if (image_addr == LLDB_INVALID_ADDRESS)
1292 {
1293 error.SetErrorString("image already unloaded");
1294 }
1295 else
1296 {
1297 DynamicLoader *loader = GetDynamicLoader();
1298 if (loader)
1299 error = loader->CanLoadImage();
1300
1301 if (error.Success())
1302 {
1303 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
1304 if (thread_sp == NULL)
1305 thread_sp = GetThreadList ().GetThreadAtIndex(0, true);
1306
1307 if (thread_sp)
1308 {
1309 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1310
1311 if (frame_sp)
1312 {
1313 ExecutionContext exe_ctx;
1314 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Inghamea9d4262010-11-05 19:25:48 +00001315 bool unwind_on_error = true;
Greg Clayton0baa3942010-11-04 01:54:29 +00001316 StreamString expr;
1317 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1318 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Ingham360f53f2010-11-30 02:22:11 +00001319 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan696cf5f2011-05-07 01:06:41 +00001320 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton0baa3942010-11-04 01:54:29 +00001321 if (result_valobj_sp->GetError().Success())
1322 {
1323 Scalar scalar;
Jim Inghamfa3a16a2011-03-31 00:19:25 +00001324 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton0baa3942010-11-04 01:54:29 +00001325 {
1326 if (scalar.UInt(1))
1327 {
1328 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1329 }
1330 else
1331 {
1332 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1333 }
1334 }
1335 }
1336 else
1337 {
1338 error = result_valobj_sp->GetError();
1339 }
1340 }
1341 }
1342 }
1343 }
1344 }
1345 else
1346 {
1347 error.SetErrorString("invalid image token");
1348 }
1349 return error;
1350}
1351
Greg Clayton75906e42011-05-11 18:39:18 +00001352const lldb::ABISP &
Chris Lattner24943d22010-06-08 16:52:24 +00001353Process::GetABI()
1354{
Greg Clayton75906e42011-05-11 18:39:18 +00001355 if (!m_abi_sp)
1356 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1357 return m_abi_sp;
Chris Lattner24943d22010-06-08 16:52:24 +00001358}
1359
Jim Ingham642036f2010-09-23 02:01:19 +00001360LanguageRuntime *
1361Process::GetLanguageRuntime(lldb::LanguageType language)
1362{
1363 LanguageRuntimeCollection::iterator pos;
1364 pos = m_language_runtimes.find (language);
1365 if (pos == m_language_runtimes.end())
1366 {
1367 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1368
1369 m_language_runtimes[language]
1370 = runtime;
1371 return runtime.get();
1372 }
1373 else
1374 return (*pos).second.get();
1375}
1376
1377CPPLanguageRuntime *
1378Process::GetCPPLanguageRuntime ()
1379{
1380 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1381 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1382 return static_cast<CPPLanguageRuntime *> (runtime);
1383 return NULL;
1384}
1385
1386ObjCLanguageRuntime *
1387Process::GetObjCLanguageRuntime ()
1388{
1389 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1390 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1391 return static_cast<ObjCLanguageRuntime *> (runtime);
1392 return NULL;
1393}
1394
Chris Lattner24943d22010-06-08 16:52:24 +00001395BreakpointSiteList &
1396Process::GetBreakpointSiteList()
1397{
1398 return m_breakpoint_site_list;
1399}
1400
1401const BreakpointSiteList &
1402Process::GetBreakpointSiteList() const
1403{
1404 return m_breakpoint_site_list;
1405}
1406
1407
1408void
1409Process::DisableAllBreakpointSites ()
1410{
1411 m_breakpoint_site_list.SetEnabledForAll (false);
1412}
1413
1414Error
1415Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1416{
1417 Error error (DisableBreakpointSiteByID (break_id));
1418
1419 if (error.Success())
1420 m_breakpoint_site_list.Remove(break_id);
1421
1422 return error;
1423}
1424
1425Error
1426Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1427{
1428 Error error;
1429 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1430 if (bp_site_sp)
1431 {
1432 if (bp_site_sp->IsEnabled())
1433 error = DisableBreakpoint (bp_site_sp.get());
1434 }
1435 else
1436 {
1437 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1438 }
1439
1440 return error;
1441}
1442
1443Error
1444Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1445{
1446 Error error;
1447 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1448 if (bp_site_sp)
1449 {
1450 if (!bp_site_sp->IsEnabled())
1451 error = EnableBreakpoint (bp_site_sp.get());
1452 }
1453 else
1454 {
1455 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1456 }
1457 return error;
1458}
1459
Stephen Wilson3fd1f362010-07-17 00:56:13 +00001460lldb::break_id_t
Chris Lattner24943d22010-06-08 16:52:24 +00001461Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1462{
Greg Claytoneea26402010-09-14 23:36:40 +00001463 const addr_t load_addr = owner->GetAddress().GetLoadAddress (&m_target);
Chris Lattner24943d22010-06-08 16:52:24 +00001464 if (load_addr != LLDB_INVALID_ADDRESS)
1465 {
1466 BreakpointSiteSP bp_site_sp;
1467
1468 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1469 // create a new breakpoint site and add it.
1470
1471 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1472
1473 if (bp_site_sp)
1474 {
1475 bp_site_sp->AddOwner (owner);
1476 owner->SetBreakpointSite (bp_site_sp);
1477 return bp_site_sp->GetID();
1478 }
1479 else
1480 {
1481 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1482 if (bp_site_sp)
1483 {
1484 if (EnableBreakpoint (bp_site_sp.get()).Success())
1485 {
1486 owner->SetBreakpointSite (bp_site_sp);
1487 return m_breakpoint_site_list.Add (bp_site_sp);
1488 }
1489 }
1490 }
1491 }
1492 // We failed to enable the breakpoint
1493 return LLDB_INVALID_BREAK_ID;
1494
1495}
1496
1497void
1498Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1499{
1500 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1501 if (num_owners == 0)
1502 {
1503 DisableBreakpoint(bp_site_sp.get());
1504 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1505 }
1506}
1507
1508
1509size_t
1510Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1511{
1512 size_t bytes_removed = 0;
1513 addr_t intersect_addr;
1514 size_t intersect_size;
1515 size_t opcode_offset;
1516 size_t idx;
1517 BreakpointSiteSP bp;
1518
1519 for (idx = 0; (bp = m_breakpoint_site_list.GetByIndex(idx)) != NULL; ++idx)
1520 {
1521 if (bp->GetType() == BreakpointSite::eSoftware)
1522 {
1523 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1524 {
1525 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1526 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1527 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1528 size_t buf_offset = intersect_addr - bp_addr;
1529 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1530 }
1531 }
1532 }
1533 return bytes_removed;
1534}
1535
1536
Greg Claytonb1888f22011-03-19 01:12:21 +00001537
1538size_t
1539Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1540{
1541 PlatformSP platform_sp (m_target.GetPlatform());
1542 if (platform_sp)
1543 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1544 return 0;
1545}
1546
Chris Lattner24943d22010-06-08 16:52:24 +00001547Error
1548Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1549{
1550 Error error;
1551 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001552 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001553 const addr_t bp_addr = bp_site->GetLoadAddress();
1554 if (log)
1555 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1556 if (bp_site->IsEnabled())
1557 {
1558 if (log)
1559 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1560 return error;
1561 }
1562
1563 if (bp_addr == LLDB_INVALID_ADDRESS)
1564 {
1565 error.SetErrorString("BreakpointSite contains an invalid load address.");
1566 return error;
1567 }
1568 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1569 // trap for the breakpoint site
1570 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1571
1572 if (bp_opcode_size == 0)
1573 {
1574 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1575 }
1576 else
1577 {
1578 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1579
1580 if (bp_opcode_bytes == NULL)
1581 {
1582 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1583 return error;
1584 }
1585
1586 // Save the original opcode by reading it
1587 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1588 {
1589 // Write a software breakpoint in place of the original opcode
1590 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1591 {
1592 uint8_t verify_bp_opcode_bytes[64];
1593 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1594 {
1595 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1596 {
1597 bp_site->SetEnabled(true);
1598 bp_site->SetType (BreakpointSite::eSoftware);
1599 if (log)
1600 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1601 bp_site->GetID(),
1602 (uint64_t)bp_addr);
1603 }
1604 else
1605 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1606 }
1607 else
1608 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1609 }
1610 else
1611 error.SetErrorString("Unable to write breakpoint trap to memory.");
1612 }
1613 else
1614 error.SetErrorString("Unable to read memory at breakpoint address.");
1615 }
Stephen Wilsonc2b98252011-01-12 04:20:03 +00001616 if (log && error.Fail())
Chris Lattner24943d22010-06-08 16:52:24 +00001617 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1618 bp_site->GetID(),
1619 (uint64_t)bp_addr,
1620 error.AsCString());
1621 return error;
1622}
1623
1624Error
1625Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1626{
1627 Error error;
1628 assert (bp_site != NULL);
Greg Claytone005f2c2010-11-06 01:53:30 +00001629 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner24943d22010-06-08 16:52:24 +00001630 addr_t bp_addr = bp_site->GetLoadAddress();
1631 lldb::user_id_t breakID = bp_site->GetID();
1632 if (log)
Stephen Wilson9ff73ed2011-01-14 21:07:07 +00001633 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner24943d22010-06-08 16:52:24 +00001634
1635 if (bp_site->IsHardware())
1636 {
1637 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1638 }
1639 else if (bp_site->IsEnabled())
1640 {
1641 const size_t break_op_size = bp_site->GetByteSize();
1642 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1643 if (break_op_size > 0)
1644 {
1645 // Clear a software breakoint instruction
Greg Clayton54e7afa2010-07-09 20:39:50 +00001646 uint8_t curr_break_op[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001647 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner24943d22010-06-08 16:52:24 +00001648 bool break_op_found = false;
1649
1650 // Read the breakpoint opcode
1651 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1652 {
1653 bool verify = false;
1654 // Make sure we have the a breakpoint opcode exists at this address
1655 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1656 {
1657 break_op_found = true;
1658 // We found a valid breakpoint opcode at this address, now restore
1659 // the saved opcode.
1660 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1661 {
1662 verify = true;
1663 }
1664 else
1665 error.SetErrorString("Memory write failed when restoring original opcode.");
1666 }
1667 else
1668 {
1669 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1670 // Set verify to true and so we can check if the original opcode has already been restored
1671 verify = true;
1672 }
1673
1674 if (verify)
1675 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001676 uint8_t verify_opcode[8];
Stephen Wilson141eeac2010-07-20 18:41:11 +00001677 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner24943d22010-06-08 16:52:24 +00001678 // Verify that our original opcode made it back to the inferior
1679 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1680 {
1681 // compare the memory we just read with the original opcode
1682 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1683 {
1684 // SUCCESS
1685 bp_site->SetEnabled(false);
1686 if (log)
1687 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1688 return error;
1689 }
1690 else
1691 {
1692 if (break_op_found)
1693 error.SetErrorString("Failed to restore original opcode.");
1694 }
1695 }
1696 else
1697 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1698 }
1699 }
1700 else
1701 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1702 }
1703 }
1704 else
1705 {
1706 if (log)
1707 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1708 return error;
1709 }
1710
1711 if (log)
1712 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1713 bp_site->GetID(),
1714 (uint64_t)bp_addr,
1715 error.AsCString());
1716 return error;
1717
1718}
1719
Greg Claytonfd119992011-01-07 06:08:19 +00001720// Comment out line below to disable memory caching
1721#define ENABLE_MEMORY_CACHING
1722// Uncomment to verify memory caching works after making changes to caching code
1723//#define VERIFY_MEMORY_READS
1724
1725#if defined (ENABLE_MEMORY_CACHING)
1726
1727#if defined (VERIFY_MEMORY_READS)
Chris Lattner24943d22010-06-08 16:52:24 +00001728
1729size_t
1730Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1731{
Greg Claytonfd119992011-01-07 06:08:19 +00001732 // Memory caching is enabled, with debug verification
1733 if (buf && size)
1734 {
1735 // Uncomment the line below to make sure memory caching is working.
1736 // I ran this through the test suite and got no assertions, so I am
1737 // pretty confident this is working well. If any changes are made to
1738 // memory caching, uncomment the line below and test your changes!
1739
1740 // Verify all memory reads by using the cache first, then redundantly
1741 // reading the same memory from the inferior and comparing to make sure
1742 // everything is exactly the same.
1743 std::string verify_buf (size, '\0');
1744 assert (verify_buf.size() == size);
1745 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1746 Error verify_error;
1747 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1748 assert (cache_bytes_read == verify_bytes_read);
1749 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1750 assert (verify_error.Success() == error.Success());
1751 return cache_bytes_read;
1752 }
1753 return 0;
1754}
1755
1756#else // #if defined (VERIFY_MEMORY_READS)
1757
1758size_t
1759Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1760{
1761 // Memory caching enabled, no verification
1762 return m_memory_cache.Read (this, addr, buf, size, error);
1763}
1764
1765#endif // #else for #if defined (VERIFY_MEMORY_READS)
1766
1767#else // #if defined (ENABLE_MEMORY_CACHING)
1768
1769size_t
1770Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1771{
1772 // Memory caching is disabled
1773 return ReadMemoryFromInferior (addr, buf, size, error);
1774}
1775
1776#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1777
1778
1779size_t
Greg Claytonb72d0f02011-04-12 05:54:46 +00001780Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1781{
1782 size_t total_cstr_len = 0;
1783 if (dst && dst_max_len)
1784 {
1785 // NULL out everything just to be safe
1786 memset (dst, 0, dst_max_len);
1787 Error error;
1788 addr_t curr_addr = addr;
1789 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1790 size_t bytes_left = dst_max_len - 1;
1791 char *curr_dst = dst;
1792
1793 while (bytes_left > 0)
1794 {
1795 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1796 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1797 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1798
1799 if (bytes_read == 0)
1800 {
1801 dst[total_cstr_len] = '\0';
1802 break;
1803 }
1804 const size_t len = strlen(curr_dst);
1805
1806 total_cstr_len += len;
1807
1808 if (len < bytes_to_read)
1809 break;
1810
1811 curr_dst += bytes_read;
1812 curr_addr += bytes_read;
1813 bytes_left -= bytes_read;
1814 }
1815 }
1816 return total_cstr_len;
1817}
1818
1819size_t
Greg Claytonfd119992011-01-07 06:08:19 +00001820Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1821{
Chris Lattner24943d22010-06-08 16:52:24 +00001822 if (buf == NULL || size == 0)
1823 return 0;
1824
1825 size_t bytes_read = 0;
1826 uint8_t *bytes = (uint8_t *)buf;
1827
1828 while (bytes_read < size)
1829 {
1830 const size_t curr_size = size - bytes_read;
1831 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1832 bytes + bytes_read,
1833 curr_size,
1834 error);
1835 bytes_read += curr_bytes_read;
1836 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1837 break;
1838 }
1839
1840 // Replace any software breakpoint opcodes that fall into this range back
1841 // into "buf" before we return
1842 if (bytes_read > 0)
1843 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1844 return bytes_read;
1845}
1846
Greg Claytonf72fdee2010-12-16 20:01:20 +00001847uint64_t
1848Process::ReadUnsignedInteger (lldb::addr_t vm_addr, size_t integer_byte_size, Error &error)
1849{
1850 if (integer_byte_size > sizeof(uint64_t))
1851 {
1852 error.SetErrorString ("unsupported integer size");
1853 }
1854 else
1855 {
1856 uint8_t tmp[sizeof(uint64_t)];
Greg Clayton395fc332011-02-15 21:59:32 +00001857 DataExtractor data (tmp,
1858 integer_byte_size,
1859 m_target.GetArchitecture().GetByteOrder(),
1860 m_target.GetArchitecture().GetAddressByteSize());
Greg Claytonf72fdee2010-12-16 20:01:20 +00001861 if (ReadMemory (vm_addr, tmp, integer_byte_size, error) == integer_byte_size)
1862 {
1863 uint32_t offset = 0;
1864 return data.GetMaxU64 (&offset, integer_byte_size);
1865 }
1866 }
1867 // Any plug-in that doesn't return success a memory read with the number
1868 // of bytes that were requested should be setting the error
1869 assert (error.Fail());
1870 return 0;
1871}
1872
Chris Lattner24943d22010-06-08 16:52:24 +00001873size_t
1874Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1875{
1876 size_t bytes_written = 0;
1877 const uint8_t *bytes = (const uint8_t *)buf;
1878
1879 while (bytes_written < size)
1880 {
1881 const size_t curr_size = size - bytes_written;
1882 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1883 bytes + bytes_written,
1884 curr_size,
1885 error);
1886 bytes_written += curr_bytes_written;
1887 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1888 break;
1889 }
1890 return bytes_written;
1891}
1892
1893size_t
1894Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1895{
Greg Claytonfd119992011-01-07 06:08:19 +00001896#if defined (ENABLE_MEMORY_CACHING)
1897 m_memory_cache.Flush (addr, size);
1898#endif
1899
Chris Lattner24943d22010-06-08 16:52:24 +00001900 if (buf == NULL || size == 0)
1901 return 0;
Jim Inghame41494a2011-04-16 00:01:13 +00001902
1903 // Need to bump the stop ID after writing so that ValueObjects will know to re-read themselves.
1904 // FUTURE: Doing this should be okay, but if anybody else gets upset about the stop_id changing when
1905 // the target hasn't run, then we will need to add a "memory generation" as well as a stop_id...
1906 m_stop_id++;
1907
Chris Lattner24943d22010-06-08 16:52:24 +00001908 // We need to write any data that would go where any current software traps
1909 // (enabled software breakpoints) any software traps (breakpoints) that we
1910 // may have placed in our tasks memory.
1911
1912 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1913 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1914
1915 if (iter == end || iter->second->GetLoadAddress() > addr + size)
1916 return DoWriteMemory(addr, buf, size, error);
1917
1918 BreakpointSiteList::collection::const_iterator pos;
1919 size_t bytes_written = 0;
Greg Clayton54e7afa2010-07-09 20:39:50 +00001920 addr_t intersect_addr = 0;
1921 size_t intersect_size = 0;
1922 size_t opcode_offset = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001923 const uint8_t *ubuf = (const uint8_t *)buf;
1924
1925 for (pos = iter; pos != end; ++pos)
1926 {
1927 BreakpointSiteSP bp;
1928 bp = pos->second;
1929
1930 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1931 assert(addr <= intersect_addr && intersect_addr < addr + size);
1932 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1933 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1934
1935 // Check for bytes before this breakpoint
1936 const addr_t curr_addr = addr + bytes_written;
1937 if (intersect_addr > curr_addr)
1938 {
1939 // There are some bytes before this breakpoint that we need to
1940 // just write to memory
1941 size_t curr_size = intersect_addr - curr_addr;
1942 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1943 ubuf + bytes_written,
1944 curr_size,
1945 error);
1946 bytes_written += curr_bytes_written;
1947 if (curr_bytes_written != curr_size)
1948 {
1949 // We weren't able to write all of the requested bytes, we
1950 // are done looping and will return the number of bytes that
1951 // we have written so far.
1952 break;
1953 }
1954 }
1955
1956 // Now write any bytes that would cover up any software breakpoints
1957 // directly into the breakpoint opcode buffer
1958 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1959 bytes_written += intersect_size;
1960 }
1961
1962 // Write any remaining bytes after the last breakpoint if we have any left
1963 if (bytes_written < size)
1964 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1965 ubuf + bytes_written,
1966 size - bytes_written,
1967 error);
Jim Inghame41494a2011-04-16 00:01:13 +00001968
Chris Lattner24943d22010-06-08 16:52:24 +00001969 return bytes_written;
1970}
1971
1972addr_t
1973Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1974{
1975 // Fixme: we should track the blocks we've allocated, and clean them up...
1976 // We could even do our own allocator here if that ends up being more efficient.
Greg Clayton2860ba92011-01-23 19:58:49 +00001977 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1978 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1979 if (log)
Greg Claytonb349adc2011-01-24 06:30:45 +00001980 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%c%c%c) => 0x%16.16llx (m_stop_id = %u)",
Greg Clayton2860ba92011-01-23 19:58:49 +00001981 size,
1982 permissions & ePermissionsReadable ? 'r' : '-',
1983 permissions & ePermissionsWritable ? 'w' : '-',
1984 permissions & ePermissionsExecutable ? 'x' : '-',
1985 (uint64_t)allocated_addr,
1986 m_stop_id);
1987 return allocated_addr;
Chris Lattner24943d22010-06-08 16:52:24 +00001988}
1989
1990Error
1991Process::DeallocateMemory (addr_t ptr)
1992{
Greg Clayton2860ba92011-01-23 19:58:49 +00001993 Error error(DoDeallocateMemory (ptr));
1994
1995 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1996 if (log)
1997 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u)",
1998 ptr,
1999 error.AsCString("SUCCESS"),
2000 m_stop_id);
2001 return error;
Chris Lattner24943d22010-06-08 16:52:24 +00002002}
2003
2004
2005Error
2006Process::EnableWatchpoint (WatchpointLocation *watchpoint)
2007{
2008 Error error;
2009 error.SetErrorString("watchpoints are not supported");
2010 return error;
2011}
2012
2013Error
2014Process::DisableWatchpoint (WatchpointLocation *watchpoint)
2015{
2016 Error error;
2017 error.SetErrorString("watchpoints are not supported");
2018 return error;
2019}
2020
2021StateType
2022Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2023{
2024 StateType state;
2025 // Now wait for the process to launch and return control to us, and then
2026 // call DidLaunch:
2027 while (1)
2028 {
Greg Clayton72e1c782011-01-22 23:43:18 +00002029 event_sp.reset();
2030 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2031
2032 if (StateIsStoppedState(state))
Chris Lattner24943d22010-06-08 16:52:24 +00002033 break;
Greg Clayton72e1c782011-01-22 23:43:18 +00002034
2035 // If state is invalid, then we timed out
2036 if (state == eStateInvalid)
2037 break;
2038
2039 if (event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002040 HandlePrivateEvent (event_sp);
2041 }
2042 return state;
2043}
2044
2045Error
2046Process::Launch
2047(
2048 char const *argv[],
2049 char const *envp[],
Greg Clayton452bf612010-08-31 18:35:14 +00002050 uint32_t launch_flags,
Chris Lattner24943d22010-06-08 16:52:24 +00002051 const char *stdin_path,
2052 const char *stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00002053 const char *stderr_path,
2054 const char *working_directory
Chris Lattner24943d22010-06-08 16:52:24 +00002055)
2056{
2057 Error error;
Chris Lattner24943d22010-06-08 16:52:24 +00002058 m_abi_sp.reset();
Greg Clayton75c703d2011-02-16 04:46:07 +00002059 m_dyld_ap.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002060 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002061
2062 Module *exe_module = m_target.GetExecutableModule().get();
2063 if (exe_module)
2064 {
Greg Clayton180546b2011-04-30 01:09:13 +00002065 char local_exec_file_path[PATH_MAX];
2066 char platform_exec_file_path[PATH_MAX];
2067 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2068 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner24943d22010-06-08 16:52:24 +00002069 if (exe_module->GetFileSpec().Exists())
2070 {
Greg Claytona2f74232011-02-24 22:24:29 +00002071 if (PrivateStateThreadIsValid ())
2072 PausePrivateStateThread ();
2073
Chris Lattner24943d22010-06-08 16:52:24 +00002074 error = WillLaunch (exe_module);
2075 if (error.Success())
2076 {
Greg Claytond8c62532010-10-07 04:19:01 +00002077 SetPublicState (eStateLaunching);
Chris Lattner24943d22010-06-08 16:52:24 +00002078 // The args coming in should not contain the application name, the
2079 // lldb_private::Process class will add this in case the executable
2080 // gets resolved to a different file than was given on the command
2081 // line (like when an applicaiton bundle is specified and will
2082 // resolve to the contained exectuable file, or the file given was
2083 // a symlink or other file system link that resolves to a different
2084 // file).
2085
2086 // Get the resolved exectuable path
2087
2088 // Make a new argument vector
2089 std::vector<const char *> exec_path_plus_argv;
2090 // Append the resolved executable path
Greg Clayton180546b2011-04-30 01:09:13 +00002091 exec_path_plus_argv.push_back (platform_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002092
2093 // Push all args if there are any
2094 if (argv)
2095 {
2096 for (int i = 0; argv[i]; ++i)
2097 exec_path_plus_argv.push_back(argv[i]);
2098 }
2099
2100 // Push a NULL to terminate the args.
2101 exec_path_plus_argv.push_back(NULL);
2102
2103 // Now launch using these arguments.
Greg Clayton53d68e72010-07-20 22:52:08 +00002104 error = DoLaunch (exe_module,
2105 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
2106 envp,
Greg Clayton452bf612010-08-31 18:35:14 +00002107 launch_flags,
Greg Clayton53d68e72010-07-20 22:52:08 +00002108 stdin_path,
2109 stdout_path,
Greg Claytonde915be2011-01-23 05:56:20 +00002110 stderr_path,
2111 working_directory);
Chris Lattner24943d22010-06-08 16:52:24 +00002112
2113 if (error.Fail())
2114 {
2115 if (GetID() != LLDB_INVALID_PROCESS_ID)
2116 {
2117 SetID (LLDB_INVALID_PROCESS_ID);
2118 const char *error_string = error.AsCString();
2119 if (error_string == NULL)
2120 error_string = "launch failed";
2121 SetExitStatus (-1, error_string);
2122 }
2123 }
2124 else
2125 {
2126 EventSP event_sp;
2127 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2128
2129 if (state == eStateStopped || state == eStateCrashed)
2130 {
Greg Clayton75c703d2011-02-16 04:46:07 +00002131
Chris Lattner24943d22010-06-08 16:52:24 +00002132 DidLaunch ();
2133
Greg Clayton4fdf7602011-03-20 04:57:14 +00002134 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002135 if (m_dyld_ap.get())
2136 m_dyld_ap->DidLaunch();
2137
Chris Lattner24943d22010-06-08 16:52:24 +00002138 // This delays passing the stopped event to listeners till DidLaunch gets
2139 // a chance to complete...
2140 HandlePrivateEvent (event_sp);
Greg Claytona2f74232011-02-24 22:24:29 +00002141
2142 if (PrivateStateThreadIsValid ())
2143 ResumePrivateStateThread ();
2144 else
2145 StartPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002146 }
2147 else if (state == eStateExited)
2148 {
2149 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2150 // not likely to work, and return an invalid pid.
2151 HandlePrivateEvent (event_sp);
2152 }
2153 }
2154 }
2155 }
2156 else
2157 {
Greg Clayton180546b2011-04-30 01:09:13 +00002158 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", local_exec_file_path);
Chris Lattner24943d22010-06-08 16:52:24 +00002159 }
2160 }
2161 return error;
2162}
2163
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002164Process::NextEventAction::EventActionResult
2165Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00002166{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002167 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2168 switch (state)
Greg Claytonc1d37752010-10-18 01:45:30 +00002169 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002170 case eStateRunning:
Greg Claytona2f74232011-02-24 22:24:29 +00002171 case eStateConnected:
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002172 return eEventActionRetry;
2173
2174 case eStateStopped:
2175 case eStateCrashed:
Jim Ingham7508e732010-08-09 23:31:02 +00002176 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002177 // During attach, prior to sending the eStateStopped event,
2178 // lldb_private::Process subclasses must set the process must set
2179 // the new process ID.
2180 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton75c703d2011-02-16 04:46:07 +00002181 m_process->CompleteAttach ();
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002182 return eEventActionSuccess;
Jim Ingham7508e732010-08-09 23:31:02 +00002183 }
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002184
2185
2186 break;
2187 default:
2188 case eStateExited:
2189 case eStateInvalid:
2190 m_exit_string.assign ("No valid Process");
2191 return eEventActionExit;
2192 break;
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002193 }
2194}
Chris Lattner24943d22010-06-08 16:52:24 +00002195
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002196Process::NextEventAction::EventActionResult
2197Process::AttachCompletionHandler::HandleBeingInterrupted()
2198{
2199 return eEventActionSuccess;
2200}
2201
2202const char *
2203Process::AttachCompletionHandler::GetExitString ()
2204{
2205 return m_exit_string.c_str();
Chris Lattner24943d22010-06-08 16:52:24 +00002206}
2207
2208Error
2209Process::Attach (lldb::pid_t attach_pid)
2210{
2211
Chris Lattner24943d22010-06-08 16:52:24 +00002212 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002213 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002214
Jim Ingham7508e732010-08-09 23:31:02 +00002215 // Find the process and its architecture. Make sure it matches the architecture
2216 // of the current Target, and if not adjust it.
2217
Greg Claytonb72d0f02011-04-12 05:54:46 +00002218 ProcessInstanceInfo process_info;
Greg Claytonb1888f22011-03-19 01:12:21 +00002219 PlatformSP platform_sp (m_target.GetDebugger().GetPlatformList().GetSelectedPlatform ());
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002220 if (platform_sp)
Jim Ingham7508e732010-08-09 23:31:02 +00002221 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002222 if (platform_sp->GetProcessInfo (attach_pid, process_info))
2223 {
2224 const ArchSpec &process_arch = process_info.GetArchitecture();
2225 if (process_arch.IsValid())
2226 GetTarget().SetArchitecture(process_arch);
2227 }
Jim Ingham7508e732010-08-09 23:31:02 +00002228 }
2229
Greg Clayton75c703d2011-02-16 04:46:07 +00002230 m_dyld_ap.reset();
2231
Greg Clayton54e7afa2010-07-09 20:39:50 +00002232 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner24943d22010-06-08 16:52:24 +00002233 if (error.Success())
2234 {
Greg Claytond8c62532010-10-07 04:19:01 +00002235 SetPublicState (eStateAttaching);
2236
Greg Clayton54e7afa2010-07-09 20:39:50 +00002237 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner24943d22010-06-08 16:52:24 +00002238 if (error.Success())
2239 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002240 SetNextEventAction(new Process::AttachCompletionHandler(this));
2241 StartPrivateStateThread();
Chris Lattner24943d22010-06-08 16:52:24 +00002242 }
2243 else
2244 {
2245 if (GetID() != LLDB_INVALID_PROCESS_ID)
2246 {
2247 SetID (LLDB_INVALID_PROCESS_ID);
2248 const char *error_string = error.AsCString();
2249 if (error_string == NULL)
2250 error_string = "attach failed";
2251
2252 SetExitStatus(-1, error_string);
2253 }
2254 }
2255 }
2256 return error;
2257}
2258
2259Error
2260Process::Attach (const char *process_name, bool wait_for_launch)
2261{
Chris Lattner24943d22010-06-08 16:52:24 +00002262 m_abi_sp.reset();
Caroline Tice861efb32010-11-16 05:07:41 +00002263 m_process_input_reader.reset();
Jim Ingham7508e732010-08-09 23:31:02 +00002264
2265 // Find the process and its architecture. Make sure it matches the architecture
2266 // of the current Target, and if not adjust it.
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002267 Error error;
Jim Ingham7508e732010-08-09 23:31:02 +00002268
Jim Inghamea294182010-08-17 21:54:19 +00002269 if (!wait_for_launch)
Jim Ingham7508e732010-08-09 23:31:02 +00002270 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002271 ProcessInstanceInfoList process_infos;
Greg Claytonb1888f22011-03-19 01:12:21 +00002272 PlatformSP platform_sp (m_target.GetDebugger().GetPlatformList().GetSelectedPlatform ());
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002273 if (platform_sp)
Jim Inghamea294182010-08-17 21:54:19 +00002274 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002275 ProcessInstanceInfoMatch match_info;
Greg Clayton24bc5d92011-03-30 18:16:51 +00002276 match_info.GetProcessInfo().SetName(process_name);
2277 match_info.SetNameMatchType (eNameMatchEquals);
2278 platform_sp->FindProcesses (match_info, process_infos);
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002279 if (process_infos.GetSize() > 1)
Chris Lattner24943d22010-06-08 16:52:24 +00002280 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002281 error.SetErrorStringWithFormat ("More than one process named %s\n", process_name);
2282 }
2283 else if (process_infos.GetSize() == 0)
2284 {
2285 error.SetErrorStringWithFormat ("Could not find a process named %s\n", process_name);
2286 }
2287 else
2288 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00002289 ProcessInstanceInfo process_info;
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002290 if (process_infos.GetInfoAtIndex (0, process_info))
2291 {
2292 const ArchSpec &process_arch = process_info.GetArchitecture();
2293 if (process_arch.IsValid() && process_arch != GetTarget().GetArchitecture())
2294 {
2295 // Set the architecture on the target.
2296 GetTarget().SetArchitecture (process_arch);
2297 }
2298 }
Chris Lattner24943d22010-06-08 16:52:24 +00002299 }
2300 }
2301 else
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002302 {
2303 error.SetErrorString ("Invalid platform");
2304 }
2305 }
2306
2307 if (error.Success())
2308 {
2309 m_dyld_ap.reset();
2310
2311 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2312 if (error.Success())
Chris Lattner24943d22010-06-08 16:52:24 +00002313 {
Greg Claytone4b9c1f2011-03-08 22:40:15 +00002314 SetPublicState (eStateAttaching);
2315 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2316 if (error.Fail())
2317 {
2318 if (GetID() != LLDB_INVALID_PROCESS_ID)
2319 {
2320 SetID (LLDB_INVALID_PROCESS_ID);
2321 const char *error_string = error.AsCString();
2322 if (error_string == NULL)
2323 error_string = "attach failed";
2324
2325 SetExitStatus(-1, error_string);
2326 }
2327 }
2328 else
2329 {
2330 SetNextEventAction(new Process::AttachCompletionHandler(this));
2331 StartPrivateStateThread();
2332 }
Chris Lattner24943d22010-06-08 16:52:24 +00002333 }
2334 }
2335 return error;
2336}
2337
Greg Clayton75c703d2011-02-16 04:46:07 +00002338void
2339Process::CompleteAttach ()
2340{
2341 // Let the process subclass figure out at much as it can about the process
2342 // before we go looking for a dynamic loader plug-in.
2343 DidAttach();
2344
2345 // We have complete the attach, now it is time to find the dynamic loader
2346 // plug-in
Greg Clayton4fdf7602011-03-20 04:57:14 +00002347 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton75c703d2011-02-16 04:46:07 +00002348 if (m_dyld_ap.get())
2349 m_dyld_ap->DidAttach();
2350
2351 // Figure out which one is the executable, and set that in our target:
2352 ModuleList &modules = m_target.GetImages();
2353
2354 size_t num_modules = modules.GetSize();
2355 for (int i = 0; i < num_modules; i++)
2356 {
2357 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Claytonb72d0f02011-04-12 05:54:46 +00002358 if (module_sp && module_sp->IsExecutable())
Greg Clayton75c703d2011-02-16 04:46:07 +00002359 {
2360 ModuleSP target_exe_module_sp (m_target.GetExecutableModule());
2361 if (target_exe_module_sp != module_sp)
2362 m_target.SetExecutableModule (module_sp, false);
2363 break;
2364 }
2365 }
2366}
2367
Chris Lattner24943d22010-06-08 16:52:24 +00002368Error
Greg Claytone71e2582011-02-04 01:58:07 +00002369Process::ConnectRemote (const char *remote_url)
2370{
Greg Claytone71e2582011-02-04 01:58:07 +00002371 m_abi_sp.reset();
2372 m_process_input_reader.reset();
2373
2374 // Find the process and its architecture. Make sure it matches the architecture
2375 // of the current Target, and if not adjust it.
2376
2377 Error error (DoConnectRemote (remote_url));
2378 if (error.Success())
2379 {
Greg Claytona2f74232011-02-24 22:24:29 +00002380 if (GetID() != LLDB_INVALID_PROCESS_ID)
2381 {
Greg Clayton24bc5d92011-03-30 18:16:51 +00002382 EventSP event_sp;
2383 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2384
2385 if (state == eStateStopped || state == eStateCrashed)
2386 {
2387 // If we attached and actually have a process on the other end, then
2388 // this ended up being the equivalent of an attach.
2389 CompleteAttach ();
2390
2391 // This delays passing the stopped event to listeners till
2392 // CompleteAttach gets a chance to complete...
2393 HandlePrivateEvent (event_sp);
2394
2395 }
Greg Claytona2f74232011-02-24 22:24:29 +00002396 }
Greg Clayton24bc5d92011-03-30 18:16:51 +00002397
2398 if (PrivateStateThreadIsValid ())
2399 ResumePrivateStateThread ();
2400 else
2401 StartPrivateStateThread ();
Greg Claytone71e2582011-02-04 01:58:07 +00002402 }
2403 return error;
2404}
2405
2406
2407Error
Chris Lattner24943d22010-06-08 16:52:24 +00002408Process::Resume ()
2409{
Greg Claytone005f2c2010-11-06 01:53:30 +00002410 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002411 if (log)
Jim Inghamac959662011-01-24 06:34:17 +00002412 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
2413 m_stop_id,
2414 StateAsCString(m_public_state.GetValue()),
2415 StateAsCString(m_private_state.GetValue()));
Chris Lattner24943d22010-06-08 16:52:24 +00002416
2417 Error error (WillResume());
2418 // Tell the process it is about to resume before the thread list
2419 if (error.Success())
2420 {
Johnny Chen9c11d472010-12-02 20:53:05 +00002421 // Now let the thread list know we are about to resume so it
Chris Lattner24943d22010-06-08 16:52:24 +00002422 // can let all of our threads know that they are about to be
2423 // resumed. Threads will each be called with
2424 // Thread::WillResume(StateType) where StateType contains the state
2425 // that they are supposed to have when the process is resumed
2426 // (suspended/running/stepping). Threads should also check
2427 // their resume signal in lldb::Thread::GetResumeSignal()
2428 // to see if they are suppoed to start back up with a signal.
2429 if (m_thread_list.WillResume())
2430 {
2431 error = DoResume();
2432 if (error.Success())
2433 {
2434 DidResume();
2435 m_thread_list.DidResume();
Jim Inghamac959662011-01-24 06:34:17 +00002436 if (log)
2437 log->Printf ("Process thinks the process has resumed.");
Chris Lattner24943d22010-06-08 16:52:24 +00002438 }
2439 }
2440 else
2441 {
Jim Inghamac959662011-01-24 06:34:17 +00002442 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner24943d22010-06-08 16:52:24 +00002443 }
2444 }
Jim Inghamac959662011-01-24 06:34:17 +00002445 else if (log)
2446 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner24943d22010-06-08 16:52:24 +00002447 return error;
2448}
2449
2450Error
2451Process::Halt ()
2452{
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002453 // Pause our private state thread so we can ensure no one else eats
2454 // the stop event out from under us.
Jim Inghamf9f40c22011-02-08 05:20:59 +00002455 Listener halt_listener ("lldb.process.halt_listener");
2456 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton20d338f2010-11-18 05:57:03 +00002457
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002458 EventSP event_sp;
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002459 Error error (WillHalt());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002460
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002461 if (error.Success())
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002462 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002463
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002464 bool caused_stop = false;
2465
2466 // Ask the process subclass to actually halt our process
2467 error = DoHalt(caused_stop);
Chris Lattner24943d22010-06-08 16:52:24 +00002468 if (error.Success())
Jim Ingham3ae449a2010-11-17 02:32:00 +00002469 {
Greg Clayton7e2f91c2011-01-29 07:10:55 +00002470 if (m_public_state.GetValue() == eStateAttaching)
2471 {
2472 SetExitStatus(SIGKILL, "Cancelled async attach.");
2473 Destroy ();
2474 }
2475 else
Jim Ingham3ae449a2010-11-17 02:32:00 +00002476 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002477 // If "caused_stop" is true, then DoHalt stopped the process. If
2478 // "caused_stop" is false, the process was already stopped.
2479 // If the DoHalt caused the process to stop, then we want to catch
2480 // this event and set the interrupted bool to true before we pass
2481 // this along so clients know that the process was interrupted by
2482 // a halt command.
2483 if (caused_stop)
Greg Clayton20d338f2010-11-18 05:57:03 +00002484 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00002485 // Wait for 1 second for the process to stop.
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002486 TimeValue timeout_time;
2487 timeout_time = TimeValue::Now();
2488 timeout_time.OffsetWithSeconds(1);
Jim Inghamf9f40c22011-02-08 05:20:59 +00002489 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2490 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002491
Jim Inghamf9f40c22011-02-08 05:20:59 +00002492 if (!got_event || state == eStateInvalid)
Greg Clayton20d338f2010-11-18 05:57:03 +00002493 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002494 // We timeout out and didn't get a stop event...
Jim Inghamf9f40c22011-02-08 05:20:59 +00002495 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton20d338f2010-11-18 05:57:03 +00002496 }
2497 else
2498 {
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002499 if (StateIsStoppedState (state))
2500 {
2501 // We caused the process to interrupt itself, so mark this
2502 // as such in the stop event so clients can tell an interrupted
2503 // process from a natural stop
2504 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2505 }
2506 else
2507 {
2508 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2509 if (log)
2510 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2511 error.SetErrorString ("Did not get stopped event after halt.");
2512 }
Greg Clayton20d338f2010-11-18 05:57:03 +00002513 }
2514 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002515 DidHalt();
Jim Ingham3ae449a2010-11-17 02:32:00 +00002516 }
2517 }
Chris Lattner24943d22010-06-08 16:52:24 +00002518 }
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002519 // Resume our private state thread before we post the event (if any)
Jim Inghamf9f40c22011-02-08 05:20:59 +00002520 RestorePrivateProcessEvents();
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002521
2522 // Post any event we might have consumed. If all goes well, we will have
2523 // stopped the process, intercepted the event and set the interrupted
2524 // bool in the event. Post it to the private event queue and that will end up
2525 // correctly setting the state.
2526 if (event_sp)
2527 m_private_state_broadcaster.BroadcastEvent(event_sp);
2528
Chris Lattner24943d22010-06-08 16:52:24 +00002529 return error;
2530}
2531
2532Error
2533Process::Detach ()
2534{
2535 Error error (WillDetach());
2536
2537 if (error.Success())
2538 {
2539 DisableAllBreakpointSites();
2540 error = DoDetach();
2541 if (error.Success())
2542 {
2543 DidDetach();
2544 StopPrivateStateThread();
2545 }
2546 }
2547 return error;
2548}
2549
2550Error
2551Process::Destroy ()
2552{
2553 Error error (WillDestroy());
2554 if (error.Success())
2555 {
2556 DisableAllBreakpointSites();
2557 error = DoDestroy();
2558 if (error.Success())
2559 {
2560 DidDestroy();
2561 StopPrivateStateThread();
2562 }
Caroline Tice861efb32010-11-16 05:07:41 +00002563 m_stdio_communication.StopReadThread();
2564 m_stdio_communication.Disconnect();
2565 if (m_process_input_reader && m_process_input_reader->IsActive())
2566 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2567 if (m_process_input_reader)
2568 m_process_input_reader.reset();
Chris Lattner24943d22010-06-08 16:52:24 +00002569 }
2570 return error;
2571}
2572
2573Error
2574Process::Signal (int signal)
2575{
2576 Error error (WillSignal());
2577 if (error.Success())
2578 {
2579 error = DoSignal(signal);
2580 if (error.Success())
2581 DidSignal();
2582 }
2583 return error;
2584}
2585
Greg Clayton395fc332011-02-15 21:59:32 +00002586lldb::ByteOrder
2587Process::GetByteOrder () const
Chris Lattner24943d22010-06-08 16:52:24 +00002588{
Greg Clayton395fc332011-02-15 21:59:32 +00002589 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner24943d22010-06-08 16:52:24 +00002590}
2591
2592uint32_t
Greg Clayton395fc332011-02-15 21:59:32 +00002593Process::GetAddressByteSize () const
Chris Lattner24943d22010-06-08 16:52:24 +00002594{
Greg Clayton395fc332011-02-15 21:59:32 +00002595 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner24943d22010-06-08 16:52:24 +00002596}
2597
Greg Clayton395fc332011-02-15 21:59:32 +00002598
Chris Lattner24943d22010-06-08 16:52:24 +00002599bool
2600Process::ShouldBroadcastEvent (Event *event_ptr)
2601{
2602 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2603 bool return_value = true;
Greg Claytone005f2c2010-11-06 01:53:30 +00002604 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002605
2606 switch (state)
2607 {
Greg Claytone71e2582011-02-04 01:58:07 +00002608 case eStateConnected:
Chris Lattner24943d22010-06-08 16:52:24 +00002609 case eStateAttaching:
2610 case eStateLaunching:
2611 case eStateDetached:
2612 case eStateExited:
2613 case eStateUnloaded:
2614 // These events indicate changes in the state of the debugging session, always report them.
2615 return_value = true;
2616 break;
2617 case eStateInvalid:
2618 // We stopped for no apparent reason, don't report it.
2619 return_value = false;
2620 break;
2621 case eStateRunning:
2622 case eStateStepping:
2623 // If we've started the target running, we handle the cases where we
2624 // are already running and where there is a transition from stopped to
2625 // running differently.
2626 // running -> running: Automatically suppress extra running events
2627 // stopped -> running: Report except when there is one or more no votes
2628 // and no yes votes.
2629 SynchronouslyNotifyStateChanged (state);
2630 switch (m_public_state.GetValue())
2631 {
2632 case eStateRunning:
2633 case eStateStepping:
2634 // We always suppress multiple runnings with no PUBLIC stop in between.
2635 return_value = false;
2636 break;
2637 default:
2638 // TODO: make this work correctly. For now always report
2639 // run if we aren't running so we don't miss any runnning
2640 // events. If I run the lldb/test/thread/a.out file and
2641 // break at main.cpp:58, run and hit the breakpoints on
2642 // multiple threads, then somehow during the stepping over
2643 // of all breakpoints no run gets reported.
2644 return_value = true;
2645
2646 // This is a transition from stop to run.
2647 switch (m_thread_list.ShouldReportRun (event_ptr))
2648 {
2649 case eVoteYes:
2650 case eVoteNoOpinion:
2651 return_value = true;
2652 break;
2653 case eVoteNo:
2654 return_value = false;
2655 break;
2656 }
2657 break;
2658 }
2659 break;
2660 case eStateStopped:
2661 case eStateCrashed:
2662 case eStateSuspended:
2663 {
2664 // We've stopped. First see if we're going to restart the target.
2665 // If we are going to stop, then we always broadcast the event.
2666 // 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 +00002667 // If no thread has an opinion, we don't report it.
Jim Ingham3ae449a2010-11-17 02:32:00 +00002668 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner24943d22010-06-08 16:52:24 +00002669 {
Greg Clayton20d338f2010-11-18 05:57:03 +00002670 if (log)
2671 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham3ae449a2010-11-17 02:32:00 +00002672 return true;
2673 }
2674 else
2675 {
Chris Lattner24943d22010-06-08 16:52:24 +00002676 RefreshStateAfterStop ();
2677
2678 if (m_thread_list.ShouldStop (event_ptr) == false)
2679 {
2680 switch (m_thread_list.ShouldReportStop (event_ptr))
2681 {
2682 case eVoteYes:
2683 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen028784b2010-10-14 00:54:32 +00002684 // Intentional fall-through here.
Chris Lattner24943d22010-06-08 16:52:24 +00002685 case eVoteNoOpinion:
Chris Lattner24943d22010-06-08 16:52:24 +00002686 case eVoteNo:
2687 return_value = false;
2688 break;
2689 }
2690
2691 if (log)
Jim Ingham3ae449a2010-11-17 02:32:00 +00002692 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner24943d22010-06-08 16:52:24 +00002693 Resume ();
2694 }
2695 else
2696 {
2697 return_value = true;
2698 SynchronouslyNotifyStateChanged (state);
2699 }
2700 }
2701 }
2702 }
2703
2704 if (log)
2705 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2706 return return_value;
2707}
2708
Chris Lattner24943d22010-06-08 16:52:24 +00002709
2710bool
2711Process::StartPrivateStateThread ()
2712{
Greg Claytone005f2c2010-11-06 01:53:30 +00002713 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002714
Greg Claytonb72d0f02011-04-12 05:54:46 +00002715 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner24943d22010-06-08 16:52:24 +00002716 if (log)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002717 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2718
2719 if (already_running)
2720 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00002721
2722 // Create a thread that watches our internal state and controls which
2723 // events make it to clients (into the DCProcess event queue).
Greg Claytona875b642011-01-09 21:07:35 +00002724 char thread_name[1024];
2725 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2726 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +00002727 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner24943d22010-06-08 16:52:24 +00002728}
2729
2730void
2731Process::PausePrivateStateThread ()
2732{
2733 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2734}
2735
2736void
2737Process::ResumePrivateStateThread ()
2738{
2739 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2740}
2741
2742void
2743Process::StopPrivateStateThread ()
2744{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002745 if (PrivateStateThreadIsValid ())
2746 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner24943d22010-06-08 16:52:24 +00002747}
2748
2749void
2750Process::ControlPrivateStateThread (uint32_t signal)
2751{
Greg Claytone005f2c2010-11-06 01:53:30 +00002752 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner24943d22010-06-08 16:52:24 +00002753
2754 assert (signal == eBroadcastInternalStateControlStop ||
2755 signal == eBroadcastInternalStateControlPause ||
2756 signal == eBroadcastInternalStateControlResume);
2757
2758 if (log)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002759 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner24943d22010-06-08 16:52:24 +00002760
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002761 // Signal the private state thread. First we should copy this is case the
2762 // thread starts exiting since the private state thread will NULL this out
2763 // when it exits
2764 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton09c81ef2011-02-08 01:34:25 +00002765 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner24943d22010-06-08 16:52:24 +00002766 {
2767 TimeValue timeout_time;
2768 bool timed_out;
2769
2770 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2771
2772 timeout_time = TimeValue::Now();
2773 timeout_time.OffsetWithSeconds(2);
2774 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2775 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2776
2777 if (signal == eBroadcastInternalStateControlStop)
2778 {
2779 if (timed_out)
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002780 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner24943d22010-06-08 16:52:24 +00002781
2782 thread_result_t result = NULL;
Greg Claytonf4fbc0b2011-01-22 17:43:17 +00002783 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Claytonc607d862010-07-22 18:34:21 +00002784 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002785 }
2786 }
2787}
2788
2789void
2790Process::HandlePrivateEvent (EventSP &event_sp)
2791{
Greg Claytone005f2c2010-11-06 01:53:30 +00002792 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002793
Greg Clayton68ca8232011-01-25 02:58:48 +00002794 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002795
2796 // First check to see if anybody wants a shot at this event:
Jim Ingham68bffc52011-01-29 04:05:41 +00002797 if (m_next_event_action_ap.get() != NULL)
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002798 {
Jim Ingham68bffc52011-01-29 04:05:41 +00002799 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002800 switch (action_result)
2801 {
2802 case NextEventAction::eEventActionSuccess:
2803 SetNextEventAction(NULL);
2804 break;
2805 case NextEventAction::eEventActionRetry:
2806 break;
2807 case NextEventAction::eEventActionExit:
Jim Ingham84c86382011-01-29 01:57:31 +00002808 // Handle Exiting Here. If we already got an exited event,
2809 // we should just propagate it. Otherwise, swallow this event,
2810 // and set our state to exit so the next event will kill us.
2811 if (new_state != eStateExited)
2812 {
2813 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham68bffc52011-01-29 04:05:41 +00002814 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham84c86382011-01-29 01:57:31 +00002815 SetNextEventAction(NULL);
2816 return;
2817 }
2818 SetNextEventAction(NULL);
Jim Inghamc2dc7c82011-01-29 01:49:25 +00002819 break;
2820 }
2821 }
2822
Chris Lattner24943d22010-06-08 16:52:24 +00002823 // See if we should broadcast this state to external clients?
2824 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner24943d22010-06-08 16:52:24 +00002825
2826 if (should_broadcast)
2827 {
2828 if (log)
2829 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002830 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2831 __FUNCTION__,
2832 GetID(),
2833 StateAsCString(new_state),
2834 StateAsCString (GetState ()),
2835 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002836 }
Jim Inghamd60d94a2011-03-11 03:53:59 +00002837 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton68ca8232011-01-25 02:58:48 +00002838 if (StateIsRunningState (new_state))
Caroline Tice861efb32010-11-16 05:07:41 +00002839 PushProcessInputReader ();
2840 else
2841 PopProcessInputReader ();
Jim Inghamd60d94a2011-03-11 03:53:59 +00002842
Chris Lattner24943d22010-06-08 16:52:24 +00002843 BroadcastEvent (event_sp);
2844 }
2845 else
2846 {
2847 if (log)
2848 {
Greg Clayton68ca8232011-01-25 02:58:48 +00002849 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2850 __FUNCTION__,
2851 GetID(),
2852 StateAsCString(new_state),
2853 StateAsCString (GetState ()),
2854 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner24943d22010-06-08 16:52:24 +00002855 }
2856 }
2857}
2858
2859void *
2860Process::PrivateStateThread (void *arg)
2861{
2862 Process *proc = static_cast<Process*> (arg);
2863 void *result = proc->RunPrivateStateThread ();
Chris Lattner24943d22010-06-08 16:52:24 +00002864 return result;
2865}
2866
2867void *
2868Process::RunPrivateStateThread ()
2869{
2870 bool control_only = false;
2871 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2872
Greg Claytone005f2c2010-11-06 01:53:30 +00002873 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner24943d22010-06-08 16:52:24 +00002874 if (log)
2875 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2876
2877 bool exit_now = false;
2878 while (!exit_now)
2879 {
2880 EventSP event_sp;
2881 WaitForEventsPrivate (NULL, event_sp, control_only);
2882 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2883 {
2884 switch (event_sp->GetType())
2885 {
2886 case eBroadcastInternalStateControlStop:
2887 exit_now = true;
2888 continue; // Go to next loop iteration so we exit without
2889 break; // doing any internal state managment below
2890
2891 case eBroadcastInternalStateControlPause:
2892 control_only = true;
2893 break;
2894
2895 case eBroadcastInternalStateControlResume:
2896 control_only = false;
2897 break;
2898 }
Jim Ingham3ae449a2010-11-17 02:32:00 +00002899
Jim Ingham3ae449a2010-11-17 02:32:00 +00002900 if (log)
2901 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2902
Chris Lattner24943d22010-06-08 16:52:24 +00002903 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham3ae449a2010-11-17 02:32:00 +00002904 continue;
Chris Lattner24943d22010-06-08 16:52:24 +00002905 }
2906
2907
2908 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2909
2910 if (internal_state != eStateInvalid)
2911 {
2912 HandlePrivateEvent (event_sp);
2913 }
2914
Greg Clayton3b2c41c2010-10-18 04:14:23 +00002915 if (internal_state == eStateInvalid ||
2916 internal_state == eStateExited ||
2917 internal_state == eStateDetached )
Jim Ingham3ae449a2010-11-17 02:32:00 +00002918 {
Jim Ingham3ae449a2010-11-17 02:32:00 +00002919 if (log)
2920 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2921
Chris Lattner24943d22010-06-08 16:52:24 +00002922 break;
Jim Ingham3ae449a2010-11-17 02:32:00 +00002923 }
Chris Lattner24943d22010-06-08 16:52:24 +00002924 }
2925
Caroline Tice926060e2010-10-29 21:48:37 +00002926 // Verify log is still enabled before attempting to write to it...
Chris Lattner24943d22010-06-08 16:52:24 +00002927 if (log)
2928 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2929
Greg Claytona4881d02011-01-22 07:12:45 +00002930 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2931 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner24943d22010-06-08 16:52:24 +00002932 return NULL;
2933}
2934
Chris Lattner24943d22010-06-08 16:52:24 +00002935//------------------------------------------------------------------
2936// Process Event Data
2937//------------------------------------------------------------------
2938
2939Process::ProcessEventData::ProcessEventData () :
2940 EventData (),
2941 m_process_sp (),
2942 m_state (eStateInvalid),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002943 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002944 m_update_state (false),
2945 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002946{
2947}
2948
2949Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2950 EventData (),
2951 m_process_sp (process_sp),
2952 m_state (state),
Greg Clayton54e7afa2010-07-09 20:39:50 +00002953 m_restarted (false),
Jim Ingham3ae449a2010-11-17 02:32:00 +00002954 m_update_state (false),
2955 m_interrupted (false)
Chris Lattner24943d22010-06-08 16:52:24 +00002956{
2957}
2958
2959Process::ProcessEventData::~ProcessEventData()
2960{
2961}
2962
2963const ConstString &
2964Process::ProcessEventData::GetFlavorString ()
2965{
2966 static ConstString g_flavor ("Process::ProcessEventData");
2967 return g_flavor;
2968}
2969
2970const ConstString &
2971Process::ProcessEventData::GetFlavor () const
2972{
2973 return ProcessEventData::GetFlavorString ();
2974}
2975
Chris Lattner24943d22010-06-08 16:52:24 +00002976void
2977Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2978{
2979 // This function gets called twice for each event, once when the event gets pulled
2980 // off of the private process event queue, and once when it gets pulled off of
2981 // the public event queue. m_update_state is used to distinguish these
2982 // two cases; it is false when we're just pulling it off for private handling,
2983 // and we don't want to do the breakpoint command handling then.
2984
2985 if (!m_update_state)
2986 return;
2987
2988 m_process_sp->SetPublicState (m_state);
2989
2990 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2991 if (m_state == eStateStopped && ! m_restarted)
2992 {
2993 int num_threads = m_process_sp->GetThreadList().GetSize();
2994 int idx;
Greg Clayton643ee732010-08-04 01:40:35 +00002995
Chris Lattner24943d22010-06-08 16:52:24 +00002996 for (idx = 0; idx < num_threads; ++idx)
2997 {
2998 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2999
Jim Ingham6297a3a2010-10-20 00:39:53 +00003000 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3001 if (stop_info_sp)
Chris Lattner24943d22010-06-08 16:52:24 +00003002 {
Jim Ingham6297a3a2010-10-20 00:39:53 +00003003 stop_info_sp->PerformAction(event_ptr);
Chris Lattner24943d22010-06-08 16:52:24 +00003004 }
3005 }
Greg Clayton643ee732010-08-04 01:40:35 +00003006
Jim Ingham6fb8baa2010-08-10 00:59:59 +00003007 // The stop action might restart the target. If it does, then we want to mark that in the
3008 // event so that whoever is receiving it will know to wait for the running event and reflect
3009 // that state appropriately.
3010
Chris Lattner24943d22010-06-08 16:52:24 +00003011 if (m_process_sp->GetPrivateState() == eStateRunning)
3012 SetRestarted(true);
Jim Inghamd60d94a2011-03-11 03:53:59 +00003013 else
3014 {
3015 // Finally, if we didn't restart, run the Stop Hooks here:
3016 // They might also restart the target, so watch for that.
3017 m_process_sp->GetTarget().RunStopHooks();
3018 if (m_process_sp->GetPrivateState() == eStateRunning)
3019 SetRestarted(true);
3020 }
3021
Chris Lattner24943d22010-06-08 16:52:24 +00003022 }
3023}
3024
3025void
3026Process::ProcessEventData::Dump (Stream *s) const
3027{
3028 if (m_process_sp)
3029 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
3030
Greg Claytonb72d0f02011-04-12 05:54:46 +00003031 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner24943d22010-06-08 16:52:24 +00003032}
3033
3034const Process::ProcessEventData *
3035Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3036{
3037 if (event_ptr)
3038 {
3039 const EventData *event_data = event_ptr->GetData();
3040 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3041 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3042 }
3043 return NULL;
3044}
3045
3046ProcessSP
3047Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3048{
3049 ProcessSP process_sp;
3050 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3051 if (data)
3052 process_sp = data->GetProcessSP();
3053 return process_sp;
3054}
3055
3056StateType
3057Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3058{
3059 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3060 if (data == NULL)
3061 return eStateInvalid;
3062 else
3063 return data->GetState();
3064}
3065
3066bool
3067Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3068{
3069 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3070 if (data == NULL)
3071 return false;
3072 else
3073 return data->GetRestarted();
3074}
3075
3076void
3077Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3078{
3079 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3080 if (data != NULL)
3081 data->SetRestarted(new_value);
3082}
3083
3084bool
Jim Ingham3ae449a2010-11-17 02:32:00 +00003085Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3086{
3087 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3088 if (data == NULL)
3089 return false;
3090 else
3091 return data->GetInterrupted ();
3092}
3093
3094void
3095Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3096{
3097 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3098 if (data != NULL)
3099 data->SetInterrupted(new_value);
3100}
3101
3102bool
Chris Lattner24943d22010-06-08 16:52:24 +00003103Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3104{
3105 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3106 if (data)
3107 {
3108 data->SetUpdateStateOnRemoval();
3109 return true;
3110 }
3111 return false;
3112}
3113
Chris Lattner24943d22010-06-08 16:52:24 +00003114void
Greg Claytona830adb2010-10-04 01:05:56 +00003115Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner24943d22010-06-08 16:52:24 +00003116{
3117 exe_ctx.target = &m_target;
3118 exe_ctx.process = this;
3119 exe_ctx.thread = NULL;
3120 exe_ctx.frame = NULL;
3121}
3122
3123lldb::ProcessSP
3124Process::GetSP ()
3125{
3126 return GetTarget().GetProcessSP();
3127}
3128
Greg Claytone4b9c1f2011-03-08 22:40:15 +00003129//uint32_t
3130//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3131//{
3132// return 0;
3133//}
3134//
3135//ArchSpec
3136//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3137//{
3138// return Host::GetArchSpecForExistingProcess (pid);
3139//}
3140//
3141//ArchSpec
3142//Process::GetArchSpecForExistingProcess (const char *process_name)
3143//{
3144// return Host::GetArchSpecForExistingProcess (process_name);
3145//}
3146//
Caroline Tice861efb32010-11-16 05:07:41 +00003147void
3148Process::AppendSTDOUT (const char * s, size_t len)
3149{
Greg Clayton20d338f2010-11-18 05:57:03 +00003150 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Tice861efb32010-11-16 05:07:41 +00003151 m_stdout_data.append (s, len);
3152
Greg Claytonb3781332010-12-05 19:16:56 +00003153 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Tice861efb32010-11-16 05:07:41 +00003154}
3155
3156void
3157Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3158{
3159 Process *process = (Process *) baton;
3160 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3161}
3162
3163size_t
3164Process::ProcessInputReaderCallback (void *baton,
3165 InputReader &reader,
3166 lldb::InputReaderAction notification,
3167 const char *bytes,
3168 size_t bytes_len)
3169{
3170 Process *process = (Process *) baton;
3171
3172 switch (notification)
3173 {
3174 case eInputReaderActivate:
3175 break;
3176
3177 case eInputReaderDeactivate:
3178 break;
3179
3180 case eInputReaderReactivate:
3181 break;
3182
Caroline Tice4a348082011-05-02 20:41:46 +00003183 case eInputReaderAsynchronousOutputWritten:
3184 break;
3185
Caroline Tice861efb32010-11-16 05:07:41 +00003186 case eInputReaderGotToken:
3187 {
3188 Error error;
3189 process->PutSTDIN (bytes, bytes_len, error);
3190 }
3191 break;
3192
Caroline Ticec4f55fe2010-11-19 20:47:54 +00003193 case eInputReaderInterrupt:
3194 process->Halt ();
3195 break;
3196
3197 case eInputReaderEndOfFile:
3198 process->AppendSTDOUT ("^D", 2);
3199 break;
3200
Caroline Tice861efb32010-11-16 05:07:41 +00003201 case eInputReaderDone:
3202 break;
3203
3204 }
3205
3206 return bytes_len;
3207}
3208
3209void
3210Process::ResetProcessInputReader ()
3211{
3212 m_process_input_reader.reset();
3213}
3214
3215void
3216Process::SetUpProcessInputReader (int file_descriptor)
3217{
3218 // First set up the Read Thread for reading/handling process I/O
3219
3220 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3221
3222 if (conn_ap.get())
3223 {
3224 m_stdio_communication.SetConnection (conn_ap.release());
3225 if (m_stdio_communication.IsConnected())
3226 {
3227 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3228 m_stdio_communication.StartReadThread();
3229
3230 // Now read thread is set up, set up input reader.
3231
3232 if (!m_process_input_reader.get())
3233 {
3234 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3235 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3236 this,
3237 eInputReaderGranularityByte,
3238 NULL,
3239 NULL,
3240 false));
3241
3242 if (err.Fail())
3243 m_process_input_reader.reset();
3244 }
3245 }
3246 }
3247}
3248
3249void
3250Process::PushProcessInputReader ()
3251{
3252 if (m_process_input_reader && !m_process_input_reader->IsActive())
3253 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3254}
3255
3256void
3257Process::PopProcessInputReader ()
3258{
3259 if (m_process_input_reader && m_process_input_reader->IsActive())
3260 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3261}
3262
Greg Claytond284b662011-02-18 01:44:25 +00003263// The process needs to know about installed plug-ins
Greg Clayton990de7b2010-11-18 23:32:35 +00003264void
Caroline Tice2a456812011-03-10 22:14:10 +00003265Process::SettingsInitialize ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003266{
Greg Claytonb3448432011-03-24 21:19:54 +00003267 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytond284b662011-02-18 01:44:25 +00003268
3269 int i=0;
3270 const char *name;
3271 OptionEnumValueElement option_enum;
3272 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3273 {
3274 if (name)
3275 {
3276 option_enum.value = i;
3277 option_enum.string_value = name;
3278 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3279 g_plugins.push_back (option_enum);
3280 }
3281 ++i;
3282 }
3283 option_enum.value = 0;
3284 option_enum.string_value = NULL;
3285 option_enum.usage = NULL;
3286 g_plugins.push_back (option_enum);
3287
3288 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3289 {
3290 if (::strcmp (name, "plugin") == 0)
3291 {
3292 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3293 break;
3294 }
3295 }
Greg Clayton990de7b2010-11-18 23:32:35 +00003296 UserSettingsControllerSP &usc = GetSettingsController();
3297 usc.reset (new SettingsController);
3298 UserSettingsController::InitializeSettingsController (usc,
3299 SettingsController::global_settings_table,
3300 SettingsController::instance_settings_table);
Caroline Tice2a456812011-03-10 22:14:10 +00003301
3302 // Now call SettingsInitialize() for each 'child' of Process settings
3303 Thread::SettingsInitialize ();
Greg Clayton990de7b2010-11-18 23:32:35 +00003304}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003305
Greg Clayton990de7b2010-11-18 23:32:35 +00003306void
Caroline Tice2a456812011-03-10 22:14:10 +00003307Process::SettingsTerminate ()
Greg Claytond284b662011-02-18 01:44:25 +00003308{
Caroline Tice2a456812011-03-10 22:14:10 +00003309 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3310
3311 Thread::SettingsTerminate ();
3312
3313 // Now terminate Process Settings.
3314
Greg Clayton990de7b2010-11-18 23:32:35 +00003315 UserSettingsControllerSP &usc = GetSettingsController();
3316 UserSettingsController::FinalizeSettingsController (usc);
3317 usc.reset();
3318}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003319
Greg Clayton990de7b2010-11-18 23:32:35 +00003320UserSettingsControllerSP &
3321Process::GetSettingsController ()
3322{
3323 static UserSettingsControllerSP g_settings_controller;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003324 return g_settings_controller;
3325}
3326
Caroline Tice1ebef442010-09-27 00:30:10 +00003327void
3328Process::UpdateInstanceName ()
3329{
3330 ModuleSP module_sp = GetTarget().GetExecutableModule();
3331 if (module_sp)
3332 {
3333 StreamString sstr;
3334 sstr.Printf ("%s", module_sp->GetFileSpec().GetFilename().AsCString());
3335
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003336 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Claytonb72d0f02011-04-12 05:54:46 +00003337 sstr.GetData());
Caroline Tice1ebef442010-09-27 00:30:10 +00003338 }
3339}
3340
Greg Clayton427f2902010-12-14 02:59:59 +00003341ExecutionResults
Jim Ingham360f53f2010-11-30 02:22:11 +00003342Process::RunThreadPlan (ExecutionContext &exe_ctx,
3343 lldb::ThreadPlanSP &thread_plan_sp,
3344 bool stop_others,
3345 bool try_all_threads,
3346 bool discard_on_error,
3347 uint32_t single_thread_timeout_usec,
3348 Stream &errors)
3349{
3350 ExecutionResults return_value = eExecutionSetupError;
3351
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003352 if (thread_plan_sp.get() == NULL)
3353 {
3354 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytonb3448432011-03-24 21:19:54 +00003355 return eExecutionSetupError;
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003356 }
3357
Jim Inghamac959662011-01-24 06:34:17 +00003358 if (m_private_state.GetValue() != eStateStopped)
3359 {
3360 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytonb3448432011-03-24 21:19:54 +00003361 return eExecutionSetupError;
Jim Inghamac959662011-01-24 06:34:17 +00003362 }
3363
Jim Ingham360f53f2010-11-30 02:22:11 +00003364 // Save this value for restoration of the execution context after we run
3365 uint32_t tid = exe_ctx.thread->GetIndexID();
3366
3367 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3368 // so we should arrange to reset them as well.
3369
3370 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
3371 lldb::StackFrameSP selected_frame_sp;
3372
3373 uint32_t selected_tid;
3374 if (selected_thread_sp != NULL)
3375 {
3376 selected_tid = selected_thread_sp->GetIndexID();
3377 selected_frame_sp = selected_thread_sp->GetSelectedFrame();
3378 }
3379 else
3380 {
3381 selected_tid = LLDB_INVALID_THREAD_ID;
3382 }
3383
3384 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
3385
Jim Ingham6ae318c2011-01-23 21:14:08 +00003386 Listener listener("lldb.process.listener.run-thread-plan");
Jim Inghamf9f40c22011-02-08 05:20:59 +00003387
3388 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3389 // restored on exit to the function.
3390
3391 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Inghamac959662011-01-24 06:34:17 +00003392
Jim Ingham6ae318c2011-01-23 21:14:08 +00003393 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003394 if (log)
3395 {
3396 StreamString s;
3397 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Inghamf9f40c22011-02-08 05:20:59 +00003398 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
3399 exe_ctx.thread->GetIndexID(),
3400 exe_ctx.thread->GetID(),
3401 s.GetData());
Jim Ingham15dcb7c2011-01-20 02:03:18 +00003402 }
3403
Jim Inghamf9f40c22011-02-08 05:20:59 +00003404 bool got_event;
3405 lldb::EventSP event_sp;
3406 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Ingham360f53f2010-11-30 02:22:11 +00003407
3408 TimeValue* timeout_ptr = NULL;
3409 TimeValue real_timeout;
3410
Jim Inghamf9f40c22011-02-08 05:20:59 +00003411 bool first_timeout = true;
3412 bool do_resume = true;
Jim Ingham360f53f2010-11-30 02:22:11 +00003413
Jim Ingham360f53f2010-11-30 02:22:11 +00003414 while (1)
3415 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003416 // We usually want to resume the process if we get to the top of the loop.
3417 // The only exception is if we get two running events with no intervening
3418 // stop, which can happen, we will just wait for then next stop event.
Jim Ingham360f53f2010-11-30 02:22:11 +00003419
Jim Inghamf9f40c22011-02-08 05:20:59 +00003420 if (do_resume)
Jim Ingham360f53f2010-11-30 02:22:11 +00003421 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003422 // Do the initial resume and wait for the running event before going further.
3423
3424 Error resume_error = exe_ctx.process->Resume ();
3425 if (!resume_error.Success())
3426 {
3427 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytonb3448432011-03-24 21:19:54 +00003428 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003429 break;
3430 }
3431
3432 real_timeout = TimeValue::Now();
3433 real_timeout.OffsetWithMicroSeconds(500000);
3434 timeout_ptr = &real_timeout;
3435
3436 got_event = listener.WaitForEvent(NULL, event_sp);
3437 if (!got_event)
3438 {
3439 if (log)
3440 log->Printf("Didn't get any event after initial resume, exiting.");
3441
3442 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003443 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003444 break;
3445 }
3446
3447 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3448 if (stop_state != eStateRunning)
3449 {
3450 if (log)
3451 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3452
3453 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003454 return_value = eExecutionSetupError;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003455 break;
3456 }
3457
3458 if (log)
3459 log->Printf ("Resuming succeeded.");
3460 // We need to call the function synchronously, so spin waiting for it to return.
3461 // If we get interrupted while executing, we're going to lose our context, and
3462 // won't be able to gather the result at this point.
3463 // We set the timeout AFTER the resume, since the resume takes some time and we
3464 // don't want to charge that to the timeout.
3465
3466 if (single_thread_timeout_usec != 0)
3467 {
3468 real_timeout = TimeValue::Now();
3469 if (first_timeout)
3470 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3471 else
3472 real_timeout.OffsetWithSeconds(10);
3473
3474 timeout_ptr = &real_timeout;
3475 }
3476 }
3477 else
3478 {
3479 if (log)
3480 log->Printf ("Handled an extra running event.");
3481 do_resume = true;
3482 }
3483
3484 // Now wait for the process to stop again:
3485 stop_state = lldb::eStateInvalid;
3486 event_sp.reset();
3487 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3488
3489 if (got_event)
3490 {
3491 if (event_sp.get())
3492 {
3493 bool keep_going = false;
3494 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3495 if (log)
3496 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3497
3498 switch (stop_state)
3499 {
3500 case lldb::eStateStopped:
3501 // Yay, we're done.
3502 if (log)
3503 log->Printf ("Execution completed successfully.");
Greg Claytonb3448432011-03-24 21:19:54 +00003504 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003505 break;
3506 case lldb::eStateCrashed:
3507 if (log)
3508 log->Printf ("Execution crashed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003509 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003510 break;
3511 case lldb::eStateRunning:
3512 do_resume = false;
3513 keep_going = true;
3514 break;
3515 default:
3516 if (log)
3517 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003518 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003519 break;
3520 }
3521 if (keep_going)
3522 continue;
3523 else
3524 break;
3525 }
3526 else
3527 {
3528 if (log)
3529 log->Printf ("got_event was true, but the event pointer was null. How odd...");
Greg Claytonb3448432011-03-24 21:19:54 +00003530 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003531 break;
3532 }
3533 }
3534 else
3535 {
3536 // If we didn't get an event that means we've timed out...
3537 // We will interrupt the process here. Depending on what we were asked to do we will
3538 // either exit, or try with all threads running for the same timeout.
Jim Ingham360f53f2010-11-30 02:22:11 +00003539 // Not really sure what to do if Halt fails here...
Jim Inghamf9f40c22011-02-08 05:20:59 +00003540
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003541 if (log) {
Jim Ingham360f53f2010-11-30 02:22:11 +00003542 if (try_all_threads)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003543 {
3544 if (first_timeout)
3545 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3546 "trying with all threads enabled.",
3547 single_thread_timeout_usec);
3548 else
3549 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3550 "and timeout: %d timed out.",
3551 single_thread_timeout_usec);
3552 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003553 else
Jim Inghamf9f40c22011-02-08 05:20:59 +00003554 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3555 "halt and abandoning execution.",
Jim Ingham360f53f2010-11-30 02:22:11 +00003556 single_thread_timeout_usec);
Stephen Wilsonc2b98252011-01-12 04:20:03 +00003557 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003558
Jim Inghamc556b462011-01-22 01:30:53 +00003559 Error halt_error = exe_ctx.process->Halt();
Jim Inghamc556b462011-01-22 01:30:53 +00003560 if (halt_error.Success())
Jim Ingham360f53f2010-11-30 02:22:11 +00003561 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003562 if (log)
Greg Clayton68ca8232011-01-25 02:58:48 +00003563 log->Printf ("Process::RunThreadPlan(): Halt succeeded.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003564
Jim Inghamf9f40c22011-02-08 05:20:59 +00003565 // If halt succeeds, it always produces a stopped event. Wait for that:
3566
3567 real_timeout = TimeValue::Now();
3568 real_timeout.OffsetWithMicroSeconds(500000);
3569
3570 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Ingham360f53f2010-11-30 02:22:11 +00003571
3572 if (got_event)
3573 {
3574 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3575 if (log)
3576 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003577 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Inghamf9f40c22011-02-08 05:20:59 +00003578 if (stop_state == lldb::eStateStopped
3579 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham360f53f2010-11-30 02:22:11 +00003580 log->Printf (" Event was the Halt interruption event.");
3581 }
3582
Jim Inghamf9f40c22011-02-08 05:20:59 +00003583 if (stop_state == lldb::eStateStopped)
Jim Ingham360f53f2010-11-30 02:22:11 +00003584 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003585 // Between the time we initiated the Halt and the time we delivered it, the process could have
3586 // already finished its job. Check that here:
Jim Ingham360f53f2010-11-30 02:22:11 +00003587
Jim Inghamf9f40c22011-02-08 05:20:59 +00003588 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3589 {
3590 if (log)
3591 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3592 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003593 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003594 break;
3595 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003596
Jim Inghamf9f40c22011-02-08 05:20:59 +00003597 if (!try_all_threads)
3598 {
3599 if (log)
3600 log->Printf ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytonb3448432011-03-24 21:19:54 +00003601 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003602 break;
3603 }
3604
3605 if (first_timeout)
3606 {
3607 // Set all the other threads to run, and return to the top of the loop, which will continue;
3608 first_timeout = false;
3609 thread_plan_sp->SetStopOthers (false);
3610 if (log)
3611 log->Printf ("Process::RunThreadPlan(): About to resume.");
3612
3613 continue;
3614 }
3615 else
3616 {
3617 // Running all threads failed, so return Interrupted.
3618 if (log)
3619 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003620 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003621 break;
3622 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003623 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003624 }
3625 else
3626 { if (log)
3627 log->Printf("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
3628 "I'm getting out of here passing Interrupted.");
Greg Claytonb3448432011-03-24 21:19:54 +00003629 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003630 break;
Jim Ingham360f53f2010-11-30 02:22:11 +00003631 }
3632 }
Jim Inghamc556b462011-01-22 01:30:53 +00003633 else
3634 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003635 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3636 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghamc556b462011-01-22 01:30:53 +00003637 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003638 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.",
3639 halt_error.AsCString());
3640 real_timeout = TimeValue::Now();
3641 real_timeout.OffsetWithMicroSeconds(500000);
3642 timeout_ptr = &real_timeout;
3643 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3644 if (!got_event || event_sp.get() == NULL)
Jim Ingham6ae318c2011-01-23 21:14:08 +00003645 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003646 // This is not going anywhere, bag out.
3647 if (log)
3648 log->Printf ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytonb3448432011-03-24 21:19:54 +00003649 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003650 break;
Jim Ingham6ae318c2011-01-23 21:14:08 +00003651 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003652 else
3653 {
3654 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3655 if (log)
3656 log->Printf ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
3657 if (stop_state == lldb::eStateStopped)
3658 {
3659 // Between the time we initiated the Halt and the time we delivered it, the process could have
3660 // already finished its job. Check that here:
3661
3662 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3663 {
3664 if (log)
3665 log->Printf ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
3666 "Exiting wait loop.");
Greg Claytonb3448432011-03-24 21:19:54 +00003667 return_value = eExecutionCompleted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003668 break;
3669 }
3670
3671 if (first_timeout)
3672 {
3673 // Set all the other threads to run, and return to the top of the loop, which will continue;
3674 first_timeout = false;
3675 thread_plan_sp->SetStopOthers (false);
3676 if (log)
3677 log->Printf ("Process::RunThreadPlan(): About to resume.");
3678
3679 continue;
3680 }
3681 else
3682 {
3683 // Running all threads failed, so return Interrupted.
3684 if (log)
3685 log->Printf("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytonb3448432011-03-24 21:19:54 +00003686 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003687 break;
3688 }
3689 }
3690 else
3691 {
3692 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3693 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytonb3448432011-03-24 21:19:54 +00003694 return_value = eExecutionInterrupted;
Jim Inghamf9f40c22011-02-08 05:20:59 +00003695 break;
3696 }
3697 }
Jim Inghamc556b462011-01-22 01:30:53 +00003698 }
3699
Jim Ingham360f53f2010-11-30 02:22:11 +00003700 }
3701
Jim Inghamf9f40c22011-02-08 05:20:59 +00003702 } // END WAIT LOOP
3703
3704 // Now do some processing on the results of the run:
3705 if (return_value == eExecutionInterrupted)
3706 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003707 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003708 {
3709 StreamString s;
3710 if (event_sp)
3711 event_sp->Dump (&s);
3712 else
3713 {
3714 log->Printf ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
3715 }
3716
3717 StreamString ts;
3718
3719 const char *event_explanation;
3720
3721 do
3722 {
3723 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3724
3725 if (!event_data)
3726 {
3727 event_explanation = "<no event data>";
3728 break;
3729 }
3730
3731 Process *process = event_data->GetProcessSP().get();
3732
3733 if (!process)
3734 {
3735 event_explanation = "<no process>";
3736 break;
3737 }
3738
3739 ThreadList &thread_list = process->GetThreadList();
3740
3741 uint32_t num_threads = thread_list.GetSize();
3742 uint32_t thread_index;
3743
3744 ts.Printf("<%u threads> ", num_threads);
3745
3746 for (thread_index = 0;
3747 thread_index < num_threads;
3748 ++thread_index)
3749 {
3750 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3751
3752 if (!thread)
3753 {
3754 ts.Printf("<?> ");
3755 continue;
3756 }
3757
3758 ts.Printf("<0x%4.4x ", thread->GetID());
3759 RegisterContext *register_context = thread->GetRegisterContext().get();
3760
3761 if (register_context)
3762 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3763 else
3764 ts.Printf("[ip unknown] ");
3765
3766 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3767 if (stop_info_sp)
3768 {
3769 const char *stop_desc = stop_info_sp->GetDescription();
3770 if (stop_desc)
3771 ts.PutCString (stop_desc);
3772 }
3773 ts.Printf(">");
3774 }
3775
3776 event_explanation = ts.GetData();
3777 } while (0);
3778
3779 if (log)
3780 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3781
3782 if (discard_on_error && thread_plan_sp)
3783 {
3784 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3785 }
3786 }
3787 }
3788 else if (return_value == eExecutionSetupError)
3789 {
3790 if (log)
3791 log->Printf("Process::RunThreadPlan(): execution set up error.");
3792
3793 if (discard_on_error && thread_plan_sp)
3794 {
3795 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3796 }
3797 }
3798 else
3799 {
Jim Ingham360f53f2010-11-30 02:22:11 +00003800 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3801 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003802 if (log)
3803 log->Printf("Process::RunThreadPlan(): thread plan is done");
Greg Claytonb3448432011-03-24 21:19:54 +00003804 return_value = eExecutionCompleted;
Jim Ingham360f53f2010-11-30 02:22:11 +00003805 }
3806 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3807 {
Greg Clayton68ca8232011-01-25 02:58:48 +00003808 if (log)
3809 log->Printf("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytonb3448432011-03-24 21:19:54 +00003810 return_value = eExecutionDiscarded;
Jim Ingham360f53f2010-11-30 02:22:11 +00003811 }
3812 else
3813 {
3814 if (log)
Jim Inghamf9f40c22011-02-08 05:20:59 +00003815 log->Printf("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Ingham360f53f2010-11-30 02:22:11 +00003816 if (discard_on_error && thread_plan_sp)
3817 {
Jim Inghamf9f40c22011-02-08 05:20:59 +00003818 if (log)
3819 log->Printf("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Jim Ingham360f53f2010-11-30 02:22:11 +00003820 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
3821 }
Jim Ingham360f53f2010-11-30 02:22:11 +00003822 }
3823 }
Jim Inghamf9f40c22011-02-08 05:20:59 +00003824
Jim Ingham360f53f2010-11-30 02:22:11 +00003825 // Thread we ran the function in may have gone away because we ran the target
3826 // Check that it's still there.
3827 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(tid, true).get();
3828 if (exe_ctx.thread)
3829 exe_ctx.frame = exe_ctx.thread->GetStackFrameAtIndex(0).get();
3830
3831 // Also restore the current process'es selected frame & thread, since this function calling may
3832 // be done behind the user's back.
3833
3834 if (selected_tid != LLDB_INVALID_THREAD_ID)
3835 {
3836 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid))
3837 {
3838 // We were able to restore the selected thread, now restore the frame:
3839 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(selected_frame_sp.get());
3840 }
3841 }
3842
3843 return return_value;
3844}
3845
3846const char *
3847Process::ExecutionResultAsCString (ExecutionResults result)
3848{
3849 const char *result_name;
3850
3851 switch (result)
3852 {
Greg Claytonb3448432011-03-24 21:19:54 +00003853 case eExecutionCompleted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003854 result_name = "eExecutionCompleted";
3855 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003856 case eExecutionDiscarded:
Jim Ingham360f53f2010-11-30 02:22:11 +00003857 result_name = "eExecutionDiscarded";
3858 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003859 case eExecutionInterrupted:
Jim Ingham360f53f2010-11-30 02:22:11 +00003860 result_name = "eExecutionInterrupted";
3861 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003862 case eExecutionSetupError:
Jim Ingham360f53f2010-11-30 02:22:11 +00003863 result_name = "eExecutionSetupError";
3864 break;
Greg Claytonb3448432011-03-24 21:19:54 +00003865 case eExecutionTimedOut:
Jim Ingham360f53f2010-11-30 02:22:11 +00003866 result_name = "eExecutionTimedOut";
3867 break;
3868 }
3869 return result_name;
3870}
3871
Greg Claytonabe0fed2011-04-18 08:33:37 +00003872void
3873Process::GetStatus (Stream &strm)
3874{
3875 const StateType state = GetState();
3876 if (StateIsStoppedState(state))
3877 {
3878 if (state == eStateExited)
3879 {
3880 int exit_status = GetExitStatus();
3881 const char *exit_description = GetExitDescription();
3882 strm.Printf ("Process %d exited with status = %i (0x%8.8x) %s\n",
3883 GetID(),
3884 exit_status,
3885 exit_status,
3886 exit_description ? exit_description : "");
3887 }
3888 else
3889 {
3890 if (state == eStateConnected)
3891 strm.Printf ("Connected to remote target.\n");
3892 else
3893 strm.Printf ("Process %d %s\n", GetID(), StateAsCString (state));
3894 }
3895 }
3896 else
3897 {
3898 strm.Printf ("Process %d is running.\n", GetID());
3899 }
3900}
3901
3902size_t
3903Process::GetThreadStatus (Stream &strm,
3904 bool only_threads_with_stop_reason,
3905 uint32_t start_frame,
3906 uint32_t num_frames,
3907 uint32_t num_frames_with_source)
3908{
3909 size_t num_thread_infos_dumped = 0;
3910
3911 const size_t num_threads = GetThreadList().GetSize();
3912 for (uint32_t i = 0; i < num_threads; i++)
3913 {
3914 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
3915 if (thread)
3916 {
3917 if (only_threads_with_stop_reason)
3918 {
3919 if (thread->GetStopInfo().get() == NULL)
3920 continue;
3921 }
3922 thread->GetStatus (strm,
3923 start_frame,
3924 num_frames,
3925 num_frames_with_source);
3926 ++num_thread_infos_dumped;
3927 }
3928 }
3929 return num_thread_infos_dumped;
3930}
3931
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003932//--------------------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00003933// class Process::SettingsController
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003934//--------------------------------------------------------------
3935
Greg Claytond0a5a232010-09-19 02:33:57 +00003936Process::SettingsController::SettingsController () :
Caroline Tice5bc8c972010-09-20 20:44:43 +00003937 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003938{
Greg Clayton638351a2010-12-04 00:10:17 +00003939 m_default_settings.reset (new ProcessInstanceSettings (*this,
3940 false,
Caroline Tice004afcb2010-09-08 17:48:55 +00003941 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003942}
3943
Greg Claytond0a5a232010-09-19 02:33:57 +00003944Process::SettingsController::~SettingsController ()
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003945{
3946}
3947
3948lldb::InstanceSettingsSP
Greg Claytond0a5a232010-09-19 02:33:57 +00003949Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003950{
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003951 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
3952 false,
3953 instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003954 lldb::InstanceSettingsSP new_settings_sp (new_settings);
3955 return new_settings_sp;
3956}
3957
3958//--------------------------------------------------------------
3959// class ProcessInstanceSettings
3960//--------------------------------------------------------------
3961
Greg Clayton638351a2010-12-04 00:10:17 +00003962ProcessInstanceSettings::ProcessInstanceSettings
3963(
3964 UserSettingsController &owner,
3965 bool live_instance,
3966 const char *name
3967) :
3968 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003969 m_run_args (),
3970 m_env_vars (),
3971 m_input_path (),
3972 m_output_path (),
3973 m_error_path (),
Caroline Ticebd666012010-12-03 18:46:09 +00003974 m_disable_aslr (true),
Greg Clayton638351a2010-12-04 00:10:17 +00003975 m_disable_stdio (false),
3976 m_inherit_host_env (true),
3977 m_got_host_env (false)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003978{
Caroline Tice396704b2010-09-09 18:26:37 +00003979 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
3980 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
3981 // 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 +00003982 // This is true for CreateInstanceName() too.
3983
3984 if (GetInstanceName () == InstanceSettings::InvalidName())
3985 {
3986 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
3987 m_owner.RegisterInstanceSettings (this);
3988 }
Caroline Tice396704b2010-09-09 18:26:37 +00003989
3990 if (live_instance)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003991 {
3992 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
3993 CopyInstanceSettings (pending_settings,false);
Caroline Tice396704b2010-09-09 18:26:37 +00003994 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00003995 }
3996}
3997
3998ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytonc0c1b0c2010-11-19 03:46:01 +00003999 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004000 m_run_args (rhs.m_run_args),
4001 m_env_vars (rhs.m_env_vars),
4002 m_input_path (rhs.m_input_path),
4003 m_output_path (rhs.m_output_path),
4004 m_error_path (rhs.m_error_path),
Caroline Ticebd666012010-12-03 18:46:09 +00004005 m_disable_aslr (rhs.m_disable_aslr),
4006 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004007{
4008 if (m_instance_name != InstanceSettings::GetDefaultName())
4009 {
4010 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4011 CopyInstanceSettings (pending_settings,false);
4012 m_owner.RemovePendingSettings (m_instance_name);
4013 }
4014}
4015
4016ProcessInstanceSettings::~ProcessInstanceSettings ()
4017{
4018}
4019
4020ProcessInstanceSettings&
4021ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4022{
4023 if (this != &rhs)
4024 {
4025 m_run_args = rhs.m_run_args;
4026 m_env_vars = rhs.m_env_vars;
4027 m_input_path = rhs.m_input_path;
4028 m_output_path = rhs.m_output_path;
4029 m_error_path = rhs.m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004030 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00004031 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton638351a2010-12-04 00:10:17 +00004032 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004033 }
4034
4035 return *this;
4036}
4037
4038
4039void
4040ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4041 const char *index_value,
4042 const char *value,
4043 const ConstString &instance_name,
4044 const SettingEntry &entry,
Greg Claytonb3448432011-03-24 21:19:54 +00004045 VarSetOperationType op,
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004046 Error &err,
4047 bool pending)
4048{
4049 if (var_name == RunArgsVarName())
4050 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
4051 else if (var_name == EnvVarsVarName())
Greg Clayton638351a2010-12-04 00:10:17 +00004052 {
Greg Claytonb72d0f02011-04-12 05:54:46 +00004053 // This is nice for local debugging, but it is isn't correct for
4054 // remote debugging. We need to stop process.env-vars from being
4055 // populated with the host environment and add this as a launch option
4056 // and get the correct environment from the Target's platform.
4057 // GetHostEnvironmentIfNeeded ();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004058 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton638351a2010-12-04 00:10:17 +00004059 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004060 else if (var_name == InputPathVarName())
4061 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
4062 else if (var_name == OutputPathVarName())
4063 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
4064 else if (var_name == ErrorPathVarName())
4065 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004066 else if (var_name == DisableASLRVarName())
Greg Clayton17cd9952011-04-22 03:55:06 +00004067 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, true, err);
Caroline Ticebd666012010-12-03 18:46:09 +00004068 else if (var_name == DisableSTDIOVarName ())
Greg Clayton17cd9952011-04-22 03:55:06 +00004069 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, false, err);
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004070}
4071
4072void
4073ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4074 bool pending)
4075{
4076 if (new_settings.get() == NULL)
4077 return;
4078
4079 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
4080
4081 m_run_args = new_process_settings->m_run_args;
4082 m_env_vars = new_process_settings->m_env_vars;
4083 m_input_path = new_process_settings->m_input_path;
4084 m_output_path = new_process_settings->m_output_path;
4085 m_error_path = new_process_settings->m_error_path;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004086 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticebd666012010-12-03 18:46:09 +00004087 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004088}
4089
Caroline Ticebcb5b452010-09-20 21:37:42 +00004090bool
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004091ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4092 const ConstString &var_name,
Caroline Tice5bc8c972010-09-20 20:44:43 +00004093 StringList &value,
Caroline Ticebcb5b452010-09-20 21:37:42 +00004094 Error *err)
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004095{
4096 if (var_name == RunArgsVarName())
4097 {
4098 if (m_run_args.GetArgumentCount() > 0)
Greg Claytonc14069e2010-09-14 03:47:41 +00004099 {
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004100 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
4101 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytonc14069e2010-09-14 03:47:41 +00004102 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004103 }
4104 else if (var_name == EnvVarsVarName())
4105 {
Greg Clayton638351a2010-12-04 00:10:17 +00004106 GetHostEnvironmentIfNeeded ();
4107
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004108 if (m_env_vars.size() > 0)
4109 {
4110 std::map<std::string, std::string>::iterator pos;
4111 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
4112 {
4113 StreamString value_str;
4114 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
4115 value.AppendString (value_str.GetData());
4116 }
4117 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004118 }
4119 else if (var_name == InputPathVarName())
4120 {
4121 value.AppendString (m_input_path.c_str());
4122 }
4123 else if (var_name == OutputPathVarName())
4124 {
4125 value.AppendString (m_output_path.c_str());
4126 }
4127 else if (var_name == ErrorPathVarName())
4128 {
4129 value.AppendString (m_error_path.c_str());
4130 }
Greg Claytona99b0bf2010-12-04 00:12:24 +00004131 else if (var_name == InheritHostEnvVarName())
4132 {
4133 if (m_inherit_host_env)
4134 value.AppendString ("true");
4135 else
4136 value.AppendString ("false");
4137 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004138 else if (var_name == DisableASLRVarName())
4139 {
4140 if (m_disable_aslr)
4141 value.AppendString ("true");
4142 else
4143 value.AppendString ("false");
4144 }
Caroline Ticebd666012010-12-03 18:46:09 +00004145 else if (var_name == DisableSTDIOVarName())
4146 {
4147 if (m_disable_stdio)
4148 value.AppendString ("true");
4149 else
4150 value.AppendString ("false");
4151 }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004152 else
Caroline Ticebcb5b452010-09-20 21:37:42 +00004153 {
4154 if (err)
4155 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4156 return false;
4157 }
4158 return true;
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004159}
4160
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004161const ConstString
4162ProcessInstanceSettings::CreateInstanceName ()
4163{
4164 static int instance_count = 1;
4165 StreamString sstr;
4166
4167 sstr.Printf ("process_%d", instance_count);
4168 ++instance_count;
4169
4170 const ConstString ret_val (sstr.GetData());
4171 return ret_val;
4172}
4173
4174const ConstString &
4175ProcessInstanceSettings::RunArgsVarName ()
4176{
4177 static ConstString run_args_var_name ("run-args");
4178
4179 return run_args_var_name;
4180}
4181
4182const ConstString &
4183ProcessInstanceSettings::EnvVarsVarName ()
4184{
4185 static ConstString env_vars_var_name ("env-vars");
4186
4187 return env_vars_var_name;
4188}
4189
4190const ConstString &
Greg Clayton638351a2010-12-04 00:10:17 +00004191ProcessInstanceSettings::InheritHostEnvVarName ()
4192{
4193 static ConstString g_name ("inherit-env");
4194
4195 return g_name;
4196}
4197
4198const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004199ProcessInstanceSettings::InputPathVarName ()
4200{
4201 static ConstString input_path_var_name ("input-path");
4202
4203 return input_path_var_name;
4204}
4205
4206const ConstString &
4207ProcessInstanceSettings::OutputPathVarName ()
4208{
Caroline Tice87097232010-09-07 18:35:40 +00004209 static ConstString output_path_var_name ("output-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004210
4211 return output_path_var_name;
4212}
4213
4214const ConstString &
4215ProcessInstanceSettings::ErrorPathVarName ()
4216{
Caroline Tice87097232010-09-07 18:35:40 +00004217 static ConstString error_path_var_name ("error-path");
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004218
4219 return error_path_var_name;
4220}
4221
4222const ConstString &
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004223ProcessInstanceSettings::DisableASLRVarName ()
4224{
4225 static ConstString disable_aslr_var_name ("disable-aslr");
4226
4227 return disable_aslr_var_name;
4228}
4229
Caroline Ticebd666012010-12-03 18:46:09 +00004230const ConstString &
4231ProcessInstanceSettings::DisableSTDIOVarName ()
4232{
4233 static ConstString disable_stdio_var_name ("disable-stdio");
4234
4235 return disable_stdio_var_name;
4236}
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004237
4238//--------------------------------------------------
Greg Claytond0a5a232010-09-19 02:33:57 +00004239// SettingsController Variable Tables
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004240//--------------------------------------------------
4241
4242SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004243Process::SettingsController::global_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004244{
4245 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4246 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4247};
4248
4249
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004250SettingEntry
Greg Claytond0a5a232010-09-19 02:33:57 +00004251Process::SettingsController::instance_settings_table[] =
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004252{
Greg Clayton638351a2010-12-04 00:10:17 +00004253 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
4254 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
4255 { "env-vars", eSetVarTypeDictionary, NULL, NULL, false, false, "A list of all the environment variables to be passed to the executable's environment, and their values." },
4256 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonde915be2011-01-23 05:56:20 +00004257 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
4258 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
4259 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
Greg Claytond284b662011-02-18 01:44:25 +00004260 { "plugin", eSetVarTypeEnum, NULL, NULL, false, false, "The plugin to be used to run the process." },
Greg Clayton638351a2010-12-04 00:10:17 +00004261 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
4262 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
4263 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice6e4c5ce2010-09-04 00:03:46 +00004264};
4265
4266
Jim Ingham7508e732010-08-09 23:31:02 +00004267