blob: 8f57d1cded0c674070de0308a43b7ab8c80effc1 [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 {
170 s.Printf ("%-10s %.*-7s ",
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:
423 error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
424 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),
Greg Clayton513c26c2011-01-29 07:10:55 +0000603 m_next_event_action_ap()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000604{
Caroline Tice1559a462010-09-27 00:30:10 +0000605 UpdateInstanceName();
606
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000607 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000608 if (log)
609 log->Printf ("%p Process::Process()", this);
610
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000611 SetEventName (eBroadcastBitStateChanged, "state-changed");
612 SetEventName (eBroadcastBitInterrupt, "interrupt");
613 SetEventName (eBroadcastBitSTDOUT, "stdout-available");
614 SetEventName (eBroadcastBitSTDERR, "stderr-available");
615
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000616 listener.StartListeningForEvents (this,
617 eBroadcastBitStateChanged |
618 eBroadcastBitInterrupt |
619 eBroadcastBitSTDOUT |
620 eBroadcastBitSTDERR);
621
622 m_private_state_listener.StartListeningForEvents(&m_private_state_broadcaster,
623 eBroadcastBitStateChanged);
624
625 m_private_state_listener.StartListeningForEvents(&m_private_state_control_broadcaster,
626 eBroadcastInternalStateControlStop |
627 eBroadcastInternalStateControlPause |
628 eBroadcastInternalStateControlResume);
629}
630
631//----------------------------------------------------------------------
632// Destructor
633//----------------------------------------------------------------------
634Process::~Process()
635{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000636 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000637 if (log)
638 log->Printf ("%p Process::~Process()", this);
639 StopPrivateStateThread();
640}
641
642void
643Process::Finalize()
644{
645 // Do any cleanup needed prior to being destructed... Subclasses
646 // that override this method should call this superclass method as well.
Jim Inghamd0a3e122011-02-16 17:54:55 +0000647
648 // We need to destroy the loader before the derived Process class gets destroyed
649 // since it is very likely that undoing the loader will require access to the real process.
Greg Clayton56d9a1b2011-08-22 02:49:39 +0000650 m_dyld_ap.reset();
651 m_os_ap.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652}
653
654void
655Process::RegisterNotificationCallbacks (const Notifications& callbacks)
656{
657 m_notifications.push_back(callbacks);
658 if (callbacks.initialize != NULL)
659 callbacks.initialize (callbacks.baton, this);
660}
661
662bool
663Process::UnregisterNotificationCallbacks(const Notifications& callbacks)
664{
665 std::vector<Notifications>::iterator pos, end = m_notifications.end();
666 for (pos = m_notifications.begin(); pos != end; ++pos)
667 {
668 if (pos->baton == callbacks.baton &&
669 pos->initialize == callbacks.initialize &&
670 pos->process_state_changed == callbacks.process_state_changed)
671 {
672 m_notifications.erase(pos);
673 return true;
674 }
675 }
676 return false;
677}
678
679void
680Process::SynchronouslyNotifyStateChanged (StateType state)
681{
682 std::vector<Notifications>::iterator notification_pos, notification_end = m_notifications.end();
683 for (notification_pos = m_notifications.begin(); notification_pos != notification_end; ++notification_pos)
684 {
685 if (notification_pos->process_state_changed)
686 notification_pos->process_state_changed (notification_pos->baton, this, state);
687 }
688}
689
690// FIXME: We need to do some work on events before the general Listener sees them.
691// For instance if we are continuing from a breakpoint, we need to ensure that we do
692// the little "insert real insn, step & stop" trick. But we can't do that when the
693// event is delivered by the broadcaster - since that is done on the thread that is
694// waiting for new events, so if we needed more than one event for our handling, we would
695// stall. So instead we do it when we fetch the event off of the queue.
696//
697
698StateType
699Process::GetNextEvent (EventSP &event_sp)
700{
701 StateType state = eStateInvalid;
702
703 if (m_listener.GetNextEventForBroadcaster (this, event_sp) && event_sp)
704 state = Process::ProcessEventData::GetStateFromEvent (event_sp.get());
705
706 return state;
707}
708
709
710StateType
711Process::WaitForProcessToStop (const TimeValue *timeout)
712{
Jim Ingham4b536182011-08-09 02:12:22 +0000713 // We can't just wait for a "stopped" event, because the stopped event may have restarted the target.
714 // We have to actually check each event, and in the case of a stopped event check the restarted flag
715 // on the event.
716 EventSP event_sp;
717 StateType state = GetState();
718 // If we are exited or detached, we won't ever get back to any
719 // other valid state...
720 if (state == eStateDetached || state == eStateExited)
721 return state;
722
723 while (state != eStateInvalid)
724 {
725 state = WaitForStateChangedEvents (timeout, event_sp);
726 switch (state)
727 {
728 case eStateCrashed:
729 case eStateDetached:
730 case eStateExited:
731 case eStateUnloaded:
732 return state;
733 case eStateStopped:
734 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
735 continue;
736 else
737 return state;
738 default:
739 continue;
740 }
741 }
742 return state;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743}
744
745
746StateType
747Process::WaitForState
748(
749 const TimeValue *timeout,
750 const StateType *match_states, const uint32_t num_match_states
751)
752{
753 EventSP event_sp;
754 uint32_t i;
Greg Clayton05faeb72010-10-07 04:19:01 +0000755 StateType state = GetState();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000756 while (state != eStateInvalid)
757 {
Greg Clayton05faeb72010-10-07 04:19:01 +0000758 // If we are exited or detached, we won't ever get back to any
759 // other valid state...
760 if (state == eStateDetached || state == eStateExited)
761 return state;
762
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000763 state = WaitForStateChangedEvents (timeout, event_sp);
764
765 for (i=0; i<num_match_states; ++i)
766 {
767 if (match_states[i] == state)
768 return state;
769 }
770 }
771 return state;
772}
773
Jim Ingham30f9b212010-10-11 23:53:14 +0000774bool
775Process::HijackProcessEvents (Listener *listener)
776{
777 if (listener != NULL)
778 {
779 return HijackBroadcaster(listener, eBroadcastBitStateChanged);
780 }
781 else
782 return false;
783}
784
785void
786Process::RestoreProcessEvents ()
787{
788 RestoreBroadcaster();
789}
790
Jim Ingham0f16e732011-02-08 05:20:59 +0000791bool
792Process::HijackPrivateProcessEvents (Listener *listener)
793{
794 if (listener != NULL)
795 {
796 return m_private_state_broadcaster.HijackBroadcaster(listener, eBroadcastBitStateChanged);
797 }
798 else
799 return false;
800}
801
802void
803Process::RestorePrivateProcessEvents ()
804{
805 m_private_state_broadcaster.RestoreBroadcaster();
806}
807
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000808StateType
809Process::WaitForStateChangedEvents (const TimeValue *timeout, EventSP &event_sp)
810{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000811 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000812
813 if (log)
814 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
815
816 StateType state = eStateInvalid;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000817 if (m_listener.WaitForEventForBroadcasterWithType (timeout,
818 this,
819 eBroadcastBitStateChanged,
820 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000821 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
822
823 if (log)
824 log->Printf ("Process::%s (timeout = %p, event_sp) => %s",
825 __FUNCTION__,
826 timeout,
827 StateAsCString(state));
828 return state;
829}
830
831Event *
832Process::PeekAtStateChangedEvents ()
833{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000834 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835
836 if (log)
837 log->Printf ("Process::%s...", __FUNCTION__);
838
839 Event *event_ptr;
Greg Clayton3fcbed62010-10-19 03:25:40 +0000840 event_ptr = m_listener.PeekAtNextEventForBroadcasterWithType (this,
841 eBroadcastBitStateChanged);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000842 if (log)
843 {
844 if (event_ptr)
845 {
846 log->Printf ("Process::%s (event_ptr) => %s",
847 __FUNCTION__,
848 StateAsCString(ProcessEventData::GetStateFromEvent (event_ptr)));
849 }
850 else
851 {
852 log->Printf ("Process::%s no events found",
853 __FUNCTION__);
854 }
855 }
856 return event_ptr;
857}
858
859StateType
860Process::WaitForStateChangedEventsPrivate (const TimeValue *timeout, EventSP &event_sp)
861{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000862 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000863
864 if (log)
865 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
866
867 StateType state = eStateInvalid;
Greg Clayton6779606a2011-01-22 23:43:18 +0000868 if (m_private_state_listener.WaitForEventForBroadcasterWithType (timeout,
869 &m_private_state_broadcaster,
870 eBroadcastBitStateChanged,
871 event_sp))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000872 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
873
874 // This is a bit of a hack, but when we wait here we could very well return
875 // to the command-line, and that could disable the log, which would render the
876 // log we got above invalid.
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000877 if (log)
Greg Clayton6779606a2011-01-22 23:43:18 +0000878 {
879 if (state == eStateInvalid)
880 log->Printf ("Process::%s (timeout = %p, event_sp) => TIMEOUT", __FUNCTION__, timeout);
881 else
882 log->Printf ("Process::%s (timeout = %p, event_sp) => %s", __FUNCTION__, timeout, StateAsCString(state));
883 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884 return state;
885}
886
887bool
888Process::WaitForEventsPrivate (const TimeValue *timeout, EventSP &event_sp, bool control_only)
889{
Greg Clayton2d4edfb2010-11-06 01:53:30 +0000890 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000891
892 if (log)
893 log->Printf ("Process::%s (timeout = %p, event_sp)...", __FUNCTION__, timeout);
894
895 if (control_only)
896 return m_private_state_listener.WaitForEventForBroadcaster(timeout, &m_private_state_control_broadcaster, event_sp);
897 else
898 return m_private_state_listener.WaitForEvent(timeout, event_sp);
899}
900
901bool
902Process::IsRunning () const
903{
904 return StateIsRunningState (m_public_state.GetValue());
905}
906
907int
908Process::GetExitStatus ()
909{
910 if (m_public_state.GetValue() == eStateExited)
911 return m_exit_status;
912 return -1;
913}
914
Greg Clayton85851dd2010-12-04 00:10:17 +0000915
916void
917Process::ProcessInstanceSettings::GetHostEnvironmentIfNeeded ()
918{
919 if (m_inherit_host_env && !m_got_host_env)
920 {
921 m_got_host_env = true;
922 StringList host_env;
923 const size_t host_env_count = Host::GetEnvironment (host_env);
924 for (size_t idx=0; idx<host_env_count; idx++)
925 {
926 const char *env_entry = host_env.GetStringAtIndex (idx);
927 if (env_entry)
928 {
Greg Claytone2956ee2010-12-15 20:52:40 +0000929 const char *equal_pos = ::strchr(env_entry, '=');
Greg Clayton85851dd2010-12-04 00:10:17 +0000930 if (equal_pos)
931 {
932 std::string key (env_entry, equal_pos - env_entry);
933 std::string value (equal_pos + 1);
934 if (m_env_vars.find (key) == m_env_vars.end())
935 m_env_vars[key] = value;
936 }
937 }
938 }
939 }
940}
941
942
943size_t
944Process::ProcessInstanceSettings::GetEnvironmentAsArgs (Args &env)
945{
946 GetHostEnvironmentIfNeeded ();
947
948 dictionary::const_iterator pos, end = m_env_vars.end();
949 for (pos = m_env_vars.begin(); pos != end; ++pos)
950 {
951 std::string env_var_equal_value (pos->first);
952 env_var_equal_value.append(1, '=');
953 env_var_equal_value.append (pos->second);
954 env.AppendArgument (env_var_equal_value.c_str());
955 }
956 return env.GetArgumentCount();
957}
958
959
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000960const char *
961Process::GetExitDescription ()
962{
963 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
964 return m_exit_string.c_str();
965 return NULL;
966}
967
Greg Clayton6779606a2011-01-22 23:43:18 +0000968bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000969Process::SetExitStatus (int status, const char *cstr)
970{
Greg Clayton414f5d32011-01-25 02:58:48 +0000971 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
972 if (log)
973 log->Printf("Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
974 status, status,
975 cstr ? "\"" : "",
976 cstr ? cstr : "NULL",
977 cstr ? "\"" : "");
978
Greg Clayton6779606a2011-01-22 23:43:18 +0000979 // We were already in the exited state
980 if (m_private_state.GetValue() == eStateExited)
Greg Clayton414f5d32011-01-25 02:58:48 +0000981 {
Greg Clayton385d6032011-01-26 23:47:29 +0000982 if (log)
983 log->Printf("Process::SetExitStatus () ignoring exit status because state was already set to eStateExited");
Greg Clayton6779606a2011-01-22 23:43:18 +0000984 return false;
Greg Clayton414f5d32011-01-25 02:58:48 +0000985 }
Greg Clayton6779606a2011-01-22 23:43:18 +0000986
987 m_exit_status = status;
988 if (cstr)
989 m_exit_string = cstr;
990 else
991 m_exit_string.clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000992
Greg Clayton6779606a2011-01-22 23:43:18 +0000993 DidExit ();
Greg Clayton10177aa2010-12-08 05:08:21 +0000994
Greg Clayton6779606a2011-01-22 23:43:18 +0000995 SetPrivateState (eStateExited);
996 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997}
998
999// This static callback can be used to watch for local child processes on
1000// the current host. The the child process exits, the process will be
1001// found in the global target list (we want to be completely sure that the
1002// lldb_private::Process doesn't go away before we can deliver the signal.
1003bool
1004Process::SetProcessExitStatus
1005(
1006 void *callback_baton,
1007 lldb::pid_t pid,
1008 int signo, // Zero for no signal
1009 int exit_status // Exit value of process if signal is zero
1010)
1011{
1012 if (signo == 0 || exit_status)
1013 {
Greg Clayton66111032010-06-23 01:19:29 +00001014 TargetSP target_sp(Debugger::FindTargetWithProcessID (pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015 if (target_sp)
1016 {
1017 ProcessSP process_sp (target_sp->GetProcessSP());
1018 if (process_sp)
1019 {
1020 const char *signal_cstr = NULL;
1021 if (signo)
1022 signal_cstr = process_sp->GetUnixSignals().GetSignalAsCString (signo);
1023
1024 process_sp->SetExitStatus (exit_status, signal_cstr);
1025 }
1026 }
1027 return true;
1028 }
1029 return false;
1030}
1031
1032
Greg Clayton56d9a1b2011-08-22 02:49:39 +00001033void
1034Process::UpdateThreadListIfNeeded ()
1035{
1036 const uint32_t stop_id = GetStopID();
1037 if (m_thread_list.GetSize(false) == 0 || stop_id != m_thread_list.GetStopID())
1038 {
1039 Mutex::Locker locker (m_thread_list.GetMutex ());
1040 ThreadList new_thread_list(this);
1041 // Always update the thread list with the protocol specific
1042 // thread list
1043 UpdateThreadList (m_thread_list, new_thread_list);
1044 OperatingSystem *os = GetOperatingSystem ();
1045 if (os)
1046 os->UpdateThreadList (m_thread_list, new_thread_list);
1047 m_thread_list.Update (new_thread_list);
1048 m_thread_list.SetStopID (stop_id);
1049 }
1050}
1051
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001052uint32_t
1053Process::GetNextThreadIndexID ()
1054{
1055 return ++m_thread_index_id;
1056}
1057
1058StateType
1059Process::GetState()
1060{
1061 // If any other threads access this we will need a mutex for it
1062 return m_public_state.GetValue ();
1063}
1064
1065void
1066Process::SetPublicState (StateType new_state)
1067{
Greg Clayton414f5d32011-01-25 02:58:48 +00001068 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001069 if (log)
1070 log->Printf("Process::SetPublicState (%s)", StateAsCString(new_state));
1071 m_public_state.SetValue (new_state);
1072}
1073
1074StateType
1075Process::GetPrivateState ()
1076{
1077 return m_private_state.GetValue();
1078}
1079
1080void
1081Process::SetPrivateState (StateType new_state)
1082{
Greg Clayton414f5d32011-01-25 02:58:48 +00001083 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084 bool state_changed = false;
1085
1086 if (log)
1087 log->Printf("Process::SetPrivateState (%s)", StateAsCString(new_state));
1088
1089 Mutex::Locker locker(m_private_state.GetMutex());
1090
1091 const StateType old_state = m_private_state.GetValueNoLock ();
1092 state_changed = old_state != new_state;
1093 if (state_changed)
1094 {
1095 m_private_state.SetValueNoLock (new_state);
1096 if (StateIsStoppedState(new_state))
1097 {
Jim Ingham4b536182011-08-09 02:12:22 +00001098 m_mod_id.BumpStopID();
Greg Clayton58be07b2011-01-07 06:08:19 +00001099 m_memory_cache.Clear();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001101 log->Printf("Process::SetPrivateState (%s) stop_id = %u", StateAsCString(new_state), m_mod_id.GetStopID());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001102 }
1103 // Use our target to get a shared pointer to ourselves...
1104 m_private_state_broadcaster.BroadcastEvent (eBroadcastBitStateChanged, new ProcessEventData (GetTarget().GetProcessSP(), new_state));
1105 }
1106 else
1107 {
1108 if (log)
1109 log->Printf("Process::SetPrivateState (%s) state didn't change. Ignoring...", StateAsCString(new_state), StateAsCString(old_state));
1110 }
1111}
1112
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113addr_t
1114Process::GetImageInfoAddress()
1115{
1116 return LLDB_INVALID_ADDRESS;
1117}
1118
Greg Clayton8f343b02010-11-04 01:54:29 +00001119//----------------------------------------------------------------------
1120// LoadImage
1121//
1122// This function provides a default implementation that works for most
1123// unix variants. Any Process subclasses that need to do shared library
1124// loading differently should override LoadImage and UnloadImage and
1125// do what is needed.
1126//----------------------------------------------------------------------
1127uint32_t
1128Process::LoadImage (const FileSpec &image_spec, Error &error)
1129{
1130 DynamicLoader *loader = GetDynamicLoader();
1131 if (loader)
1132 {
1133 error = loader->CanLoadImage();
1134 if (error.Fail())
1135 return LLDB_INVALID_IMAGE_TOKEN;
1136 }
1137
1138 if (error.Success())
1139 {
1140 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001141
1142 if (thread_sp)
1143 {
1144 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1145
1146 if (frame_sp)
1147 {
1148 ExecutionContext exe_ctx;
1149 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001150 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001151 StreamString expr;
1152 char path[PATH_MAX];
1153 image_spec.GetPath(path, sizeof(path));
1154 expr.Printf("dlopen (\"%s\", 2)", path);
1155 const char *prefix = "extern \"C\" void* dlopen (const char *path, int mode);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001156 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan63697e52011-05-07 01:06:41 +00001157 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +00001158 if (result_valobj_sp->GetError().Success())
1159 {
1160 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001161 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001162 {
1163 addr_t image_ptr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1164 if (image_ptr != 0 && image_ptr != LLDB_INVALID_ADDRESS)
1165 {
1166 uint32_t image_token = m_image_tokens.size();
1167 m_image_tokens.push_back (image_ptr);
1168 return image_token;
1169 }
1170 }
1171 }
1172 }
1173 }
1174 }
1175 return LLDB_INVALID_IMAGE_TOKEN;
1176}
1177
1178//----------------------------------------------------------------------
1179// UnloadImage
1180//
1181// This function provides a default implementation that works for most
1182// unix variants. Any Process subclasses that need to do shared library
1183// loading differently should override LoadImage and UnloadImage and
1184// do what is needed.
1185//----------------------------------------------------------------------
1186Error
1187Process::UnloadImage (uint32_t image_token)
1188{
1189 Error error;
1190 if (image_token < m_image_tokens.size())
1191 {
1192 const addr_t image_addr = m_image_tokens[image_token];
1193 if (image_addr == LLDB_INVALID_ADDRESS)
1194 {
1195 error.SetErrorString("image already unloaded");
1196 }
1197 else
1198 {
1199 DynamicLoader *loader = GetDynamicLoader();
1200 if (loader)
1201 error = loader->CanLoadImage();
1202
1203 if (error.Success())
1204 {
1205 ThreadSP thread_sp(GetThreadList ().GetSelectedThread());
Greg Clayton8f343b02010-11-04 01:54:29 +00001206
1207 if (thread_sp)
1208 {
1209 StackFrameSP frame_sp (thread_sp->GetStackFrameAtIndex (0));
1210
1211 if (frame_sp)
1212 {
1213 ExecutionContext exe_ctx;
1214 frame_sp->CalculateExecutionContext (exe_ctx);
Jim Ingham399f1ca2010-11-05 19:25:48 +00001215 bool unwind_on_error = true;
Greg Clayton8f343b02010-11-04 01:54:29 +00001216 StreamString expr;
1217 expr.Printf("dlclose ((void *)0x%llx)", image_addr);
1218 const char *prefix = "extern \"C\" int dlclose(void* handle);\n";
Jim Inghamf48169b2010-11-30 02:22:11 +00001219 lldb::ValueObjectSP result_valobj_sp;
Sean Callanan63697e52011-05-07 01:06:41 +00001220 ClangUserExpression::Evaluate (exe_ctx, unwind_on_error, expr.GetData(), prefix, result_valobj_sp);
Greg Clayton8f343b02010-11-04 01:54:29 +00001221 if (result_valobj_sp->GetError().Success())
1222 {
1223 Scalar scalar;
Jim Ingham6035b672011-03-31 00:19:25 +00001224 if (result_valobj_sp->ResolveValue (scalar))
Greg Clayton8f343b02010-11-04 01:54:29 +00001225 {
1226 if (scalar.UInt(1))
1227 {
1228 error.SetErrorStringWithFormat("expression failed: \"%s\"", expr.GetData());
1229 }
1230 else
1231 {
1232 m_image_tokens[image_token] = LLDB_INVALID_ADDRESS;
1233 }
1234 }
1235 }
1236 else
1237 {
1238 error = result_valobj_sp->GetError();
1239 }
1240 }
1241 }
1242 }
1243 }
1244 }
1245 else
1246 {
1247 error.SetErrorString("invalid image token");
1248 }
1249 return error;
1250}
1251
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001252const lldb::ABISP &
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001253Process::GetABI()
1254{
Greg Clayton31f1d2f2011-05-11 18:39:18 +00001255 if (!m_abi_sp)
1256 m_abi_sp = ABI::FindPlugin(m_target.GetArchitecture());
1257 return m_abi_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001258}
1259
Jim Ingham22777012010-09-23 02:01:19 +00001260LanguageRuntime *
1261Process::GetLanguageRuntime(lldb::LanguageType language)
1262{
1263 LanguageRuntimeCollection::iterator pos;
1264 pos = m_language_runtimes.find (language);
1265 if (pos == m_language_runtimes.end())
1266 {
1267 lldb::LanguageRuntimeSP runtime(LanguageRuntime::FindPlugin(this, language));
1268
1269 m_language_runtimes[language]
1270 = runtime;
1271 return runtime.get();
1272 }
1273 else
1274 return (*pos).second.get();
1275}
1276
1277CPPLanguageRuntime *
1278Process::GetCPPLanguageRuntime ()
1279{
1280 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeC_plus_plus);
1281 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeC_plus_plus)
1282 return static_cast<CPPLanguageRuntime *> (runtime);
1283 return NULL;
1284}
1285
1286ObjCLanguageRuntime *
1287Process::GetObjCLanguageRuntime ()
1288{
1289 LanguageRuntime *runtime = GetLanguageRuntime(eLanguageTypeObjC);
1290 if (runtime != NULL && runtime->GetLanguageType() == eLanguageTypeObjC)
1291 return static_cast<ObjCLanguageRuntime *> (runtime);
1292 return NULL;
1293}
1294
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001295BreakpointSiteList &
1296Process::GetBreakpointSiteList()
1297{
1298 return m_breakpoint_site_list;
1299}
1300
1301const BreakpointSiteList &
1302Process::GetBreakpointSiteList() const
1303{
1304 return m_breakpoint_site_list;
1305}
1306
1307
1308void
1309Process::DisableAllBreakpointSites ()
1310{
1311 m_breakpoint_site_list.SetEnabledForAll (false);
1312}
1313
1314Error
1315Process::ClearBreakpointSiteByID (lldb::user_id_t break_id)
1316{
1317 Error error (DisableBreakpointSiteByID (break_id));
1318
1319 if (error.Success())
1320 m_breakpoint_site_list.Remove(break_id);
1321
1322 return error;
1323}
1324
1325Error
1326Process::DisableBreakpointSiteByID (lldb::user_id_t break_id)
1327{
1328 Error error;
1329 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1330 if (bp_site_sp)
1331 {
1332 if (bp_site_sp->IsEnabled())
1333 error = DisableBreakpoint (bp_site_sp.get());
1334 }
1335 else
1336 {
1337 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1338 }
1339
1340 return error;
1341}
1342
1343Error
1344Process::EnableBreakpointSiteByID (lldb::user_id_t break_id)
1345{
1346 Error error;
1347 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID (break_id);
1348 if (bp_site_sp)
1349 {
1350 if (!bp_site_sp->IsEnabled())
1351 error = EnableBreakpoint (bp_site_sp.get());
1352 }
1353 else
1354 {
1355 error.SetErrorStringWithFormat("invalid breakpoint site ID: %i", break_id);
1356 }
1357 return error;
1358}
1359
Stephen Wilson50bd94f2010-07-17 00:56:13 +00001360lldb::break_id_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001361Process::CreateBreakpointSite (BreakpointLocationSP &owner, bool use_hardware)
1362{
Greg Clayton92bb12c2011-05-19 18:17:41 +00001363 const addr_t load_addr = owner->GetAddress().GetOpcodeLoadAddress (&m_target);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001364 if (load_addr != LLDB_INVALID_ADDRESS)
1365 {
1366 BreakpointSiteSP bp_site_sp;
1367
1368 // Look up this breakpoint site. If it exists, then add this new owner, otherwise
1369 // create a new breakpoint site and add it.
1370
1371 bp_site_sp = m_breakpoint_site_list.FindByAddress (load_addr);
1372
1373 if (bp_site_sp)
1374 {
1375 bp_site_sp->AddOwner (owner);
1376 owner->SetBreakpointSite (bp_site_sp);
1377 return bp_site_sp->GetID();
1378 }
1379 else
1380 {
1381 bp_site_sp.reset (new BreakpointSite (&m_breakpoint_site_list, owner, load_addr, LLDB_INVALID_THREAD_ID, use_hardware));
1382 if (bp_site_sp)
1383 {
1384 if (EnableBreakpoint (bp_site_sp.get()).Success())
1385 {
1386 owner->SetBreakpointSite (bp_site_sp);
1387 return m_breakpoint_site_list.Add (bp_site_sp);
1388 }
1389 }
1390 }
1391 }
1392 // We failed to enable the breakpoint
1393 return LLDB_INVALID_BREAK_ID;
1394
1395}
1396
1397void
1398Process::RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, lldb::user_id_t owner_loc_id, BreakpointSiteSP &bp_site_sp)
1399{
1400 uint32_t num_owners = bp_site_sp->RemoveOwner (owner_id, owner_loc_id);
1401 if (num_owners == 0)
1402 {
1403 DisableBreakpoint(bp_site_sp.get());
1404 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1405 }
1406}
1407
1408
1409size_t
1410Process::RemoveBreakpointOpcodesFromBuffer (addr_t bp_addr, size_t size, uint8_t *buf) const
1411{
1412 size_t bytes_removed = 0;
1413 addr_t intersect_addr;
1414 size_t intersect_size;
1415 size_t opcode_offset;
1416 size_t idx;
1417 BreakpointSiteSP bp;
Jim Ingham20c77192011-06-29 19:42:28 +00001418 BreakpointSiteList bp_sites_in_range;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001419
Jim Ingham20c77192011-06-29 19:42:28 +00001420 if (m_breakpoint_site_list.FindInRange (bp_addr, bp_addr + size, bp_sites_in_range))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001421 {
Jim Ingham20c77192011-06-29 19:42:28 +00001422 for (idx = 0; (bp = bp_sites_in_range.GetByIndex(idx)) != NULL; ++idx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001423 {
Jim Ingham20c77192011-06-29 19:42:28 +00001424 if (bp->GetType() == BreakpointSite::eSoftware)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001425 {
Jim Ingham20c77192011-06-29 19:42:28 +00001426 if (bp->IntersectsRange(bp_addr, size, &intersect_addr, &intersect_size, &opcode_offset))
1427 {
1428 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1429 assert(bp_addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= bp_addr + size);
1430 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1431 size_t buf_offset = intersect_addr - bp_addr;
1432 ::memcpy(buf + buf_offset, bp->GetSavedOpcodeBytes() + opcode_offset, intersect_size);
1433 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001434 }
1435 }
1436 }
1437 return bytes_removed;
1438}
1439
1440
Greg Claytonded470d2011-03-19 01:12:21 +00001441
1442size_t
1443Process::GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site)
1444{
1445 PlatformSP platform_sp (m_target.GetPlatform());
1446 if (platform_sp)
1447 return platform_sp->GetSoftwareBreakpointTrapOpcode (m_target, bp_site);
1448 return 0;
1449}
1450
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001451Error
1452Process::EnableSoftwareBreakpoint (BreakpointSite *bp_site)
1453{
1454 Error error;
1455 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001456 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001457 const addr_t bp_addr = bp_site->GetLoadAddress();
1458 if (log)
1459 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx", bp_site->GetID(), (uint64_t)bp_addr);
1460 if (bp_site->IsEnabled())
1461 {
1462 if (log)
1463 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already enabled", bp_site->GetID(), (uint64_t)bp_addr);
1464 return error;
1465 }
1466
1467 if (bp_addr == LLDB_INVALID_ADDRESS)
1468 {
1469 error.SetErrorString("BreakpointSite contains an invalid load address.");
1470 return error;
1471 }
1472 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1473 // trap for the breakpoint site
1474 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1475
1476 if (bp_opcode_size == 0)
1477 {
1478 error.SetErrorStringWithFormat ("Process::GetSoftwareBreakpointTrapOpcode() returned zero, unable to get breakpoint trap for address 0x%llx.\n", bp_addr);
1479 }
1480 else
1481 {
1482 const uint8_t * const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1483
1484 if (bp_opcode_bytes == NULL)
1485 {
1486 error.SetErrorString ("BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1487 return error;
1488 }
1489
1490 // Save the original opcode by reading it
1491 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, error) == bp_opcode_size)
1492 {
1493 // Write a software breakpoint in place of the original opcode
1494 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1495 {
1496 uint8_t verify_bp_opcode_bytes[64];
1497 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, error) == bp_opcode_size)
1498 {
1499 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, bp_opcode_size) == 0)
1500 {
1501 bp_site->SetEnabled(true);
1502 bp_site->SetType (BreakpointSite::eSoftware);
1503 if (log)
1504 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS",
1505 bp_site->GetID(),
1506 (uint64_t)bp_addr);
1507 }
1508 else
1509 error.SetErrorString("Failed to verify the breakpoint trap in memory.");
1510 }
1511 else
1512 error.SetErrorString("Unable to read memory to verify breakpoint trap.");
1513 }
1514 else
1515 error.SetErrorString("Unable to write breakpoint trap to memory.");
1516 }
1517 else
1518 error.SetErrorString("Unable to read memory at breakpoint address.");
1519 }
Stephen Wilson78a4feb2011-01-12 04:20:03 +00001520 if (log && error.Fail())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001521 log->Printf ("Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1522 bp_site->GetID(),
1523 (uint64_t)bp_addr,
1524 error.AsCString());
1525 return error;
1526}
1527
1528Error
1529Process::DisableSoftwareBreakpoint (BreakpointSite *bp_site)
1530{
1531 Error error;
1532 assert (bp_site != NULL);
Greg Clayton2d4edfb2010-11-06 01:53:30 +00001533 LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001534 addr_t bp_addr = bp_site->GetLoadAddress();
1535 lldb::user_id_t breakID = bp_site->GetID();
1536 if (log)
Stephen Wilson5394e0d2011-01-14 21:07:07 +00001537 log->Printf ("Process::DisableBreakpoint (breakID = %d) addr = 0x%llx", breakID, (uint64_t)bp_addr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001538
1539 if (bp_site->IsHardware())
1540 {
1541 error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1542 }
1543 else if (bp_site->IsEnabled())
1544 {
1545 const size_t break_op_size = bp_site->GetByteSize();
1546 const uint8_t * const break_op = bp_site->GetTrapOpcodeBytes();
1547 if (break_op_size > 0)
1548 {
1549 // Clear a software breakoint instruction
Greg Claytonc982c762010-07-09 20:39:50 +00001550 uint8_t curr_break_op[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001551 assert (break_op_size <= sizeof(curr_break_op));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001552 bool break_op_found = false;
1553
1554 // Read the breakpoint opcode
1555 if (DoReadMemory (bp_addr, curr_break_op, break_op_size, error) == break_op_size)
1556 {
1557 bool verify = false;
1558 // Make sure we have the a breakpoint opcode exists at this address
1559 if (::memcmp (curr_break_op, break_op, break_op_size) == 0)
1560 {
1561 break_op_found = true;
1562 // We found a valid breakpoint opcode at this address, now restore
1563 // the saved opcode.
1564 if (DoWriteMemory (bp_addr, bp_site->GetSavedOpcodeBytes(), break_op_size, error) == break_op_size)
1565 {
1566 verify = true;
1567 }
1568 else
1569 error.SetErrorString("Memory write failed when restoring original opcode.");
1570 }
1571 else
1572 {
1573 error.SetErrorString("Original breakpoint trap is no longer in memory.");
1574 // Set verify to true and so we can check if the original opcode has already been restored
1575 verify = true;
1576 }
1577
1578 if (verify)
1579 {
Greg Claytonc982c762010-07-09 20:39:50 +00001580 uint8_t verify_opcode[8];
Stephen Wilson4ab47682010-07-20 18:41:11 +00001581 assert (break_op_size < sizeof(verify_opcode));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001582 // Verify that our original opcode made it back to the inferior
1583 if (DoReadMemory (bp_addr, verify_opcode, break_op_size, error) == break_op_size)
1584 {
1585 // compare the memory we just read with the original opcode
1586 if (::memcmp (bp_site->GetSavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
1587 {
1588 // SUCCESS
1589 bp_site->SetEnabled(false);
1590 if (log)
1591 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- SUCCESS", bp_site->GetID(), (uint64_t)bp_addr);
1592 return error;
1593 }
1594 else
1595 {
1596 if (break_op_found)
1597 error.SetErrorString("Failed to restore original opcode.");
1598 }
1599 }
1600 else
1601 error.SetErrorString("Failed to read memory to verify that breakpoint trap was restored.");
1602 }
1603 }
1604 else
1605 error.SetErrorString("Unable to read memory that should contain the breakpoint trap.");
1606 }
1607 }
1608 else
1609 {
1610 if (log)
1611 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- already disabled", bp_site->GetID(), (uint64_t)bp_addr);
1612 return error;
1613 }
1614
1615 if (log)
1616 log->Printf ("Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%llx -- FAILED: %s",
1617 bp_site->GetID(),
1618 (uint64_t)bp_addr,
1619 error.AsCString());
1620 return error;
1621
1622}
1623
Greg Clayton58be07b2011-01-07 06:08:19 +00001624// Comment out line below to disable memory caching
1625#define ENABLE_MEMORY_CACHING
1626// Uncomment to verify memory caching works after making changes to caching code
1627//#define VERIFY_MEMORY_READS
1628
1629#if defined (ENABLE_MEMORY_CACHING)
1630
1631#if defined (VERIFY_MEMORY_READS)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001632
1633size_t
1634Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1635{
Greg Clayton58be07b2011-01-07 06:08:19 +00001636 // Memory caching is enabled, with debug verification
1637 if (buf && size)
1638 {
1639 // Uncomment the line below to make sure memory caching is working.
1640 // I ran this through the test suite and got no assertions, so I am
1641 // pretty confident this is working well. If any changes are made to
1642 // memory caching, uncomment the line below and test your changes!
1643
1644 // Verify all memory reads by using the cache first, then redundantly
1645 // reading the same memory from the inferior and comparing to make sure
1646 // everything is exactly the same.
1647 std::string verify_buf (size, '\0');
1648 assert (verify_buf.size() == size);
1649 const size_t cache_bytes_read = m_memory_cache.Read (this, addr, buf, size, error);
1650 Error verify_error;
1651 const size_t verify_bytes_read = ReadMemoryFromInferior (addr, const_cast<char *>(verify_buf.data()), verify_buf.size(), verify_error);
1652 assert (cache_bytes_read == verify_bytes_read);
1653 assert (memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1654 assert (verify_error.Success() == error.Success());
1655 return cache_bytes_read;
1656 }
1657 return 0;
1658}
1659
1660#else // #if defined (VERIFY_MEMORY_READS)
1661
1662size_t
1663Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1664{
1665 // Memory caching enabled, no verification
Greg Claytond495c532011-05-17 03:37:42 +00001666 return m_memory_cache.Read (addr, buf, size, error);
Greg Clayton58be07b2011-01-07 06:08:19 +00001667}
1668
1669#endif // #else for #if defined (VERIFY_MEMORY_READS)
1670
1671#else // #if defined (ENABLE_MEMORY_CACHING)
1672
1673size_t
1674Process::ReadMemory (addr_t addr, void *buf, size_t size, Error &error)
1675{
1676 // Memory caching is disabled
1677 return ReadMemoryFromInferior (addr, buf, size, error);
1678}
1679
1680#endif // #else for #if defined (ENABLE_MEMORY_CACHING)
1681
1682
1683size_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001684Process::ReadCStringFromMemory (addr_t addr, char *dst, size_t dst_max_len)
1685{
1686 size_t total_cstr_len = 0;
1687 if (dst && dst_max_len)
1688 {
1689 // NULL out everything just to be safe
1690 memset (dst, 0, dst_max_len);
1691 Error error;
1692 addr_t curr_addr = addr;
1693 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
1694 size_t bytes_left = dst_max_len - 1;
1695 char *curr_dst = dst;
1696
1697 while (bytes_left > 0)
1698 {
1699 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1700 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1701 size_t bytes_read = ReadMemory (curr_addr, curr_dst, bytes_to_read, error);
1702
1703 if (bytes_read == 0)
1704 {
1705 dst[total_cstr_len] = '\0';
1706 break;
1707 }
1708 const size_t len = strlen(curr_dst);
1709
1710 total_cstr_len += len;
1711
1712 if (len < bytes_to_read)
1713 break;
1714
1715 curr_dst += bytes_read;
1716 curr_addr += bytes_read;
1717 bytes_left -= bytes_read;
1718 }
1719 }
1720 return total_cstr_len;
1721}
1722
1723size_t
Greg Clayton58be07b2011-01-07 06:08:19 +00001724Process::ReadMemoryFromInferior (addr_t addr, void *buf, size_t size, Error &error)
1725{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001726 if (buf == NULL || size == 0)
1727 return 0;
1728
1729 size_t bytes_read = 0;
1730 uint8_t *bytes = (uint8_t *)buf;
1731
1732 while (bytes_read < size)
1733 {
1734 const size_t curr_size = size - bytes_read;
1735 const size_t curr_bytes_read = DoReadMemory (addr + bytes_read,
1736 bytes + bytes_read,
1737 curr_size,
1738 error);
1739 bytes_read += curr_bytes_read;
1740 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
1741 break;
1742 }
1743
1744 // Replace any software breakpoint opcodes that fall into this range back
1745 // into "buf" before we return
1746 if (bytes_read > 0)
1747 RemoveBreakpointOpcodesFromBuffer (addr, bytes_read, (uint8_t *)buf);
1748 return bytes_read;
1749}
1750
Greg Clayton58a4c462010-12-16 20:01:20 +00001751uint64_t
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001752Process::ReadUnsignedIntegerFromMemory (lldb::addr_t vm_addr, size_t integer_byte_size, uint64_t fail_value, Error &error)
Greg Clayton58a4c462010-12-16 20:01:20 +00001753{
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001754 Scalar scalar;
1755 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, error))
1756 return scalar.ULongLong(fail_value);
1757 return fail_value;
1758}
1759
1760addr_t
1761Process::ReadPointerFromMemory (lldb::addr_t vm_addr, Error &error)
1762{
1763 Scalar scalar;
1764 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, error))
1765 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
1766 return LLDB_INVALID_ADDRESS;
1767}
1768
1769
1770bool
1771Process::WritePointerToMemory (lldb::addr_t vm_addr,
1772 lldb::addr_t ptr_value,
1773 Error &error)
1774{
1775 Scalar scalar;
1776 const uint32_t addr_byte_size = GetAddressByteSize();
1777 if (addr_byte_size <= 4)
1778 scalar = (uint32_t)ptr_value;
Greg Clayton58a4c462010-12-16 20:01:20 +00001779 else
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001780 scalar = ptr_value;
1781 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == addr_byte_size;
Greg Clayton58a4c462010-12-16 20:01:20 +00001782}
1783
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001784size_t
1785Process::WriteMemoryPrivate (addr_t addr, const void *buf, size_t size, Error &error)
1786{
1787 size_t bytes_written = 0;
1788 const uint8_t *bytes = (const uint8_t *)buf;
1789
1790 while (bytes_written < size)
1791 {
1792 const size_t curr_size = size - bytes_written;
1793 const size_t curr_bytes_written = DoWriteMemory (addr + bytes_written,
1794 bytes + bytes_written,
1795 curr_size,
1796 error);
1797 bytes_written += curr_bytes_written;
1798 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
1799 break;
1800 }
1801 return bytes_written;
1802}
1803
1804size_t
1805Process::WriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
1806{
Greg Clayton58be07b2011-01-07 06:08:19 +00001807#if defined (ENABLE_MEMORY_CACHING)
1808 m_memory_cache.Flush (addr, size);
1809#endif
1810
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001811 if (buf == NULL || size == 0)
1812 return 0;
Jim Ingham78a685a2011-04-16 00:01:13 +00001813
Jim Ingham4b536182011-08-09 02:12:22 +00001814 m_mod_id.BumpMemoryID();
Jim Ingham78a685a2011-04-16 00:01:13 +00001815
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001816 // We need to write any data that would go where any current software traps
1817 // (enabled software breakpoints) any software traps (breakpoints) that we
1818 // may have placed in our tasks memory.
1819
1820 BreakpointSiteList::collection::const_iterator iter = m_breakpoint_site_list.GetMap()->lower_bound (addr);
1821 BreakpointSiteList::collection::const_iterator end = m_breakpoint_site_list.GetMap()->end();
1822
1823 if (iter == end || iter->second->GetLoadAddress() > addr + size)
Greg Claytonb4aaf2e2011-05-16 02:35:02 +00001824 return WriteMemoryPrivate (addr, buf, size, error);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001825
1826 BreakpointSiteList::collection::const_iterator pos;
1827 size_t bytes_written = 0;
Greg Claytonc982c762010-07-09 20:39:50 +00001828 addr_t intersect_addr = 0;
1829 size_t intersect_size = 0;
1830 size_t opcode_offset = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001831 const uint8_t *ubuf = (const uint8_t *)buf;
1832
1833 for (pos = iter; pos != end; ++pos)
1834 {
1835 BreakpointSiteSP bp;
1836 bp = pos->second;
1837
1838 assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
1839 assert(addr <= intersect_addr && intersect_addr < addr + size);
1840 assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
1841 assert(opcode_offset + intersect_size <= bp->GetByteSize());
1842
1843 // Check for bytes before this breakpoint
1844 const addr_t curr_addr = addr + bytes_written;
1845 if (intersect_addr > curr_addr)
1846 {
1847 // There are some bytes before this breakpoint that we need to
1848 // just write to memory
1849 size_t curr_size = intersect_addr - curr_addr;
1850 size_t curr_bytes_written = WriteMemoryPrivate (curr_addr,
1851 ubuf + bytes_written,
1852 curr_size,
1853 error);
1854 bytes_written += curr_bytes_written;
1855 if (curr_bytes_written != curr_size)
1856 {
1857 // We weren't able to write all of the requested bytes, we
1858 // are done looping and will return the number of bytes that
1859 // we have written so far.
1860 break;
1861 }
1862 }
1863
1864 // Now write any bytes that would cover up any software breakpoints
1865 // directly into the breakpoint opcode buffer
1866 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
1867 bytes_written += intersect_size;
1868 }
1869
1870 // Write any remaining bytes after the last breakpoint if we have any left
1871 if (bytes_written < size)
1872 bytes_written += WriteMemoryPrivate (addr + bytes_written,
1873 ubuf + bytes_written,
1874 size - bytes_written,
1875 error);
Jim Ingham78a685a2011-04-16 00:01:13 +00001876
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001877 return bytes_written;
1878}
Greg Claytonf3ef3d22011-05-22 22:46:53 +00001879
1880size_t
1881Process::WriteScalarToMemory (addr_t addr, const Scalar &scalar, uint32_t byte_size, Error &error)
1882{
1883 if (byte_size == UINT32_MAX)
1884 byte_size = scalar.GetByteSize();
1885 if (byte_size > 0)
1886 {
1887 uint8_t buf[32];
1888 const size_t mem_size = scalar.GetAsMemoryData (buf, byte_size, GetByteOrder(), error);
1889 if (mem_size > 0)
1890 return WriteMemory(addr, buf, mem_size, error);
1891 else
1892 error.SetErrorString ("failed to get scalar as memory data");
1893 }
1894 else
1895 {
1896 error.SetErrorString ("invalid scalar value");
1897 }
1898 return 0;
1899}
1900
1901size_t
1902Process::ReadScalarIntegerFromMemory (addr_t addr,
1903 uint32_t byte_size,
1904 bool is_signed,
1905 Scalar &scalar,
1906 Error &error)
1907{
1908 uint64_t uval;
1909
1910 if (byte_size <= sizeof(uval))
1911 {
1912 size_t bytes_read = ReadMemory (addr, &uval, byte_size, error);
1913 if (bytes_read == byte_size)
1914 {
1915 DataExtractor data (&uval, sizeof(uval), GetByteOrder(), GetAddressByteSize());
1916 uint32_t offset = 0;
1917 if (byte_size <= 4)
1918 scalar = data.GetMaxU32 (&offset, byte_size);
1919 else
1920 scalar = data.GetMaxU64 (&offset, byte_size);
1921
1922 if (is_signed)
1923 scalar.SignExtend(byte_size * 8);
1924 return bytes_read;
1925 }
1926 }
1927 else
1928 {
1929 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1930 }
1931 return 0;
1932}
1933
Greg Claytond495c532011-05-17 03:37:42 +00001934#define USE_ALLOCATE_MEMORY_CACHE 1
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001935addr_t
1936Process::AllocateMemory(size_t size, uint32_t permissions, Error &error)
1937{
Jim Inghamf72ce3a2011-06-20 17:32:44 +00001938 if (GetPrivateState() != eStateStopped)
1939 return LLDB_INVALID_ADDRESS;
1940
Greg Claytond495c532011-05-17 03:37:42 +00001941#if defined (USE_ALLOCATE_MEMORY_CACHE)
1942 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
1943#else
Greg Claytonb2daec92011-01-23 19:58:49 +00001944 addr_t allocated_addr = DoAllocateMemory (size, permissions, error);
1945 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1946 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001947 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 +00001948 size,
Greg Claytond495c532011-05-17 03:37:42 +00001949 GetPermissionsAsCString (permissions),
Greg Claytonb2daec92011-01-23 19:58:49 +00001950 (uint64_t)allocated_addr,
Jim Ingham4b536182011-08-09 02:12:22 +00001951 m_mod_id.GetStopID(),
1952 m_mod_id.GetMemoryID());
Greg Claytonb2daec92011-01-23 19:58:49 +00001953 return allocated_addr;
Greg Claytond495c532011-05-17 03:37:42 +00001954#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001955}
1956
1957Error
1958Process::DeallocateMemory (addr_t ptr)
1959{
Greg Claytond495c532011-05-17 03:37:42 +00001960 Error error;
1961#if defined (USE_ALLOCATE_MEMORY_CACHE)
1962 if (!m_allocated_memory_cache.DeallocateMemory(ptr))
1963 {
1964 error.SetErrorStringWithFormat ("deallocation of memory at 0x%llx failed.", (uint64_t)ptr);
1965 }
1966#else
1967 error = DoDeallocateMemory (ptr);
Greg Claytonb2daec92011-01-23 19:58:49 +00001968
1969 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1970 if (log)
Jim Ingham4b536182011-08-09 02:12:22 +00001971 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 +00001972 ptr,
1973 error.AsCString("SUCCESS"),
Jim Ingham4b536182011-08-09 02:12:22 +00001974 m_mod_id.GetStopID(),
1975 m_mod_id.GetMemoryID());
Greg Claytond495c532011-05-17 03:37:42 +00001976#endif
Greg Claytonb2daec92011-01-23 19:58:49 +00001977 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001978}
1979
1980
1981Error
1982Process::EnableWatchpoint (WatchpointLocation *watchpoint)
1983{
1984 Error error;
1985 error.SetErrorString("watchpoints are not supported");
1986 return error;
1987}
1988
1989Error
1990Process::DisableWatchpoint (WatchpointLocation *watchpoint)
1991{
1992 Error error;
1993 error.SetErrorString("watchpoints are not supported");
1994 return error;
1995}
1996
1997StateType
1998Process::WaitForProcessStopPrivate (const TimeValue *timeout, EventSP &event_sp)
1999{
2000 StateType state;
2001 // Now wait for the process to launch and return control to us, and then
2002 // call DidLaunch:
2003 while (1)
2004 {
Greg Clayton6779606a2011-01-22 23:43:18 +00002005 event_sp.reset();
2006 state = WaitForStateChangedEventsPrivate (timeout, event_sp);
2007
2008 if (StateIsStoppedState(state))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002009 break;
Greg Clayton6779606a2011-01-22 23:43:18 +00002010
2011 // If state is invalid, then we timed out
2012 if (state == eStateInvalid)
2013 break;
2014
2015 if (event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002016 HandlePrivateEvent (event_sp);
2017 }
2018 return state;
2019}
2020
2021Error
2022Process::Launch
2023(
2024 char const *argv[],
2025 char const *envp[],
Greg Claytonf681b942010-08-31 18:35:14 +00002026 uint32_t launch_flags,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002027 const char *stdin_path,
2028 const char *stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00002029 const char *stderr_path,
2030 const char *working_directory
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002031)
2032{
2033 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002034 m_abi_sp.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002035 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002036 m_os_ap.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002037 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002038
Greg Claytonaa149cb2011-08-11 02:48:45 +00002039 Module *exe_module = m_target.GetExecutableModulePointer();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002040 if (exe_module)
2041 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002042 char local_exec_file_path[PATH_MAX];
2043 char platform_exec_file_path[PATH_MAX];
2044 exe_module->GetFileSpec().GetPath(local_exec_file_path, sizeof(local_exec_file_path));
2045 exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path, sizeof(platform_exec_file_path));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002046 if (exe_module->GetFileSpec().Exists())
2047 {
Greg Clayton71337622011-02-24 22:24:29 +00002048 if (PrivateStateThreadIsValid ())
2049 PausePrivateStateThread ();
2050
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002051 error = WillLaunch (exe_module);
2052 if (error.Success())
2053 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002054 SetPublicState (eStateLaunching);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002055 // The args coming in should not contain the application name, the
2056 // lldb_private::Process class will add this in case the executable
2057 // gets resolved to a different file than was given on the command
2058 // line (like when an applicaiton bundle is specified and will
2059 // resolve to the contained exectuable file, or the file given was
2060 // a symlink or other file system link that resolves to a different
2061 // file).
2062
2063 // Get the resolved exectuable path
2064
2065 // Make a new argument vector
2066 std::vector<const char *> exec_path_plus_argv;
2067 // Append the resolved executable path
Greg Clayton2289fa42011-04-30 01:09:13 +00002068 exec_path_plus_argv.push_back (platform_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002069
2070 // Push all args if there are any
2071 if (argv)
2072 {
2073 for (int i = 0; argv[i]; ++i)
2074 exec_path_plus_argv.push_back(argv[i]);
2075 }
2076
2077 // Push a NULL to terminate the args.
2078 exec_path_plus_argv.push_back(NULL);
2079
2080 // Now launch using these arguments.
Greg Clayton471b31c2010-07-20 22:52:08 +00002081 error = DoLaunch (exe_module,
2082 exec_path_plus_argv.empty() ? NULL : &exec_path_plus_argv.front(),
2083 envp,
Greg Claytonf681b942010-08-31 18:35:14 +00002084 launch_flags,
Greg Clayton471b31c2010-07-20 22:52:08 +00002085 stdin_path,
2086 stdout_path,
Greg Claytonbd82a5d2011-01-23 05:56:20 +00002087 stderr_path,
2088 working_directory);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002089
2090 if (error.Fail())
2091 {
2092 if (GetID() != LLDB_INVALID_PROCESS_ID)
2093 {
2094 SetID (LLDB_INVALID_PROCESS_ID);
2095 const char *error_string = error.AsCString();
2096 if (error_string == NULL)
2097 error_string = "launch failed";
2098 SetExitStatus (-1, error_string);
2099 }
2100 }
2101 else
2102 {
2103 EventSP event_sp;
Greg Clayton1a38ea72011-06-22 01:42:17 +00002104 TimeValue timeout_time;
2105 timeout_time = TimeValue::Now();
2106 timeout_time.OffsetWithSeconds(10);
2107 StateType state = WaitForProcessStopPrivate(&timeout_time, event_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108
Greg Clayton1a38ea72011-06-22 01:42:17 +00002109 if (state == eStateInvalid || event_sp.get() == NULL)
2110 {
2111 // We were able to launch the process, but we failed to
2112 // catch the initial stop.
2113 SetExitStatus (0, "failed to catch stop after launch");
2114 Destroy();
2115 }
2116 else if (state == eStateStopped || state == eStateCrashed)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002117 {
Greg Clayton93d3c8332011-02-16 04:46:07 +00002118
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002119 DidLaunch ();
2120
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002121 m_dyld_ap.reset (DynamicLoader::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002122 if (m_dyld_ap.get())
2123 m_dyld_ap->DidLaunch();
2124
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002125 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126 // This delays passing the stopped event to listeners till DidLaunch gets
2127 // a chance to complete...
2128 HandlePrivateEvent (event_sp);
Greg Clayton71337622011-02-24 22:24:29 +00002129
2130 if (PrivateStateThreadIsValid ())
2131 ResumePrivateStateThread ();
2132 else
2133 StartPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002134 }
2135 else if (state == eStateExited)
2136 {
2137 // We exited while trying to launch somehow. Don't call DidLaunch as that's
2138 // not likely to work, and return an invalid pid.
2139 HandlePrivateEvent (event_sp);
2140 }
2141 }
2142 }
2143 }
2144 else
2145 {
Greg Clayton2289fa42011-04-30 01:09:13 +00002146 error.SetErrorStringWithFormat("File doesn't exist: '%s'.\n", local_exec_file_path);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002147 }
2148 }
2149 return error;
2150}
2151
Jim Inghambb3a2832011-01-29 01:49:25 +00002152Process::NextEventAction::EventActionResult
2153Process::AttachCompletionHandler::PerformAction (lldb::EventSP &event_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002154{
Jim Inghambb3a2832011-01-29 01:49:25 +00002155 StateType state = ProcessEventData::GetStateFromEvent (event_sp.get());
2156 switch (state)
Greg Clayton19388cf2010-10-18 01:45:30 +00002157 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002158 case eStateRunning:
Greg Clayton71337622011-02-24 22:24:29 +00002159 case eStateConnected:
Greg Clayton513c26c2011-01-29 07:10:55 +00002160 return eEventActionRetry;
2161
2162 case eStateStopped:
2163 case eStateCrashed:
Jim Ingham5aee1622010-08-09 23:31:02 +00002164 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002165 // During attach, prior to sending the eStateStopped event,
2166 // lldb_private::Process subclasses must set the process must set
2167 // the new process ID.
2168 assert (m_process->GetID() != LLDB_INVALID_PROCESS_ID);
Greg Clayton93d3c8332011-02-16 04:46:07 +00002169 m_process->CompleteAttach ();
Greg Clayton513c26c2011-01-29 07:10:55 +00002170 return eEventActionSuccess;
Jim Ingham5aee1622010-08-09 23:31:02 +00002171 }
Greg Clayton513c26c2011-01-29 07:10:55 +00002172
2173
2174 break;
2175 default:
2176 case eStateExited:
2177 case eStateInvalid:
2178 m_exit_string.assign ("No valid Process");
2179 return eEventActionExit;
2180 break;
Jim Inghambb3a2832011-01-29 01:49:25 +00002181 }
2182}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002183
Jim Inghambb3a2832011-01-29 01:49:25 +00002184Process::NextEventAction::EventActionResult
2185Process::AttachCompletionHandler::HandleBeingInterrupted()
2186{
2187 return eEventActionSuccess;
2188}
2189
2190const char *
2191Process::AttachCompletionHandler::GetExitString ()
2192{
2193 return m_exit_string.c_str();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002194}
2195
2196Error
2197Process::Attach (lldb::pid_t attach_pid)
2198{
2199
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002200 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002201 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002202
Jim Ingham5aee1622010-08-09 23:31:02 +00002203 // Find the process and its architecture. Make sure it matches the architecture
2204 // of the current Target, and if not adjust it.
2205
Greg Clayton8b82f082011-04-12 05:54:46 +00002206 ProcessInstanceInfo process_info;
Greg Claytonded470d2011-03-19 01:12:21 +00002207 PlatformSP platform_sp (m_target.GetDebugger().GetPlatformList().GetSelectedPlatform ());
Greg Claytone996fd32011-03-08 22:40:15 +00002208 if (platform_sp)
Jim Ingham5aee1622010-08-09 23:31:02 +00002209 {
Greg Claytone996fd32011-03-08 22:40:15 +00002210 if (platform_sp->GetProcessInfo (attach_pid, process_info))
2211 {
2212 const ArchSpec &process_arch = process_info.GetArchitecture();
2213 if (process_arch.IsValid())
2214 GetTarget().SetArchitecture(process_arch);
2215 }
Jim Ingham5aee1622010-08-09 23:31:02 +00002216 }
2217
Greg Clayton93d3c8332011-02-16 04:46:07 +00002218 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002219 m_os_ap.reset();
Greg Clayton93d3c8332011-02-16 04:46:07 +00002220
Greg Claytonc982c762010-07-09 20:39:50 +00002221 Error error (WillAttachToProcessWithID(attach_pid));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002222 if (error.Success())
2223 {
Greg Clayton05faeb72010-10-07 04:19:01 +00002224 SetPublicState (eStateAttaching);
2225
Greg Claytonc982c762010-07-09 20:39:50 +00002226 error = DoAttachToProcessWithID (attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002227 if (error.Success())
2228 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002229 SetNextEventAction(new Process::AttachCompletionHandler(this));
2230 StartPrivateStateThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002231 }
2232 else
2233 {
2234 if (GetID() != LLDB_INVALID_PROCESS_ID)
2235 {
2236 SetID (LLDB_INVALID_PROCESS_ID);
2237 const char *error_string = error.AsCString();
2238 if (error_string == NULL)
2239 error_string = "attach failed";
2240
2241 SetExitStatus(-1, error_string);
2242 }
2243 }
2244 }
2245 return error;
2246}
2247
2248Error
2249Process::Attach (const char *process_name, bool wait_for_launch)
2250{
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002251 m_abi_sp.reset();
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002252 m_process_input_reader.reset();
Jim Ingham5aee1622010-08-09 23:31:02 +00002253
2254 // Find the process and its architecture. Make sure it matches the architecture
2255 // of the current Target, and if not adjust it.
Greg Claytone996fd32011-03-08 22:40:15 +00002256 Error error;
Jim Ingham5aee1622010-08-09 23:31:02 +00002257
Jim Ingham2ecb7422010-08-17 21:54:19 +00002258 if (!wait_for_launch)
Jim Ingham5aee1622010-08-09 23:31:02 +00002259 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002260 ProcessInstanceInfoList process_infos;
Greg Claytonded470d2011-03-19 01:12:21 +00002261 PlatformSP platform_sp (m_target.GetDebugger().GetPlatformList().GetSelectedPlatform ());
Greg Claytone996fd32011-03-08 22:40:15 +00002262 if (platform_sp)
Jim Ingham2ecb7422010-08-17 21:54:19 +00002263 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002264 ProcessInstanceInfoMatch match_info;
Greg Clayton32e0a752011-03-30 18:16:51 +00002265 match_info.GetProcessInfo().SetName(process_name);
2266 match_info.SetNameMatchType (eNameMatchEquals);
2267 platform_sp->FindProcesses (match_info, process_infos);
Greg Claytone996fd32011-03-08 22:40:15 +00002268 if (process_infos.GetSize() > 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002269 {
Greg Claytone996fd32011-03-08 22:40:15 +00002270 error.SetErrorStringWithFormat ("More than one process named %s\n", process_name);
2271 }
2272 else if (process_infos.GetSize() == 0)
2273 {
2274 error.SetErrorStringWithFormat ("Could not find a process named %s\n", process_name);
2275 }
2276 else
2277 {
Greg Clayton8b82f082011-04-12 05:54:46 +00002278 ProcessInstanceInfo process_info;
Greg Claytone996fd32011-03-08 22:40:15 +00002279 if (process_infos.GetInfoAtIndex (0, process_info))
2280 {
2281 const ArchSpec &process_arch = process_info.GetArchitecture();
2282 if (process_arch.IsValid() && process_arch != GetTarget().GetArchitecture())
2283 {
2284 // Set the architecture on the target.
2285 GetTarget().SetArchitecture (process_arch);
2286 }
2287 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002288 }
2289 }
2290 else
Greg Claytone996fd32011-03-08 22:40:15 +00002291 {
2292 error.SetErrorString ("Invalid platform");
2293 }
2294 }
2295
2296 if (error.Success())
2297 {
2298 m_dyld_ap.reset();
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002299 m_os_ap.reset();
Greg Claytone996fd32011-03-08 22:40:15 +00002300
2301 error = WillAttachToProcessWithName(process_name, wait_for_launch);
2302 if (error.Success())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002303 {
Greg Claytone996fd32011-03-08 22:40:15 +00002304 SetPublicState (eStateAttaching);
2305 error = DoAttachToProcessWithName (process_name, wait_for_launch);
2306 if (error.Fail())
2307 {
2308 if (GetID() != LLDB_INVALID_PROCESS_ID)
2309 {
2310 SetID (LLDB_INVALID_PROCESS_ID);
2311 const char *error_string = error.AsCString();
2312 if (error_string == NULL)
2313 error_string = "attach failed";
2314
2315 SetExitStatus(-1, error_string);
2316 }
2317 }
2318 else
2319 {
2320 SetNextEventAction(new Process::AttachCompletionHandler(this));
2321 StartPrivateStateThread();
2322 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002323 }
2324 }
2325 return error;
2326}
2327
Greg Clayton93d3c8332011-02-16 04:46:07 +00002328void
2329Process::CompleteAttach ()
2330{
2331 // Let the process subclass figure out at much as it can about the process
2332 // before we go looking for a dynamic loader plug-in.
2333 DidAttach();
2334
2335 // We have complete the attach, now it is time to find the dynamic loader
2336 // plug-in
Greg Clayton7a5388b2011-03-20 04:57:14 +00002337 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002338 if (m_dyld_ap.get())
2339 m_dyld_ap->DidAttach();
2340
Greg Clayton56d9a1b2011-08-22 02:49:39 +00002341 m_os_ap.reset (OperatingSystem::FindPlugin (this, NULL));
Greg Clayton93d3c8332011-02-16 04:46:07 +00002342 // Figure out which one is the executable, and set that in our target:
2343 ModuleList &modules = m_target.GetImages();
2344
2345 size_t num_modules = modules.GetSize();
2346 for (int i = 0; i < num_modules; i++)
2347 {
2348 ModuleSP module_sp (modules.GetModuleAtIndex(i));
Greg Clayton8b82f082011-04-12 05:54:46 +00002349 if (module_sp && module_sp->IsExecutable())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002350 {
Greg Claytonaa149cb2011-08-11 02:48:45 +00002351 if (m_target.GetExecutableModulePointer() != module_sp.get())
Greg Clayton93d3c8332011-02-16 04:46:07 +00002352 m_target.SetExecutableModule (module_sp, false);
2353 break;
2354 }
2355 }
2356}
2357
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002358Error
Greg Claytonb766a732011-02-04 01:58:07 +00002359Process::ConnectRemote (const char *remote_url)
2360{
Greg Claytonb766a732011-02-04 01:58:07 +00002361 m_abi_sp.reset();
2362 m_process_input_reader.reset();
2363
2364 // Find the process and its architecture. Make sure it matches the architecture
2365 // of the current Target, and if not adjust it.
2366
2367 Error error (DoConnectRemote (remote_url));
2368 if (error.Success())
2369 {
Greg Clayton71337622011-02-24 22:24:29 +00002370 if (GetID() != LLDB_INVALID_PROCESS_ID)
2371 {
Greg Clayton32e0a752011-03-30 18:16:51 +00002372 EventSP event_sp;
2373 StateType state = WaitForProcessStopPrivate(NULL, event_sp);
2374
2375 if (state == eStateStopped || state == eStateCrashed)
2376 {
2377 // If we attached and actually have a process on the other end, then
2378 // this ended up being the equivalent of an attach.
2379 CompleteAttach ();
2380
2381 // This delays passing the stopped event to listeners till
2382 // CompleteAttach gets a chance to complete...
2383 HandlePrivateEvent (event_sp);
2384
2385 }
Greg Clayton71337622011-02-24 22:24:29 +00002386 }
Greg Clayton32e0a752011-03-30 18:16:51 +00002387
2388 if (PrivateStateThreadIsValid ())
2389 ResumePrivateStateThread ();
2390 else
2391 StartPrivateStateThread ();
Greg Claytonb766a732011-02-04 01:58:07 +00002392 }
2393 return error;
2394}
2395
2396
2397Error
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002398Process::Resume ()
2399{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002400 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002401 if (log)
Jim Ingham444586b2011-01-24 06:34:17 +00002402 log->Printf("Process::Resume() m_stop_id = %u, public state: %s private state: %s",
Jim Ingham4b536182011-08-09 02:12:22 +00002403 m_mod_id.GetStopID(),
Jim Ingham444586b2011-01-24 06:34:17 +00002404 StateAsCString(m_public_state.GetValue()),
2405 StateAsCString(m_private_state.GetValue()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002406
2407 Error error (WillResume());
2408 // Tell the process it is about to resume before the thread list
2409 if (error.Success())
2410 {
Johnny Chenc4221e42010-12-02 20:53:05 +00002411 // Now let the thread list know we are about to resume so it
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002412 // can let all of our threads know that they are about to be
2413 // resumed. Threads will each be called with
2414 // Thread::WillResume(StateType) where StateType contains the state
2415 // that they are supposed to have when the process is resumed
2416 // (suspended/running/stepping). Threads should also check
2417 // their resume signal in lldb::Thread::GetResumeSignal()
2418 // to see if they are suppoed to start back up with a signal.
2419 if (m_thread_list.WillResume())
2420 {
2421 error = DoResume();
2422 if (error.Success())
2423 {
2424 DidResume();
2425 m_thread_list.DidResume();
Jim Ingham444586b2011-01-24 06:34:17 +00002426 if (log)
2427 log->Printf ("Process thinks the process has resumed.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002428 }
2429 }
2430 else
2431 {
Jim Ingham444586b2011-01-24 06:34:17 +00002432 error.SetErrorStringWithFormat("Process::WillResume() thread list returned false after WillResume");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002433 }
2434 }
Jim Ingham444586b2011-01-24 06:34:17 +00002435 else if (log)
2436 log->Printf ("Process::WillResume() got an error \"%s\".", error.AsCString("<unknown error>"));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002437 return error;
2438}
2439
2440Error
2441Process::Halt ()
2442{
Jim Inghambb3a2832011-01-29 01:49:25 +00002443 // Pause our private state thread so we can ensure no one else eats
2444 // the stop event out from under us.
Jim Ingham0f16e732011-02-08 05:20:59 +00002445 Listener halt_listener ("lldb.process.halt_listener");
2446 HijackPrivateProcessEvents(&halt_listener);
Greg Clayton3af9ea52010-11-18 05:57:03 +00002447
Jim Inghambb3a2832011-01-29 01:49:25 +00002448 EventSP event_sp;
Greg Clayton513c26c2011-01-29 07:10:55 +00002449 Error error (WillHalt());
Jim Inghambb3a2832011-01-29 01:49:25 +00002450
Greg Clayton513c26c2011-01-29 07:10:55 +00002451 if (error.Success())
Jim Inghambb3a2832011-01-29 01:49:25 +00002452 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002453
Greg Clayton513c26c2011-01-29 07:10:55 +00002454 bool caused_stop = false;
2455
2456 // Ask the process subclass to actually halt our process
2457 error = DoHalt(caused_stop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002458 if (error.Success())
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002459 {
Greg Clayton513c26c2011-01-29 07:10:55 +00002460 if (m_public_state.GetValue() == eStateAttaching)
2461 {
2462 SetExitStatus(SIGKILL, "Cancelled async attach.");
2463 Destroy ();
2464 }
2465 else
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002466 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002467 // If "caused_stop" is true, then DoHalt stopped the process. If
2468 // "caused_stop" is false, the process was already stopped.
2469 // If the DoHalt caused the process to stop, then we want to catch
2470 // this event and set the interrupted bool to true before we pass
2471 // this along so clients know that the process was interrupted by
2472 // a halt command.
2473 if (caused_stop)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002474 {
Jim Ingham0f16e732011-02-08 05:20:59 +00002475 // Wait for 1 second for the process to stop.
Jim Inghambb3a2832011-01-29 01:49:25 +00002476 TimeValue timeout_time;
2477 timeout_time = TimeValue::Now();
2478 timeout_time.OffsetWithSeconds(1);
Jim Ingham0f16e732011-02-08 05:20:59 +00002479 bool got_event = halt_listener.WaitForEvent (&timeout_time, event_sp);
2480 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002481
Jim Ingham0f16e732011-02-08 05:20:59 +00002482 if (!got_event || state == eStateInvalid)
Greg Clayton3af9ea52010-11-18 05:57:03 +00002483 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002484 // We timeout out and didn't get a stop event...
Jim Ingham0f16e732011-02-08 05:20:59 +00002485 error.SetErrorStringWithFormat ("Halt timed out. State = %s", StateAsCString(GetState()));
Greg Clayton3af9ea52010-11-18 05:57:03 +00002486 }
2487 else
2488 {
Jim Inghambb3a2832011-01-29 01:49:25 +00002489 if (StateIsStoppedState (state))
2490 {
2491 // We caused the process to interrupt itself, so mark this
2492 // as such in the stop event so clients can tell an interrupted
2493 // process from a natural stop
2494 ProcessEventData::SetInterruptedInEvent (event_sp.get(), true);
2495 }
2496 else
2497 {
2498 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2499 if (log)
2500 log->Printf("Process::Halt() failed to stop, state is: %s", StateAsCString(state));
2501 error.SetErrorString ("Did not get stopped event after halt.");
2502 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00002503 }
2504 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002505 DidHalt();
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002506 }
2507 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002508 }
Jim Inghambb3a2832011-01-29 01:49:25 +00002509 // Resume our private state thread before we post the event (if any)
Jim Ingham0f16e732011-02-08 05:20:59 +00002510 RestorePrivateProcessEvents();
Jim Inghambb3a2832011-01-29 01:49:25 +00002511
2512 // Post any event we might have consumed. If all goes well, we will have
2513 // stopped the process, intercepted the event and set the interrupted
2514 // bool in the event. Post it to the private event queue and that will end up
2515 // correctly setting the state.
2516 if (event_sp)
2517 m_private_state_broadcaster.BroadcastEvent(event_sp);
2518
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002519 return error;
2520}
2521
2522Error
2523Process::Detach ()
2524{
2525 Error error (WillDetach());
2526
2527 if (error.Success())
2528 {
2529 DisableAllBreakpointSites();
2530 error = DoDetach();
2531 if (error.Success())
2532 {
2533 DidDetach();
2534 StopPrivateStateThread();
2535 }
2536 }
2537 return error;
2538}
2539
2540Error
2541Process::Destroy ()
2542{
2543 Error error (WillDestroy());
2544 if (error.Success())
2545 {
2546 DisableAllBreakpointSites();
2547 error = DoDestroy();
2548 if (error.Success())
2549 {
2550 DidDestroy();
2551 StopPrivateStateThread();
2552 }
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002553 m_stdio_communication.StopReadThread();
2554 m_stdio_communication.Disconnect();
2555 if (m_process_input_reader && m_process_input_reader->IsActive())
2556 m_target.GetDebugger().PopInputReader (m_process_input_reader);
2557 if (m_process_input_reader)
2558 m_process_input_reader.reset();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002559 }
2560 return error;
2561}
2562
2563Error
2564Process::Signal (int signal)
2565{
2566 Error error (WillSignal());
2567 if (error.Success())
2568 {
2569 error = DoSignal(signal);
2570 if (error.Success())
2571 DidSignal();
2572 }
2573 return error;
2574}
2575
Greg Clayton514487e2011-02-15 21:59:32 +00002576lldb::ByteOrder
2577Process::GetByteOrder () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002578{
Greg Clayton514487e2011-02-15 21:59:32 +00002579 return m_target.GetArchitecture().GetByteOrder();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002580}
2581
2582uint32_t
Greg Clayton514487e2011-02-15 21:59:32 +00002583Process::GetAddressByteSize () const
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002584{
Greg Clayton514487e2011-02-15 21:59:32 +00002585 return m_target.GetArchitecture().GetAddressByteSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002586}
2587
Greg Clayton514487e2011-02-15 21:59:32 +00002588
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002589bool
2590Process::ShouldBroadcastEvent (Event *event_ptr)
2591{
2592 const StateType state = Process::ProcessEventData::GetStateFromEvent (event_ptr);
2593 bool return_value = true;
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002594 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002595
2596 switch (state)
2597 {
Greg Claytonb766a732011-02-04 01:58:07 +00002598 case eStateConnected:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002599 case eStateAttaching:
2600 case eStateLaunching:
2601 case eStateDetached:
2602 case eStateExited:
2603 case eStateUnloaded:
2604 // These events indicate changes in the state of the debugging session, always report them.
2605 return_value = true;
2606 break;
2607 case eStateInvalid:
2608 // We stopped for no apparent reason, don't report it.
2609 return_value = false;
2610 break;
2611 case eStateRunning:
2612 case eStateStepping:
2613 // If we've started the target running, we handle the cases where we
2614 // are already running and where there is a transition from stopped to
2615 // running differently.
2616 // running -> running: Automatically suppress extra running events
2617 // stopped -> running: Report except when there is one or more no votes
2618 // and no yes votes.
2619 SynchronouslyNotifyStateChanged (state);
2620 switch (m_public_state.GetValue())
2621 {
2622 case eStateRunning:
2623 case eStateStepping:
2624 // We always suppress multiple runnings with no PUBLIC stop in between.
2625 return_value = false;
2626 break;
2627 default:
2628 // TODO: make this work correctly. For now always report
2629 // run if we aren't running so we don't miss any runnning
2630 // events. If I run the lldb/test/thread/a.out file and
2631 // break at main.cpp:58, run and hit the breakpoints on
2632 // multiple threads, then somehow during the stepping over
2633 // of all breakpoints no run gets reported.
2634 return_value = true;
2635
2636 // This is a transition from stop to run.
2637 switch (m_thread_list.ShouldReportRun (event_ptr))
2638 {
2639 case eVoteYes:
2640 case eVoteNoOpinion:
2641 return_value = true;
2642 break;
2643 case eVoteNo:
2644 return_value = false;
2645 break;
2646 }
2647 break;
2648 }
2649 break;
2650 case eStateStopped:
2651 case eStateCrashed:
2652 case eStateSuspended:
2653 {
2654 // We've stopped. First see if we're going to restart the target.
2655 // If we are going to stop, then we always broadcast the event.
2656 // 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 +00002657 // If no thread has an opinion, we don't report it.
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002658 if (ProcessEventData::GetInterruptedFromEvent (event_ptr))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002659 {
Greg Clayton3af9ea52010-11-18 05:57:03 +00002660 if (log)
2661 log->Printf ("Process::ShouldBroadcastEvent (%p) stopped due to an interrupt, state: %s", event_ptr, StateAsCString(state));
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002662 return true;
2663 }
2664 else
2665 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002666 RefreshStateAfterStop ();
2667
2668 if (m_thread_list.ShouldStop (event_ptr) == false)
2669 {
2670 switch (m_thread_list.ShouldReportStop (event_ptr))
2671 {
2672 case eVoteYes:
2673 Process::ProcessEventData::SetRestartedInEvent (event_ptr, true);
Johnny Chen3c230652010-10-14 00:54:32 +00002674 // Intentional fall-through here.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002675 case eVoteNoOpinion:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002676 case eVoteNo:
2677 return_value = false;
2678 break;
2679 }
2680
2681 if (log)
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002682 log->Printf ("Process::ShouldBroadcastEvent (%p) Restarting process from state: %s", event_ptr, StateAsCString(state));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002683 Resume ();
2684 }
2685 else
2686 {
2687 return_value = true;
2688 SynchronouslyNotifyStateChanged (state);
2689 }
2690 }
2691 }
2692 }
2693
2694 if (log)
2695 log->Printf ("Process::ShouldBroadcastEvent (%p) => %s", event_ptr, StateAsCString(state), return_value ? "YES" : "NO");
2696 return return_value;
2697}
2698
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002699
2700bool
2701Process::StartPrivateStateThread ()
2702{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002703 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002704
Greg Clayton8b82f082011-04-12 05:54:46 +00002705 bool already_running = PrivateStateThreadIsValid ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002706 if (log)
Greg Clayton8b82f082011-04-12 05:54:46 +00002707 log->Printf ("Process::%s()%s ", __FUNCTION__, already_running ? " already running" : " starting private state thread");
2708
2709 if (already_running)
2710 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002711
2712 // Create a thread that watches our internal state and controls which
2713 // events make it to clients (into the DCProcess event queue).
Greg Clayton3e06bd92011-01-09 21:07:35 +00002714 char thread_name[1024];
2715 snprintf(thread_name, sizeof(thread_name), "<lldb.process.internal-state(pid=%i)>", GetID());
2716 m_private_state_thread = Host::ThreadCreate (thread_name, Process::PrivateStateThread, this, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +00002717 return IS_VALID_LLDB_HOST_THREAD(m_private_state_thread);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002718}
2719
2720void
2721Process::PausePrivateStateThread ()
2722{
2723 ControlPrivateStateThread (eBroadcastInternalStateControlPause);
2724}
2725
2726void
2727Process::ResumePrivateStateThread ()
2728{
2729 ControlPrivateStateThread (eBroadcastInternalStateControlResume);
2730}
2731
2732void
2733Process::StopPrivateStateThread ()
2734{
Greg Clayton8b82f082011-04-12 05:54:46 +00002735 if (PrivateStateThreadIsValid ())
2736 ControlPrivateStateThread (eBroadcastInternalStateControlStop);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002737}
2738
2739void
2740Process::ControlPrivateStateThread (uint32_t signal)
2741{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002742 LogSP log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743
2744 assert (signal == eBroadcastInternalStateControlStop ||
2745 signal == eBroadcastInternalStateControlPause ||
2746 signal == eBroadcastInternalStateControlResume);
2747
2748 if (log)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002749 log->Printf ("Process::%s (signal = %d)", __FUNCTION__, signal);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002750
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002751 // Signal the private state thread. First we should copy this is case the
2752 // thread starts exiting since the private state thread will NULL this out
2753 // when it exits
2754 const lldb::thread_t private_state_thread = m_private_state_thread;
Greg Clayton2da6d492011-02-08 01:34:25 +00002755 if (IS_VALID_LLDB_HOST_THREAD(private_state_thread))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002756 {
2757 TimeValue timeout_time;
2758 bool timed_out;
2759
2760 m_private_state_control_broadcaster.BroadcastEvent (signal, NULL);
2761
2762 timeout_time = TimeValue::Now();
2763 timeout_time.OffsetWithSeconds(2);
2764 m_private_state_control_wait.WaitForValueEqualTo (true, &timeout_time, &timed_out);
2765 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2766
2767 if (signal == eBroadcastInternalStateControlStop)
2768 {
2769 if (timed_out)
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002770 Host::ThreadCancel (private_state_thread, NULL);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002771
2772 thread_result_t result = NULL;
Greg Clayton7ecb3a02011-01-22 17:43:17 +00002773 Host::ThreadJoin (private_state_thread, &result, NULL);
Greg Clayton49182ed2010-07-22 18:34:21 +00002774 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002775 }
2776 }
2777}
2778
2779void
2780Process::HandlePrivateEvent (EventSP &event_sp)
2781{
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002782 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Jim Inghambb3a2832011-01-29 01:49:25 +00002783
Greg Clayton414f5d32011-01-25 02:58:48 +00002784 const StateType new_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
Jim Inghambb3a2832011-01-29 01:49:25 +00002785
2786 // First check to see if anybody wants a shot at this event:
Jim Ingham754ab982011-01-29 04:05:41 +00002787 if (m_next_event_action_ap.get() != NULL)
Jim Inghambb3a2832011-01-29 01:49:25 +00002788 {
Jim Ingham754ab982011-01-29 04:05:41 +00002789 NextEventAction::EventActionResult action_result = m_next_event_action_ap->PerformAction(event_sp);
Jim Inghambb3a2832011-01-29 01:49:25 +00002790 switch (action_result)
2791 {
2792 case NextEventAction::eEventActionSuccess:
2793 SetNextEventAction(NULL);
2794 break;
2795 case NextEventAction::eEventActionRetry:
2796 break;
2797 case NextEventAction::eEventActionExit:
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002798 // Handle Exiting Here. If we already got an exited event,
2799 // we should just propagate it. Otherwise, swallow this event,
2800 // and set our state to exit so the next event will kill us.
2801 if (new_state != eStateExited)
2802 {
2803 // FIXME: should cons up an exited event, and discard this one.
Jim Ingham754ab982011-01-29 04:05:41 +00002804 SetExitStatus(0, m_next_event_action_ap->GetExitString());
Jim Ingham2a5fdd42011-01-29 01:57:31 +00002805 SetNextEventAction(NULL);
2806 return;
2807 }
2808 SetNextEventAction(NULL);
Jim Inghambb3a2832011-01-29 01:49:25 +00002809 break;
2810 }
2811 }
2812
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002813 // See if we should broadcast this state to external clients?
2814 const bool should_broadcast = ShouldBroadcastEvent (event_sp.get());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002815
2816 if (should_broadcast)
2817 {
2818 if (log)
2819 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002820 log->Printf ("Process::%s (pid = %i) broadcasting new state %s (old state %s) to %s",
2821 __FUNCTION__,
2822 GetID(),
2823 StateAsCString(new_state),
2824 StateAsCString (GetState ()),
2825 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002826 }
Jim Ingham9575d842011-03-11 03:53:59 +00002827 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
Greg Clayton414f5d32011-01-25 02:58:48 +00002828 if (StateIsRunningState (new_state))
Caroline Ticeef5c6d02010-11-16 05:07:41 +00002829 PushProcessInputReader ();
2830 else
2831 PopProcessInputReader ();
Jim Ingham9575d842011-03-11 03:53:59 +00002832
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002833 BroadcastEvent (event_sp);
2834 }
2835 else
2836 {
2837 if (log)
2838 {
Greg Clayton414f5d32011-01-25 02:58:48 +00002839 log->Printf ("Process::%s (pid = %i) suppressing state %s (old state %s): should_broadcast == false",
2840 __FUNCTION__,
2841 GetID(),
2842 StateAsCString(new_state),
2843 StateAsCString (GetState ()),
2844 IsHijackedForEvent(eBroadcastBitStateChanged) ? "hijacked" : "public");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002845 }
2846 }
2847}
2848
2849void *
2850Process::PrivateStateThread (void *arg)
2851{
2852 Process *proc = static_cast<Process*> (arg);
2853 void *result = proc->RunPrivateStateThread ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002854 return result;
2855}
2856
2857void *
2858Process::RunPrivateStateThread ()
2859{
2860 bool control_only = false;
2861 m_private_state_control_wait.SetValue (false, eBroadcastNever);
2862
Greg Clayton2d4edfb2010-11-06 01:53:30 +00002863 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002864 if (log)
2865 log->Printf ("Process::%s (arg = %p, pid = %i) thread starting...", __FUNCTION__, this, GetID());
2866
2867 bool exit_now = false;
2868 while (!exit_now)
2869 {
2870 EventSP event_sp;
2871 WaitForEventsPrivate (NULL, event_sp, control_only);
2872 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster))
2873 {
2874 switch (event_sp->GetType())
2875 {
2876 case eBroadcastInternalStateControlStop:
2877 exit_now = true;
2878 continue; // Go to next loop iteration so we exit without
2879 break; // doing any internal state managment below
2880
2881 case eBroadcastInternalStateControlPause:
2882 control_only = true;
2883 break;
2884
2885 case eBroadcastInternalStateControlResume:
2886 control_only = false;
2887 break;
2888 }
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002889
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002890 if (log)
2891 log->Printf ("Process::%s (arg = %p, pid = %i) got a control event: %d", __FUNCTION__, this, GetID(), event_sp->GetType());
2892
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002893 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002894 continue;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002895 }
2896
2897
2898 const StateType internal_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
2899
2900 if (internal_state != eStateInvalid)
2901 {
2902 HandlePrivateEvent (event_sp);
2903 }
2904
Greg Clayton58d1c9a2010-10-18 04:14:23 +00002905 if (internal_state == eStateInvalid ||
2906 internal_state == eStateExited ||
2907 internal_state == eStateDetached )
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002908 {
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002909 if (log)
2910 log->Printf ("Process::%s (arg = %p, pid = %i) about to exit with internal state %s...", __FUNCTION__, this, GetID(), StateAsCString(internal_state));
2911
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002912 break;
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002913 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002914 }
2915
Caroline Tice20ad3c42010-10-29 21:48:37 +00002916 // Verify log is still enabled before attempting to write to it...
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002917 if (log)
2918 log->Printf ("Process::%s (arg = %p, pid = %i) thread exiting...", __FUNCTION__, this, GetID());
2919
Greg Clayton6ed95942011-01-22 07:12:45 +00002920 m_private_state_control_wait.SetValue (true, eBroadcastAlways);
2921 m_private_state_thread = LLDB_INVALID_HOST_THREAD;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002922 return NULL;
2923}
2924
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002925//------------------------------------------------------------------
2926// Process Event Data
2927//------------------------------------------------------------------
2928
2929Process::ProcessEventData::ProcessEventData () :
2930 EventData (),
2931 m_process_sp (),
2932 m_state (eStateInvalid),
Greg Claytonc982c762010-07-09 20:39:50 +00002933 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00002934 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002935 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002936{
2937}
2938
2939Process::ProcessEventData::ProcessEventData (const ProcessSP &process_sp, StateType state) :
2940 EventData (),
2941 m_process_sp (process_sp),
2942 m_state (state),
Greg Claytonc982c762010-07-09 20:39:50 +00002943 m_restarted (false),
Jim Inghama8604692011-05-22 21:45:01 +00002944 m_update_state (0),
Jim Ingham0d8bcc72010-11-17 02:32:00 +00002945 m_interrupted (false)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002946{
2947}
2948
2949Process::ProcessEventData::~ProcessEventData()
2950{
2951}
2952
2953const ConstString &
2954Process::ProcessEventData::GetFlavorString ()
2955{
2956 static ConstString g_flavor ("Process::ProcessEventData");
2957 return g_flavor;
2958}
2959
2960const ConstString &
2961Process::ProcessEventData::GetFlavor () const
2962{
2963 return ProcessEventData::GetFlavorString ();
2964}
2965
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002966void
2967Process::ProcessEventData::DoOnRemoval (Event *event_ptr)
2968{
2969 // This function gets called twice for each event, once when the event gets pulled
Jim Inghama8604692011-05-22 21:45:01 +00002970 // off of the private process event queue, and then any number of times, first when it gets pulled off of
2971 // the public event queue, then other times when we're pretending that this is where we stopped at the
2972 // end of expression evaluation. m_update_state is used to distinguish these
2973 // three cases; it is 0 when we're just pulling it off for private handling,
2974 // and > 1 for expression evaluation, and we don't want to do the breakpoint command handling then.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002975
Jim Inghama8604692011-05-22 21:45:01 +00002976 if (m_update_state != 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002977 return;
2978
2979 m_process_sp->SetPublicState (m_state);
2980
2981 // If we're stopped and haven't restarted, then do the breakpoint commands here:
2982 if (m_state == eStateStopped && ! m_restarted)
2983 {
2984 int num_threads = m_process_sp->GetThreadList().GetSize();
2985 int idx;
Greg Claytonf4b47e12010-08-04 01:40:35 +00002986
Jim Ingham4b536182011-08-09 02:12:22 +00002987 // The actions might change one of the thread's stop_info's opinions about whether we should
2988 // stop the process, so we need to query that as we go.
2989 bool still_should_stop = true;
2990
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002991 for (idx = 0; idx < num_threads; ++idx)
2992 {
2993 lldb::ThreadSP thread_sp = m_process_sp->GetThreadList().GetThreadAtIndex(idx);
2994
Jim Inghamb15bfc72010-10-20 00:39:53 +00002995 StopInfoSP stop_info_sp = thread_sp->GetStopInfo ();
2996 if (stop_info_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997 {
Jim Inghamb15bfc72010-10-20 00:39:53 +00002998 stop_info_sp->PerformAction(event_ptr);
Jim Ingham4b536182011-08-09 02:12:22 +00002999 // The stop action might restart the target. If it does, then we want to mark that in the
3000 // event so that whoever is receiving it will know to wait for the running event and reflect
3001 // that state appropriately.
3002 // We also need to stop processing actions, since they aren't expecting the target to be running.
3003 if (m_process_sp->GetPrivateState() == eStateRunning)
3004 {
3005 SetRestarted (true);
3006 break;
3007 }
3008 else if (!stop_info_sp->ShouldStop(event_ptr))
3009 {
3010 still_should_stop = false;
3011 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003012 }
3013 }
Jim Ingham3ebcf7f2010-08-10 00:59:59 +00003014
Jim Ingham4b536182011-08-09 02:12:22 +00003015
3016 if (m_process_sp->GetPrivateState() != eStateRunning)
Jim Ingham9575d842011-03-11 03:53:59 +00003017 {
Jim Ingham4b536182011-08-09 02:12:22 +00003018 if (!still_should_stop)
3019 {
3020 // We've been asked to continue, so do that here.
Jim Ingham9575d842011-03-11 03:53:59 +00003021 SetRestarted(true);
Jim Ingham4b536182011-08-09 02:12:22 +00003022 m_process_sp->Resume();
3023 }
3024 else
3025 {
3026 // If we didn't restart, run the Stop Hooks here:
3027 // They might also restart the target, so watch for that.
3028 m_process_sp->GetTarget().RunStopHooks();
3029 if (m_process_sp->GetPrivateState() == eStateRunning)
3030 SetRestarted(true);
3031 }
Jim Ingham9575d842011-03-11 03:53:59 +00003032 }
3033
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003034 }
3035}
3036
3037void
3038Process::ProcessEventData::Dump (Stream *s) const
3039{
3040 if (m_process_sp)
3041 s->Printf(" process = %p (pid = %u), ", m_process_sp.get(), m_process_sp->GetID());
3042
Greg Clayton8b82f082011-04-12 05:54:46 +00003043 s->Printf("state = %s", StateAsCString(GetState()));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003044}
3045
3046const Process::ProcessEventData *
3047Process::ProcessEventData::GetEventDataFromEvent (const Event *event_ptr)
3048{
3049 if (event_ptr)
3050 {
3051 const EventData *event_data = event_ptr->GetData();
3052 if (event_data && event_data->GetFlavor() == ProcessEventData::GetFlavorString())
3053 return static_cast <const ProcessEventData *> (event_ptr->GetData());
3054 }
3055 return NULL;
3056}
3057
3058ProcessSP
3059Process::ProcessEventData::GetProcessFromEvent (const Event *event_ptr)
3060{
3061 ProcessSP process_sp;
3062 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3063 if (data)
3064 process_sp = data->GetProcessSP();
3065 return process_sp;
3066}
3067
3068StateType
3069Process::ProcessEventData::GetStateFromEvent (const Event *event_ptr)
3070{
3071 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3072 if (data == NULL)
3073 return eStateInvalid;
3074 else
3075 return data->GetState();
3076}
3077
3078bool
3079Process::ProcessEventData::GetRestartedFromEvent (const Event *event_ptr)
3080{
3081 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3082 if (data == NULL)
3083 return false;
3084 else
3085 return data->GetRestarted();
3086}
3087
3088void
3089Process::ProcessEventData::SetRestartedInEvent (Event *event_ptr, bool new_value)
3090{
3091 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3092 if (data != NULL)
3093 data->SetRestarted(new_value);
3094}
3095
3096bool
Jim Ingham0d8bcc72010-11-17 02:32:00 +00003097Process::ProcessEventData::GetInterruptedFromEvent (const Event *event_ptr)
3098{
3099 const ProcessEventData *data = GetEventDataFromEvent (event_ptr);
3100 if (data == NULL)
3101 return false;
3102 else
3103 return data->GetInterrupted ();
3104}
3105
3106void
3107Process::ProcessEventData::SetInterruptedInEvent (Event *event_ptr, bool new_value)
3108{
3109 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3110 if (data != NULL)
3111 data->SetInterrupted(new_value);
3112}
3113
3114bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115Process::ProcessEventData::SetUpdateStateOnRemoval (Event *event_ptr)
3116{
3117 ProcessEventData *data = const_cast<ProcessEventData *>(GetEventDataFromEvent (event_ptr));
3118 if (data)
3119 {
3120 data->SetUpdateStateOnRemoval();
3121 return true;
3122 }
3123 return false;
3124}
3125
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003126void
Greg Clayton0603aa92010-10-04 01:05:56 +00003127Process::CalculateExecutionContext (ExecutionContext &exe_ctx)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003128{
3129 exe_ctx.target = &m_target;
3130 exe_ctx.process = this;
3131 exe_ctx.thread = NULL;
3132 exe_ctx.frame = NULL;
3133}
3134
3135lldb::ProcessSP
3136Process::GetSP ()
3137{
3138 return GetTarget().GetProcessSP();
3139}
3140
Greg Claytone996fd32011-03-08 22:40:15 +00003141//uint32_t
3142//Process::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3143//{
3144// return 0;
3145//}
3146//
3147//ArchSpec
3148//Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
3149//{
3150// return Host::GetArchSpecForExistingProcess (pid);
3151//}
3152//
3153//ArchSpec
3154//Process::GetArchSpecForExistingProcess (const char *process_name)
3155//{
3156// return Host::GetArchSpecForExistingProcess (process_name);
3157//}
3158//
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003159void
3160Process::AppendSTDOUT (const char * s, size_t len)
3161{
Greg Clayton3af9ea52010-11-18 05:57:03 +00003162 Mutex::Locker locker (m_stdio_communication_mutex);
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003163 m_stdout_data.append (s, len);
3164
Greg Claytona9ff3062010-12-05 19:16:56 +00003165 BroadcastEventIfUnique (eBroadcastBitSTDOUT, new ProcessEventData (GetTarget().GetProcessSP(), GetState()));
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003166}
3167
3168void
3169Process::STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len)
3170{
3171 Process *process = (Process *) baton;
3172 process->AppendSTDOUT (static_cast<const char *>(src), src_len);
3173}
3174
3175size_t
3176Process::ProcessInputReaderCallback (void *baton,
3177 InputReader &reader,
3178 lldb::InputReaderAction notification,
3179 const char *bytes,
3180 size_t bytes_len)
3181{
3182 Process *process = (Process *) baton;
3183
3184 switch (notification)
3185 {
3186 case eInputReaderActivate:
3187 break;
3188
3189 case eInputReaderDeactivate:
3190 break;
3191
3192 case eInputReaderReactivate:
3193 break;
3194
Caroline Tice969ed3d2011-05-02 20:41:46 +00003195 case eInputReaderAsynchronousOutputWritten:
3196 break;
3197
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003198 case eInputReaderGotToken:
3199 {
3200 Error error;
3201 process->PutSTDIN (bytes, bytes_len, error);
3202 }
3203 break;
3204
Caroline Ticeefed6132010-11-19 20:47:54 +00003205 case eInputReaderInterrupt:
3206 process->Halt ();
3207 break;
3208
3209 case eInputReaderEndOfFile:
3210 process->AppendSTDOUT ("^D", 2);
3211 break;
3212
Caroline Ticeef5c6d02010-11-16 05:07:41 +00003213 case eInputReaderDone:
3214 break;
3215
3216 }
3217
3218 return bytes_len;
3219}
3220
3221void
3222Process::ResetProcessInputReader ()
3223{
3224 m_process_input_reader.reset();
3225}
3226
3227void
3228Process::SetUpProcessInputReader (int file_descriptor)
3229{
3230 // First set up the Read Thread for reading/handling process I/O
3231
3232 std::auto_ptr<ConnectionFileDescriptor> conn_ap (new ConnectionFileDescriptor (file_descriptor, true));
3233
3234 if (conn_ap.get())
3235 {
3236 m_stdio_communication.SetConnection (conn_ap.release());
3237 if (m_stdio_communication.IsConnected())
3238 {
3239 m_stdio_communication.SetReadThreadBytesReceivedCallback (STDIOReadThreadBytesReceived, this);
3240 m_stdio_communication.StartReadThread();
3241
3242 // Now read thread is set up, set up input reader.
3243
3244 if (!m_process_input_reader.get())
3245 {
3246 m_process_input_reader.reset (new InputReader(m_target.GetDebugger()));
3247 Error err (m_process_input_reader->Initialize (Process::ProcessInputReaderCallback,
3248 this,
3249 eInputReaderGranularityByte,
3250 NULL,
3251 NULL,
3252 false));
3253
3254 if (err.Fail())
3255 m_process_input_reader.reset();
3256 }
3257 }
3258 }
3259}
3260
3261void
3262Process::PushProcessInputReader ()
3263{
3264 if (m_process_input_reader && !m_process_input_reader->IsActive())
3265 m_target.GetDebugger().PushInputReader (m_process_input_reader);
3266}
3267
3268void
3269Process::PopProcessInputReader ()
3270{
3271 if (m_process_input_reader && m_process_input_reader->IsActive())
3272 m_target.GetDebugger().PopInputReader (m_process_input_reader);
3273}
3274
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003275// The process needs to know about installed plug-ins
Greg Clayton99d0faf2010-11-18 23:32:35 +00003276void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003277Process::SettingsInitialize ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003278{
Greg Claytone0d378b2011-03-24 21:19:54 +00003279 static std::vector<OptionEnumValueElement> g_plugins;
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003280
3281 int i=0;
3282 const char *name;
3283 OptionEnumValueElement option_enum;
3284 while ((name = PluginManager::GetProcessPluginNameAtIndex (i)) != NULL)
3285 {
3286 if (name)
3287 {
3288 option_enum.value = i;
3289 option_enum.string_value = name;
3290 option_enum.usage = PluginManager::GetProcessPluginDescriptionAtIndex (i);
3291 g_plugins.push_back (option_enum);
3292 }
3293 ++i;
3294 }
3295 option_enum.value = 0;
3296 option_enum.string_value = NULL;
3297 option_enum.usage = NULL;
3298 g_plugins.push_back (option_enum);
3299
3300 for (i=0; (name = SettingsController::instance_settings_table[i].var_name); ++i)
3301 {
3302 if (::strcmp (name, "plugin") == 0)
3303 {
3304 SettingsController::instance_settings_table[i].enum_values = &g_plugins[0];
3305 break;
3306 }
3307 }
Greg Clayton99d0faf2010-11-18 23:32:35 +00003308 UserSettingsControllerSP &usc = GetSettingsController();
3309 usc.reset (new SettingsController);
3310 UserSettingsController::InitializeSettingsController (usc,
3311 SettingsController::global_settings_table,
3312 SettingsController::instance_settings_table);
Caroline Tice20bd37f2011-03-10 22:14:10 +00003313
3314 // Now call SettingsInitialize() for each 'child' of Process settings
3315 Thread::SettingsInitialize ();
Greg Clayton99d0faf2010-11-18 23:32:35 +00003316}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003317
Greg Clayton99d0faf2010-11-18 23:32:35 +00003318void
Caroline Tice20bd37f2011-03-10 22:14:10 +00003319Process::SettingsTerminate ()
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00003320{
Caroline Tice20bd37f2011-03-10 22:14:10 +00003321 // Must call SettingsTerminate() on each 'child' of Process settings before terminating Process settings.
3322
3323 Thread::SettingsTerminate ();
3324
3325 // Now terminate Process Settings.
3326
Greg Clayton99d0faf2010-11-18 23:32:35 +00003327 UserSettingsControllerSP &usc = GetSettingsController();
3328 UserSettingsController::FinalizeSettingsController (usc);
3329 usc.reset();
3330}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003331
Greg Clayton99d0faf2010-11-18 23:32:35 +00003332UserSettingsControllerSP &
3333Process::GetSettingsController ()
3334{
3335 static UserSettingsControllerSP g_settings_controller;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00003336 return g_settings_controller;
3337}
3338
Caroline Tice1559a462010-09-27 00:30:10 +00003339void
3340Process::UpdateInstanceName ()
3341{
Greg Claytonaa149cb2011-08-11 02:48:45 +00003342 Module *module = GetTarget().GetExecutableModulePointer();
3343 if (module)
Caroline Tice1559a462010-09-27 00:30:10 +00003344 {
3345 StreamString sstr;
Greg Claytonaa149cb2011-08-11 02:48:45 +00003346 sstr.Printf ("%s", module->GetFileSpec().GetFilename().AsCString());
Caroline Tice1559a462010-09-27 00:30:10 +00003347
Greg Claytondbe54502010-11-19 03:46:01 +00003348 GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
Greg Clayton8b82f082011-04-12 05:54:46 +00003349 sstr.GetData());
Caroline Tice1559a462010-09-27 00:30:10 +00003350 }
3351}
3352
Greg Clayton8b2fe6d2010-12-14 02:59:59 +00003353ExecutionResults
Jim Inghamf48169b2010-11-30 02:22:11 +00003354Process::RunThreadPlan (ExecutionContext &exe_ctx,
3355 lldb::ThreadPlanSP &thread_plan_sp,
3356 bool stop_others,
3357 bool try_all_threads,
3358 bool discard_on_error,
3359 uint32_t single_thread_timeout_usec,
3360 Stream &errors)
3361{
3362 ExecutionResults return_value = eExecutionSetupError;
3363
Jim Ingham77787032011-01-20 02:03:18 +00003364 if (thread_plan_sp.get() == NULL)
3365 {
3366 errors.Printf("RunThreadPlan called with empty thread plan.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003367 return eExecutionSetupError;
Jim Ingham77787032011-01-20 02:03:18 +00003368 }
3369
Jim Ingham17e5c4e2011-05-17 22:24:54 +00003370 // We rely on the thread plan we are running returning "PlanCompleted" if when it successfully completes.
3371 // For that to be true the plan can't be private - since private plans suppress themselves in the
3372 // GetCompletedPlan call.
3373
3374 bool orig_plan_private = thread_plan_sp->GetPrivate();
3375 thread_plan_sp->SetPrivate(false);
3376
Jim Ingham444586b2011-01-24 06:34:17 +00003377 if (m_private_state.GetValue() != eStateStopped)
3378 {
3379 errors.Printf ("RunThreadPlan called while the private state was not stopped.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003380 return eExecutionSetupError;
Jim Ingham444586b2011-01-24 06:34:17 +00003381 }
3382
Jim Ingham66243842011-08-13 00:56:10 +00003383 // Save the thread & frame from the exe_ctx for restoration after we run
Greg Clayton92bb12c2011-05-19 18:17:41 +00003384 const uint32_t thread_idx_id = exe_ctx.thread->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003385 StackID ctx_frame_id = exe_ctx.thread->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003386
3387 // N.B. Running the target may unset the currently selected thread and frame. We don't want to do that either,
3388 // so we should arrange to reset them as well.
3389
3390 lldb::ThreadSP selected_thread_sp = exe_ctx.process->GetThreadList().GetSelectedThread();
Jim Inghamf48169b2010-11-30 02:22:11 +00003391
Jim Ingham66243842011-08-13 00:56:10 +00003392 uint32_t selected_tid;
3393 StackID selected_stack_id;
Jim Inghamf48169b2010-11-30 02:22:11 +00003394 if (selected_thread_sp != NULL)
3395 {
3396 selected_tid = selected_thread_sp->GetIndexID();
Jim Ingham66243842011-08-13 00:56:10 +00003397 selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
Jim Inghamf48169b2010-11-30 02:22:11 +00003398 }
3399 else
3400 {
3401 selected_tid = LLDB_INVALID_THREAD_ID;
3402 }
3403
3404 exe_ctx.thread->QueueThreadPlan(thread_plan_sp, true);
3405
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003406 Listener listener("lldb.process.listener.run-thread-plan");
Jim Ingham0f16e732011-02-08 05:20:59 +00003407
3408 // This process event hijacker Hijacks the Public events and its destructor makes sure that the process events get
3409 // restored on exit to the function.
3410
3411 ProcessEventHijacker run_thread_plan_hijacker (*this, &listener);
Jim Ingham444586b2011-01-24 06:34:17 +00003412
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003413 lldb::LogSP log(lldb_private::GetLogIfAnyCategoriesSet (LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS));
Jim Ingham77787032011-01-20 02:03:18 +00003414 if (log)
3415 {
3416 StreamString s;
3417 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
Jim Ingham0f16e732011-02-08 05:20:59 +00003418 log->Printf ("Process::RunThreadPlan(): Resuming thread %u - 0x%4.4x to run thread plan \"%s\".",
3419 exe_ctx.thread->GetIndexID(),
3420 exe_ctx.thread->GetID(),
3421 s.GetData());
Jim Ingham77787032011-01-20 02:03:18 +00003422 }
3423
Jim Ingham0f16e732011-02-08 05:20:59 +00003424 bool got_event;
3425 lldb::EventSP event_sp;
3426 lldb::StateType stop_state = lldb::eStateInvalid;
Jim Inghamf48169b2010-11-30 02:22:11 +00003427
3428 TimeValue* timeout_ptr = NULL;
3429 TimeValue real_timeout;
3430
Jim Ingham0f16e732011-02-08 05:20:59 +00003431 bool first_timeout = true;
3432 bool do_resume = true;
Jim Inghamf48169b2010-11-30 02:22:11 +00003433
Jim Inghamf48169b2010-11-30 02:22:11 +00003434 while (1)
3435 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003436 // We usually want to resume the process if we get to the top of the loop.
3437 // The only exception is if we get two running events with no intervening
3438 // stop, which can happen, we will just wait for then next stop event.
Jim Inghamf48169b2010-11-30 02:22:11 +00003439
Jim Ingham0f16e732011-02-08 05:20:59 +00003440 if (do_resume)
Jim Inghamf48169b2010-11-30 02:22:11 +00003441 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003442 // Do the initial resume and wait for the running event before going further.
3443
3444 Error resume_error = exe_ctx.process->Resume ();
3445 if (!resume_error.Success())
3446 {
3447 errors.Printf("Error resuming inferior: \"%s\".\n", resume_error.AsCString());
Greg Claytone0d378b2011-03-24 21:19:54 +00003448 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003449 break;
3450 }
3451
3452 real_timeout = TimeValue::Now();
3453 real_timeout.OffsetWithMicroSeconds(500000);
3454 timeout_ptr = &real_timeout;
3455
3456 got_event = listener.WaitForEvent(NULL, event_sp);
3457 if (!got_event)
3458 {
3459 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003460 log->PutCString("Didn't get any event after initial resume, exiting.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003461
3462 errors.Printf("Didn't get any event after initial resume, exiting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003463 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003464 break;
3465 }
3466
3467 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3468 if (stop_state != eStateRunning)
3469 {
3470 if (log)
3471 log->Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
3472
3473 errors.Printf("Didn't get running event after initial resume, got %s instead.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003474 return_value = eExecutionSetupError;
Jim Ingham0f16e732011-02-08 05:20:59 +00003475 break;
3476 }
3477
3478 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003479 log->PutCString ("Resuming succeeded.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003480 // We need to call the function synchronously, so spin waiting for it to return.
3481 // If we get interrupted while executing, we're going to lose our context, and
3482 // won't be able to gather the result at this point.
3483 // We set the timeout AFTER the resume, since the resume takes some time and we
3484 // don't want to charge that to the timeout.
3485
3486 if (single_thread_timeout_usec != 0)
3487 {
3488 real_timeout = TimeValue::Now();
3489 if (first_timeout)
3490 real_timeout.OffsetWithMicroSeconds(single_thread_timeout_usec);
3491 else
3492 real_timeout.OffsetWithSeconds(10);
3493
3494 timeout_ptr = &real_timeout;
3495 }
3496 }
3497 else
3498 {
3499 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003500 log->PutCString ("Handled an extra running event.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003501 do_resume = true;
3502 }
3503
3504 // Now wait for the process to stop again:
3505 stop_state = lldb::eStateInvalid;
3506 event_sp.reset();
3507 got_event = listener.WaitForEvent (timeout_ptr, event_sp);
3508
3509 if (got_event)
3510 {
3511 if (event_sp.get())
3512 {
3513 bool keep_going = false;
3514 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3515 if (log)
3516 log->Printf("In while loop, got event: %s.", StateAsCString(stop_state));
3517
3518 switch (stop_state)
3519 {
3520 case lldb::eStateStopped:
Jim Ingham160f78c2011-05-17 01:10:11 +00003521 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003522 // Yay, we're done. Now make sure that our thread plan actually completed.
3523 ThreadSP thread_sp = exe_ctx.process->GetThreadList().FindThreadByIndexID (thread_idx_id);
3524 if (!thread_sp)
Jim Ingham160f78c2011-05-17 01:10:11 +00003525 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003526 // Ooh, our thread has vanished. Unlikely that this was successful execution...
Jim Ingham160f78c2011-05-17 01:10:11 +00003527 if (log)
Greg Clayton54e8ac52011-06-03 22:12:42 +00003528 log->Printf ("Execution completed but our thread (index-id=%u) has vanished.", thread_idx_id);
3529 return_value = eExecutionInterrupted;
Jim Ingham160f78c2011-05-17 01:10:11 +00003530 }
3531 else
3532 {
Greg Clayton54e8ac52011-06-03 22:12:42 +00003533 StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
3534 StopReason stop_reason = eStopReasonInvalid;
3535 if (stop_info_sp)
3536 stop_reason = stop_info_sp->GetStopReason();
3537 if (stop_reason == eStopReasonPlanComplete)
3538 {
3539 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003540 log->PutCString ("Execution completed successfully.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003541 // Now mark this plan as private so it doesn't get reported as the stop reason
3542 // after this point.
3543 if (thread_plan_sp)
3544 thread_plan_sp->SetPrivate (orig_plan_private);
3545 return_value = eExecutionCompleted;
3546 }
3547 else
3548 {
3549 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003550 log->PutCString ("Thread plan didn't successfully complete.");
Greg Clayton54e8ac52011-06-03 22:12:42 +00003551
3552 return_value = eExecutionInterrupted;
3553 }
Jim Ingham160f78c2011-05-17 01:10:11 +00003554 }
Greg Clayton54e8ac52011-06-03 22:12:42 +00003555 }
3556 break;
3557
Jim Ingham0f16e732011-02-08 05:20:59 +00003558 case lldb::eStateCrashed:
3559 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003560 log->PutCString ("Execution crashed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003561 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003562 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003563
Jim Ingham0f16e732011-02-08 05:20:59 +00003564 case lldb::eStateRunning:
3565 do_resume = false;
3566 keep_going = true;
3567 break;
Greg Clayton54e8ac52011-06-03 22:12:42 +00003568
Jim Ingham0f16e732011-02-08 05:20:59 +00003569 default:
3570 if (log)
3571 log->Printf("Execution stopped with unexpected state: %s.", StateAsCString(stop_state));
Jim Ingham160f78c2011-05-17 01:10:11 +00003572
3573 errors.Printf ("Execution stopped with unexpected state.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003574 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003575 break;
3576 }
3577 if (keep_going)
3578 continue;
3579 else
3580 break;
3581 }
3582 else
3583 {
3584 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003585 log->PutCString ("got_event was true, but the event pointer was null. How odd...");
Greg Claytone0d378b2011-03-24 21:19:54 +00003586 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003587 break;
3588 }
3589 }
3590 else
3591 {
3592 // If we didn't get an event that means we've timed out...
3593 // We will interrupt the process here. Depending on what we were asked to do we will
3594 // either exit, or try with all threads running for the same timeout.
Jim Inghamf48169b2010-11-30 02:22:11 +00003595 // Not really sure what to do if Halt fails here...
Jim Ingham0f16e732011-02-08 05:20:59 +00003596
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003597 if (log) {
Jim Inghamf48169b2010-11-30 02:22:11 +00003598 if (try_all_threads)
Jim Ingham0f16e732011-02-08 05:20:59 +00003599 {
3600 if (first_timeout)
3601 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3602 "trying with all threads enabled.",
3603 single_thread_timeout_usec);
3604 else
3605 log->Printf ("Process::RunThreadPlan(): Restarting function with all threads enabled "
3606 "and timeout: %d timed out.",
3607 single_thread_timeout_usec);
3608 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003609 else
Jim Ingham0f16e732011-02-08 05:20:59 +00003610 log->Printf ("Process::RunThreadPlan(): Running function with timeout: %d timed out, "
3611 "halt and abandoning execution.",
Jim Inghamf48169b2010-11-30 02:22:11 +00003612 single_thread_timeout_usec);
Stephen Wilson78a4feb2011-01-12 04:20:03 +00003613 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003614
Jim Inghame22e88b2011-01-22 01:30:53 +00003615 Error halt_error = exe_ctx.process->Halt();
Jim Inghame22e88b2011-01-22 01:30:53 +00003616 if (halt_error.Success())
Jim Inghamf48169b2010-11-30 02:22:11 +00003617 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003618 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003619 log->PutCString ("Process::RunThreadPlan(): Halt succeeded.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003620
Jim Ingham0f16e732011-02-08 05:20:59 +00003621 // If halt succeeds, it always produces a stopped event. Wait for that:
3622
3623 real_timeout = TimeValue::Now();
3624 real_timeout.OffsetWithMicroSeconds(500000);
3625
3626 got_event = listener.WaitForEvent(&real_timeout, event_sp);
Jim Inghamf48169b2010-11-30 02:22:11 +00003627
3628 if (got_event)
3629 {
3630 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3631 if (log)
3632 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003633 log->Printf ("Process::RunThreadPlan(): Stopped with event: %s", StateAsCString(stop_state));
Jim Ingham0f16e732011-02-08 05:20:59 +00003634 if (stop_state == lldb::eStateStopped
3635 && Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
Jim Ingham20829ac2011-08-09 22:24:33 +00003636 log->PutCString (" Event was the Halt interruption event.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003637 }
3638
Jim Ingham0f16e732011-02-08 05:20:59 +00003639 if (stop_state == lldb::eStateStopped)
Jim Inghamf48169b2010-11-30 02:22:11 +00003640 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003641 // Between the time we initiated the Halt and the time we delivered it, the process could have
3642 // already finished its job. Check that here:
Jim Inghamf48169b2010-11-30 02:22:11 +00003643
Jim Ingham0f16e732011-02-08 05:20:59 +00003644 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3645 {
3646 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003647 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003648 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003649 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003650 break;
3651 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003652
Jim Ingham0f16e732011-02-08 05:20:59 +00003653 if (!try_all_threads)
3654 {
3655 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003656 log->PutCString ("try_all_threads was false, we stopped so now we're quitting.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003657 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003658 break;
3659 }
3660
3661 if (first_timeout)
3662 {
3663 // Set all the other threads to run, and return to the top of the loop, which will continue;
3664 first_timeout = false;
3665 thread_plan_sp->SetStopOthers (false);
3666 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003667 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003668
3669 continue;
3670 }
3671 else
3672 {
3673 // Running all threads failed, so return Interrupted.
3674 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003675 log->PutCString("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003676 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003677 break;
3678 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003679 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003680 }
3681 else
3682 { if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003683 log->PutCString("Process::RunThreadPlan(): halt said it succeeded, but I got no event. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003684 "I'm getting out of here passing Interrupted.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003685 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003686 break;
Jim Inghamf48169b2010-11-30 02:22:11 +00003687 }
3688 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003689 else
3690 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003691 // This branch is to work around some problems with gdb-remote's Halt. It is a little racy, and can return
3692 // an error from halt, but if you wait a bit you'll get a stopped event anyway.
Jim Inghame22e88b2011-01-22 01:30:53 +00003693 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003694 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.",
3695 halt_error.AsCString());
3696 real_timeout = TimeValue::Now();
3697 real_timeout.OffsetWithMicroSeconds(500000);
3698 timeout_ptr = &real_timeout;
3699 got_event = listener.WaitForEvent(&real_timeout, event_sp);
3700 if (!got_event || event_sp.get() == NULL)
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003701 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003702 // This is not going anywhere, bag out.
3703 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003704 log->PutCString ("Process::RunThreadPlan(): halt failed: and waiting for the stopped event failed.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003705 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003706 break;
Jim Ingham1e7a9ee2011-01-23 21:14:08 +00003707 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003708 else
3709 {
3710 stop_state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3711 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003712 log->PutCString ("Process::RunThreadPlan(): halt failed: but then I got a stopped event. Whatever...");
Jim Ingham0f16e732011-02-08 05:20:59 +00003713 if (stop_state == lldb::eStateStopped)
3714 {
3715 // Between the time we initiated the Halt and the time we delivered it, the process could have
3716 // already finished its job. Check that here:
3717
3718 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3719 {
3720 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003721 log->PutCString ("Process::RunThreadPlan(): Even though we timed out, the call plan was done. "
Jim Ingham0f16e732011-02-08 05:20:59 +00003722 "Exiting wait loop.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003723 return_value = eExecutionCompleted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003724 break;
3725 }
3726
3727 if (first_timeout)
3728 {
3729 // Set all the other threads to run, and return to the top of the loop, which will continue;
3730 first_timeout = false;
3731 thread_plan_sp->SetStopOthers (false);
3732 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003733 log->PutCString ("Process::RunThreadPlan(): About to resume.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003734
3735 continue;
3736 }
3737 else
3738 {
3739 // Running all threads failed, so return Interrupted.
3740 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003741 log->PutCString ("Process::RunThreadPlan(): running all threads timed out.");
Greg Claytone0d378b2011-03-24 21:19:54 +00003742 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003743 break;
3744 }
3745 }
3746 else
3747 {
Sean Callanan39821ac2011-08-09 22:07:08 +00003748 if (log)
3749 log->Printf ("Process::RunThreadPlan(): halt failed, I waited and didn't get"
3750 " a stopped event, instead got %s.", StateAsCString(stop_state));
Greg Claytone0d378b2011-03-24 21:19:54 +00003751 return_value = eExecutionInterrupted;
Jim Ingham0f16e732011-02-08 05:20:59 +00003752 break;
3753 }
3754 }
Jim Inghame22e88b2011-01-22 01:30:53 +00003755 }
3756
Jim Inghamf48169b2010-11-30 02:22:11 +00003757 }
3758
Jim Ingham0f16e732011-02-08 05:20:59 +00003759 } // END WAIT LOOP
3760
3761 // Now do some processing on the results of the run:
3762 if (return_value == eExecutionInterrupted)
3763 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003764 if (log)
Jim Ingham0f16e732011-02-08 05:20:59 +00003765 {
3766 StreamString s;
3767 if (event_sp)
3768 event_sp->Dump (&s);
3769 else
3770 {
Jim Ingham20829ac2011-08-09 22:24:33 +00003771 log->PutCString ("Process::RunThreadPlan(): Stop event that interrupted us is NULL.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003772 }
3773
3774 StreamString ts;
3775
Jim Ingham20829ac2011-08-09 22:24:33 +00003776 const char *event_explanation = NULL;
Jim Ingham0f16e732011-02-08 05:20:59 +00003777
3778 do
3779 {
3780 const Process::ProcessEventData *event_data = Process::ProcessEventData::GetEventDataFromEvent (event_sp.get());
3781
3782 if (!event_data)
3783 {
3784 event_explanation = "<no event data>";
3785 break;
3786 }
3787
3788 Process *process = event_data->GetProcessSP().get();
3789
3790 if (!process)
3791 {
3792 event_explanation = "<no process>";
3793 break;
3794 }
3795
3796 ThreadList &thread_list = process->GetThreadList();
3797
3798 uint32_t num_threads = thread_list.GetSize();
3799 uint32_t thread_index;
3800
3801 ts.Printf("<%u threads> ", num_threads);
3802
3803 for (thread_index = 0;
3804 thread_index < num_threads;
3805 ++thread_index)
3806 {
3807 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
3808
3809 if (!thread)
3810 {
3811 ts.Printf("<?> ");
3812 continue;
3813 }
3814
3815 ts.Printf("<0x%4.4x ", thread->GetID());
3816 RegisterContext *register_context = thread->GetRegisterContext().get();
3817
3818 if (register_context)
3819 ts.Printf("[ip 0x%llx] ", register_context->GetPC());
3820 else
3821 ts.Printf("[ip unknown] ");
3822
3823 lldb::StopInfoSP stop_info_sp = thread->GetStopInfo();
3824 if (stop_info_sp)
3825 {
3826 const char *stop_desc = stop_info_sp->GetDescription();
3827 if (stop_desc)
3828 ts.PutCString (stop_desc);
3829 }
3830 ts.Printf(">");
3831 }
3832
3833 event_explanation = ts.GetData();
3834 } while (0);
3835
3836 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003837 {
3838 if (event_explanation)
3839 log->Printf("Process::RunThreadPlan(): execution interrupted: %s %s", s.GetData(), event_explanation);
3840 else
3841 log->Printf("Process::RunThreadPlan(): execution interrupted: %s", s.GetData());
3842 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003843
3844 if (discard_on_error && thread_plan_sp)
3845 {
3846 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003847 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00003848 }
3849 }
3850 }
3851 else if (return_value == eExecutionSetupError)
3852 {
3853 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003854 log->PutCString("Process::RunThreadPlan(): execution set up error.");
Jim Ingham0f16e732011-02-08 05:20:59 +00003855
3856 if (discard_on_error && thread_plan_sp)
3857 {
3858 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003859 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Ingham0f16e732011-02-08 05:20:59 +00003860 }
3861 }
3862 else
3863 {
Jim Inghamf48169b2010-11-30 02:22:11 +00003864 if (exe_ctx.thread->IsThreadPlanDone (thread_plan_sp.get()))
3865 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003866 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003867 log->PutCString("Process::RunThreadPlan(): thread plan is done");
Greg Claytone0d378b2011-03-24 21:19:54 +00003868 return_value = eExecutionCompleted;
Jim Inghamf48169b2010-11-30 02:22:11 +00003869 }
3870 else if (exe_ctx.thread->WasThreadPlanDiscarded (thread_plan_sp.get()))
3871 {
Greg Clayton414f5d32011-01-25 02:58:48 +00003872 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003873 log->PutCString("Process::RunThreadPlan(): thread plan was discarded");
Greg Claytone0d378b2011-03-24 21:19:54 +00003874 return_value = eExecutionDiscarded;
Jim Inghamf48169b2010-11-30 02:22:11 +00003875 }
3876 else
3877 {
3878 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003879 log->PutCString("Process::RunThreadPlan(): thread plan stopped in mid course");
Jim Inghamf48169b2010-11-30 02:22:11 +00003880 if (discard_on_error && thread_plan_sp)
3881 {
Jim Ingham0f16e732011-02-08 05:20:59 +00003882 if (log)
Jim Ingham20829ac2011-08-09 22:24:33 +00003883 log->PutCString("Process::RunThreadPlan(): discarding thread plan 'cause discard_on_error is set.");
Jim Inghamf48169b2010-11-30 02:22:11 +00003884 exe_ctx.thread->DiscardThreadPlansUpToPlan (thread_plan_sp);
Jim Ingham4b536182011-08-09 02:12:22 +00003885 thread_plan_sp->SetPrivate (orig_plan_private);
Jim Inghamf48169b2010-11-30 02:22:11 +00003886 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003887 }
3888 }
Jim Ingham0f16e732011-02-08 05:20:59 +00003889
Jim Inghamf48169b2010-11-30 02:22:11 +00003890 // Thread we ran the function in may have gone away because we ran the target
Jim Ingham66243842011-08-13 00:56:10 +00003891 // Check that it's still there, and if it is put it back in the context. Also restore the
3892 // frame in the context if it is still present.
Greg Clayton92bb12c2011-05-19 18:17:41 +00003893 exe_ctx.thread = exe_ctx.process->GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
Jim Inghamf48169b2010-11-30 02:22:11 +00003894 if (exe_ctx.thread)
Jim Ingham66243842011-08-13 00:56:10 +00003895 {
3896 exe_ctx.frame = exe_ctx.thread->GetFrameWithStackID (ctx_frame_id).get();
3897 }
Jim Inghamf48169b2010-11-30 02:22:11 +00003898
3899 // Also restore the current process'es selected frame & thread, since this function calling may
3900 // be done behind the user's back.
3901
3902 if (selected_tid != LLDB_INVALID_THREAD_ID)
3903 {
Jim Ingham66243842011-08-13 00:56:10 +00003904 if (exe_ctx.process->GetThreadList().SetSelectedThreadByIndexID (selected_tid) && selected_stack_id.IsValid())
Jim Inghamf48169b2010-11-30 02:22:11 +00003905 {
3906 // We were able to restore the selected thread, now restore the frame:
Jim Ingham66243842011-08-13 00:56:10 +00003907 StackFrameSP old_frame_sp = exe_ctx.process->GetThreadList().GetSelectedThread()->GetFrameWithStackID(selected_stack_id);
3908 if (old_frame_sp)
3909 exe_ctx.process->GetThreadList().GetSelectedThread()->SetSelectedFrame(old_frame_sp.get());
Jim Inghamf48169b2010-11-30 02:22:11 +00003910 }
3911 }
3912
3913 return return_value;
3914}
3915
3916const char *
3917Process::ExecutionResultAsCString (ExecutionResults result)
3918{
3919 const char *result_name;
3920
3921 switch (result)
3922 {
Greg Claytone0d378b2011-03-24 21:19:54 +00003923 case eExecutionCompleted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003924 result_name = "eExecutionCompleted";
3925 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003926 case eExecutionDiscarded:
Jim Inghamf48169b2010-11-30 02:22:11 +00003927 result_name = "eExecutionDiscarded";
3928 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003929 case eExecutionInterrupted:
Jim Inghamf48169b2010-11-30 02:22:11 +00003930 result_name = "eExecutionInterrupted";
3931 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003932 case eExecutionSetupError:
Jim Inghamf48169b2010-11-30 02:22:11 +00003933 result_name = "eExecutionSetupError";
3934 break;
Greg Claytone0d378b2011-03-24 21:19:54 +00003935 case eExecutionTimedOut:
Jim Inghamf48169b2010-11-30 02:22:11 +00003936 result_name = "eExecutionTimedOut";
3937 break;
3938 }
3939 return result_name;
3940}
3941
Greg Clayton7260f622011-04-18 08:33:37 +00003942void
3943Process::GetStatus (Stream &strm)
3944{
3945 const StateType state = GetState();
3946 if (StateIsStoppedState(state))
3947 {
3948 if (state == eStateExited)
3949 {
3950 int exit_status = GetExitStatus();
3951 const char *exit_description = GetExitDescription();
3952 strm.Printf ("Process %d exited with status = %i (0x%8.8x) %s\n",
3953 GetID(),
3954 exit_status,
3955 exit_status,
3956 exit_description ? exit_description : "");
3957 }
3958 else
3959 {
3960 if (state == eStateConnected)
3961 strm.Printf ("Connected to remote target.\n");
3962 else
3963 strm.Printf ("Process %d %s\n", GetID(), StateAsCString (state));
3964 }
3965 }
3966 else
3967 {
3968 strm.Printf ("Process %d is running.\n", GetID());
3969 }
3970}
3971
3972size_t
3973Process::GetThreadStatus (Stream &strm,
3974 bool only_threads_with_stop_reason,
3975 uint32_t start_frame,
3976 uint32_t num_frames,
3977 uint32_t num_frames_with_source)
3978{
3979 size_t num_thread_infos_dumped = 0;
3980
3981 const size_t num_threads = GetThreadList().GetSize();
3982 for (uint32_t i = 0; i < num_threads; i++)
3983 {
3984 Thread *thread = GetThreadList().GetThreadAtIndex(i).get();
3985 if (thread)
3986 {
3987 if (only_threads_with_stop_reason)
3988 {
3989 if (thread->GetStopInfo().get() == NULL)
3990 continue;
3991 }
3992 thread->GetStatus (strm,
3993 start_frame,
3994 num_frames,
3995 num_frames_with_source);
3996 ++num_thread_infos_dumped;
3997 }
3998 }
3999 return num_thread_infos_dumped;
4000}
4001
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004002//--------------------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004003// class Process::SettingsController
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004004//--------------------------------------------------------------
4005
Greg Clayton1b654882010-09-19 02:33:57 +00004006Process::SettingsController::SettingsController () :
Caroline Ticedaccaa92010-09-20 20:44:43 +00004007 UserSettingsController ("process", Target::GetSettingsController())
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004008{
Greg Clayton85851dd2010-12-04 00:10:17 +00004009 m_default_settings.reset (new ProcessInstanceSettings (*this,
4010 false,
Caroline Tice91123da2010-09-08 17:48:55 +00004011 InstanceSettings::GetDefaultName().AsCString()));
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004012}
4013
Greg Clayton1b654882010-09-19 02:33:57 +00004014Process::SettingsController::~SettingsController ()
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004015{
4016}
4017
4018lldb::InstanceSettingsSP
Greg Clayton1b654882010-09-19 02:33:57 +00004019Process::SettingsController::CreateInstanceSettings (const char *instance_name)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004020{
Greg Claytondbe54502010-11-19 03:46:01 +00004021 ProcessInstanceSettings *new_settings = new ProcessInstanceSettings (*GetSettingsController(),
4022 false,
4023 instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004024 lldb::InstanceSettingsSP new_settings_sp (new_settings);
4025 return new_settings_sp;
4026}
4027
4028//--------------------------------------------------------------
4029// class ProcessInstanceSettings
4030//--------------------------------------------------------------
4031
Greg Clayton85851dd2010-12-04 00:10:17 +00004032ProcessInstanceSettings::ProcessInstanceSettings
4033(
4034 UserSettingsController &owner,
4035 bool live_instance,
4036 const char *name
4037) :
4038 InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004039 m_run_args (),
4040 m_env_vars (),
4041 m_input_path (),
4042 m_output_path (),
4043 m_error_path (),
Caroline Ticef8da8632010-12-03 18:46:09 +00004044 m_disable_aslr (true),
Greg Clayton85851dd2010-12-04 00:10:17 +00004045 m_disable_stdio (false),
4046 m_inherit_host_env (true),
4047 m_got_host_env (false)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004048{
Caroline Ticef20e8232010-09-09 18:26:37 +00004049 // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
4050 // until the vtables for ProcessInstanceSettings are properly set up, i.e. AFTER all the initializers.
4051 // 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 +00004052 // This is true for CreateInstanceName() too.
4053
4054 if (GetInstanceName () == InstanceSettings::InvalidName())
4055 {
4056 ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
4057 m_owner.RegisterInstanceSettings (this);
4058 }
Caroline Ticef20e8232010-09-09 18:26:37 +00004059
4060 if (live_instance)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004061 {
4062 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4063 CopyInstanceSettings (pending_settings,false);
Caroline Ticef20e8232010-09-09 18:26:37 +00004064 //m_owner.RemovePendingSettings (m_instance_name);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004065 }
4066}
4067
4068ProcessInstanceSettings::ProcessInstanceSettings (const ProcessInstanceSettings &rhs) :
Greg Claytondbe54502010-11-19 03:46:01 +00004069 InstanceSettings (*Process::GetSettingsController(), CreateInstanceName().AsCString()),
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004070 m_run_args (rhs.m_run_args),
4071 m_env_vars (rhs.m_env_vars),
4072 m_input_path (rhs.m_input_path),
4073 m_output_path (rhs.m_output_path),
4074 m_error_path (rhs.m_error_path),
Caroline Ticef8da8632010-12-03 18:46:09 +00004075 m_disable_aslr (rhs.m_disable_aslr),
4076 m_disable_stdio (rhs.m_disable_stdio)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004077{
4078 if (m_instance_name != InstanceSettings::GetDefaultName())
4079 {
4080 const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
4081 CopyInstanceSettings (pending_settings,false);
4082 m_owner.RemovePendingSettings (m_instance_name);
4083 }
4084}
4085
4086ProcessInstanceSettings::~ProcessInstanceSettings ()
4087{
4088}
4089
4090ProcessInstanceSettings&
4091ProcessInstanceSettings::operator= (const ProcessInstanceSettings &rhs)
4092{
4093 if (this != &rhs)
4094 {
4095 m_run_args = rhs.m_run_args;
4096 m_env_vars = rhs.m_env_vars;
4097 m_input_path = rhs.m_input_path;
4098 m_output_path = rhs.m_output_path;
4099 m_error_path = rhs.m_error_path;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004100 m_disable_aslr = rhs.m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00004101 m_disable_stdio = rhs.m_disable_stdio;
Greg Clayton85851dd2010-12-04 00:10:17 +00004102 m_inherit_host_env = rhs.m_inherit_host_env;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004103 }
4104
4105 return *this;
4106}
4107
4108
4109void
4110ProcessInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
4111 const char *index_value,
4112 const char *value,
4113 const ConstString &instance_name,
4114 const SettingEntry &entry,
Greg Claytone0d378b2011-03-24 21:19:54 +00004115 VarSetOperationType op,
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004116 Error &err,
4117 bool pending)
4118{
4119 if (var_name == RunArgsVarName())
4120 UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
4121 else if (var_name == EnvVarsVarName())
Greg Clayton85851dd2010-12-04 00:10:17 +00004122 {
Greg Clayton8b82f082011-04-12 05:54:46 +00004123 // This is nice for local debugging, but it is isn't correct for
4124 // remote debugging. We need to stop process.env-vars from being
4125 // populated with the host environment and add this as a launch option
4126 // and get the correct environment from the Target's platform.
4127 // GetHostEnvironmentIfNeeded ();
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004128 UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
Greg Clayton85851dd2010-12-04 00:10:17 +00004129 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004130 else if (var_name == InputPathVarName())
4131 UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
4132 else if (var_name == OutputPathVarName())
4133 UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
4134 else if (var_name == ErrorPathVarName())
4135 UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004136 else if (var_name == DisableASLRVarName())
Greg Clayton385aa282011-04-22 03:55:06 +00004137 UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, true, err);
Caroline Ticef8da8632010-12-03 18:46:09 +00004138 else if (var_name == DisableSTDIOVarName ())
Greg Clayton385aa282011-04-22 03:55:06 +00004139 UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, false, err);
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004140}
4141
4142void
4143ProcessInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
4144 bool pending)
4145{
4146 if (new_settings.get() == NULL)
4147 return;
4148
4149 ProcessInstanceSettings *new_process_settings = (ProcessInstanceSettings *) new_settings.get();
4150
4151 m_run_args = new_process_settings->m_run_args;
4152 m_env_vars = new_process_settings->m_env_vars;
4153 m_input_path = new_process_settings->m_input_path;
4154 m_output_path = new_process_settings->m_output_path;
4155 m_error_path = new_process_settings->m_error_path;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004156 m_disable_aslr = new_process_settings->m_disable_aslr;
Caroline Ticef8da8632010-12-03 18:46:09 +00004157 m_disable_stdio = new_process_settings->m_disable_stdio;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004158}
4159
Caroline Tice12cecd72010-09-20 21:37:42 +00004160bool
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004161ProcessInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
4162 const ConstString &var_name,
Caroline Ticedaccaa92010-09-20 20:44:43 +00004163 StringList &value,
Caroline Tice12cecd72010-09-20 21:37:42 +00004164 Error *err)
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004165{
4166 if (var_name == RunArgsVarName())
4167 {
4168 if (m_run_args.GetArgumentCount() > 0)
Greg Claytona52c1552010-09-14 03:47:41 +00004169 {
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004170 for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
4171 value.AppendString (m_run_args.GetArgumentAtIndex (i));
Greg Claytona52c1552010-09-14 03:47:41 +00004172 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004173 }
4174 else if (var_name == EnvVarsVarName())
4175 {
Greg Clayton85851dd2010-12-04 00:10:17 +00004176 GetHostEnvironmentIfNeeded ();
4177
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004178 if (m_env_vars.size() > 0)
4179 {
4180 std::map<std::string, std::string>::iterator pos;
4181 for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
4182 {
4183 StreamString value_str;
4184 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
4185 value.AppendString (value_str.GetData());
4186 }
4187 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004188 }
4189 else if (var_name == InputPathVarName())
4190 {
4191 value.AppendString (m_input_path.c_str());
4192 }
4193 else if (var_name == OutputPathVarName())
4194 {
4195 value.AppendString (m_output_path.c_str());
4196 }
4197 else if (var_name == ErrorPathVarName())
4198 {
4199 value.AppendString (m_error_path.c_str());
4200 }
Greg Clayton5c5f1a12010-12-04 00:12:24 +00004201 else if (var_name == InheritHostEnvVarName())
4202 {
4203 if (m_inherit_host_env)
4204 value.AppendString ("true");
4205 else
4206 value.AppendString ("false");
4207 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004208 else if (var_name == DisableASLRVarName())
4209 {
4210 if (m_disable_aslr)
4211 value.AppendString ("true");
4212 else
4213 value.AppendString ("false");
4214 }
Caroline Ticef8da8632010-12-03 18:46:09 +00004215 else if (var_name == DisableSTDIOVarName())
4216 {
4217 if (m_disable_stdio)
4218 value.AppendString ("true");
4219 else
4220 value.AppendString ("false");
4221 }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004222 else
Caroline Tice12cecd72010-09-20 21:37:42 +00004223 {
4224 if (err)
4225 err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
4226 return false;
4227 }
4228 return true;
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004229}
4230
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004231const ConstString
4232ProcessInstanceSettings::CreateInstanceName ()
4233{
4234 static int instance_count = 1;
4235 StreamString sstr;
4236
4237 sstr.Printf ("process_%d", instance_count);
4238 ++instance_count;
4239
4240 const ConstString ret_val (sstr.GetData());
4241 return ret_val;
4242}
4243
4244const ConstString &
4245ProcessInstanceSettings::RunArgsVarName ()
4246{
4247 static ConstString run_args_var_name ("run-args");
4248
4249 return run_args_var_name;
4250}
4251
4252const ConstString &
4253ProcessInstanceSettings::EnvVarsVarName ()
4254{
4255 static ConstString env_vars_var_name ("env-vars");
4256
4257 return env_vars_var_name;
4258}
4259
4260const ConstString &
Greg Clayton85851dd2010-12-04 00:10:17 +00004261ProcessInstanceSettings::InheritHostEnvVarName ()
4262{
4263 static ConstString g_name ("inherit-env");
4264
4265 return g_name;
4266}
4267
4268const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004269ProcessInstanceSettings::InputPathVarName ()
4270{
4271 static ConstString input_path_var_name ("input-path");
4272
4273 return input_path_var_name;
4274}
4275
4276const ConstString &
4277ProcessInstanceSettings::OutputPathVarName ()
4278{
Caroline Tice49e27372010-09-07 18:35:40 +00004279 static ConstString output_path_var_name ("output-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004280
4281 return output_path_var_name;
4282}
4283
4284const ConstString &
4285ProcessInstanceSettings::ErrorPathVarName ()
4286{
Caroline Tice49e27372010-09-07 18:35:40 +00004287 static ConstString error_path_var_name ("error-path");
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004288
4289 return error_path_var_name;
4290}
4291
4292const ConstString &
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004293ProcessInstanceSettings::DisableASLRVarName ()
4294{
4295 static ConstString disable_aslr_var_name ("disable-aslr");
4296
4297 return disable_aslr_var_name;
4298}
4299
Caroline Ticef8da8632010-12-03 18:46:09 +00004300const ConstString &
4301ProcessInstanceSettings::DisableSTDIOVarName ()
4302{
4303 static ConstString disable_stdio_var_name ("disable-stdio");
4304
4305 return disable_stdio_var_name;
4306}
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004307
4308//--------------------------------------------------
Greg Clayton1b654882010-09-19 02:33:57 +00004309// SettingsController Variable Tables
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004310//--------------------------------------------------
4311
4312SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004313Process::SettingsController::global_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004314{
4315 //{ "var-name", var-type , "default", enum-table, init'd, hidden, "help-text"},
4316 { NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
4317};
4318
4319
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004320SettingEntry
Greg Clayton1b654882010-09-19 02:33:57 +00004321Process::SettingsController::instance_settings_table[] =
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004322{
Greg Clayton85851dd2010-12-04 00:10:17 +00004323 //{ "var-name", var-type, "default", enum-table, init'd, hidden, "help-text"},
4324 { "run-args", eSetVarTypeArray, NULL, NULL, false, false, "A list containing all the arguments to be passed to the executable when it is run." },
4325 { "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." },
4326 { "inherit-env", eSetVarTypeBoolean, "true", NULL, false, false, "Inherit the environment from the process that is running LLDB." },
Greg Claytonbd82a5d2011-01-23 05:56:20 +00004327 { "input-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for reading its input." },
4328 { "output-path", eSetVarTypeString, NULL, NULL, false, false, "The file/path to be used by the executable program for writing its output." },
4329 { "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 +00004330 { "plugin", eSetVarTypeEnum, NULL, NULL, false, false, "The plugin to be used to run the process." },
Greg Clayton85851dd2010-12-04 00:10:17 +00004331 { "disable-aslr", eSetVarTypeBoolean, "true", NULL, false, false, "Disable Address Space Layout Randomization (ASLR)" },
4332 { "disable-stdio", eSetVarTypeBoolean, "false", NULL, false, false, "Disable stdin/stdout for process (e.g. for a GUI application)" },
4333 { NULL, eSetVarTypeNone, NULL, NULL, false, false, NULL }
Caroline Tice3df9a8d2010-09-04 00:03:46 +00004334};
4335
4336
Jim Ingham5aee1622010-08-09 23:31:02 +00004337