blob: 671084de4243c5949ebe46b913869054f977db67 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Process.cpp ---------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/Target/Process.h"
11
12#include "lldb/lldb-private-log.h"
13
14#include "lldb/Breakpoint/StoppointCallbackContext.h"
15#include "lldb/Breakpoint/BreakpointLocation.h"
16#include "lldb/Core/Event.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000017#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/Debugger.h"
Caroline Ticeef5c6d02010-11-16 05:07:41 +000019#include "lldb/Core/InputReader.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
21#include "lldb/Core/PluginManager.h"
22#include "lldb/Core/State.h"
Greg Claytoneb0103f2011-04-07 22:46:35 +000023#include "lldb/Expression/ClangUserExpression.h"
Caroline Tice3df9a8d2010-09-04 00:03:46 +000024#include "lldb/Interpreter/CommandInterpreter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Host/Host.h"
26#include "lldb/Target/ABI.h"
Greg Clayton8f343b02010-11-04 01:54:29 +000027#include "lldb/Target/DynamicLoader.h"
Greg Clayton56d9a1b2011-08-22 02:49:39 +000028#include "lldb/Target/OperatingSystem.h"
Jim Ingham22777012010-09-23 02:01:19 +000029#include "lldb/Target/LanguageRuntime.h"
30#include "lldb/Target/CPPLanguageRuntime.h"
31#include "lldb/Target/ObjCLanguageRuntime.h"
Greg Claytone996fd32011-03-08 22:40:15 +000032#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033#include "lldb/Target/RegisterContext.h"
Greg Claytonf4b47e12010-08-04 01:40:35 +000034#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Target/Target.h"
36#include "lldb/Target/TargetList.h"
37#include "lldb/Target/Thread.h"
38#include "lldb/Target/ThreadPlan.h"
39
40using namespace lldb;
41using namespace lldb_private;
42
Greg Clayton32e0a752011-03-30 18:16:51 +000043void
Greg Clayton8b82f082011-04-12 05:54:46 +000044ProcessInstanceInfo::Dump (Stream &s, Platform *platform) const
Greg Clayton32e0a752011-03-30 18:16:51 +000045{
46 const char *cstr;
Greg Clayton95bf0fd2011-04-01 00:29:43 +000047 if (m_pid != LLDB_INVALID_PROCESS_ID)
48 s.Printf (" pid = %i\n", m_pid);
49
50 if (m_parent_pid != LLDB_INVALID_PROCESS_ID)
51 s.Printf (" parent = %i\n", m_parent_pid);
52
53 if (m_executable)
54 {
55 s.Printf (" name = %s\n", m_executable.GetFilename().GetCString());
56 s.PutCString (" file = ");
57 m_executable.Dump(&s);
58 s.EOL();
59 }
Greg Clayton8b82f082011-04-12 05:54:46 +000060 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +000061 if (argc > 0)
62 {
63 for (uint32_t i=0; i<argc; i++)
64 {
Greg Clayton8b82f082011-04-12 05:54:46 +000065 const char *arg = m_arguments.GetArgumentAtIndex(i);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000066 if (i < 10)
Greg Clayton8b82f082011-04-12 05:54:46 +000067 s.Printf (" arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000068 else
Greg Clayton8b82f082011-04-12 05:54:46 +000069 s.Printf ("arg[%u] = %s\n", i, arg);
Greg Clayton95bf0fd2011-04-01 00:29:43 +000070 }
71 }
Greg Clayton8b82f082011-04-12 05:54:46 +000072
73 const uint32_t envc = m_environment.GetArgumentCount();
74 if (envc > 0)
75 {
76 for (uint32_t i=0; i<envc; i++)
77 {
78 const char *env = m_environment.GetArgumentAtIndex(i);
79 if (i < 10)
80 s.Printf (" env[%u] = %s\n", i, env);
81 else
82 s.Printf ("env[%u] = %s\n", i, env);
83 }
84 }
85
Greg Clayton95bf0fd2011-04-01 00:29:43 +000086 if (m_arch.IsValid())
87 s.Printf (" arch = %s\n", m_arch.GetTriple().str().c_str());
88
Greg Clayton8b82f082011-04-12 05:54:46 +000089 if (m_uid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000090 {
Greg Clayton8b82f082011-04-12 05:54:46 +000091 cstr = platform->GetUserName (m_uid);
92 s.Printf (" uid = %-5u (%s)\n", m_uid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000093 }
Greg Clayton8b82f082011-04-12 05:54:46 +000094 if (m_gid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +000095 {
Greg Clayton8b82f082011-04-12 05:54:46 +000096 cstr = platform->GetGroupName (m_gid);
97 s.Printf (" gid = %-5u (%s)\n", m_gid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +000098 }
Greg Clayton8b82f082011-04-12 05:54:46 +000099 if (m_euid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000100 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000101 cstr = platform->GetUserName (m_euid);
102 s.Printf (" euid = %-5u (%s)\n", m_euid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000103 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000104 if (m_egid != UINT32_MAX)
Greg Clayton32e0a752011-03-30 18:16:51 +0000105 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000106 cstr = platform->GetGroupName (m_egid);
107 s.Printf (" egid = %-5u (%s)\n", m_egid, cstr ? cstr : "");
Greg Clayton32e0a752011-03-30 18:16:51 +0000108 }
109}
110
111void
Greg Clayton8b82f082011-04-12 05:54:46 +0000112ProcessInstanceInfo::DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose)
Greg Clayton32e0a752011-03-30 18:16:51 +0000113{
Greg Clayton8b82f082011-04-12 05:54:46 +0000114 const char *label;
115 if (show_args || verbose)
116 label = "ARGUMENTS";
117 else
118 label = "NAME";
119
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000120 if (verbose)
121 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000122 s.Printf ("PID PARENT USER GROUP EFF USER EFF GROUP TRIPLE %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000123 s.PutCString ("====== ====== ========== ========== ========== ========== ======================== ============================\n");
124 }
125 else
126 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000127 s.Printf ("PID PARENT USER ARCH %s\n", label);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000128 s.PutCString ("====== ====== ========== ======= ============================\n");
129 }
Greg Clayton32e0a752011-03-30 18:16:51 +0000130}
131
132void
Greg Clayton8b82f082011-04-12 05:54:46 +0000133ProcessInstanceInfo::DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000134{
135 if (m_pid != LLDB_INVALID_PROCESS_ID)
136 {
137 const char *cstr;
138 s.Printf ("%-6u %-6u ", m_pid, m_parent_pid);
139
Greg Clayton32e0a752011-03-30 18:16:51 +0000140
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000141 if (verbose)
142 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000143 cstr = platform->GetUserName (m_uid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000144 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
145 s.Printf ("%-10s ", cstr);
146 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000147 s.Printf ("%-10u ", m_uid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000148
Greg Clayton8b82f082011-04-12 05:54:46 +0000149 cstr = platform->GetGroupName (m_gid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000150 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
151 s.Printf ("%-10s ", cstr);
152 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000153 s.Printf ("%-10u ", m_gid);
Greg Clayton32e0a752011-03-30 18:16:51 +0000154
Greg Clayton8b82f082011-04-12 05:54:46 +0000155 cstr = platform->GetUserName (m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000156 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
157 s.Printf ("%-10s ", cstr);
158 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000159 s.Printf ("%-10u ", m_euid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000160
Greg Clayton8b82f082011-04-12 05:54:46 +0000161 cstr = platform->GetGroupName (m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000162 if (cstr && cstr[0]) // Watch for empty string that indicates lookup failed
163 s.Printf ("%-10s ", cstr);
164 else
Greg Clayton8b82f082011-04-12 05:54:46 +0000165 s.Printf ("%-10u ", m_egid);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000166 s.Printf ("%-24s ", m_arch.IsValid() ? m_arch.GetTriple().str().c_str() : "");
167 }
168 else
169 {
Jason Molendafd54b362011-09-20 21:44:10 +0000170 s.Printf ("%-10s %-7d %s ",
Greg Clayton8b82f082011-04-12 05:54:46 +0000171 platform->GetUserName (m_euid),
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000172 (int)m_arch.GetTriple().getArchName().size(),
173 m_arch.GetTriple().getArchName().data());
174 }
175
Greg Clayton8b82f082011-04-12 05:54:46 +0000176 if (verbose || show_args)
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000177 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000178 const uint32_t argc = m_arguments.GetArgumentCount();
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000179 if (argc > 0)
180 {
181 for (uint32_t i=0; i<argc; i++)
182 {
183 if (i > 0)
184 s.PutChar (' ');
Greg Clayton8b82f082011-04-12 05:54:46 +0000185 s.PutCString (m_arguments.GetArgumentAtIndex(i));
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000186 }
187 }
188 }
189 else
190 {
191 s.PutCString (GetName());
192 }
193
194 s.EOL();
Greg Clayton32e0a752011-03-30 18:16:51 +0000195 }
196}
197
Greg Clayton8b82f082011-04-12 05:54:46 +0000198
199void
200ProcessInfo::SetArgumentsFromArgs (const Args& args,
201 bool first_arg_is_executable,
202 bool first_arg_is_executable_and_argument)
203{
204 // Copy all arguments
205 m_arguments = args;
206
207 // Is the first argument the executable?
208 if (first_arg_is_executable)
209 {
210 const char *first_arg = args.GetArgumentAtIndex (0);
211 if (first_arg)
212 {
213 // Yes the first argument is an executable, set it as the executable
214 // in the launch options. Don't resolve the file path as the path
215 // could be a remote platform path
216 const bool resolve = false;
217 m_executable.SetFile(first_arg, resolve);
218
219 // If argument zero is an executable and shouldn't be included
220 // in the arguments, remove it from the front of the arguments
221 if (first_arg_is_executable_and_argument == false)
222 m_arguments.DeleteArgumentAtIndex (0);
223 }
224 }
225}
226
Greg Clayton32e0a752011-03-30 18:16:51 +0000227bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000228ProcessLaunchInfo::FileAction::Open (int fd, const char *path, bool read, bool write)
229{
230 if ((read || write) && fd >= 0 && path && path[0])
231 {
232 m_action = eFileActionOpen;
233 m_fd = fd;
234 if (read && write)
235 m_arg = O_RDWR;
236 else if (read)
237 m_arg = O_RDONLY;
238 else
239 m_arg = O_WRONLY;
240 m_path.assign (path);
241 return true;
242 }
243 else
244 {
245 Clear();
246 }
247 return false;
248}
249
250bool
251ProcessLaunchInfo::FileAction::Close (int fd)
252{
253 Clear();
254 if (fd >= 0)
255 {
256 m_action = eFileActionClose;
257 m_fd = fd;
258 }
259 return m_fd >= 0;
260}
261
262
263bool
264ProcessLaunchInfo::FileAction::Duplicate (int fd, int dup_fd)
265{
266 Clear();
267 if (fd >= 0 && dup_fd >= 0)
268 {
269 m_action = eFileActionDuplicate;
270 m_fd = fd;
271 m_arg = dup_fd;
272 }
273 return m_fd >= 0;
274}
275
276
277
278bool
279ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (posix_spawn_file_actions_t *file_actions,
280 const FileAction *info,
281 Log *log,
282 Error& error)
283{
284 if (info == NULL)
285 return false;
286
287 switch (info->m_action)
288 {
289 case eFileActionNone:
290 error.Clear();
291 break;
292
293 case eFileActionClose:
294 if (info->m_fd == -1)
295 error.SetErrorString ("invalid fd for posix_spawn_file_actions_addclose(...)");
296 else
297 {
298 error.SetError (::posix_spawn_file_actions_addclose (file_actions, info->m_fd),
299 eErrorTypePOSIX);
300 if (log && (error.Fail() || log))
301 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
302 file_actions, info->m_fd);
303 }
304 break;
305
306 case eFileActionDuplicate:
307 if (info->m_fd == -1)
308 error.SetErrorString ("invalid fd for posix_spawn_file_actions_adddup2(...)");
309 else if (info->m_arg == -1)
310 error.SetErrorString ("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
311 else
312 {
313 error.SetError (::posix_spawn_file_actions_adddup2 (file_actions, info->m_fd, info->m_arg),
314 eErrorTypePOSIX);
315 if (log && (error.Fail() || log))
316 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
317 file_actions, info->m_fd, info->m_arg);
318 }
319 break;
320
321 case eFileActionOpen:
322 if (info->m_fd == -1)
323 error.SetErrorString ("invalid fd in posix_spawn_file_actions_addopen(...)");
324 else
325 {
326 int oflag = info->m_arg;
327 mode_t mode = 0;
328
329 error.SetError (::posix_spawn_file_actions_addopen (file_actions,
330 info->m_fd,
331 info->m_path.c_str(),
332 oflag,
333 mode),
334 eErrorTypePOSIX);
335 if (error.Fail() || log)
336 error.PutToLog(log,
337 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
338 file_actions, info->m_fd, info->m_path.c_str(), oflag, mode);
339 }
340 break;
341
342 default:
343 error.SetErrorStringWithFormat ("invalid file action: %i", info->m_action);
344 break;
345 }
346 return error.Success();
347}
348
349Error
Greg Claytonf6b8b582011-04-13 00:18:08 +0000350ProcessLaunchCommandOptions::SetOptionValue (uint32_t option_idx, const char *option_arg)
Greg Clayton8b82f082011-04-12 05:54:46 +0000351{
352 Error error;
353 char short_option = (char) m_getopt_table[option_idx].val;
354
355 switch (short_option)
356 {
357 case 's': // Stop at program entry point
358 launch_info.GetFlags().Set (eLaunchFlagStopAtEntry);
359 break;
360
361 case 'e': // STDERR for read + write
362 {
363 ProcessLaunchInfo::FileAction action;
364 if (action.Open(STDERR_FILENO, option_arg, true, true))
365 launch_info.AppendFileAction (action);
366 }
367 break;
368
369 case 'i': // STDIN for read only
370 {
371 ProcessLaunchInfo::FileAction action;
372 if (action.Open(STDIN_FILENO, option_arg, true, false))
373 launch_info.AppendFileAction (action);
374 }
375 break;
376
377 case 'o': // Open STDOUT for write only
378 {
379 ProcessLaunchInfo::FileAction action;
380 if (action.Open(STDOUT_FILENO, option_arg, false, true))
381 launch_info.AppendFileAction (action);
382 }
383 break;
384
385 case 'p': // Process plug-in name
386 launch_info.SetProcessPluginName (option_arg);
387 break;
388
389 case 'n': // Disable STDIO
390 {
391 ProcessLaunchInfo::FileAction action;
392 if (action.Open(STDERR_FILENO, "/dev/null", true, true))
393 launch_info.AppendFileAction (action);
394 if (action.Open(STDOUT_FILENO, "/dev/null", false, true))
395 launch_info.AppendFileAction (action);
396 if (action.Open(STDIN_FILENO, "/dev/null", true, false))
397 launch_info.AppendFileAction (action);
398 }
399 break;
400
401 case 'w':
402 launch_info.SetWorkingDirectory (option_arg);
403 break;
404
405 case 't': // Open process in new terminal window
406 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
407 break;
408
409 case 'a':
410 launch_info.GetArchitecture().SetTriple (option_arg,
411 m_interpreter.GetPlatform(true).get());
412 break;
413
414 case 'A':
415 launch_info.GetFlags().Set (eLaunchFlagDisableASLR);
416 break;
417
418 case 'v':
419 launch_info.GetEnvironmentEntries().AppendArgument(option_arg);
420 break;
421
422 default:
Greg Clayton86edbf42011-10-26 00:56:27 +0000423 error.SetErrorStringWithFormat("unrecognized short option character '%c'", short_option);
Greg Clayton8b82f082011-04-12 05:54:46 +0000424 break;
425
426 }
427 return error;
428}
429
430OptionDefinition
431ProcessLaunchCommandOptions::g_option_table[] =
432{
433{ 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."},
434{ LLDB_OPT_SET_ALL, false, "disable-aslr", 'A', no_argument, NULL, 0, eArgTypeNone, "Disable address space layout randomization when launching a process."},
435{ LLDB_OPT_SET_ALL, false, "plugin", 'p', required_argument, NULL, 0, eArgTypePlugin, "Name of the process plugin you want to use."},
436{ LLDB_OPT_SET_ALL, false, "working-dir", 'w', required_argument, NULL, 0, eArgTypePath, "Set the current working directory to <path> when running the inferior."},
437{ LLDB_OPT_SET_ALL, false, "arch", 'a', required_argument, NULL, 0, eArgTypeArchitecture, "Set the architecture for the process to launch when ambiguous."},
438{ 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."},
439
440{ LLDB_OPT_SET_1 , false, "stdin", 'i', required_argument, NULL, 0, eArgTypePath, "Redirect stdin for the process to <path>."},
441{ LLDB_OPT_SET_1 , false, "stdout", 'o', required_argument, NULL, 0, eArgTypePath, "Redirect stdout for the process to <path>."},
442{ LLDB_OPT_SET_1 , false, "stderr", 'e', required_argument, NULL, 0, eArgTypePath, "Redirect stderr for the process to <path>."},
443
444{ LLDB_OPT_SET_2 , false, "tty", 't', no_argument, NULL, 0, eArgTypeNone, "Start the process in a terminal (not supported on all platforms)."},
445
446{ 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."},
447
448{ 0 , false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
449};
450
451
452
453bool
454ProcessInstanceInfoMatch::NameMatches (const char *process_name) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000455{
456 if (m_name_match_type == eNameMatchIgnore || process_name == NULL)
457 return true;
458 const char *match_name = m_match_info.GetName();
459 if (!match_name)
460 return true;
461
462 return lldb_private::NameMatches (process_name, m_name_match_type, match_name);
463}
464
465bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000466ProcessInstanceInfoMatch::Matches (const ProcessInstanceInfo &proc_info) const
Greg Clayton32e0a752011-03-30 18:16:51 +0000467{
468 if (!NameMatches (proc_info.GetName()))
469 return false;
470
471 if (m_match_info.ProcessIDIsValid() &&
472 m_match_info.GetProcessID() != proc_info.GetProcessID())
473 return false;
474
475 if (m_match_info.ParentProcessIDIsValid() &&
476 m_match_info.GetParentProcessID() != proc_info.GetParentProcessID())
477 return false;
478
Greg Clayton8b82f082011-04-12 05:54:46 +0000479 if (m_match_info.UserIDIsValid () &&
480 m_match_info.GetUserID() != proc_info.GetUserID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000481 return false;
482
Greg Clayton8b82f082011-04-12 05:54:46 +0000483 if (m_match_info.GroupIDIsValid () &&
484 m_match_info.GetGroupID() != proc_info.GetGroupID())
Greg Clayton32e0a752011-03-30 18:16:51 +0000485 return false;
486
487 if (m_match_info.EffectiveUserIDIsValid () &&
488 m_match_info.GetEffectiveUserID() != proc_info.GetEffectiveUserID())
489 return false;
490
491 if (m_match_info.EffectiveGroupIDIsValid () &&
492 m_match_info.GetEffectiveGroupID() != proc_info.GetEffectiveGroupID())
493 return false;
494
495 if (m_match_info.GetArchitecture().IsValid() &&
496 m_match_info.GetArchitecture() != proc_info.GetArchitecture())
497 return false;
498 return true;
499}
500
501bool
Greg Clayton8b82f082011-04-12 05:54:46 +0000502ProcessInstanceInfoMatch::MatchAllProcesses () const
Greg Clayton32e0a752011-03-30 18:16:51 +0000503{
504 if (m_name_match_type != eNameMatchIgnore)
505 return false;
506
507 if (m_match_info.ProcessIDIsValid())
508 return false;
509
510 if (m_match_info.ParentProcessIDIsValid())
511 return false;
512
Greg Clayton8b82f082011-04-12 05:54:46 +0000513 if (m_match_info.UserIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000514 return false;
515
Greg Clayton8b82f082011-04-12 05:54:46 +0000516 if (m_match_info.GroupIDIsValid ())
Greg Clayton32e0a752011-03-30 18:16:51 +0000517 return false;
518
519 if (m_match_info.EffectiveUserIDIsValid ())
520 return false;
521
522 if (m_match_info.EffectiveGroupIDIsValid ())
523 return false;
524
525 if (m_match_info.GetArchitecture().IsValid())
526 return false;
527
528 if (m_match_all_users)
529 return false;
530
531 return true;
532
533}
534
535void
Greg Clayton8b82f082011-04-12 05:54:46 +0000536ProcessInstanceInfoMatch::Clear()
Greg Clayton32e0a752011-03-30 18:16:51 +0000537{
538 m_match_info.Clear();
539 m_name_match_type = eNameMatchIgnore;
540 m_match_all_users = false;
541}
Greg Clayton58be07b2011-01-07 06:08:19 +0000542
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000543Process*
544Process::FindPlugin (Target &target, const char *plugin_name, Listener &listener)
545{
546 ProcessCreateInstance create_callback = NULL;
547 if (plugin_name)
548 {
549 create_callback = PluginManager::GetProcessCreateCallbackForPluginName (plugin_name);
550 if (create_callback)
551 {
552 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000553 if (debugger_ap->CanDebug(target, true))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000554 return debugger_ap.release();
555 }
556 }
557 else
558 {
Greg Claytonc982c762010-07-09 20:39:50 +0000559 for (uint32_t idx = 0; (create_callback = PluginManager::GetProcessCreateCallbackAtIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000560 {
Greg Claytonc982c762010-07-09 20:39:50 +0000561 std::auto_ptr<Process> debugger_ap(create_callback(target, listener));
Greg Clayton3a29bdb2011-07-17 20:36:25 +0000562 if (debugger_ap->CanDebug(target, false))
Greg Claytonc982c762010-07-09 20:39:50 +0000563 return debugger_ap.release();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000564 }
565 }
566 return NULL;
567}
568
569
570//----------------------------------------------------------------------
571// Process constructor
572//----------------------------------------------------------------------
573Process::Process(Target &target, Listener &listener) :
574 UserID (LLDB_INVALID_PROCESS_ID),
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000575 Broadcaster ("lldb.process"),
Greg Claytondbe54502010-11-19 03:46:01 +0000576 ProcessInstanceSettings (*GetSettingsController()),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000577 m_target (target),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000578 m_public_state (eStateUnloaded),
579 m_private_state (eStateUnloaded),
580 m_private_state_broadcaster ("lldb.process.internal_state_broadcaster"),
581 m_private_state_control_broadcaster ("lldb.process.internal_state_control_broadcaster"),
582 m_private_state_listener ("lldb.process.internal_state_listener"),
583 m_private_state_control_wait(),
584 m_private_state_thread (LLDB_INVALID_HOST_THREAD),
Jim Ingham4b536182011-08-09 02:12:22 +0000585 m_mod_id (),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000586 m_thread_index_id (0),
587 m_exit_status (-1),
588 m_exit_string (),
589 m_thread_list (this),
590 m_notifications (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000591 m_image_tokens (),
592 m_listener (listener),
593 m_breakpoint_site_list (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000594 m_dynamic_checkers_ap (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000595 m_unix_signals (),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000596 m_abi_sp (),
Caroline Ticeef5c6d02010-11-16 05:07:41 +0000597 m_process_input_reader (),
Greg Clayton3e06bd92011-01-09 21:07:35 +0000598 m_stdio_communication ("process.stdio"),
Greg Clayton3af9ea52010-11-18 05:57:03 +0000599 m_stdio_communication_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton58be07b2011-01-07 06:08:19 +0000600 m_stdout_data (),
Greg Claytond495c532011-05-17 03:37:42 +0000601 m_memory_cache (*this),
602 m_allocated_memory_cache (*this),
Jim Ingham8314c522011-09-15 21:36:42 +0000603 m_attached_to_process (false),
Sean Callanan90539452011-09-20 23:01:51 +0000604 m_next_event_action_ap(),
605 m_can_jit(eCanJITYes)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000606{
Caroline Tice1559a462010-09-27 00:30:10 +0000607 UpdateInstanceName();
608
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000609 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000610 if (log)
611 log->Printf ("%p Process::Process()", this);
612
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000613 SetEventName (eBroadcastBitStateChanged, "state-changed");
614 SetEventName (eBroadcastBitInterrupt, "interrupt");
615 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
616 SetEventName (eBroadcastBitSTDERR, "stderr-available");
617
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 listener.StartListeningForEvents (this,
619 eBroadcastBitStateChanged |
620 eBroadcastBitInterrupt |
621 eBroadcastBitSTDOUT |
622 eBroadcastBitSTDERR);
623
624 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
625 eBroadcastBitStateChanged);
626
627 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
628 eBroadcastInternalStateControlStop |
629 eBroadcastInternalStateControlPause |
630 eBroadcastInternalStateControlResume);
631}
632
633//----------------------------------------------------------------------
634// Destructor
635//----------------------------------------------------------------------
636Process::~Process()
637{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000638 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639 if (log)
640 log->Printf ("%p Process::~Process()", this);
641 StopPrivateStateThread();
642}
643
644void
645Process::Finalize()
646{
Greg Clayton1ed54f52011-10-01 00:45:15 +0000647 // Clear our broadcaster before we proceed with destroying
648 Broadcaster::Clear();
649
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000650 // Do any cleanup needed prior to being destructed... Subclasses
651 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000652
653 // We need to destroy the loader before the derived Process class gets destroyed
654 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000655 m_dyld_ap.reset();
656 m_os_ap.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000657}
658
659void
660Process::RegisterNotificationCallbacks (const Notifications& callbacks)
661{
662 m_notifications.push_back(callbacks);
663 if (callbacks.initialize != NULL)
664 callbacks.initialize (callbacks.baton, this);
665}
666
667bool
668Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
669{
670 std::vector<Notifications>::iterator pos, end = m_notifications.end();
671 for (pos = m_notifications.begin(); pos != end; ++pos)
672 {
673 if (pos->baton == callbacks.baton &&
674 pos->initialize == callbacks.initialize &&
675 pos->process_state_changed == callbacks.process_state_changed)
676 {
677 m_notifications.erase(pos);
678 return true;
679 }
680 }
681 return false;
682}
683
684void
685Process::SynchronouslyNotifyStateChanged (StateType state)
686{
687 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
688 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
689 {
690 if (notification_pos->process_state_changed)
691 notification_pos->process_state_changed (notification_pos->baton, this, state);
692 }
693}
694
695// FIXME: We need to do some work on events before the general Listener sees them.
696// For instance if we are continuing from a breakpoint, we need to ensure that we do
697// the little "insert real insn, step & stop" trick. But we can't do that when the
698// event is delivered by the broadcaster - since that is done on the thread that is
699// waiting for new events, so if we needed more than one event for our handling, we would
700// stall. So instead we do it when we fetch the event off of the queue.
701//
702
703StateType
704Process::GetNextEvent (EventSP &event_sp)
705{
706 StateType state = eStateInvalid;
707
708 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
709 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
710
711 return state;
712}
713
714
715StateType
716Process::WaitForProcessToStop (const TimeValue *timeout)
717{
Jim Ingham4b536182011-08-09 02:12:22 +0000718 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
719 // We have to actually check each event, and in the case of a stopped event check the restarted flag
720 // on the event.
721 EventSP event_sp;
722 StateType state = GetState();
723 // If we are exited or detached, we won't ever get back to any
724 // other valid state...
725 if (state == eStateDetached || state == eStateExited)
726 return state;
727
728 while (state != eStateInvalid)
729 {
730 state = WaitForStateChangedEvents (timeout, event_sp);
731 switch (state)
732 {
733 case eStateCrashed:
734 case eStateDetached:
735 case eStateExited:
736 case eStateUnloaded:
737 return state;
738 case eStateStopped:
739 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
740 continue;
741 else
742 return state;
743 default:
744 continue;
745 }
746 }
747 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000748}
749
750
751StateType
752Process::WaitForState
753(
754 const TimeValue *timeout,
755 const StateType *match_states, const uint32_t num_match_states
756)
757{
758 EventSP event_sp;
759 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000760 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761 while (state != eStateInvalid)
762 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000763 // If we are exited or detached, we won't ever get back to any
764 // other valid state...
765 if (state == eStateDetached || state == eStateExited)
766 return state;
767
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000768 state = WaitForStateChangedEvents (timeout, event_sp);
769
770 for (i=0; i<num_match_states; ++i)
771 {
772 if (match_states[i] == state)
773 return state;
774 }
775 }
776 return state;
777}
778
Jim Ingham30f9b212010-10-11 23:53:14 +0000779bool
780Process::HijackProcessEvents (Listener *listener)
781{
782 if (listener != NULL)
783 {
784 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
785 }
786 else
787 return false;
788}
789
790void
791Process::RestoreProcessEvents ()
792{
793 RestoreBroadcaster();
794}
795
Jim Ingham0f16e732011-02-08 05:20:59 +0000796bool
797Process::HijackPrivateProcessEvents (Listener *listener)
798{
799 if (listener != NULL)
800 {
801 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
802 }
803 else
804 return false;
805}
806
807void
808Process::RestorePrivateProcessEvents ()
809{
810 m_private_state_broadcaster.RestoreBroadcaster();
811}
812
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813StateType
814Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
815{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000816 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000817
818 if (log)
819 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
820
821 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000822 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
823 this,
824 eBroadcastBitStateChanged,
825 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000826 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
827
828 if (log)
829 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
830 __FUNCTION__,
831 timeout,
832 StateAsCString(state));
833 return state;
834}
835
836Event *
837Process::PeekAtStateChangedEvents ()
838{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000839 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000840
841 if (log)
842 log->Printf ("Process::%s...", __FUNCTION__);
843
844 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000845 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
846 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000847 if (log)
848 {
849 if (event_ptr)
850 {
851 log->Printf ("Process::%s (event_ptr) => %s",
852 __FUNCTION__,
853 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
854 }
855 else
856 {
857 log->Printf ("Process::%s no events found",
858 __FUNCTION__);
859 }
860 }
861 return event_ptr;
862}
863
864StateType
865Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
866{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000867 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000868
869 if (log)
870 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
871
872 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +0000873 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
874 &m_private_state_broadcaster,
875 eBroadcastBitStateChanged,
876 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000877 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
878
879 // This is a bit of a hack, but when we wait here we could very well return
880 // to the command-line, and that could disable the log, which would render the
881 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000882 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +0000883 {
884 if (state == eStateInvalid)
885 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
886 else
887 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
888 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000889 return state;
890}
891
892bool
893Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
894{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000895 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000896
897 if (log)
898 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
899
900 if (control_only)
901 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
902 else
903 return m_private_state_listener.WaitForEvent(timeout, event_sp);
904}
905
906bool
907Process::IsRunning () const
908{
909 return StateIsRunningState (m_public_state.GetValue());
910}
911
912int
913Process::GetExitStatus ()
914{
915 if (m_public_state.GetValue() == eStateExited)
916 return m_exit_status;
917 return -1;
918}
919
Greg Clayton85851dd2010-12-04 00:10:17 +0000920
921void
922Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
923{
924 if (m_inherit_host_env && !m_got_host_env)
925 {
926 m_got_host_env = true;
927 StringList host_env;
928 const size_t host_env_count = Host::GetEnvironment (host_env);
929 for (size_t idx=0; idx<host_env_count; idx++)
930 {
931 const char *env_entry = host_env.GetStringAtIndex (idx);
932 if (env_entry)
933 {
Greg Claytone2956ee2010-12-15 20:52:40 +0000934 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton85851dd2010-12-04 00:10:17 +0000935 if (equal_pos)
936 {
937 std::string key (env_entry, equal_pos - env_entry);
938 std::string value (equal_pos + 1);
939 if (m_env_vars.find (key) == m_env_vars.end())
940 m_env_vars[key] = value;
941 }
942 }
943 }
944 }
945}
946
947
948size_t
949Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
950{
951 GetHostEnvironmentIfNeeded ();
952
953 dictionary::const_iterator pos, end = m_env_vars.end();
954 for (pos = m_env_vars.begin(); pos != end; ++pos)
955 {
956 std::string env_var_equal_value (pos->first);
957 env_var_equal_value.append(1, '=');
958 env_var_equal_value.append (pos->second);
959 env.AppendArgument (env_var_equal_value.c_str());
960 }
961 return env.GetArgumentCount();
962}
963
964
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000965const char *
966Process::GetExitDescription ()
967{
968 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
969 return m_exit_string.c_str();
970 return NULL;
971}
972
Greg Clayton6779606a2011-01-22 23:43:18 +0000973bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000974Process::SetExitStatus (int status, const char *cstr)
975{
Greg Clayton414f5d32011-01-25 02:58:48 +0000976 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
977 if (log)
978 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
979 status, status,
980 cstr ? "\"" : "",
981 cstr ? cstr : "NULL",
982 cstr ? "\"" : "");
983
Greg Clayton6779606a2011-01-22 23:43:18 +0000984 // We were already in the exited state
985 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +0000986 {
Greg Clayton385d6032011-01-26 23:47:29 +0000987 if (log)
988 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +0000989 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +0000990 }
Greg Clayton6779606a2011-01-22 23:43:18 +0000991
992 m_exit_status = status;
993 if (cstr)
994 m_exit_string = cstr;
995 else
996 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997
Greg Clayton6779606a2011-01-22 23:43:18 +0000998 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +0000999
Greg Clayton6779606a2011-01-22 23:43:18 +00001000 SetPrivateState (eStateExited);
1001 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002}
1003
1004// This static callback can be used to watch for local child processes on
1005// the current host. The the child process exits, the process will be
1006// found in the global target list (we want to be completely sure that the
1007// lldb_private::Process doesn't go away before we can deliver the signal.
1008bool
1009Process::SetProcessExitStatus
1010(
1011 void *callback_baton,
1012 lldb::pid_t pid,
1013 int signo, // Zero for no signal
1014 int exit_status // Exit value of process if signal is zero
1015)
1016{
1017 if (signo == 0 || exit_status)
1018 {
Greg Clayton66111032010-06-23 01:19:29 +00001019 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001020 if (target_sp)
1021 {
1022 ProcessSP process_sp (target_sp->GetProcessSP());
1023 if (process_sp)
1024 {
1025 const char *signal_cstr = NULL;
1026 if (signo)
1027 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1028
1029 process_sp->SetExitStatus (exit_status, signal_cstr);
1030 }
1031 }
1032 return true;
1033 }
1034 return false;
1035}
1036
1037
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001038void
1039Process::UpdateThreadListIfNeeded ()
1040{
1041 const uint32_t stop_id = GetStopID();
1042 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1043 {
1044 Mutex::Locker locker (m_thread_list.GetMutex ());
1045 ThreadList new_thread_list(this);
1046 // Always update the thread list with the protocol specific
1047 // thread list
1048 UpdateThreadList (m_thread_list, new_thread_list);
1049 OperatingSystem *os = GetOperatingSystem ();
1050 if (os)
1051 os->UpdateThreadList (m_thread_list, new_thread_list);
1052 m_thread_list.Update (new_thread_list);
1053 m_thread_list.SetStopID (stop_id);
1054 }
1055}
1056
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057uint32_t
1058Process::GetNextThreadIndexID ()
1059{
1060 return ++m_thread_index_id;
1061}
1062
1063StateType
1064Process::GetState()
1065{
1066 // If any other threads access this we will need a mutex for it
1067 return m_public_state.GetValue ();
1068}
1069
1070void
1071Process::SetPublicState (StateType new_state)
1072{
Greg Clayton414f5d32011-01-25 02:58:48 +00001073 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074 if (log)
1075 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1076 m_public_state.SetValue (new_state);
1077}
1078
1079StateType
1080Process::GetPrivateState ()
1081{
1082 return m_private_state.GetValue();
1083}
1084
1085void
1086Process::SetPrivateState (StateType new_state)
1087{
Greg Clayton414f5d32011-01-25 02:58:48 +00001088 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089 bool state_changed = false;
1090
1091 if (log)
1092 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1093
1094 Mutex::Locker locker(m_private_state.GetMutex());
1095
1096 const StateType old_state = m_private_state.GetValueNoLock ();
1097 state_changed = old_state != new_state;
1098 if (state_changed)
1099 {
1100 m_private_state.SetValueNoLock (new_state);
1101 if (StateIsStoppedState(new_state))
1102 {
Jim Ingham4b536182011-08-09 02:12:22 +00001103 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001104 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001106 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001107 }
1108 // Use our target to get a shared pointer to ourselves...
1109 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1110 }
1111 else
1112 {
1113 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001114 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115 }
1116}
1117
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118addr_t
1119Process::GetImageInfoAddress()
1120{
1121 return LLDB_INVALID_ADDRESS;
1122}
1123
Greg Clayton8f343b02010-11-04 01:54:29 +00001124//----------------------------------------------------------------------
1125// LoadImage
1126//
1127// This function provides a default implementation that works for most
1128// unix variants. Any Process subclasses that need to do shared library
1129// loading differently should override LoadImage and UnloadImage and
1130// do what is needed.
1131//----------------------------------------------------------------------
1132uint32_t
1133Process::LoadImage (const FileSpec &image_spec, Error &error)
1134{
1135 DynamicLoader *loader = GetDynamicLoader();
1136 if (loader)
1137 {
1138 error = loader->CanLoadImage();
1139 if (error.Fail())
1140 return LLDB_INVALID_IMAGE_TOKEN;
1141 }
1142
1143 if (error.Success())
1144 {
1145 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001146
1147 if (thread_sp)
1148 {
1149 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1150
1151 if (frame_sp)
1152 {
1153 ExecutionContext exe_ctx;
1154 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001155 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001156 StreamString expr;
1157 char path[PATH_MAX];
1158 image_spec.GetPath(path, sizeof(path));
1159 expr.Printf("dlopen (\"%s\", 2)", path);
1160 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001161 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001162 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Johnny Chene92aa432011-09-09 00:01:43 +00001163 error = result_valobj_sp->GetError();
1164 if (error.Success())
Greg Clayton8f343b02010-11-04 01:54:29 +00001165 {
1166 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001167 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001168 {
1169 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1170 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1171 {
1172 uint32_t image_token = m_image_tokens.size();
1173 m_image_tokens.push_back (image_ptr);
1174 return image_token;
1175 }
1176 }
1177 }
1178 }
1179 }
1180 }
1181 return LLDB_INVALID_IMAGE_TOKEN;
1182}
1183
1184//----------------------------------------------------------------------
1185// UnloadImage
1186//
1187// This function provides a default implementation that works for most
1188// unix variants. Any Process subclasses that need to do shared library
1189// loading differently should override LoadImage and UnloadImage and
1190// do what is needed.
1191//----------------------------------------------------------------------
1192Error
1193Process::UnloadImage (uint32_t image_token)
1194{
1195 Error error;
1196 if (image_token < m_image_tokens.size())
1197 {
1198 const addr_t image_addr = m_image_tokens[image_token];
1199 if (image_addr == LLDB_INVALID_ADDRESS)
1200 {
1201 error.SetErrorString("image already unloaded");
1202 }
1203 else
1204 {
1205 DynamicLoader *loader = GetDynamicLoader();
1206 if (loader)
1207 error = loader->CanLoadImage();
1208
1209 if (error.Success())
1210 {
1211 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001212
1213 if (thread_sp)
1214 {
1215 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1216
1217 if (frame_sp)
1218 {
1219 ExecutionContext exe_ctx;
1220 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001221 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001222 StreamString expr;
1223 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1224 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001225 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan3bfdaa22011-09-15 02:13:07 +00001226 ClangUserExpression::Evaluate (exe_ctx, eExecutionPolicyAlways, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +00001227 if (result_valobj_sp->GetError().Success())
1228 {
1229 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001230 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001231 {
1232 if (scalar.UInt(1))
1233 {
1234 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1235 }
1236 else
1237 {
1238 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1239 }
1240 }
1241 }
1242 else
1243 {
1244 error = result_valobj_sp->GetError();
1245 }
1246 }
1247 }
1248 }
1249 }
1250 }
1251 else
1252 {
1253 error.SetErrorString("invalid image token");
1254 }
1255 return error;
1256}
1257
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001258const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001259Process::GetABI()
1260{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001261 if (!m_abi_sp)
1262 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1263 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001264}
1265
Jim Ingham22777012010-09-23 02:01:19 +00001266LanguageRuntime *
1267Process::GetLanguageRuntime(lldb::LanguageType language)
1268{
1269 LanguageRuntimeCollection::iterator pos;
1270 pos = m_language_runtimes.find (language);
1271 if (pos == m_language_runtimes.end())
1272 {
1273 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1274
1275 m_language_runtimes[language]
1276 = runtime;
1277 return runtime.get();
1278 }
1279 else
1280 return (*pos).second.get();
1281}
1282
1283CPPLanguageRuntime *
1284Process::GetCPPLanguageRuntime ()
1285{
1286 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1287 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1288 return static_cast<CPPLanguageRuntime *> (runtime);
1289 return NULL;
1290}
1291
1292ObjCLanguageRuntime *
1293Process::GetObjCLanguageRuntime ()
1294{
1295 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1296 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1297 return static_cast<ObjCLanguageRuntime *> (runtime);
1298 return NULL;
1299}
1300
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001301BreakpointSiteList &
1302Process::GetBreakpointSiteList()
1303{
1304 return m_breakpoint_site_list;
1305}
1306
1307const BreakpointSiteList &
1308Process::GetBreakpointSiteList() const
1309{
1310 return m_breakpoint_site_list;
1311}
1312
1313
1314void
1315Process::DisableAllBreakpointSites ()
1316{
1317 m_breakpoint_site_list.SetEnabledForAll (false);
1318}
1319
1320Error
1321Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1322{
1323 Error error (DisableBreakpointSiteByID (break_id));
1324
1325 if (error.Success())
1326 m_breakpoint_site_list.Remove(break_id);
1327
1328 return error;
1329}
1330
1331Error
1332Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1333{
1334 Error error;
1335 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1336 if (bp_site_sp)
1337 {
1338 if (bp_site_sp->IsEnabled())
1339 error = DisableBreakpoint (bp_site_sp.get());
1340 }
1341 else
1342 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001343 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001344 }
1345
1346 return error;
1347}
1348
1349Error
1350Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1351{
1352 Error error;
1353 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1354 if (bp_site_sp)
1355 {
1356 if (!bp_site_sp->IsEnabled())
1357 error = EnableBreakpoint (bp_site_sp.get());
1358 }
1359 else
1360 {
Greg Clayton81c22f62011-10-19 18:09:39 +00001361 error.SetErrorStringWithFormat("invalid breakpoint site ID: %llu", break_id);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001362 }
1363 return error;
1364}
1365
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001366lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001367Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1368{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001369 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001370 if (load_addr != LLDB_INVALID_ADDRESS)
1371 {
1372 BreakpointSiteSP bp_site_sp;
1373
1374 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1375 // create a new breakpoint site and add it.
1376
1377 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1378
1379 if (bp_site_sp)
1380 {
1381 bp_site_sp->AddOwner (owner);
1382 owner->SetBreakpointSite (bp_site_sp);
1383 return bp_site_sp->GetID();
1384 }
1385 else
1386 {
1387 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1388 if (bp_site_sp)
1389 {
1390 if (EnableBreakpoint (bp_site_sp.get()).Success())
1391 {
1392 owner->SetBreakpointSite (bp_site_sp);
1393 return m_breakpoint_site_list.Add (bp_site_sp);
1394 }
1395 }
1396 }
1397 }
1398 // We failed to enable the breakpoint
1399 return LLDB_INVALID_BREAK_ID;
1400
1401}
1402
1403void
1404Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1405{
1406 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1407 if (num_owners == 0)
1408 {
1409 DisableBreakpoint(bp_site_sp.get());
1410 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1411 }
1412}
1413
1414
1415size_t
1416Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1417{
1418 size_t bytes_removed = 0;
1419 addr_t intersect_addr;
1420 size_t intersect_size;
1421 size_t opcode_offset;
1422 size_t idx;
Greg Clayton4d122c42011-09-17 08:33:22 +00001423 BreakpointSiteSP bp_sp;
Jim Ingham20c77192011-06-29 19:42:28 +00001424 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001425
Jim Ingham20c77192011-06-29 19:42:28 +00001426 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001427 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001428 for (idx = 0; (bp_sp = bp_sites_in_range.GetByIndex(idx)); ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001429 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001430 if (bp_sp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001431 {
Greg Clayton4d122c42011-09-17 08:33:22 +00001432 if (bp_sp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
Jim Ingham20c77192011-06-29 19:42:28 +00001433 {
1434 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1435 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
Greg Clayton4d122c42011-09-17 08:33:22 +00001436 assert(opcode_offset + intersect_size <= bp_sp->GetByteSize());
Jim Ingham20c77192011-06-29 19:42:28 +00001437 size_t buf_offset = intersect_addr - bp_addr;
Greg Clayton4d122c42011-09-17 08:33:22 +00001438 ::memcpy(buf + buf_offset, bp_sp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
Jim Ingham20c77192011-06-29 19:42:28 +00001439 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001440 }
1441 }
1442 }
1443 return bytes_removed;
1444}
1445
1446
Greg Claytonded470d2011-03-19 01:12:21 +00001447
1448size_t
1449Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1450{
1451 PlatformSP platform_sp (m_target.GetPlatform());
1452 if (platform_sp)
1453 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1454 return 0;
1455}
1456
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001457Error
1458Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1459{
1460 Error error;
1461 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001462 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001463 const addr_t bp_addr = bp_site->GetLoadAddress();
1464 if (log)
1465 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1466 if (bp_site->IsEnabled())
1467 {
1468 if (log)
1469 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1470 return error;
1471 }
1472
1473 if (bp_addr == LLDB_INVALID_ADDRESS)
1474 {
1475 error.SetErrorString("BreakpointSite contains an invalid load address.");
1476 return error;
1477 }
1478 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1479 // trap for the breakpoint site
1480 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1481
1482 if (bp_opcode_size == 0)
1483 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001484 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx", bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001485 }
1486 else
1487 {
1488 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1489
1490 if (bp_opcode_bytes == NULL)
1491 {
1492 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1493 return error;
1494 }
1495
1496 // Save the original opcode by reading it
1497 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1498 {
1499 // Write a software breakpoint in place of the original opcode
1500 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1501 {
1502 uint8_t verify_bp_opcode_bytes[64];
1503 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1504 {
1505 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1506 {
1507 bp_site->SetEnabled(true);
1508 bp_site->SetType (BreakpointSite::eSoftware);
1509 if (log)
1510 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1511 bp_site->GetID(),
1512 (uint64_t)bp_addr);
1513 }
1514 else
Greg Clayton86edbf42011-10-26 00:56:27 +00001515 error.SetErrorString("failed to verify the breakpoint trap in memory.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001516 }
1517 else
1518 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1519 }
1520 else
1521 error.SetErrorString("Unable to write breakpoint trap to memory.");
1522 }
1523 else
1524 error.SetErrorString("Unable to read memory at breakpoint address.");
1525 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001526 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001527 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1528 bp_site->GetID(),
1529 (uint64_t)bp_addr,
1530 error.AsCString());
1531 return error;
1532}
1533
1534Error
1535Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1536{
1537 Error error;
1538 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001539 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001540 addr_t bp_addr = bp_site->GetLoadAddress();
1541 lldb::user_id_t breakID = bp_site->GetID();
1542 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00001543 log->Printf ("Process::DisableBreakpoint (breakID = %llu) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001544
1545 if (bp_site->IsHardware())
1546 {
1547 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1548 }
1549 else if (bp_site->IsEnabled())
1550 {
1551 const size_t break_op_size = bp_site->GetByteSize();
1552 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1553 if (break_op_size > 0)
1554 {
1555 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001556 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001557 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001558 bool break_op_found = false;
1559
1560 // Read the breakpoint opcode
1561 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1562 {
1563 bool verify = false;
1564 // Make sure we have the a breakpoint opcode exists at this address
1565 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1566 {
1567 break_op_found = true;
1568 // We found a valid breakpoint opcode at this address, now restore
1569 // the saved opcode.
1570 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1571 {
1572 verify = true;
1573 }
1574 else
1575 error.SetErrorString("Memory write failed when restoring original opcode.");
1576 }
1577 else
1578 {
1579 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1580 // Set verify to true and so we can check if the original opcode has already been restored
1581 verify = true;
1582 }
1583
1584 if (verify)
1585 {
Greg Claytonc982c762010-07-09 20:39:50 +00001586 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001587 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001588 // Verify that our original opcode made it back to the inferior
1589 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1590 {
1591 // compare the memory we just read with the original opcode
1592 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1593 {
1594 // SUCCESS
1595 bp_site->SetEnabled(false);
1596 if (log)
1597 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1598 return error;
1599 }
1600 else
1601 {
1602 if (break_op_found)
1603 error.SetErrorString("Failed to restore original opcode.");
1604 }
1605 }
1606 else
1607 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1608 }
1609 }
1610 else
1611 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1612 }
1613 }
1614 else
1615 {
1616 if (log)
1617 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1618 return error;
1619 }
1620
1621 if (log)
1622 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1623 bp_site->GetID(),
1624 (uint64_t)bp_addr,
1625 error.AsCString());
1626 return error;
1627
1628}
1629
Greg Clayton58be07b2011-01-07 06:08:19 +00001630// Comment out line below to disable memory caching
1631#define ENABLE_MEMORY_CACHING
1632// Uncomment to verify memory caching works after making changes to caching code
1633//#define VERIFY_MEMORY_READS
1634
1635#if defined (ENABLE_MEMORY_CACHING)
1636
1637#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001638
1639size_t
1640Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1641{
Greg Clayton58be07b2011-01-07 06:08:19 +00001642 // Memory caching is enabled, with debug verification
1643 if (buf && size)
1644 {
1645 // Uncomment the line below to make sure memory caching is working.
1646 // I ran this through the test suite and got no assertions, so I am
1647 // pretty confident this is working well. If any changes are made to
1648 // memory caching, uncomment the line below and test your changes!
1649
1650 // Verify all memory reads by using the cache first, then redundantly
1651 // reading the same memory from the inferior and comparing to make sure
1652 // everything is exactly the same.
1653 std::string verify_buf (size, '\0');
1654 assert (verify_buf.size() == size);
1655 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1656 Error verify_error;
1657 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1658 assert (cache_bytes_read == verify_bytes_read);
1659 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1660 assert (verify_error.Success() == error.Success());
1661 return cache_bytes_read;
1662 }
1663 return 0;
1664}
1665
1666#else // #if defined (VERIFY_MEMORY_READS)
1667
1668size_t
1669Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1670{
1671 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001672 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001673}
1674
1675#endif // #else for #if defined (VERIFY_MEMORY_READS)
1676
1677#else // #if defined (ENABLE_MEMORY_CACHING)
1678
1679size_t
1680Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1681{
1682 // Memory caching is disabled
1683 return ReadMemoryFromInferior (addr, buf, size, error);
1684}
1685
1686#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1687
1688
1689size_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001690Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1691{
1692 size_t total_cstr_len = 0;
1693 if (dst && dst_max_len)
1694 {
1695 // NULL out everything just to be safe
1696 memset (dst, 0, dst_max_len);
1697 Error error;
1698 addr_t curr_addr = addr;
1699 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1700 size_t bytes_left = dst_max_len - 1;
1701 char *curr_dst = dst;
1702
1703 while (bytes_left > 0)
1704 {
1705 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1706 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1707 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1708
1709 if (bytes_read == 0)
1710 {
1711 dst[total_cstr_len] = '\0';
1712 break;
1713 }
1714 const size_t len = strlen(curr_dst);
1715
1716 total_cstr_len += len;
1717
1718 if (len < bytes_to_read)
1719 break;
1720
1721 curr_dst += bytes_read;
1722 curr_addr += bytes_read;
1723 bytes_left -= bytes_read;
1724 }
1725 }
1726 return total_cstr_len;
1727}
1728
1729size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00001730Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1731{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001732 if (buf == NULL || size == 0)
1733 return 0;
1734
1735 size_t bytes_read = 0;
1736 uint8_t *bytes = (uint8_t *)buf;
1737
1738 while (bytes_read < size)
1739 {
1740 const size_t curr_size = size - bytes_read;
1741 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1742 bytes + bytes_read,
1743 curr_size,
1744 error);
1745 bytes_read += curr_bytes_read;
1746 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1747 break;
1748 }
1749
1750 // Replace any software breakpoint opcodes that fall into this range back
1751 // into "buf" before we return
1752 if (bytes_read > 0)
1753 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1754 return bytes_read;
1755}
1756
Greg Clayton58a4c462010-12-16 20:01:20 +00001757uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001758Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00001759{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001760 Scalar scalar;
1761 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1762 return scalar.ULongLong(fail_value);
1763 return fail_value;
1764}
1765
1766addr_t
1767Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1768{
1769 Scalar scalar;
1770 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1771 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1772 return LLDB_INVALID_ADDRESS;
1773}
1774
1775
1776bool
1777Process::WritePointerToMemory (lldb::addr_t vm_addr,
1778 lldb::addr_t ptr_value,
1779 Error &error)
1780{
1781 Scalar scalar;
1782 const uint32_t addr_byte_size = GetAddressByteSize();
1783 if (addr_byte_size <= 4)
1784 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00001785 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001786 scalar = ptr_value;
1787 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00001788}
1789
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001790size_t
1791Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1792{
1793 size_t bytes_written = 0;
1794 const uint8_t *bytes = (const uint8_t *)buf;
1795
1796 while (bytes_written < size)
1797 {
1798 const size_t curr_size = size - bytes_written;
1799 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1800 bytes + bytes_written,
1801 curr_size,
1802 error);
1803 bytes_written += curr_bytes_written;
1804 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1805 break;
1806 }
1807 return bytes_written;
1808}
1809
1810size_t
1811Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1812{
Greg Clayton58be07b2011-01-07 06:08:19 +00001813#if defined (ENABLE_MEMORY_CACHING)
1814 m_memory_cache.Flush (addr, size);
1815#endif
1816
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001817 if (buf == NULL || size == 0)
1818 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00001819
Jim Ingham4b536182011-08-09 02:12:22 +00001820 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00001821
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001822 // We need to write any data that would go where any current software traps
1823 // (enabled software breakpoints) any software traps (breakpoints) that we
1824 // may have placed in our tasks memory.
1825
1826 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1827 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1828
1829 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00001830 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001831
1832 BreakpointSiteList::collection::const_iterator pos;
1833 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001834 addr_t intersect_addr = 0;
1835 size_t intersect_size = 0;
1836 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001837 const uint8_t *ubuf = (const uint8_t *)buf;
1838
1839 for (pos = iter; pos != end; ++pos)
1840 {
1841 BreakpointSiteSP bp;
1842 bp = pos->second;
1843
1844 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1845 assert(addr <= intersect_addr && intersect_addr < addr + size);
1846 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1847 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1848
1849 // Check for bytes before this breakpoint
1850 const addr_t curr_addr = addr + bytes_written;
1851 if (intersect_addr > curr_addr)
1852 {
1853 // There are some bytes before this breakpoint that we need to
1854 // just write to memory
1855 size_t curr_size = intersect_addr - curr_addr;
1856 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1857 ubuf + bytes_written,
1858 curr_size,
1859 error);
1860 bytes_written += curr_bytes_written;
1861 if (curr_bytes_written != curr_size)
1862 {
1863 // We weren't able to write all of the requested bytes, we
1864 // are done looping and will return the number of bytes that
1865 // we have written so far.
1866 break;
1867 }
1868 }
1869
1870 // Now write any bytes that would cover up any software breakpoints
1871 // directly into the breakpoint opcode buffer
1872 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1873 bytes_written += intersect_size;
1874 }
1875
1876 // Write any remaining bytes after the last breakpoint if we have any left
1877 if (bytes_written < size)
1878 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1879 ubuf + bytes_written,
1880 size - bytes_written,
1881 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00001882
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001883 return bytes_written;
1884}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001885
1886size_t
1887Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
1888{
1889 if (byte_size == UINT32_MAX)
1890 byte_size = scalar.GetByteSize();
1891 if (byte_size > 0)
1892 {
1893 uint8_t buf[32];
1894 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
1895 if (mem_size > 0)
1896 return WriteMemory(addr, buf, mem_size, error);
1897 else
1898 error.SetErrorString ("failed to get scalar as memory data");
1899 }
1900 else
1901 {
1902 error.SetErrorString ("invalid scalar value");
1903 }
1904 return 0;
1905}
1906
1907size_t
1908Process::ReadScalarIntegerFromMemory (addr_t addr,
1909 uint32_t byte_size,
1910 bool is_signed,
1911 Scalar &scalar,
1912 Error &error)
1913{
1914 uint64_t uval;
1915
1916 if (byte_size <= sizeof(uval))
1917 {
1918 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
1919 if (bytes_read == byte_size)
1920 {
1921 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
1922 uint32_t offset = 0;
1923 if (byte_size <= 4)
1924 scalar = data.GetMaxU32 (&offset, byte_size);
1925 else
1926 scalar = data.GetMaxU64 (&offset, byte_size);
1927
1928 if (is_signed)
1929 scalar.SignExtend(byte_size * 8);
1930 return bytes_read;
1931 }
1932 }
1933 else
1934 {
1935 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1936 }
1937 return 0;
1938}
1939
Greg Claytond495c532011-05-17 03:37:42 +00001940#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001941addr_t
1942Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1943{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00001944 if (GetPrivateState() != eStateStopped)
1945 return LLDB_INVALID_ADDRESS;
1946
Greg Claytond495c532011-05-17 03:37:42 +00001947#if defined (USE_ALLOCATE_MEMORY_CACHE)
1948 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
1949#else
Greg Claytonb2daec92011-01-23 19:58:49 +00001950 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1951 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1952 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001953 log->Printf("Process::AllocateMemory(size=%4zu, permissions=%s) => 0x%16.16llx (m_stop_id = %u m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00001954 size,
Greg Claytond495c532011-05-17 03:37:42 +00001955 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00001956 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00001957 m_mod_id.GetStopID(),
1958 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00001959 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00001960#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001961}
1962
Sean Callanan90539452011-09-20 23:01:51 +00001963bool
1964Process::CanJIT ()
1965{
1966 return m_can_jit == eCanJITYes;
1967}
1968
1969void
1970Process::SetCanJIT (bool can_jit)
1971{
1972 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
1973}
1974
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001975Error
1976Process::DeallocateMemory (addr_t ptr)
1977{
Greg Claytond495c532011-05-17 03:37:42 +00001978 Error error;
1979#if defined (USE_ALLOCATE_MEMORY_CACHE)
1980 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
1981 {
1982 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
1983 }
1984#else
1985 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00001986
1987 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1988 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001989 log->Printf("Process::DeallocateMemory(addr=0x%16.16llx) => err = %s (m_stop_id = %u, m_memory_id = %u)",
Greg Claytonb2daec92011-01-23 19:58:49 +00001990 ptr,
1991 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00001992 m_mod_id.GetStopID(),
1993 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00001994#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00001995 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001996}
1997
1998
1999Error
Johnny Chen01a67862011-10-14 00:42:25 +00002000Process::EnableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002001{
2002 Error error;
2003 error.SetErrorString("watchpoints are not supported");
2004 return error;
2005}
2006
2007Error
Johnny Chen01a67862011-10-14 00:42:25 +00002008Process::DisableWatchpoint (Watchpoint *watchpoint)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002009{
2010 Error error;
2011 error.SetErrorString("watchpoints are not supported");
2012 return error;
2013}
2014
2015StateType
2016Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
2017{
2018 StateType state;
2019 // Now wait for the process to launch and return control to us, and then
2020 // call DidLaunch:
2021 while (1)
2022 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002023 event_sp.reset();
2024 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2025
2026 if (StateIsStoppedState(state))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002027 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002028
2029 // If state is invalid, then we timed out
2030 if (state == eStateInvalid)
2031 break;
2032
2033 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002034 HandlePrivateEvent (event_sp);
2035 }
2036 return state;
2037}
2038
2039Error
2040Process::Launch
2041(
2042 char const *argv[],
2043 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00002044 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002045 const char *stdin_path,
2046 const char *stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00002047 const char *stderr_path,
2048 const char *working_directory
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002049)
2050{
2051 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002052 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002053 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002054 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002055 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002056
Greg Claytonaa149cb2011-08-11 02:48:45 +00002057 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002058 if (exe_module)
2059 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002060 char local_exec_file_path[PATH_MAX];
2061 char platform_exec_file_path[PATH_MAX];
2062 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2063 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002064 if (exe_module->GetFileSpec().Exists())
2065 {
Greg Clayton71337622011-02-24 22:24:29 +00002066 if (PrivateStateThreadIsValid ())
2067 PausePrivateStateThread ();
2068
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002069 error = WillLaunch (exe_module);
2070 if (error.Success())
2071 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002072 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002073 // The args coming in should not contain the application name, the
2074 // lldb_private::Process class will add this in case the executable
2075 // gets resolved to a different file than was given on the command
2076 // line (like when an applicaiton bundle is specified and will
2077 // resolve to the contained exectuable file, or the file given was
2078 // a symlink or other file system link that resolves to a different
2079 // file).
2080
2081 // Get the resolved exectuable path
2082
2083 // Make a new argument vector
2084 std::vector<const char *> exec_path_plus_argv;
2085 // Append the resolved executable path
Greg Clayton2289fa42011-04-30 01:09:13 +00002086 exec_path_plus_argv.push_back (platform_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002087
2088 // Push all args if there are any
2089 if (argv)
2090 {
2091 for (int i = 0; argv[i]; ++i)
2092 exec_path_plus_argv.push_back(argv[i]);
2093 }
2094
2095 // Push a NULL to terminate the args.
2096 exec_path_plus_argv.push_back(NULL);
2097
2098 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00002099 error = DoLaunch (exe_module,
2100 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
2101 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00002102 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00002103 stdin_path,
2104 stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00002105 stderr_path,
2106 working_directory);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002107
2108 if (error.Fail())
2109 {
2110 if (GetID() != LLDB_INVALID_PROCESS_ID)
2111 {
2112 SetID (LLDB_INVALID_PROCESS_ID);
2113 const char *error_string = error.AsCString();
2114 if (error_string == NULL)
2115 error_string = "launch failed";
2116 SetExitStatus (-1, error_string);
2117 }
2118 }
2119 else
2120 {
2121 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002122 TimeValue timeout_time;
2123 timeout_time = TimeValue::Now();
2124 timeout_time.OffsetWithSeconds(10);
2125 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126
Greg Clayton1a38ea72011-06-22 01:42:17 +00002127 if (state == eStateInvalid || event_sp.get() == NULL)
2128 {
2129 // We were able to launch the process, but we failed to
2130 // catch the initial stop.
2131 SetExitStatus (0, "failed to catch stop after launch");
2132 Destroy();
2133 }
2134 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002135 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002136
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002137 DidLaunch ();
2138
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002139 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002140 if (m_dyld_ap.get())
2141 m_dyld_ap->DidLaunch();
2142
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002143 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144 // This delays passing the stopped event to listeners till DidLaunch gets
2145 // a chance to complete...
2146 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002147
2148 if (PrivateStateThreadIsValid ())
2149 ResumePrivateStateThread ();
2150 else
2151 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002152 }
2153 else if (state == eStateExited)
2154 {
2155 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2156 // not likely to work, and return an invalid pid.
2157 HandlePrivateEvent (event_sp);
2158 }
2159 }
2160 }
2161 }
2162 else
2163 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002164 error.SetErrorStringWithFormat("file doesn't exist: '%s'", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002165 }
2166 }
2167 return error;
2168}
2169
Jim Inghambb3a2832011-01-29 01:49:25 +00002170Process::NextEventAction::EventActionResult
2171Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002172{
Jim Inghambb3a2832011-01-29 01:49:25 +00002173 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2174 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002175 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002176 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002177 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002178 return eEventActionRetry;
2179
2180 case eStateStopped:
2181 case eStateCrashed:
Jim Ingham5aee1622010-08-09 23:31:02 +00002182 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002183 // During attach, prior to sending the eStateStopped event,
2184 // lldb_private::Process subclasses must set the process must set
2185 // the new process ID.
2186 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton93d3c8332011-02-16 04:46:07 +00002187 m_process->CompleteAttach ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002188 return eEventActionSuccess;
Jim Ingham5aee1622010-08-09 23:31:02 +00002189 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002190
2191
2192 break;
2193 default:
2194 case eStateExited:
2195 case eStateInvalid:
2196 m_exit_string.assign ("No valid Process");
2197 return eEventActionExit;
2198 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002199 }
2200}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002201
Jim Inghambb3a2832011-01-29 01:49:25 +00002202Process::NextEventAction::EventActionResult
2203Process::AttachCompletionHandler::HandleBeingInterrupted()
2204{
2205 return eEventActionSuccess;
2206}
2207
2208const char *
2209Process::AttachCompletionHandler::GetExitString ()
2210{
2211 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002212}
2213
2214Error
2215Process::Attach (lldb::pid_t attach_pid)
2216{
2217
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002218 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002219 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002220
Greg Clayton93d3c8332011-02-16 04:46:07 +00002221 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002222 m_os_ap.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002223
Greg Claytonc982c762010-07-09 20:39:50 +00002224 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002225 if (error.Success())
2226 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002227 SetPublicState (eStateAttaching);
2228
Greg Claytonc982c762010-07-09 20:39:50 +00002229 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002230 if (error.Success())
2231 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002232 SetNextEventAction(new Process::AttachCompletionHandler(this));
2233 StartPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002234 }
2235 else
2236 {
2237 if (GetID() != LLDB_INVALID_PROCESS_ID)
2238 {
2239 SetID (LLDB_INVALID_PROCESS_ID);
2240 const char *error_string = error.AsCString();
2241 if (error_string == NULL)
2242 error_string = "attach failed";
2243
2244 SetExitStatus(-1, error_string);
2245 }
2246 }
2247 }
2248 return error;
2249}
2250
2251Error
2252Process::Attach (const char *process_name, bool wait_for_launch)
2253{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002254 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002255 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002256
2257 // Find the process and its architecture. Make sure it matches the architecture
2258 // of the current Target, and if not adjust it.
Greg Claytone996fd32011-03-08 22:40:15 +00002259 Error error;
Jim Ingham5aee1622010-08-09 23:31:02 +00002260
Jim Ingham2ecb7422010-08-17 21:54:19 +00002261 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00002262 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002263 ProcessInstanceInfoList process_infos;
Jim Ingham4299fdb2011-09-15 01:10:17 +00002264 PlatformSP platform_sp (m_target.GetPlatform ());
2265 assert (platform_sp.get());
2266
Greg Claytone996fd32011-03-08 22:40:15 +00002267 if (platform_sp)
Jim Ingham2ecb7422010-08-17 21:54:19 +00002268 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002269 ProcessInstanceInfoMatch match_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002270 match_info.GetProcessInfo().SetName(process_name);
2271 match_info.SetNameMatchType (eNameMatchEquals);
2272 platform_sp->FindProcesses (match_info, process_infos);
Greg Claytone996fd32011-03-08 22:40:15 +00002273 if (process_infos.GetSize() > 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002274 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002275 error.SetErrorStringWithFormat ("more than one process named %s", process_name);
Greg Claytone996fd32011-03-08 22:40:15 +00002276 }
2277 else if (process_infos.GetSize() == 0)
2278 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002279 error.SetErrorStringWithFormat ("could not find a process named %s", process_name);
Greg Claytone996fd32011-03-08 22:40:15 +00002280 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002281 }
2282 else
Greg Claytone996fd32011-03-08 22:40:15 +00002283 {
Greg Clayton86edbf42011-10-26 00:56:27 +00002284 error.SetErrorString ("invalid platform");
Greg Claytone996fd32011-03-08 22:40:15 +00002285 }
2286 }
2287
2288 if (error.Success())
2289 {
2290 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002291 m_os_ap.reset();
Greg Claytone996fd32011-03-08 22:40:15 +00002292
2293 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2294 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002295 {
Greg Claytone996fd32011-03-08 22:40:15 +00002296 SetPublicState (eStateAttaching);
2297 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2298 if (error.Fail())
2299 {
2300 if (GetID() != LLDB_INVALID_PROCESS_ID)
2301 {
2302 SetID (LLDB_INVALID_PROCESS_ID);
2303 const char *error_string = error.AsCString();
2304 if (error_string == NULL)
2305 error_string = "attach failed";
2306
2307 SetExitStatus(-1, error_string);
2308 }
2309 }
2310 else
2311 {
2312 SetNextEventAction(new Process::AttachCompletionHandler(this));
2313 StartPrivateStateThread();
2314 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002315 }
2316 }
2317 return error;
2318}
2319
Greg Clayton93d3c8332011-02-16 04:46:07 +00002320void
2321Process::CompleteAttach ()
2322{
2323 // Let the process subclass figure out at much as it can about the process
2324 // before we go looking for a dynamic loader plug-in.
Jim Ingham8314c522011-09-15 21:36:42 +00002325 m_attached_to_process = true;
Greg Clayton93d3c8332011-02-16 04:46:07 +00002326 DidAttach();
2327
Jim Ingham4299fdb2011-09-15 01:10:17 +00002328 // We just attached. If we have a platform, ask it for the process architecture, and if it isn't
2329 // the same as the one we've already set, switch architectures.
2330 PlatformSP platform_sp (m_target.GetPlatform ());
2331 assert (platform_sp.get());
2332 if (platform_sp)
2333 {
2334 ProcessInstanceInfo process_info;
2335 platform_sp->GetProcessInfo (GetID(), process_info);
2336 const ArchSpec &process_arch = process_info.GetArchitecture();
2337 if (process_arch.IsValid() && m_target.GetArchitecture() != process_arch)
2338 m_target.SetArchitecture (process_arch);
2339 }
2340
2341 // We have completed the attach, now it is time to find the dynamic loader
Greg Clayton93d3c8332011-02-16 04:46:07 +00002342 // plug-in
Greg Clayton7a5388b2011-03-20 04:57:14 +00002343 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002344 if (m_dyld_ap.get())
2345 m_dyld_ap->DidAttach();
2346
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002347 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002348 // Figure out which one is the executable, and set that in our target:
2349 ModuleList &modules = m_target.GetImages();
2350
2351 size_t num_modules = modules.GetSize();
2352 for (int i = 0; i < num_modules; i++)
2353 {
2354 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002355 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002356 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002357 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002358 m_target.SetExecutableModule (module_sp, false);
2359 break;
2360 }
2361 }
2362}
2363
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002364Error
Greg Claytonb766a732011-02-04 01:58:07 +00002365Process::ConnectRemote (const char *remote_url)
2366{
Greg Claytonb766a732011-02-04 01:58:07 +00002367 m_abi_sp.reset();
2368 m_process_input_reader.reset();
2369
2370 // Find the process and its architecture. Make sure it matches the architecture
2371 // of the current Target, and if not adjust it.
2372
2373 Error error (DoConnectRemote (remote_url));
2374 if (error.Success())
2375 {
Greg Clayton71337622011-02-24 22:24:29 +00002376 if (GetID() != LLDB_INVALID_PROCESS_ID)
2377 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002378 EventSP event_sp;
2379 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2380
2381 if (state == eStateStopped || state == eStateCrashed)
2382 {
2383 // If we attached and actually have a process on the other end, then
2384 // this ended up being the equivalent of an attach.
2385 CompleteAttach ();
2386
2387 // This delays passing the stopped event to listeners till
2388 // CompleteAttach gets a chance to complete...
2389 HandlePrivateEvent (event_sp);
2390
2391 }
Greg Clayton71337622011-02-24 22:24:29 +00002392 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002393
2394 if (PrivateStateThreadIsValid ())
2395 ResumePrivateStateThread ();
2396 else
2397 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002398 }
2399 return error;
2400}
2401
2402
2403Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002404Process::Resume ()
2405{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002406 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002407 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002408 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002409 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002410 StateAsCString(m_public_state.GetValue()),
2411 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002412
2413 Error error (WillResume());
2414 // Tell the process it is about to resume before the thread list
2415 if (error.Success())
2416 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002417 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002418 // can let all of our threads know that they are about to be
2419 // resumed. Threads will each be called with
2420 // Thread::WillResume(StateType) where StateType contains the state
2421 // that they are supposed to have when the process is resumed
2422 // (suspended/running/stepping). Threads should also check
2423 // their resume signal in lldb::Thread::GetResumeSignal()
2424 // to see if they are suppoed to start back up with a signal.
2425 if (m_thread_list.WillResume())
2426 {
2427 error = DoResume();
2428 if (error.Success())
2429 {
2430 DidResume();
2431 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00002432 if (log)
2433 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002434 }
2435 }
2436 else
2437 {
Jim Ingham444586b2011-01-24 06:34:17 +00002438 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002439 }
2440 }
Jim Ingham444586b2011-01-24 06:34:17 +00002441 else if (log)
2442 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002443 return error;
2444}
2445
2446Error
2447Process::Halt ()
2448{
Jim Inghambb3a2832011-01-29 01:49:25 +00002449 // Pause our private state thread so we can ensure no one else eats
2450 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002451 Listener halt_listener ("lldb.process.halt_listener");
2452 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002453
Jim Inghambb3a2832011-01-29 01:49:25 +00002454 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002455 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002456
Greg Clayton513c26c2011-01-29 07:10:55 +00002457 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002458 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002459
Greg Clayton513c26c2011-01-29 07:10:55 +00002460 bool caused_stop = false;
2461
2462 // Ask the process subclass to actually halt our process
2463 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002464 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002465 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002466 if (m_public_state.GetValue() == eStateAttaching)
2467 {
2468 SetExitStatus(SIGKILL, "Cancelled async attach.");
2469 Destroy ();
2470 }
2471 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002472 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002473 // If "caused_stop" is true, then DoHalt stopped the process. If
2474 // "caused_stop" is false, the process was already stopped.
2475 // If the DoHalt caused the process to stop, then we want to catch
2476 // this event and set the interrupted bool to true before we pass
2477 // this along so clients know that the process was interrupted by
2478 // a halt command.
2479 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002480 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002481 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002482 TimeValue timeout_time;
2483 timeout_time = TimeValue::Now();
2484 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002485 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2486 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002487
Jim Ingham0f16e732011-02-08 05:20:59 +00002488 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002489 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002490 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002491 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002492 }
2493 else
2494 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002495 if (StateIsStoppedState (state))
2496 {
2497 // We caused the process to interrupt itself, so mark this
2498 // as such in the stop event so clients can tell an interrupted
2499 // process from a natural stop
2500 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2501 }
2502 else
2503 {
2504 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2505 if (log)
2506 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2507 error.SetErrorString ("Did not get stopped event after halt.");
2508 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002509 }
2510 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002511 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002512 }
2513 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002514 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002515 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002516 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002517
2518 // Post any event we might have consumed. If all goes well, we will have
2519 // stopped the process, intercepted the event and set the interrupted
2520 // bool in the event. Post it to the private event queue and that will end up
2521 // correctly setting the state.
2522 if (event_sp)
2523 m_private_state_broadcaster.BroadcastEvent(event_sp);
2524
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002525 return error;
2526}
2527
2528Error
2529Process::Detach ()
2530{
2531 Error error (WillDetach());
2532
2533 if (error.Success())
2534 {
2535 DisableAllBreakpointSites();
2536 error = DoDetach();
2537 if (error.Success())
2538 {
2539 DidDetach();
2540 StopPrivateStateThread();
2541 }
2542 }
2543 return error;
2544}
2545
2546Error
2547Process::Destroy ()
2548{
2549 Error error (WillDestroy());
2550 if (error.Success())
2551 {
2552 DisableAllBreakpointSites();
2553 error = DoDestroy();
2554 if (error.Success())
2555 {
2556 DidDestroy();
2557 StopPrivateStateThread();
2558 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002559 m_stdio_communication.StopReadThread();
2560 m_stdio_communication.Disconnect();
2561 if (m_process_input_reader && m_process_input_reader->IsActive())
2562 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2563 if (m_process_input_reader)
2564 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002565 }
2566 return error;
2567}
2568
2569Error
2570Process::Signal (int signal)
2571{
2572 Error error (WillSignal());
2573 if (error.Success())
2574 {
2575 error = DoSignal(signal);
2576 if (error.Success())
2577 DidSignal();
2578 }
2579 return error;
2580}
2581
Greg Clayton514487e2011-02-15 21:59:32 +00002582lldb::ByteOrder
2583Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002584{
Greg Clayton514487e2011-02-15 21:59:32 +00002585 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002586}
2587
2588uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002589Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002590{
Greg Clayton514487e2011-02-15 21:59:32 +00002591 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002592}
2593
Greg Clayton514487e2011-02-15 21:59:32 +00002594
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002595bool
2596Process::ShouldBroadcastEvent (Event *event_ptr)
2597{
2598 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2599 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002600 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002601
2602 switch (state)
2603 {
Greg Claytonb766a732011-02-04 01:58:07 +00002604 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002605 case eStateAttaching:
2606 case eStateLaunching:
2607 case eStateDetached:
2608 case eStateExited:
2609 case eStateUnloaded:
2610 // These events indicate changes in the state of the debugging session, always report them.
2611 return_value = true;
2612 break;
2613 case eStateInvalid:
2614 // We stopped for no apparent reason, don't report it.
2615 return_value = false;
2616 break;
2617 case eStateRunning:
2618 case eStateStepping:
2619 // If we've started the target running, we handle the cases where we
2620 // are already running and where there is a transition from stopped to
2621 // running differently.
2622 // running -> running: Automatically suppress extra running events
2623 // stopped -> running: Report except when there is one or more no votes
2624 // and no yes votes.
2625 SynchronouslyNotifyStateChanged (state);
2626 switch (m_public_state.GetValue())
2627 {
2628 case eStateRunning:
2629 case eStateStepping:
2630 // We always suppress multiple runnings with no PUBLIC stop in between.
2631 return_value = false;
2632 break;
2633 default:
2634 // TODO: make this work correctly. For now always report
2635 // run if we aren't running so we don't miss any runnning
2636 // events. If I run the lldb/test/thread/a.out file and
2637 // break at main.cpp:58, run and hit the breakpoints on
2638 // multiple threads, then somehow during the stepping over
2639 // of all breakpoints no run gets reported.
2640 return_value = true;
2641
2642 // This is a transition from stop to run.
2643 switch (m_thread_list.ShouldReportRun (event_ptr))
2644 {
2645 case eVoteYes:
2646 case eVoteNoOpinion:
2647 return_value = true;
2648 break;
2649 case eVoteNo:
2650 return_value = false;
2651 break;
2652 }
2653 break;
2654 }
2655 break;
2656 case eStateStopped:
2657 case eStateCrashed:
2658 case eStateSuspended:
2659 {
2660 // We've stopped. First see if we're going to restart the target.
2661 // If we are going to stop, then we always broadcast the event.
2662 // If we aren't going to stop, let the thread plans decide if we're going to report this event.
Jim Inghamb01e7422010-06-19 04:45:32 +00002663 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002664 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002665 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00002666 if (log)
2667 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002668 return true;
2669 }
2670 else
2671 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002672 RefreshStateAfterStop ();
2673
2674 if (m_thread_list.ShouldStop (event_ptr) == false)
2675 {
2676 switch (m_thread_list.ShouldReportStop (event_ptr))
2677 {
2678 case eVoteYes:
2679 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002680 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002681 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002682 case eVoteNo:
2683 return_value = false;
2684 break;
2685 }
2686
2687 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002688 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002689 Resume ();
2690 }
2691 else
2692 {
2693 return_value = true;
2694 SynchronouslyNotifyStateChanged (state);
2695 }
2696 }
2697 }
2698 }
2699
2700 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00002701 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s - %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002702 return return_value;
2703}
2704
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002705
2706bool
2707Process::StartPrivateStateThread ()
2708{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002709 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002710
Greg Clayton8b82f082011-04-12 05:54:46 +00002711 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002712 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00002713 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2714
2715 if (already_running)
2716 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002717
2718 // Create a thread that watches our internal state and controls which
2719 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002720 char thread_name[1024];
Greg Clayton81c22f62011-10-19 18:09:39 +00002721 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%llu)>", GetID());
Greg Clayton3e06bd92011-01-09 21:07:35 +00002722 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00002723 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724}
2725
2726void
2727Process::PausePrivateStateThread ()
2728{
2729 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2730}
2731
2732void
2733Process::ResumePrivateStateThread ()
2734{
2735 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2736}
2737
2738void
2739Process::StopPrivateStateThread ()
2740{
Greg Clayton8b82f082011-04-12 05:54:46 +00002741 if (PrivateStateThreadIsValid ())
2742 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743}
2744
2745void
2746Process::ControlPrivateStateThread (uint32_t signal)
2747{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002748 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002749
2750 assert (signal == eBroadcastInternalStateControlStop ||
2751 signal == eBroadcastInternalStateControlPause ||
2752 signal == eBroadcastInternalStateControlResume);
2753
2754 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002755 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002757 // Signal the private state thread. First we should copy this is case the
2758 // thread starts exiting since the private state thread will NULL this out
2759 // when it exits
2760 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00002761 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762 {
2763 TimeValue timeout_time;
2764 bool timed_out;
2765
2766 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2767
2768 timeout_time = TimeValue::Now();
2769 timeout_time.OffsetWithSeconds(2);
2770 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2771 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2772
2773 if (signal == eBroadcastInternalStateControlStop)
2774 {
2775 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002776 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002777
2778 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002779 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002780 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002781 }
2782 }
2783}
2784
2785void
2786Process::HandlePrivateEvent (EventSP &event_sp)
2787{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002788 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00002789
Greg Clayton414f5d32011-01-25 02:58:48 +00002790 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002791
2792 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00002793 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00002794 {
Jim Ingham754ab982011-01-29 04:05:41 +00002795 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002796 switch (action_result)
2797 {
2798 case NextEventAction::eEventActionSuccess:
2799 SetNextEventAction(NULL);
2800 break;
2801 case NextEventAction::eEventActionRetry:
2802 break;
2803 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002804 // Handle Exiting Here. If we already got an exited event,
2805 // we should just propagate it. Otherwise, swallow this event,
2806 // and set our state to exit so the next event will kill us.
2807 if (new_state != eStateExited)
2808 {
2809 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00002810 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002811 SetNextEventAction(NULL);
2812 return;
2813 }
2814 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00002815 break;
2816 }
2817 }
2818
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002819 // See if we should broadcast this state to external clients?
2820 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002821
2822 if (should_broadcast)
2823 {
2824 if (log)
2825 {
Greg Clayton81c22f62011-10-19 18:09:39 +00002826 log->Printf ("Process::%s (pid = %llu) broadcasting new state %s (old state %s) to %s",
Greg Clayton414f5d32011-01-25 02:58:48 +00002827 __FUNCTION__,
2828 GetID(),
2829 StateAsCString(new_state),
2830 StateAsCString (GetState ()),
2831 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002832 }
Jim Ingham9575d842011-03-11 03:53:59 +00002833 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00002834 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002835 PushProcessInputReader ();
2836 else
2837 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00002838
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002839 BroadcastEvent (event_sp);
2840 }
2841 else
2842 {
2843 if (log)
2844 {
Greg Clayton81c22f62011-10-19 18:09:39 +00002845 log->Printf ("Process::%s (pid = %llu) suppressing state %s (old state %s): should_broadcast == false",
Greg Clayton414f5d32011-01-25 02:58:48 +00002846 __FUNCTION__,
2847 GetID(),
2848 StateAsCString(new_state),
Jason Molendafd54b362011-09-20 21:44:10 +00002849 StateAsCString (GetState ()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002850 }
2851 }
2852}
2853
2854void *
2855Process::PrivateStateThread (void *arg)
2856{
2857 Process *proc = static_cast<Process*> (arg);
2858 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002859 return result;
2860}
2861
2862void *
2863Process::RunPrivateStateThread ()
2864{
2865 bool control_only = false;
2866 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2867
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002868 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002869 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002870 log->Printf ("Process::%s (arg = %p, pid = %llu) thread starting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002871
2872 bool exit_now = false;
2873 while (!exit_now)
2874 {
2875 EventSP event_sp;
2876 WaitForEventsPrivate (NULL, event_sp, control_only);
2877 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2878 {
2879 switch (event_sp->GetType())
2880 {
2881 case eBroadcastInternalStateControlStop:
2882 exit_now = true;
2883 continue; // Go to next loop iteration so we exit without
2884 break; // doing any internal state managment below
2885
2886 case eBroadcastInternalStateControlPause:
2887 control_only = true;
2888 break;
2889
2890 case eBroadcastInternalStateControlResume:
2891 control_only = false;
2892 break;
2893 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002894
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002895 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002896 log->Printf ("Process::%s (arg = %p, pid = %llu) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002897
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002898 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002899 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002900 }
2901
2902
2903 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2904
2905 if (internal_state != eStateInvalid)
2906 {
2907 HandlePrivateEvent (event_sp);
2908 }
2909
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002910 if (internal_state == eStateInvalid ||
2911 internal_state == eStateExited ||
2912 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002913 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002914 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002915 log->Printf ("Process::%s (arg = %p, pid = %llu) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002916
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002917 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002918 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002919 }
2920
Caroline Tice20ad3c42010-10-29 21:48:37 +00002921 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002922 if (log)
Greg Clayton81c22f62011-10-19 18:09:39 +00002923 log->Printf ("Process::%s (arg = %p, pid = %llu) thread exiting...", __FUNCTION__, this, GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002924
Greg Clayton6ed95942011-01-22 07:12:45 +00002925 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2926 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002927 return NULL;
2928}
2929
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002930//------------------------------------------------------------------
2931// Process Event Data
2932//------------------------------------------------------------------
2933
2934Process::ProcessEventData::ProcessEventData () :
2935 EventData (),
2936 m_process_sp (),
2937 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002938 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00002939 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002940 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002941{
2942}
2943
2944Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2945 EventData (),
2946 m_process_sp (process_sp),
2947 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002948 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00002949 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002950 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002951{
2952}
2953
2954Process::ProcessEventData::~ProcessEventData()
2955{
2956}
2957
2958const ConstString &
2959Process::ProcessEventData::GetFlavorString ()
2960{
2961 static ConstString g_flavor ("Process::ProcessEventData");
2962 return g_flavor;
2963}
2964
2965const ConstString &
2966Process::ProcessEventData::GetFlavor () const
2967{
2968 return ProcessEventData::GetFlavorString ();
2969}
2970
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002971void
2972Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2973{
2974 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00002975 // off of the private process event queue, and then any number of times, first when it gets pulled off of
2976 // the public event queue, then other times when we're pretending that this is where we stopped at the
2977 // end of expression evaluation. m_update_state is used to distinguish these
2978 // three cases; it is 0 when we're just pulling it off for private handling,
2979 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002980
Jim Inghama8604692011-05-22 21:45:01 +00002981 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002982 return;
2983
2984 m_process_sp->SetPublicState (m_state);
2985
2986 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2987 if (m_state == eStateStopped && ! m_restarted)
2988 {
2989 int num_threads = m_process_sp->GetThreadList().GetSize();
2990 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002991
Jim Ingham4b536182011-08-09 02:12:22 +00002992 // The actions might change one of the thread's stop_info's opinions about whether we should
2993 // stop the process, so we need to query that as we go.
2994 bool still_should_stop = true;
2995
Chris Lattner30fdc8d2010-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 Inghamb15bfc72010-10-20 00:39:53 +00003000 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
3001 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003002 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00003003 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00003004 // The stop action might restart the target. If it does, then we want to mark that in the
3005 // event so that whoever is receiving it will know to wait for the running event and reflect
3006 // that state appropriately.
3007 // We also need to stop processing actions, since they aren't expecting the target to be running.
3008 if (m_process_sp->GetPrivateState() == eStateRunning)
3009 {
3010 SetRestarted (true);
3011 break;
3012 }
3013 else if (!stop_info_sp->ShouldStop(event_ptr))
3014 {
3015 still_should_stop = false;
3016 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003017 }
3018 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003019
Jim Ingham4b536182011-08-09 02:12:22 +00003020
3021 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003022 {
Jim Ingham4b536182011-08-09 02:12:22 +00003023 if (!still_should_stop)
3024 {
3025 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003026 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003027 m_process_sp->Resume();
3028 }
3029 else
3030 {
3031 // If we didn't restart, run the Stop Hooks here:
3032 // They might also restart the target, so watch for that.
3033 m_process_sp->GetTarget().RunStopHooks();
3034 if (m_process_sp->GetPrivateState() == eStateRunning)
3035 SetRestarted(true);
3036 }
Jim Ingham9575d842011-03-11 03:53:59 +00003037 }
3038
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003039 }
3040}
3041
3042void
3043Process::ProcessEventData::Dump (Stream *s) const
3044{
3045 if (m_process_sp)
Greg Clayton81c22f62011-10-19 18:09:39 +00003046 s->Printf(" process = %p (pid = %llu), ", m_process_sp.get(), m_process_sp->GetID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003047
Greg Clayton8b82f082011-04-12 05:54:46 +00003048 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003049}
3050
3051const Process::ProcessEventData *
3052Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3053{
3054 if (event_ptr)
3055 {
3056 const EventData *event_data = event_ptr->GetData();
3057 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3058 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3059 }
3060 return NULL;
3061}
3062
3063ProcessSP
3064Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3065{
3066 ProcessSP process_sp;
3067 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3068 if (data)
3069 process_sp = data->GetProcessSP();
3070 return process_sp;
3071}
3072
3073StateType
3074Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3075{
3076 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3077 if (data == NULL)
3078 return eStateInvalid;
3079 else
3080 return data->GetState();
3081}
3082
3083bool
3084Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3085{
3086 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3087 if (data == NULL)
3088 return false;
3089 else
3090 return data->GetRestarted();
3091}
3092
3093void
3094Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3095{
3096 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3097 if (data != NULL)
3098 data->SetRestarted(new_value);
3099}
3100
3101bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003102Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3103{
3104 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3105 if (data == NULL)
3106 return false;
3107 else
3108 return data->GetInterrupted ();
3109}
3110
3111void
3112Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3113{
3114 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3115 if (data != NULL)
3116 data->SetInterrupted(new_value);
3117}
3118
3119bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003120Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3121{
3122 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3123 if (data)
3124 {
3125 data->SetUpdateStateOnRemoval();
3126 return true;
3127 }
3128 return false;
3129}
3130
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003131void
Greg Clayton0603aa92010-10-04 01:05:56 +00003132Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003133{
Greg Claytonc14ee322011-09-22 04:58:26 +00003134 exe_ctx.SetTargetPtr (&m_target);
3135 exe_ctx.SetProcessPtr (this);
3136 exe_ctx.SetThreadPtr(NULL);
3137 exe_ctx.SetFramePtr (NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003138}
3139
3140lldb::ProcessSP
3141Process::GetSP ()
3142{
3143 return GetTarget().GetProcessSP();
3144}
3145
Greg Claytone996fd32011-03-08 22:40:15 +00003146//uint32_t
3147//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3148//{
3149// return 0;
3150//}
3151//
3152//ArchSpec
3153//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3154//{
3155// return Host::GetArchSpecForExistingProcess (pid);
3156//}
3157//
3158//ArchSpec
3159//Process::GetArchSpecForExistingProcess (const char *process_name)
3160//{
3161// return Host::GetArchSpecForExistingProcess (process_name);
3162//}
3163//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003164void
3165Process::AppendSTDOUT (const char * s, size_t len)
3166{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003167 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003168 m_stdout_data.append (s, len);
3169
Greg Claytona9ff3062010-12-05 19:16:56 +00003170 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003171}
3172
3173void
3174Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3175{
3176 Process *process = (Process *) baton;
3177 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3178}
3179
3180size_t
3181Process::ProcessInputReaderCallback (void *baton,
3182 InputReader &reader,
3183 lldb::InputReaderAction notification,
3184 const char *bytes,
3185 size_t bytes_len)
3186{
3187 Process *process = (Process *) baton;
3188
3189 switch (notification)
3190 {
3191 case eInputReaderActivate:
3192 break;
3193
3194 case eInputReaderDeactivate:
3195 break;
3196
3197 case eInputReaderReactivate:
3198 break;
3199
Caroline Tice969ed3d2011-05-02 20:41:46 +00003200 case eInputReaderAsynchronousOutputWritten:
3201 break;
3202
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003203 case eInputReaderGotToken:
3204 {
3205 Error error;
3206 process->PutSTDIN (bytes, bytes_len, error);
3207 }
3208 break;
3209
Caroline Ticeefed6132010-11-19 20:47:54 +00003210 case eInputReaderInterrupt:
3211 process->Halt ();
3212 break;
3213
3214 case eInputReaderEndOfFile:
3215 process->AppendSTDOUT ("^D", 2);
3216 break;
3217
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003218 case eInputReaderDone:
3219 break;
3220
3221 }
3222
3223 return bytes_len;
3224}
3225
3226void
3227Process::ResetProcessInputReader ()
3228{
3229 m_process_input_reader.reset();
3230}
3231
3232void
3233Process::SetUpProcessInputReader (int file_descriptor)
3234{
3235 // First set up the Read Thread for reading/handling process I/O
3236
3237 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3238
3239 if (conn_ap.get())
3240 {
3241 m_stdio_communication.SetConnection (conn_ap.release());
3242 if (m_stdio_communication.IsConnected())
3243 {
3244 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3245 m_stdio_communication.StartReadThread();
3246
3247 // Now read thread is set up, set up input reader.
3248
3249 if (!m_process_input_reader.get())
3250 {
3251 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3252 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3253 this,
3254 eInputReaderGranularityByte,
3255 NULL,
3256 NULL,
3257 false));
3258
3259 if (err.Fail())
3260 m_process_input_reader.reset();
3261 }
3262 }
3263 }
3264}
3265
3266void
3267Process::PushProcessInputReader ()
3268{
3269 if (m_process_input_reader && !m_process_input_reader->IsActive())
3270 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3271}
3272
3273void
3274Process::PopProcessInputReader ()
3275{
3276 if (m_process_input_reader && m_process_input_reader->IsActive())
3277 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3278}
3279
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003280// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003281void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003282Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003283{
Greg Claytone0d378b2011-03-24 21:19:54 +00003284 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003285
3286 int i=0;
3287 const char *name;
3288 OptionEnumValueElement option_enum;
3289 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3290 {
3291 if (name)
3292 {
3293 option_enum.value = i;
3294 option_enum.string_value = name;
3295 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3296 g_plugins.push_back (option_enum);
3297 }
3298 ++i;
3299 }
3300 option_enum.value = 0;
3301 option_enum.string_value = NULL;
3302 option_enum.usage = NULL;
3303 g_plugins.push_back (option_enum);
3304
3305 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3306 {
3307 if (::strcmp (name, "plugin") == 0)
3308 {
3309 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3310 break;
3311 }
3312 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003313 UserSettingsControllerSP &usc = GetSettingsController();
3314 usc.reset (new SettingsController);
3315 UserSettingsController::InitializeSettingsController (usc,
3316 SettingsController::global_settings_table,
3317 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003318
3319 // Now call SettingsInitialize() for each 'child' of Process settings
3320 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003321}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003322
Greg Clayton99d0faf2010-11-18 23:32:35 +00003323void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003324Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003325{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003326 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3327
3328 Thread::SettingsTerminate ();
3329
3330 // Now terminate Process Settings.
3331
Greg Clayton99d0faf2010-11-18 23:32:35 +00003332 UserSettingsControllerSP &usc = GetSettingsController();
3333 UserSettingsController::FinalizeSettingsController (usc);
3334 usc.reset();
3335}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003336
Greg Clayton99d0faf2010-11-18 23:32:35 +00003337UserSettingsControllerSP &
3338Process::GetSettingsController ()
3339{
3340 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003341 return g_settings_controller;
3342}
3343
Caroline Tice1559a462010-09-27 00:30:10 +00003344void
3345Process::UpdateInstanceName ()
3346{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003347 Module *module = GetTarget().GetExecutableModulePointer();
3348 if (module)
Caroline Tice1559a462010-09-27 00:30:10 +00003349 {
3350 StreamString sstr;
Greg Claytonaa149cb2011-08-11 02:48:45 +00003351 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003352
Greg Claytondbe54502010-11-19 03:46:01 +00003353 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Clayton8b82f082011-04-12 05:54:46 +00003354 sstr.GetData());
Caroline Tice1559a462010-09-27 00:30:10 +00003355 }
3356}
3357
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003358ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003359Process::RunThreadPlan (ExecutionContext &exe_ctx,
3360 lldb::ThreadPlanSP &thread_plan_sp,
3361 bool stop_others,
3362 bool try_all_threads,
3363 bool discard_on_error,
3364 uint32_t single_thread_timeout_usec,
3365 Stream &errors)
3366{
3367 ExecutionResults return_value = eExecutionSetupError;
3368
Jim Ingham77787032011-01-20 02:03:18 +00003369 if (thread_plan_sp.get() == NULL)
3370 {
3371 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003372 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003373 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003374
3375 if (exe_ctx.GetProcessPtr() != this)
3376 {
3377 errors.Printf("RunThreadPlan called on wrong process.");
3378 return eExecutionSetupError;
3379 }
3380
3381 Thread *thread = exe_ctx.GetThreadPtr();
3382 if (thread == NULL)
3383 {
3384 errors.Printf("RunThreadPlan called with invalid thread.");
3385 return eExecutionSetupError;
3386 }
Jim Ingham77787032011-01-20 02:03:18 +00003387
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003388 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3389 // For that to be true the plan can't be private - since private plans suppress themselves in the
3390 // GetCompletedPlan call.
3391
3392 bool orig_plan_private = thread_plan_sp->GetPrivate();
3393 thread_plan_sp->SetPrivate(false);
3394
Jim Ingham444586b2011-01-24 06:34:17 +00003395 if (m_private_state.GetValue() != eStateStopped)
3396 {
3397 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003398 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003399 }
3400
Jim Ingham66243842011-08-13 00:56:10 +00003401 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Claytonc14ee322011-09-22 04:58:26 +00003402 const uint32_t thread_idx_id = thread->GetIndexID();
3403 StackID ctx_frame_id = thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003404
3405 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3406 // so we should arrange to reset them as well.
3407
Greg Claytonc14ee322011-09-22 04:58:26 +00003408 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003409
Jim Ingham66243842011-08-13 00:56:10 +00003410 uint32_t selected_tid;
3411 StackID selected_stack_id;
Greg Clayton762f7132011-09-18 18:59:15 +00003412 if (selected_thread_sp)
Jim Inghamf48169b2010-11-30 02:22:11 +00003413 {
3414 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003415 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003416 }
3417 else
3418 {
3419 selected_tid = LLDB_INVALID_THREAD_ID;
3420 }
3421
Greg Claytonc14ee322011-09-22 04:58:26 +00003422 thread->QueueThreadPlan(thread_plan_sp, true);
Jim Inghamf48169b2010-11-30 02:22:11 +00003423
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003424 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003425
3426 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3427 // restored on exit to the function.
3428
3429 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003430
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003431 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003432 if (log)
3433 {
3434 StreamString s;
3435 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Greg Clayton81c22f62011-10-19 18:09:39 +00003436 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4llx to run thread plan \"%s\".",
Greg Claytonc14ee322011-09-22 04:58:26 +00003437 thread->GetIndexID(),
3438 thread->GetID(),
Jim Ingham0f16e732011-02-08 05:20:59 +00003439 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003440 }
3441
Jim Ingham0f16e732011-02-08 05:20:59 +00003442 bool got_event;
3443 lldb::EventSP event_sp;
3444 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003445
3446 TimeValue* timeout_ptr = NULL;
3447 TimeValue real_timeout;
3448
Jim Ingham0f16e732011-02-08 05:20:59 +00003449 bool first_timeout = true;
3450 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003451
Jim Inghamf48169b2010-11-30 02:22:11 +00003452 while (1)
3453 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003454 // We usually want to resume the process if we get to the top of the loop.
3455 // The only exception is if we get two running events with no intervening
3456 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003457
Jim Ingham0f16e732011-02-08 05:20:59 +00003458 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003459 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003460 // Do the initial resume and wait for the running event before going further.
3461
Greg Claytonc14ee322011-09-22 04:58:26 +00003462 Error resume_error = Resume ();
Jim Ingham0f16e732011-02-08 05:20:59 +00003463 if (!resume_error.Success())
3464 {
3465 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003466 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003467 break;
3468 }
3469
3470 real_timeout = TimeValue::Now();
3471 real_timeout.OffsetWithMicroSeconds(500000);
3472 timeout_ptr = &real_timeout;
3473
3474 got_event = listener.WaitForEvent(NULL, event_sp);
3475 if (!got_event)
3476 {
3477 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003478 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003479
3480 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003481 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003482 break;
3483 }
3484
3485 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3486 if (stop_state != eStateRunning)
3487 {
3488 if (log)
3489 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3490
3491 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003492 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003493 break;
3494 }
3495
3496 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003497 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003498 // We need to call the function synchronously, so spin waiting for it to return.
3499 // If we get interrupted while executing, we're going to lose our context, and
3500 // won't be able to gather the result at this point.
3501 // We set the timeout AFTER the resume, since the resume takes some time and we
3502 // don't want to charge that to the timeout.
3503
3504 if (single_thread_timeout_usec != 0)
3505 {
3506 real_timeout = TimeValue::Now();
3507 if (first_timeout)
3508 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3509 else
3510 real_timeout.OffsetWithSeconds(10);
3511
3512 timeout_ptr = &real_timeout;
3513 }
3514 }
3515 else
3516 {
3517 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003518 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003519 do_resume = true;
3520 }
3521
3522 // Now wait for the process to stop again:
3523 stop_state = lldb::eStateInvalid;
3524 event_sp.reset();
3525 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3526
3527 if (got_event)
3528 {
3529 if (event_sp.get())
3530 {
3531 bool keep_going = false;
3532 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3533 if (log)
3534 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3535
3536 switch (stop_state)
3537 {
3538 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00003539 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003540 // Yay, we're done. Now make sure that our thread plan actually completed.
Greg Claytonc14ee322011-09-22 04:58:26 +00003541 ThreadSP thread_sp = GetThreadList().FindThreadByIndexID (thread_idx_id);
Greg Clayton54e8ac52011-06-03 22:12:42 +00003542 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00003543 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003544 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00003545 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00003546 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3547 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00003548 }
3549 else
3550 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003551 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3552 StopReason stop_reason = eStopReasonInvalid;
3553 if (stop_info_sp)
3554 stop_reason = stop_info_sp->GetStopReason();
3555 if (stop_reason == eStopReasonPlanComplete)
3556 {
3557 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003558 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003559 // Now mark this plan as private so it doesn't get reported as the stop reason
3560 // after this point.
3561 if (thread_plan_sp)
3562 thread_plan_sp->SetPrivate (orig_plan_private);
3563 return_value = eExecutionCompleted;
3564 }
3565 else
3566 {
3567 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003568 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003569
3570 return_value = eExecutionInterrupted;
3571 }
Jim Ingham160f78c2011-05-17 01:10:11 +00003572 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00003573 }
3574 break;
3575
Jim Ingham0f16e732011-02-08 05:20:59 +00003576 case lldb::eStateCrashed:
3577 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003578 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003579 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003580 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003581
Jim Ingham0f16e732011-02-08 05:20:59 +00003582 case lldb::eStateRunning:
3583 do_resume = false;
3584 keep_going = true;
3585 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003586
Jim Ingham0f16e732011-02-08 05:20:59 +00003587 default:
3588 if (log)
3589 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00003590
3591 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003592 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003593 break;
3594 }
3595 if (keep_going)
3596 continue;
3597 else
3598 break;
3599 }
3600 else
3601 {
3602 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003603 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00003604 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003605 break;
3606 }
3607 }
3608 else
3609 {
3610 // If we didn't get an event that means we've timed out...
3611 // We will interrupt the process here. Depending on what we were asked to do we will
3612 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00003613 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00003614
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003615 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00003616 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00003617 {
3618 if (first_timeout)
3619 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3620 "trying with all threads enabled.",
3621 single_thread_timeout_usec);
3622 else
3623 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3624 "and timeout: %d timed out.",
3625 single_thread_timeout_usec);
3626 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003627 else
Jim Ingham0f16e732011-02-08 05:20:59 +00003628 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3629 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00003630 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003631 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003632
Greg Claytonc14ee322011-09-22 04:58:26 +00003633 Error halt_error = Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00003634 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00003635 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003636 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003637 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003638
Jim Ingham0f16e732011-02-08 05:20:59 +00003639 // If halt succeeds, it always produces a stopped event. Wait for that:
3640
3641 real_timeout = TimeValue::Now();
3642 real_timeout.OffsetWithMicroSeconds(500000);
3643
3644 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00003645
3646 if (got_event)
3647 {
3648 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3649 if (log)
3650 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003651 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00003652 if (stop_state == lldb::eStateStopped
3653 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00003654 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003655 }
3656
Jim Ingham0f16e732011-02-08 05:20:59 +00003657 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00003658 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003659 // 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:
Jim Inghamf48169b2010-11-30 02:22:11 +00003661
Greg Claytonc14ee322011-09-22 04:58:26 +00003662 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00003663 {
3664 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003665 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003666 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003667 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003668 break;
3669 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003670
Jim Ingham0f16e732011-02-08 05:20:59 +00003671 if (!try_all_threads)
3672 {
3673 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003674 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003675 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003676 break;
3677 }
3678
3679 if (first_timeout)
3680 {
3681 // Set all the other threads to run, and return to the top of the loop, which will continue;
3682 first_timeout = false;
3683 thread_plan_sp->SetStopOthers (false);
3684 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003685 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003686
3687 continue;
3688 }
3689 else
3690 {
3691 // Running all threads failed, so return Interrupted.
3692 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003693 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003694 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003695 break;
3696 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003697 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003698 }
3699 else
3700 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003701 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003702 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003703 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003704 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00003705 }
3706 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003707 else
3708 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003709 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3710 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00003711 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003712 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.",
3713 halt_error.AsCString());
3714 real_timeout = TimeValue::Now();
3715 real_timeout.OffsetWithMicroSeconds(500000);
3716 timeout_ptr = &real_timeout;
3717 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3718 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003719 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003720 // This is not going anywhere, bag out.
3721 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003722 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003723 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003724 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003725 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003726 else
3727 {
3728 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3729 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003730 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00003731 if (stop_state == lldb::eStateStopped)
3732 {
3733 // Between the time we initiated the Halt and the time we delivered it, the process could have
3734 // already finished its job. Check that here:
3735
Greg Claytonc14ee322011-09-22 04:58:26 +00003736 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Ingham0f16e732011-02-08 05:20:59 +00003737 {
3738 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003739 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003740 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003741 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003742 break;
3743 }
3744
3745 if (first_timeout)
3746 {
3747 // Set all the other threads to run, and return to the top of the loop, which will continue;
3748 first_timeout = false;
3749 thread_plan_sp->SetStopOthers (false);
3750 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003751 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003752
3753 continue;
3754 }
3755 else
3756 {
3757 // Running all threads failed, so return Interrupted.
3758 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003759 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003760 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003761 break;
3762 }
3763 }
3764 else
3765 {
Sean Callanan39821ac2011-08-09 22:07:08 +00003766 if (log)
3767 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3768 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003769 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003770 break;
3771 }
3772 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003773 }
3774
Jim Inghamf48169b2010-11-30 02:22:11 +00003775 }
3776
Jim Ingham0f16e732011-02-08 05:20:59 +00003777 } // END WAIT LOOP
3778
3779 // Now do some processing on the results of the run:
3780 if (return_value == eExecutionInterrupted)
3781 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003782 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003783 {
3784 StreamString s;
3785 if (event_sp)
3786 event_sp->Dump (&s);
3787 else
3788 {
Jim Ingham20829ac2011-08-09 22:24:33 +00003789 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003790 }
3791
3792 StreamString ts;
3793
Jim Ingham20829ac2011-08-09 22:24:33 +00003794 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00003795
3796 do
3797 {
3798 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3799
3800 if (!event_data)
3801 {
3802 event_explanation = "<no event data>";
3803 break;
3804 }
3805
3806 Process *process = event_data->GetProcessSP().get();
3807
3808 if (!process)
3809 {
3810 event_explanation = "<no process>";
3811 break;
3812 }
3813
3814 ThreadList &thread_list = process->GetThreadList();
3815
3816 uint32_t num_threads = thread_list.GetSize();
3817 uint32_t thread_index;
3818
3819 ts.Printf("<%u threads> ", num_threads);
3820
3821 for (thread_index = 0;
3822 thread_index < num_threads;
3823 ++thread_index)
3824 {
3825 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3826
3827 if (!thread)
3828 {
3829 ts.Printf("<?> ");
3830 continue;
3831 }
3832
Greg Clayton81c22f62011-10-19 18:09:39 +00003833 ts.Printf("<0x%4.4llx ", thread->GetID());
Jim Ingham0f16e732011-02-08 05:20:59 +00003834 RegisterContext *register_context = thread->GetRegisterContext().get();
3835
3836 if (register_context)
3837 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3838 else
3839 ts.Printf("[ip unknown] ");
3840
3841 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3842 if (stop_info_sp)
3843 {
3844 const char *stop_desc = stop_info_sp->GetDescription();
3845 if (stop_desc)
3846 ts.PutCString (stop_desc);
3847 }
3848 ts.Printf(">");
3849 }
3850
3851 event_explanation = ts.GetData();
3852 } while (0);
3853
3854 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003855 {
3856 if (event_explanation)
3857 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3858 else
3859 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
3860 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003861
3862 if (discard_on_error && thread_plan_sp)
3863 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003864 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003865 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00003866 }
3867 }
3868 }
3869 else if (return_value == eExecutionSetupError)
3870 {
3871 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003872 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003873
3874 if (discard_on_error && thread_plan_sp)
3875 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003876 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003877 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00003878 }
3879 }
3880 else
3881 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003882 if (thread->IsThreadPlanDone (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00003883 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003884 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003885 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00003886 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00003887 }
Greg Claytonc14ee322011-09-22 04:58:26 +00003888 else if (thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
Jim Inghamf48169b2010-11-30 02:22:11 +00003889 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003890 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003891 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00003892 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00003893 }
3894 else
3895 {
3896 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003897 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00003898 if (discard_on_error && thread_plan_sp)
3899 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003900 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003901 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Greg Claytonc14ee322011-09-22 04:58:26 +00003902 thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003903 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00003904 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003905 }
3906 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003907
Jim Inghamf48169b2010-11-30 02:22:11 +00003908 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00003909 // Check that it's still there, and if it is put it back in the context. Also restore the
3910 // frame in the context if it is still present.
Greg Claytonc14ee322011-09-22 04:58:26 +00003911 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
3912 if (thread)
Jim Ingham66243842011-08-13 00:56:10 +00003913 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003914 exe_ctx.SetFrameSP (thread->GetFrameWithStackID (ctx_frame_id));
Jim Ingham66243842011-08-13 00:56:10 +00003915 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003916
3917 // Also restore the current process'es selected frame & thread, since this function calling may
3918 // be done behind the user's back.
3919
3920 if (selected_tid != LLDB_INVALID_THREAD_ID)
3921 {
Greg Claytonc14ee322011-09-22 04:58:26 +00003922 if (GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00003923 {
3924 // We were able to restore the selected thread, now restore the frame:
Greg Claytonc14ee322011-09-22 04:58:26 +00003925 StackFrameSP old_frame_sp = GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
Jim Ingham66243842011-08-13 00:56:10 +00003926 if (old_frame_sp)
Greg Claytonc14ee322011-09-22 04:58:26 +00003927 GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00003928 }
3929 }
3930
3931 return return_value;
3932}
3933
3934const char *
3935Process::ExecutionResultAsCString (ExecutionResults result)
3936{
3937 const char *result_name;
3938
3939 switch (result)
3940 {
Greg Claytone0d378b2011-03-24 21:19:54 +00003941 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003942 result_name = "eExecutionCompleted";
3943 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003944 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00003945 result_name = "eExecutionDiscarded";
3946 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003947 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003948 result_name = "eExecutionInterrupted";
3949 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003950 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00003951 result_name = "eExecutionSetupError";
3952 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003953 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00003954 result_name = "eExecutionTimedOut";
3955 break;
3956 }
3957 return result_name;
3958}
3959
Greg Clayton7260f622011-04-18 08:33:37 +00003960void
3961Process::GetStatus (Stream &strm)
3962{
3963 const StateType state = GetState();
3964 if (StateIsStoppedState(state))
3965 {
3966 if (state == eStateExited)
3967 {
3968 int exit_status = GetExitStatus();
3969 const char *exit_description = GetExitDescription();
Greg Clayton81c22f62011-10-19 18:09:39 +00003970 strm.Printf ("Process %llu exited with status = %i (0x%8.8x) %s\n",
Greg Clayton7260f622011-04-18 08:33:37 +00003971 GetID(),
3972 exit_status,
3973 exit_status,
3974 exit_description ? exit_description : "");
3975 }
3976 else
3977 {
3978 if (state == eStateConnected)
3979 strm.Printf ("Connected to remote target.\n");
3980 else
Greg Clayton81c22f62011-10-19 18:09:39 +00003981 strm.Printf ("Process %llu %s\n", GetID(), StateAsCString (state));
Greg Clayton7260f622011-04-18 08:33:37 +00003982 }
3983 }
3984 else
3985 {
Greg Clayton81c22f62011-10-19 18:09:39 +00003986 strm.Printf ("Process %llu is running.\n", GetID());
Greg Clayton7260f622011-04-18 08:33:37 +00003987 }
3988}
3989
3990size_t
3991Process::GetThreadStatus (Stream &strm,
3992 bool only_threads_with_stop_reason,
3993 uint32_t start_frame,
3994 uint32_t num_frames,
3995 uint32_t num_frames_with_source)
3996{
3997 size_t num_thread_infos_dumped = 0;
3998
3999 const size_t num_threads = GetThreadList().GetSize();
4000 for (uint32_t i = 0; i < num_threads; i++)
4001 {
4002 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
4003 if (thread)
4004 {
4005 if (only_threads_with_stop_reason)
4006 {
4007 if (thread->GetStopInfo().get() == NULL)
4008 continue;
4009 }
4010 thread->GetStatus (strm,
4011 start_frame,
4012 num_frames,
4013 num_frames_with_source);
4014 ++num_thread_infos_dumped;
4015 }
4016 }
4017 return num_thread_infos_dumped;
4018}
4019
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004020//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004021// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004022//--------------------------------------------------------------
4023
Greg Clayton1b654882010-09-19 02:33:57 +00004024Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004025 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004026{
Greg Clayton85851dd2010-12-04 00:10:17 +00004027 m_default_settings.reset (new ProcessInstanceSettings (*this,
4028 false,
Caroline Tice91123da2010-09-08 17:48:55 +00004029 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004030}
4031
Greg Clayton1b654882010-09-19 02:33:57 +00004032Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004033{
4034}
4035
4036lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004037Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004038{
Greg Claytondbe54502010-11-19 03:46:01 +00004039 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4040 false,
4041 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004042 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4043 return new_settings_sp;
4044}
4045
4046//--------------------------------------------------------------
4047// class ProcessInstanceSettings
4048//--------------------------------------------------------------
4049
Greg Clayton85851dd2010-12-04 00:10:17 +00004050ProcessInstanceSettings::ProcessInstanceSettings
4051(
4052 UserSettingsController &owner,
4053 bool live_instance,
4054 const char *name
4055) :
4056 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004057 m_run_args (),
4058 m_env_vars (),
4059 m_input_path (),
4060 m_output_path (),
4061 m_error_path (),
Caroline Ticef8da8632010-12-03 18:46:09 +00004062 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00004063 m_disable_stdio (false),
4064 m_inherit_host_env (true),
4065 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004066{
Caroline Ticef20e8232010-09-09 18:26:37 +00004067 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4068 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4069 // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
Caroline Tice9e41c152010-09-16 19:05:55 +00004070 // This is true for CreateInstanceName() too.
4071
4072 if (GetInstanceName () == InstanceSettings::InvalidName())
4073 {
4074 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4075 m_owner.RegisterInstanceSettings (this);
4076 }
Caroline Ticef20e8232010-09-09 18:26:37 +00004077
4078 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004079 {
4080 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4081 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00004082 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004083 }
4084}
4085
4086ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00004087 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004088 m_run_args (rhs.m_run_args),
4089 m_env_vars (rhs.m_env_vars),
4090 m_input_path (rhs.m_input_path),
4091 m_output_path (rhs.m_output_path),
4092 m_error_path (rhs.m_error_path),
Caroline Ticef8da8632010-12-03 18:46:09 +00004093 m_disable_aslr (rhs.m_disable_aslr),
4094 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004095{
4096 if (m_instance_name != InstanceSettings::GetDefaultName())
4097 {
4098 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4099 CopyInstanceSettings (pending_settings,false);
4100 m_owner.RemovePendingSettings (m_instance_name);
4101 }
4102}
4103
4104ProcessInstanceSettings::~ProcessInstanceSettings ()
4105{
4106}
4107
4108ProcessInstanceSettings&
4109ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4110{
4111 if (this != &rhs)
4112 {
4113 m_run_args = rhs.m_run_args;
4114 m_env_vars = rhs.m_env_vars;
4115 m_input_path = rhs.m_input_path;
4116 m_output_path = rhs.m_output_path;
4117 m_error_path = rhs.m_error_path;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004118 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00004119 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00004120 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004121 }
4122
4123 return *this;
4124}
4125
4126
4127void
4128ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4129 const char *index_value,
4130 const char *value,
4131 const ConstString &instance_name,
4132 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004133 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004134 Error &err,
4135 bool pending)
4136{
4137 if (var_name == RunArgsVarName())
4138 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
4139 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00004140 {
Greg Clayton8b82f082011-04-12 05:54:46 +00004141 // This is nice for local debugging, but it is isn't correct for
4142 // remote debugging. We need to stop process.env-vars from being
4143 // populated with the host environment and add this as a launch option
4144 // and get the correct environment from the Target's platform.
4145 // GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004146 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00004147 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004148 else if (var_name == InputPathVarName())
4149 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
4150 else if (var_name == OutputPathVarName())
4151 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
4152 else if (var_name == ErrorPathVarName())
4153 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004154 else if (var_name == DisableASLRVarName())
Greg Clayton385aa282011-04-22 03:55:06 +00004155 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, true, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00004156 else if (var_name == DisableSTDIOVarName ())
Greg Clayton385aa282011-04-22 03:55:06 +00004157 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, false, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004158}
4159
4160void
4161ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4162 bool pending)
4163{
4164 if (new_settings.get() == NULL)
4165 return;
4166
4167 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
4168
4169 m_run_args = new_process_settings->m_run_args;
4170 m_env_vars = new_process_settings->m_env_vars;
4171 m_input_path = new_process_settings->m_input_path;
4172 m_output_path = new_process_settings->m_output_path;
4173 m_error_path = new_process_settings->m_error_path;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004174 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00004175 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004176}
4177
Caroline Tice12cecd72010-09-20 21:37:42 +00004178bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004179ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4180 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004181 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004182 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004183{
4184 if (var_name == RunArgsVarName())
4185 {
4186 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00004187 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004188 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
4189 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00004190 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004191 }
4192 else if (var_name == EnvVarsVarName())
4193 {
Greg Clayton85851dd2010-12-04 00:10:17 +00004194 GetHostEnvironmentIfNeeded ();
4195
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004196 if (m_env_vars.size() > 0)
4197 {
4198 std::map<std::string, std::string>::iterator pos;
4199 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
4200 {
4201 StreamString value_str;
4202 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
4203 value.AppendString (value_str.GetData());
4204 }
4205 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004206 }
4207 else if (var_name == InputPathVarName())
4208 {
4209 value.AppendString (m_input_path.c_str());
4210 }
4211 else if (var_name == OutputPathVarName())
4212 {
4213 value.AppendString (m_output_path.c_str());
4214 }
4215 else if (var_name == ErrorPathVarName())
4216 {
4217 value.AppendString (m_error_path.c_str());
4218 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00004219 else if (var_name == InheritHostEnvVarName())
4220 {
4221 if (m_inherit_host_env)
4222 value.AppendString ("true");
4223 else
4224 value.AppendString ("false");
4225 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004226 else if (var_name == DisableASLRVarName())
4227 {
4228 if (m_disable_aslr)
4229 value.AppendString ("true");
4230 else
4231 value.AppendString ("false");
4232 }
Caroline Ticef8da8632010-12-03 18:46:09 +00004233 else if (var_name == DisableSTDIOVarName())
4234 {
4235 if (m_disable_stdio)
4236 value.AppendString ("true");
4237 else
4238 value.AppendString ("false");
4239 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004240 else
Caroline Tice12cecd72010-09-20 21:37:42 +00004241 {
4242 if (err)
4243 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4244 return false;
4245 }
4246 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004247}
4248
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004249const ConstString
4250ProcessInstanceSettings::CreateInstanceName ()
4251{
4252 static int instance_count = 1;
4253 StreamString sstr;
4254
4255 sstr.Printf ("process_%d", instance_count);
4256 ++instance_count;
4257
4258 const ConstString ret_val (sstr.GetData());
4259 return ret_val;
4260}
4261
4262const ConstString &
4263ProcessInstanceSettings::RunArgsVarName ()
4264{
4265 static ConstString run_args_var_name ("run-args");
4266
4267 return run_args_var_name;
4268}
4269
4270const ConstString &
4271ProcessInstanceSettings::EnvVarsVarName ()
4272{
4273 static ConstString env_vars_var_name ("env-vars");
4274
4275 return env_vars_var_name;
4276}
4277
4278const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00004279ProcessInstanceSettings::InheritHostEnvVarName ()
4280{
4281 static ConstString g_name ("inherit-env");
4282
4283 return g_name;
4284}
4285
4286const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004287ProcessInstanceSettings::InputPathVarName ()
4288{
4289 static ConstString input_path_var_name ("input-path");
4290
4291 return input_path_var_name;
4292}
4293
4294const ConstString &
4295ProcessInstanceSettings::OutputPathVarName ()
4296{
Caroline Tice49e27372010-09-07 18:35:40 +00004297 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004298
4299 return output_path_var_name;
4300}
4301
4302const ConstString &
4303ProcessInstanceSettings::ErrorPathVarName ()
4304{
Caroline Tice49e27372010-09-07 18:35:40 +00004305 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004306
4307 return error_path_var_name;
4308}
4309
4310const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004311ProcessInstanceSettings::DisableASLRVarName ()
4312{
4313 static ConstString disable_aslr_var_name ("disable-aslr");
4314
4315 return disable_aslr_var_name;
4316}
4317
Caroline Ticef8da8632010-12-03 18:46:09 +00004318const ConstString &
4319ProcessInstanceSettings::DisableSTDIOVarName ()
4320{
4321 static ConstString disable_stdio_var_name ("disable-stdio");
4322
4323 return disable_stdio_var_name;
4324}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004325
4326//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004327// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004328//--------------------------------------------------
4329
4330SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004331Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004332{
4333 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4334 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4335};
4336
4337
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004338SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004339Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004340{
Greg Clayton85851dd2010-12-04 00:10:17 +00004341 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
4342 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
4343 { "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." },
4344 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonbd82a5d2011-01-23 05:56:20 +00004345 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
4346 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
4347 { "error-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writings its error messages." },
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00004348 { "plugin", eSetVarTypeEnum, NULL, NULL, false, false, "The plugin to be used to run the process." },
Greg Clayton85851dd2010-12-04 00:10:17 +00004349 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
4350 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
4351 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004352};
4353
4354
Jim Ingham5aee1622010-08-09 23:31:02 +00004355